charlieCs commited on
Commit
26c65ff
1 Parent(s): a79f52c

upload model

Browse files
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data/recoteam_583/mlapp/foundation_models/Orion-14B-Base",
3
+ "architectures": [
4
+ "OrionForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_orion.OrionConfig",
9
+ "AutoModel": "modeling_orion.OrionForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_orion.OrionForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "eos_token_id": 2,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 5120,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 15360,
18
+ "max_position_embeddings": 4096,
19
+ "max_sequence_length": 4096,
20
+ "model_type": "orion",
21
+ "num_attention_heads": 40,
22
+ "num_hidden_layers": 40,
23
+ "num_key_value_heads": 40,
24
+ "pad_token_id": 0,
25
+ "pretraining_tp": 1,
26
+ "rms_norm_eps": 1e-05,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.38.2",
32
+ "use_cache": false,
33
+ "vocab_size": 84608
34
+ }
configuration_orion.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, OrionStar Inc. All rights reserved.
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+ class OrionConfig(PretrainedConfig):
6
+ model_type = "orion"
7
+ keys_to_ignore_at_inference = ["past_key_values"]
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=84608,
12
+ hidden_size=4096,
13
+ intermediate_size=15360,
14
+ num_hidden_layers=40,
15
+ num_attention_heads=40,
16
+ num_key_value_heads=40,
17
+ hidden_act="silu",
18
+ max_position_embeddings=4096,
19
+ initializer_range=0.02,
20
+ rms_norm_eps=1e-5,
21
+ use_cache=True,
22
+ pad_token_id=None,
23
+ bos_token_id=1,
24
+ eos_token_id=2,
25
+ pretraining_tp=1,
26
+ tie_word_embeddings=False,
27
+ rope_theta=10000.0,
28
+ rope_scaling=None,
29
+ attention_bias=False,
30
+ **kwargs,
31
+ ):
32
+ self.vocab_size = vocab_size
33
+ self.max_position_embeddings = max_position_embeddings
34
+ self.hidden_size = hidden_size
35
+ self.intermediate_size = intermediate_size
36
+ self.num_hidden_layers = num_hidden_layers
37
+ self.num_attention_heads = num_attention_heads
38
+
39
+ # for backward compatibility
40
+ if num_key_value_heads is None:
41
+ num_key_value_heads = num_attention_heads
42
+
43
+ self.num_key_value_heads = num_key_value_heads
44
+ self.hidden_act = hidden_act
45
+ self.initializer_range = initializer_range
46
+ self.rms_norm_eps = rms_norm_eps
47
+ self.pretraining_tp = pretraining_tp
48
+ self.use_cache = use_cache
49
+ self.rope_theta = rope_theta
50
+ self.rope_scaling = rope_scaling
51
+ self._rope_scaling_validation()
52
+ self.attention_bias = attention_bias
53
+
54
+ super().__init__(
55
+ pad_token_id=pad_token_id,
56
+ bos_token_id=bos_token_id,
57
+ eos_token_id=eos_token_id,
58
+ tie_word_embeddings=tie_word_embeddings,
59
+ **kwargs,
60
+ )
61
+
62
+ def _rope_scaling_validation(self):
63
+ """
64
+ Validate the `rope_scaling` configuration.
65
+ """
66
+ if self.rope_scaling is None:
67
+ return
68
+
69
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
70
+ raise ValueError(
71
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
72
+ f"got {self.rope_scaling}"
73
+ )
74
+ rope_scaling_type = self.rope_scaling.get("type", None)
75
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
76
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
77
+ raise ValueError(
78
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
79
+ )
80
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
81
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
82
+
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.38.2"
7
+ }
modeling_orion.py ADDED
@@ -0,0 +1,1097 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 OrionStar Inc. team. All rights reserved.
2
+ # Copied and adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
3
+
4
+ from transformers import AutoConfig, AutoModel
5
+
6
+ from .configuration_orion import OrionConfig
7
+
8
+ import numbers
9
+ import importlib
10
+ import math
11
+ from typing import List, Optional, Tuple, Union
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from torch.nn.parameter import Parameter
16
+ import torch.utils.checkpoint
17
+ from torch import nn
18
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
19
+ from torch.nn import init
20
+
21
+ from transformers.activations import ACT2FN
22
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
25
+ from transformers.utils import (
26
+ add_start_docstrings,
27
+ add_start_docstrings_to_model_forward,
28
+ is_flash_attn_available,
29
+ logging,
30
+ replace_return_docstrings,
31
+ )
32
+
33
+ if is_flash_attn_available():
34
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
35
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ _CONFIG_FOR_DOC = "OrionConfig"
40
+
41
+ def _get_unpad_data(padding_mask):
42
+ seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32)
43
+ indices = torch.nonzero(padding_mask.flatten(), as_tuple=False).flatten()
44
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
45
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
46
+ return (
47
+ indices,
48
+ cu_seqlens,
49
+ max_seqlen_in_batch,
50
+ )
51
+
52
+
53
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
54
+ def _make_causal_mask(
55
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
56
+ ):
57
+ """
58
+ Make causal mask used for bi-directional self-attention.
59
+ """
60
+ bsz, tgt_len = input_ids_shape
61
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
62
+ mask_cond = torch.arange(mask.size(-1), device=device)
63
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
64
+ mask = mask.to(dtype)
65
+
66
+ if past_key_values_length > 0:
67
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
68
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
69
+
70
+
71
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
72
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
73
+ """
74
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
75
+ """
76
+ bsz, src_len = mask.size()
77
+ tgt_len = tgt_len if tgt_len is not None else src_len
78
+
79
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
80
+
81
+ inverted_mask = 1.0 - expanded_mask
82
+
83
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
84
+
85
+ class OrionRotaryEmbedding(nn.Module):
86
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
87
+ super().__init__()
88
+
89
+ self.dim = dim
90
+ self.max_position_embeddings = max_position_embeddings
91
+ self.base = base
92
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
93
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
94
+
95
+ # Build here to make `torch.jit.trace` work.
96
+ self._set_cos_sin_cache(
97
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
98
+ )
99
+
100
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
101
+ self.max_seq_len_cached = seq_len
102
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
103
+
104
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
105
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
106
+ emb = torch.cat((freqs, freqs), dim=-1)
107
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
108
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
109
+
110
+ def forward(self, x, seq_len=None):
111
+ # x: [bs, num_attention_heads, seq_len, head_size]
112
+ if seq_len > self.max_seq_len_cached:
113
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
114
+
115
+ return (
116
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
117
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
118
+ )
119
+
120
+
121
+ class OrionLinearScalingRotaryEmbedding(OrionRotaryEmbedding):
122
+ """OrionRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
123
+
124
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
125
+ self.scaling_factor = scaling_factor
126
+ super().__init__(dim, max_position_embeddings, base, device)
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+ t = t / self.scaling_factor
132
+
133
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
134
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
135
+ emb = torch.cat((freqs, freqs), dim=-1)
136
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
137
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
138
+
139
+
140
+ class OrionDynamicNTKScalingRotaryEmbedding(OrionRotaryEmbedding):
141
+ """OrionRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
142
+
143
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
144
+ self.scaling_factor = scaling_factor
145
+ super().__init__(dim, max_position_embeddings, base, device)
146
+
147
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
148
+ self.max_seq_len_cached = seq_len
149
+
150
+ if seq_len > self.max_position_embeddings:
151
+ base = self.base * (
152
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
153
+ ) ** (self.dim / (self.dim - 2))
154
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
155
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
156
+
157
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
158
+
159
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
160
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
161
+ emb = torch.cat((freqs, freqs), dim=-1)
162
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
163
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
164
+
165
+
166
+ def rotate_half(x):
167
+ """Rotates half the hidden dims of the input."""
168
+ x1 = x[..., : x.shape[-1] // 2]
169
+ x2 = x[..., x.shape[-1] // 2 :]
170
+ return torch.cat((-x2, x1), dim=-1)
171
+
172
+
173
+ # Copied from transformers.models.gpt_neox.modeling_gpt_neox.apply_rotary_pos_emb
174
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
175
+ cos = cos[position_ids].unsqueeze(1) # [seq_len, dim] -> [batch_size, 1, seq_len, head_dim]
176
+ sin = sin[position_ids].unsqueeze(1)
177
+ q_embed = (q * cos) + (rotate_half(q) * sin)
178
+ k_embed = (k * cos) + (rotate_half(k) * sin)
179
+ return q_embed, k_embed
180
+
181
+
182
+ class OrionMLP(nn.Module):
183
+ def __init__(self, config):
184
+ super().__init__()
185
+ self.config = config
186
+ self.hidden_size = config.hidden_size
187
+ self.intermediate_size = config.intermediate_size
188
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
189
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
190
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
191
+ self.act_fn = ACT2FN[config.hidden_act]
192
+
193
+ def forward(self, x):
194
+ if self.config.pretraining_tp > 1:
195
+ slice = self.intermediate_size // self.config.pretraining_tp
196
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
197
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
198
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
199
+
200
+ gate_proj = torch.cat(
201
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
202
+ )
203
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
204
+
205
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
206
+ down_proj = [
207
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
208
+ ]
209
+ down_proj = sum(down_proj)
210
+ else:
211
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
212
+
213
+ return down_proj
214
+
215
+
216
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
217
+ """
218
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
219
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
220
+ """
221
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
222
+ if n_rep == 1:
223
+ return hidden_states
224
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
225
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
226
+
227
+
228
+ class OrionAttention(nn.Module):
229
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
230
+
231
+ def __init__(self, config: OrionConfig):
232
+ super().__init__()
233
+ self.config = config
234
+ self.hidden_size = config.hidden_size
235
+ self.num_heads = config.num_attention_heads
236
+ self.head_dim = self.hidden_size // self.num_heads
237
+ self.num_key_value_heads = config.num_key_value_heads
238
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
239
+ self.max_position_embeddings = config.max_position_embeddings
240
+ self.rope_theta = config.rope_theta
241
+
242
+ if (self.head_dim * self.num_heads) != self.hidden_size:
243
+ raise ValueError(
244
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
245
+ f" and `num_heads`: {self.num_heads})."
246
+ )
247
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
248
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
249
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
250
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
251
+ self._init_rope()
252
+
253
+ def _init_rope(self):
254
+ if self.config.rope_scaling is None:
255
+ self.rotary_emb = OrionRotaryEmbedding(
256
+ self.head_dim,
257
+ max_position_embeddings=self.max_position_embeddings,
258
+ base=self.rope_theta,
259
+ )
260
+ else:
261
+ scaling_type = self.config.rope_scaling["type"]
262
+ scaling_factor = self.config.rope_scaling["factor"]
263
+ if scaling_type == "linear":
264
+ self.rotary_emb = OrionLinearScalingRotaryEmbedding(
265
+ self.head_dim,
266
+ max_position_embeddings=self.max_position_embeddings,
267
+ scaling_factor=scaling_factor,
268
+ base=self.rope_theta,
269
+ )
270
+ elif scaling_type == "dynamic":
271
+ self.rotary_emb = OrionDynamicNTKScalingRotaryEmbedding(
272
+ self.head_dim,
273
+ max_position_embeddings=self.max_position_embeddings,
274
+ scaling_factor=scaling_factor,
275
+ base=self.rope_theta,
276
+ )
277
+ else:
278
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
279
+
280
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
281
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
282
+
283
+ def forward(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ attention_mask: Optional[torch.Tensor] = None,
287
+ position_ids: Optional[torch.LongTensor] = None,
288
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
289
+ output_attentions: bool = False,
290
+ use_cache: bool = False,
291
+ padding_mask: Optional[torch.LongTensor] = None,
292
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
293
+ bsz, q_len, _ = hidden_states.size()
294
+
295
+ if self.config.pretraining_tp > 1:
296
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
297
+ query_slices = self.q_proj.weight.split(
298
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
299
+ )
300
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
301
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
302
+
303
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
304
+ query_states = torch.cat(query_states, dim=-1)
305
+
306
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
307
+ key_states = torch.cat(key_states, dim=-1)
308
+
309
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
310
+ value_states = torch.cat(value_states, dim=-1)
311
+
312
+ else:
313
+ query_states = self.q_proj(hidden_states)
314
+ key_states = self.k_proj(hidden_states)
315
+ value_states = self.v_proj(hidden_states)
316
+
317
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
318
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
319
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
320
+
321
+ kv_seq_len = key_states.shape[-2]
322
+ if past_key_value is not None:
323
+ kv_seq_len += past_key_value[0].shape[-2]
324
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
325
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
326
+
327
+ if past_key_value is not None:
328
+ # reuse k, v, self_attention
329
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
330
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
331
+
332
+ past_key_value = (key_states, value_states) if use_cache else None
333
+
334
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
335
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
336
+
337
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
338
+
339
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
340
+ raise ValueError(
341
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
342
+ f" {attn_weights.size()}"
343
+ )
344
+
345
+ if attention_mask is not None:
346
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
347
+ raise ValueError(
348
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
349
+ )
350
+ attn_weights = attn_weights + attention_mask
351
+
352
+ # upcast attention to fp32
353
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
354
+ attn_output = torch.matmul(attn_weights, value_states)
355
+
356
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
357
+ raise ValueError(
358
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
359
+ f" {attn_output.size()}"
360
+ )
361
+
362
+ attn_output = attn_output.transpose(1, 2).contiguous()
363
+
364
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
365
+
366
+ if self.config.pretraining_tp > 1:
367
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
368
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
369
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
370
+ else:
371
+ attn_output = self.o_proj(attn_output)
372
+
373
+ if not output_attentions:
374
+ attn_weights = None
375
+
376
+ return attn_output, attn_weights, past_key_value
377
+
378
+
379
+ class OrionFlashAttention2(OrionAttention):
380
+ """
381
+ Orion flash attention module. This module inherits from `OrionAttention` as the weights of the module stays
382
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
383
+ flash attention and deal with padding tokens in case the input contains any of them.
384
+ """
385
+
386
+ def forward(
387
+ self,
388
+ hidden_states: torch.Tensor,
389
+ attention_mask: Optional[torch.Tensor] = None,
390
+ position_ids: Optional[torch.LongTensor] = None,
391
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
392
+ output_attentions: bool = False,
393
+ use_cache: bool = False,
394
+ padding_mask: Optional[torch.LongTensor] = None,
395
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
396
+ # OrionFlashAttention2 attention does not support output_attentions
397
+ output_attentions = False
398
+
399
+ bsz, q_len, _ = hidden_states.size()
400
+
401
+ query_states = self.q_proj(hidden_states)
402
+ key_states = self.k_proj(hidden_states)
403
+ value_states = self.v_proj(hidden_states)
404
+
405
+ # Flash attention requires the input to have the shape
406
+ # batch_size x seq_length x head_dime x hidden_dim
407
+ # therefore we just need to keep the original shape
408
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
409
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
410
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
411
+
412
+ kv_seq_len = key_states.shape[-2]
413
+ if past_key_value is not None:
414
+ kv_seq_len += past_key_value[0].shape[-2]
415
+
416
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
417
+
418
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
419
+
420
+ if past_key_value is not None:
421
+ # reuse k, v, self_attention
422
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
423
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
424
+
425
+ past_key_value = (key_states, value_states) if use_cache else None
426
+
427
+ query_states = query_states.transpose(1, 2)
428
+ key_states = key_states.transpose(1, 2)
429
+ value_states = value_states.transpose(1, 2)
430
+
431
+ # TODO: llama does not have dropout in the config??
432
+ # It is recommended to use dropout with FA according to the docs
433
+ # when training.
434
+ dropout_rate = 0.0 # if not self.training else self.attn_dropout
435
+
436
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
437
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
438
+ # cast them back in float16 just to be sure everything works as expected.
439
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
440
+ # in fp32. (LlamaRMSNorm handles it correctly)
441
+ input_dtype = query_states.dtype
442
+ if input_dtype == torch.float32:
443
+ logger.warning_once(
444
+ "The input hidden states seems to be silently casted in float32, this might be related to"
445
+ " the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
446
+ " float16."
447
+ )
448
+
449
+ query_states = query_states.to(torch.float16)
450
+ key_states = key_states.to(torch.float16)
451
+ value_states = value_states.to(torch.float16)
452
+
453
+ attn_output = self._flash_attention_forward(
454
+ query_states, key_states, value_states, padding_mask, q_len, dropout=dropout_rate
455
+ )
456
+
457
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
458
+ attn_output = self.o_proj(attn_output)
459
+
460
+ if not output_attentions:
461
+ attn_weights = None
462
+
463
+ return attn_output, attn_weights, past_key_value
464
+
465
+ def _flash_attention_forward(
466
+ self, query_states, key_states, value_states, padding_mask, query_length, dropout=0.0, softmax_scale=None
467
+ ):
468
+ """
469
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
470
+ first unpad the input, then computes the attention scores and pad the final attention scores.
471
+
472
+ Args:
473
+ query_states (`torch.Tensor`):
474
+ Input query states to be passed to Flash Attention API
475
+ key_states (`torch.Tensor`):
476
+ Input key states to be passed to Flash Attention API
477
+ value_states (`torch.Tensor`):
478
+ Input value states to be passed to Flash Attention API
479
+ padding_mask (`torch.Tensor`):
480
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
481
+ position of padding tokens and 1 for the position of non-padding tokens.
482
+ dropout (`int`, *optional*):
483
+ Attention dropout
484
+ softmax_scale (`float`, *optional*):
485
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
486
+ """
487
+ # Contains at least one padding token in the sequence
488
+ if padding_mask is not None:
489
+ batch_size = query_states.shape[0]
490
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
491
+ query_states, key_states, value_states, padding_mask, query_length
492
+ )
493
+
494
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
495
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
496
+
497
+ attn_output_unpad = flash_attn_varlen_func(
498
+ query_states,
499
+ key_states,
500
+ value_states,
501
+ cu_seqlens_q=cu_seqlens_q,
502
+ cu_seqlens_k=cu_seqlens_k,
503
+ max_seqlen_q=max_seqlen_in_batch_q,
504
+ max_seqlen_k=max_seqlen_in_batch_k,
505
+ dropout_p=dropout,
506
+ softmax_scale=softmax_scale,
507
+ causal=True,
508
+ )
509
+
510
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
511
+ else:
512
+ attn_output = flash_attn_func(
513
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True
514
+ )
515
+
516
+ return attn_output
517
+
518
+ def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length):
519
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask)
520
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
521
+
522
+ key_layer = index_first_axis(
523
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
524
+ )
525
+ value_layer = index_first_axis(
526
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
527
+ )
528
+ if query_length == kv_seq_len:
529
+ query_layer = index_first_axis(
530
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
531
+ )
532
+ cu_seqlens_q = cu_seqlens_k
533
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
534
+ indices_q = indices_k
535
+ elif query_length == 1:
536
+ max_seqlen_in_batch_q = 1
537
+ cu_seqlens_q = torch.arange(
538
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
539
+ ) # There is a memcpy here, that is very bad.
540
+ indices_q = cu_seqlens_q[:-1]
541
+ query_layer = query_layer.squeeze(1)
542
+ else:
543
+ # The -q_len: slice assumes left padding.
544
+ padding_mask = padding_mask[:, -query_length:]
545
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask)
546
+
547
+ return (
548
+ query_layer,
549
+ key_layer,
550
+ value_layer,
551
+ indices_q,
552
+ (cu_seqlens_q, cu_seqlens_k),
553
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
554
+ )
555
+
556
+
557
+ class OrionDecoderLayer(nn.Module):
558
+ def __init__(self, config: OrionConfig):
559
+ super().__init__()
560
+ self.hidden_size = config.hidden_size
561
+ self.self_attn = (
562
+ OrionAttention(config=config)
563
+ if not getattr(config, "_flash_attn_2_enabled", False)
564
+ else OrionFlashAttention2(config=config)
565
+ )
566
+ self.mlp = OrionMLP(config)
567
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
568
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
569
+
570
+ def forward(
571
+ self,
572
+ hidden_states: torch.Tensor,
573
+ attention_mask: Optional[torch.Tensor] = None,
574
+ position_ids: Optional[torch.LongTensor] = None,
575
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
576
+ output_attentions: Optional[bool] = False,
577
+ use_cache: Optional[bool] = False,
578
+ padding_mask: Optional[torch.LongTensor] = None,
579
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
580
+ """
581
+ Args:
582
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
583
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
584
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
585
+ output_attentions (`bool`, *optional*):
586
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
587
+ returned tensors for more detail.
588
+ use_cache (`bool`, *optional*):
589
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
590
+ (see `past_key_values`).
591
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
592
+ """
593
+
594
+ residual = hidden_states
595
+
596
+ hidden_states = self.input_layernorm(hidden_states)
597
+
598
+ # Self Attention
599
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
600
+ hidden_states=hidden_states,
601
+ attention_mask=attention_mask,
602
+ position_ids=position_ids,
603
+ past_key_value=past_key_value,
604
+ output_attentions=output_attentions,
605
+ use_cache=use_cache,
606
+ padding_mask=padding_mask,
607
+ )
608
+ hidden_states = residual + hidden_states
609
+
610
+ # Fully Connected
611
+ residual = hidden_states
612
+ hidden_states = self.post_attention_layernorm(hidden_states)
613
+ hidden_states = self.mlp(hidden_states)
614
+ hidden_states = residual + hidden_states
615
+
616
+ outputs = (hidden_states,)
617
+
618
+ if output_attentions:
619
+ outputs += (self_attn_weights,)
620
+
621
+ if use_cache:
622
+ outputs += (present_key_value,)
623
+
624
+ return outputs
625
+
626
+ class OrionPreTrainedModel(PreTrainedModel):
627
+ config_class = OrionConfig
628
+ base_model_prefix = "model"
629
+ supports_gradient_checkpointing = True
630
+ _no_split_modules = ["OrionDecoderLayer"]
631
+ _skip_keys_device_placement = "past_key_values"
632
+ _supports_flash_attn_2 = True
633
+
634
+ def _init_weights(self, module):
635
+ std = self.config.initializer_range
636
+ if isinstance(module, nn.Linear):
637
+ module.weight.data.normal_(mean=0.0, std=std)
638
+ if module.bias is not None:
639
+ module.bias.data.zero_()
640
+ elif isinstance(module, nn.Embedding):
641
+ module.weight.data.normal_(mean=0.0, std=std)
642
+ if module.padding_idx is not None:
643
+ module.weight.data[module.padding_idx].zero_()
644
+
645
+ def _set_gradient_checkpointing(self, module, value=False):
646
+ if isinstance(module, OrionModel):
647
+ module.gradient_checkpointing = value
648
+
649
+ class OrionModel(OrionPreTrainedModel):
650
+ """
651
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OrionDecoderLayer`]
652
+
653
+ Args:
654
+ config: OrionConfig
655
+ """
656
+
657
+ def __init__(self, config: OrionConfig):
658
+ super().__init__(config)
659
+ self.padding_idx = config.pad_token_id
660
+ self.vocab_size = config.vocab_size
661
+
662
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
663
+ self.layers = nn.ModuleList([OrionDecoderLayer(config) for _ in range(config.num_hidden_layers)])
664
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
665
+
666
+ self.gradient_checkpointing = False
667
+ # Initialize weights and apply final processing
668
+ self.post_init()
669
+
670
+ def get_input_embeddings(self):
671
+ return self.embed_tokens
672
+
673
+ def set_input_embeddings(self, value):
674
+ self.embed_tokens = value
675
+
676
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
677
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
678
+ # create causal mask
679
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
680
+ combined_attention_mask = None
681
+ if input_shape[-1] > 1:
682
+ combined_attention_mask = _make_causal_mask(
683
+ input_shape,
684
+ inputs_embeds.dtype,
685
+ device=inputs_embeds.device,
686
+ past_key_values_length=past_key_values_length,
687
+ )
688
+
689
+ if attention_mask is not None:
690
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
691
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
692
+ inputs_embeds.device
693
+ )
694
+ combined_attention_mask = (
695
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
696
+ )
697
+
698
+ return combined_attention_mask
699
+
700
+ def forward(
701
+ self,
702
+ input_ids: torch.LongTensor = None,
703
+ attention_mask: Optional[torch.Tensor] = None,
704
+ position_ids: Optional[torch.LongTensor] = None,
705
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
706
+ inputs_embeds: Optional[torch.FloatTensor] = None,
707
+ use_cache: Optional[bool] = None,
708
+ output_attentions: Optional[bool] = None,
709
+ output_hidden_states: Optional[bool] = None,
710
+ return_dict: Optional[bool] = None,
711
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
712
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
713
+ output_hidden_states = (
714
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
715
+ )
716
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
717
+
718
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
719
+
720
+ # retrieve input_ids and inputs_embeds
721
+ if input_ids is not None and inputs_embeds is not None:
722
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
723
+ elif input_ids is not None:
724
+ batch_size, seq_length = input_ids.shape
725
+ elif inputs_embeds is not None:
726
+ batch_size, seq_length, _ = inputs_embeds.shape
727
+ else:
728
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
729
+
730
+ seq_length_with_past = seq_length
731
+ past_key_values_length = 0
732
+
733
+ if past_key_values is not None:
734
+ past_key_values_length = past_key_values[0][0].shape[2]
735
+ seq_length_with_past = seq_length_with_past + past_key_values_length
736
+
737
+ if position_ids is None:
738
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
739
+ position_ids = torch.arange(
740
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
741
+ )
742
+ position_ids = position_ids.unsqueeze(0)
743
+
744
+ if inputs_embeds is None:
745
+ inputs_embeds = self.embed_tokens(input_ids)
746
+ # embed positions
747
+ if attention_mask is None:
748
+ attention_mask = torch.ones(
749
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
750
+ )
751
+ padding_mask = None
752
+ else:
753
+ if 0 in attention_mask:
754
+ padding_mask = attention_mask
755
+ else:
756
+ padding_mask = None
757
+
758
+ attention_mask = self._prepare_decoder_attention_mask(
759
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
760
+ )
761
+
762
+ hidden_states = inputs_embeds
763
+
764
+ if self.gradient_checkpointing and self.training:
765
+ if use_cache:
766
+ logger.warning_once(
767
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
768
+ )
769
+ use_cache = False
770
+
771
+ # decoder layers
772
+ all_hidden_states = () if output_hidden_states else None
773
+ all_self_attns = () if output_attentions else None
774
+ next_decoder_cache = () if use_cache else None
775
+
776
+ for idx, decoder_layer in enumerate(self.layers):
777
+ if output_hidden_states:
778
+ all_hidden_states += (hidden_states,)
779
+
780
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
781
+
782
+ if self.gradient_checkpointing and self.training:
783
+
784
+ def create_custom_forward(module):
785
+ def custom_forward(*inputs):
786
+ # None for past_key_value
787
+ return module(*inputs, past_key_value, output_attentions, padding_mask=padding_mask)
788
+
789
+ return custom_forward
790
+
791
+ layer_outputs = torch.utils.checkpoint.checkpoint(
792
+ create_custom_forward(decoder_layer), hidden_states, attention_mask, position_ids
793
+ )
794
+ else:
795
+ layer_outputs = decoder_layer(
796
+ hidden_states,
797
+ attention_mask=attention_mask,
798
+ position_ids=position_ids,
799
+ past_key_value=past_key_value,
800
+ output_attentions=output_attentions,
801
+ use_cache=use_cache,
802
+ padding_mask=padding_mask,
803
+ )
804
+
805
+ hidden_states = layer_outputs[0]
806
+
807
+ if use_cache:
808
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
809
+
810
+ if output_attentions:
811
+ all_self_attns += (layer_outputs[1],)
812
+
813
+ hidden_states = self.norm(hidden_states)
814
+
815
+ # add hidden states from the last decoder layer
816
+ if output_hidden_states:
817
+ all_hidden_states += (hidden_states,)
818
+
819
+ next_cache = next_decoder_cache if use_cache else None
820
+ if not return_dict:
821
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
822
+ return BaseModelOutputWithPast(
823
+ last_hidden_state=hidden_states,
824
+ past_key_values=next_cache,
825
+ hidden_states=all_hidden_states,
826
+ attentions=all_self_attns,
827
+ )
828
+
829
+
830
+ class OrionForCausalLM(OrionPreTrainedModel):
831
+ model_type = "orion"
832
+ _tied_weights_keys = ["lm_head.weight"]
833
+
834
+ def __init__(self, config):
835
+ super().__init__(config)
836
+ self.model = OrionModel(config)
837
+ self.vocab_size = config.vocab_size
838
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
839
+
840
+ # Initialize weights and apply final processing
841
+ self.post_init()
842
+
843
+ def get_input_embeddings(self):
844
+ return self.model.embed_tokens
845
+
846
+ def set_input_embeddings(self, value):
847
+ self.model.embed_tokens = value
848
+
849
+ def get_output_embeddings(self):
850
+ return self.lm_head
851
+
852
+ def set_output_embeddings(self, new_embeddings):
853
+ self.lm_head = new_embeddings
854
+
855
+ def set_decoder(self, decoder):
856
+ self.model = decoder
857
+
858
+ def get_decoder(self):
859
+ return self.model
860
+
861
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
862
+ def forward(
863
+ self,
864
+ input_ids: torch.LongTensor = None,
865
+ attention_mask: Optional[torch.Tensor] = None,
866
+ position_ids: Optional[torch.LongTensor] = None,
867
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
868
+ inputs_embeds: Optional[torch.FloatTensor] = None,
869
+ labels: Optional[torch.LongTensor] = None,
870
+ use_cache: Optional[bool] = None,
871
+ output_attentions: Optional[bool] = None,
872
+ output_hidden_states: Optional[bool] = None,
873
+ return_dict: Optional[bool] = None,
874
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
875
+ r"""
876
+ Args:
877
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
878
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
879
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
880
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
881
+
882
+ Returns:
883
+
884
+ Example:
885
+
886
+ ```python
887
+ >>> from transformers import AutoTokenizer, OrionForCausalLM
888
+
889
+ >>> model = OrionForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
890
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
891
+
892
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
893
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
894
+
895
+ >>> # Generate
896
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
897
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
898
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
899
+ ```"""
900
+
901
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
902
+ output_hidden_states = (
903
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
904
+ )
905
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
906
+
907
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
908
+ outputs = self.model(
909
+ input_ids=input_ids,
910
+ attention_mask=attention_mask,
911
+ position_ids=position_ids,
912
+ past_key_values=past_key_values,
913
+ inputs_embeds=inputs_embeds,
914
+ use_cache=use_cache,
915
+ output_attentions=output_attentions,
916
+ output_hidden_states=output_hidden_states,
917
+ return_dict=return_dict,
918
+ )
919
+
920
+ hidden_states = outputs[0]
921
+ if self.config.pretraining_tp > 1:
922
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
923
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
924
+ logits = torch.cat(logits, dim=-1)
925
+ else:
926
+ logits = self.lm_head(hidden_states)
927
+ logits = logits.float()
928
+
929
+ loss = None
930
+ if labels is not None:
931
+ # Shift so that tokens < n predict n
932
+ shift_logits = logits[..., :-1, :].contiguous()
933
+ shift_labels = labels[..., 1:].contiguous()
934
+ # Flatten the tokens
935
+ loss_fct = CrossEntropyLoss()
936
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
937
+ shift_labels = shift_labels.view(-1)
938
+ # Enable model parallelism
939
+ shift_labels = shift_labels.to(shift_logits.device)
940
+ loss = loss_fct(shift_logits, shift_labels)
941
+
942
+ if not return_dict:
943
+ output = (logits,) + outputs[1:]
944
+ return (loss,) + output if loss is not None else output
945
+
946
+ return CausalLMOutputWithPast(
947
+ loss=loss,
948
+ logits=logits,
949
+ past_key_values=outputs.past_key_values,
950
+ hidden_states=outputs.hidden_states,
951
+ attentions=outputs.attentions,
952
+ )
953
+
954
+ def prepare_inputs_for_generation(
955
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
956
+ ):
957
+ if past_key_values:
958
+ input_ids = input_ids[:, -1:]
959
+
960
+ position_ids = kwargs.get("position_ids", None)
961
+ if attention_mask is not None and position_ids is None:
962
+ # create position_ids on the fly for batch generation
963
+ position_ids = attention_mask.long().cumsum(-1) - 1
964
+ position_ids.masked_fill_(attention_mask == 0, 1)
965
+ if past_key_values:
966
+ position_ids = position_ids[:, -1].unsqueeze(-1)
967
+
968
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
969
+ if inputs_embeds is not None and past_key_values is None:
970
+ model_inputs = {"inputs_embeds": inputs_embeds}
971
+ else:
972
+ model_inputs = {"input_ids": input_ids}
973
+
974
+ model_inputs.update(
975
+ {
976
+ "position_ids": position_ids,
977
+ "past_key_values": past_key_values,
978
+ "use_cache": kwargs.get("use_cache"),
979
+ "attention_mask": attention_mask,
980
+ }
981
+ )
982
+ return model_inputs
983
+
984
+ @staticmethod
985
+ def _reorder_cache(past_key_values, beam_idx):
986
+ reordered_past = ()
987
+ for layer_past in past_key_values:
988
+ reordered_past += (
989
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
990
+ )
991
+ return reordered_past
992
+
993
+ class OrionForSequenceClassification(OrionPreTrainedModel):
994
+ def __init__(self, config):
995
+ super().__init__(config)
996
+ self.num_labels = config.num_labels
997
+ self.model = OrionModel(config)
998
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
999
+
1000
+ # Initialize weights and apply final processing
1001
+ self.post_init()
1002
+
1003
+ def get_input_embeddings(self):
1004
+ return self.model.embed_tokens
1005
+
1006
+ def set_input_embeddings(self, value):
1007
+ self.model.embed_tokens = value
1008
+
1009
+ def forward(
1010
+ self,
1011
+ input_ids: torch.LongTensor = None,
1012
+ attention_mask: Optional[torch.Tensor] = None,
1013
+ position_ids: Optional[torch.LongTensor] = None,
1014
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1015
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1016
+ labels: Optional[torch.LongTensor] = None,
1017
+ use_cache: Optional[bool] = None,
1018
+ output_attentions: Optional[bool] = None,
1019
+ output_hidden_states: Optional[bool] = None,
1020
+ return_dict: Optional[bool] = None,
1021
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1022
+ r"""
1023
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1024
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1025
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1026
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1027
+ """
1028
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1029
+
1030
+ transformer_outputs = self.model(
1031
+ input_ids,
1032
+ attention_mask=attention_mask,
1033
+ position_ids=position_ids,
1034
+ past_key_values=past_key_values,
1035
+ inputs_embeds=inputs_embeds,
1036
+ use_cache=use_cache,
1037
+ output_attentions=output_attentions,
1038
+ output_hidden_states=output_hidden_states,
1039
+ return_dict=return_dict,
1040
+ )
1041
+ hidden_states = transformer_outputs[0]
1042
+ logits = self.score(hidden_states)
1043
+
1044
+ if input_ids is not None:
1045
+ batch_size = input_ids.shape[0]
1046
+ else:
1047
+ batch_size = inputs_embeds.shape[0]
1048
+
1049
+ if self.config.pad_token_id is None and batch_size != 1:
1050
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1051
+ if self.config.pad_token_id is None:
1052
+ sequence_lengths = -1
1053
+ else:
1054
+ if input_ids is not None:
1055
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1056
+ logits.device
1057
+ )
1058
+ else:
1059
+ sequence_lengths = -1
1060
+
1061
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1062
+
1063
+ loss = None
1064
+ if labels is not None:
1065
+ labels = labels.to(logits.device)
1066
+ if self.config.problem_type is None:
1067
+ if self.num_labels == 1:
1068
+ self.config.problem_type = "regression"
1069
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1070
+ self.config.problem_type = "single_label_classification"
1071
+ else:
1072
+ self.config.problem_type = "multi_label_classification"
1073
+
1074
+ if self.config.problem_type == "regression":
1075
+ loss_fct = MSELoss()
1076
+ if self.num_labels == 1:
1077
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1078
+ else:
1079
+ loss = loss_fct(pooled_logits, labels)
1080
+ elif self.config.problem_type == "single_label_classification":
1081
+ loss_fct = CrossEntropyLoss()
1082
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1083
+ elif self.config.problem_type == "multi_label_classification":
1084
+ loss_fct = BCEWithLogitsLoss()
1085
+ loss = loss_fct(pooled_logits, labels)
1086
+ if not return_dict:
1087
+ output = (pooled_logits,) + transformer_outputs[1:]
1088
+ return ((loss,) + output) if loss is not None else output
1089
+
1090
+ return SequenceClassifierOutputWithPast(
1091
+ loss=loss,
1092
+ logits=pooled_logits,
1093
+ past_key_values=transformer_outputs.past_key_values,
1094
+ hidden_states=transformer_outputs.hidden_states,
1095
+ attentions=transformer_outputs.attentions,
1096
+ )
1097
+
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": true
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": true
15
+ },
16
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": true
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": true
29
+ }
30
+ }
tokenization_orion.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, OrionStar Inc. All rights reserved.
2
+
3
+ import os
4
+ from shutil import copyfile
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+ import re
7
+
8
+ import sentencepiece as spm
9
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
10
+
11
+
12
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
13
+
14
+ PRETRAINED_VOCAB_FILES_MAP = {
15
+ "vocab_file": {},
16
+ "tokenizer_file": {},
17
+ }
18
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
19
+
20
+
21
+ class OrionTokenizer(PreTrainedTokenizer):
22
+ """
23
+ Construct a Orion tokenizer. Based on byte-level Byte-Pair-Encoding.
24
+
25
+ Args:
26
+ vocab_file (`str`):
27
+ Path to the vocabulary file.
28
+ """
29
+
30
+ vocab_files_names = VOCAB_FILES_NAMES
31
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
32
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
33
+ model_input_names = ["input_ids", "attention_mask"]
34
+
35
+ def __init__(
36
+ self,
37
+ vocab_file,
38
+ unk_token="<unk>",
39
+ bos_token="<s>",
40
+ eos_token="</s>",
41
+ pad_token=None,
42
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
43
+ add_bos_token=True,
44
+ add_eos_token=False,
45
+ clean_up_tokenization_spaces=False,
46
+ **kwargs,
47
+ ):
48
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
49
+ bos_token = (
50
+ AddedToken(bos_token, lstrip=False, rstrip=False)
51
+ if isinstance(bos_token, str)
52
+ else bos_token
53
+ )
54
+ eos_token = (
55
+ AddedToken(eos_token, lstrip=False, rstrip=False)
56
+ if isinstance(eos_token, str)
57
+ else eos_token
58
+ )
59
+ unk_token = (
60
+ AddedToken(unk_token, lstrip=False, rstrip=False)
61
+ if isinstance(unk_token, str)
62
+ else unk_token
63
+ )
64
+ pad_token = (
65
+ AddedToken(pad_token, lstrip=False, rstrip=False)
66
+ if isinstance(pad_token, str)
67
+ else pad_token
68
+ )
69
+ self.vocab_file = vocab_file
70
+ self.add_bos_token = add_bos_token
71
+ self.add_eos_token = add_eos_token
72
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
73
+ self.sp_model.Load(vocab_file)
74
+
75
+ super().__init__(
76
+ bos_token=bos_token,
77
+ eos_token=eos_token,
78
+ unk_token=unk_token,
79
+ pad_token=pad_token,
80
+ add_bos_token=add_bos_token,
81
+ add_eos_token=add_eos_token,
82
+ sp_model_kwargs=self.sp_model_kwargs,
83
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
84
+ **kwargs,
85
+ )
86
+
87
+ def __getstate__(self):
88
+ state = self.__dict__.copy()
89
+ state["sp_model"] = None
90
+ return state
91
+
92
+ def __setstate__(self, d):
93
+ self.__dict__ = d
94
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
95
+ self.sp_model.Load(self.vocab_file)
96
+
97
+ @property
98
+ def vocab_size(self):
99
+ """Returns vocab size"""
100
+ return self.sp_model.get_piece_size()
101
+
102
+ def get_vocab(self):
103
+ """Returns vocab as a dict"""
104
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
105
+ vocab.update(self.added_tokens_encoder)
106
+ return vocab
107
+
108
+ def _tokenize(self, text):
109
+ """Returns a tokenized string."""
110
+ return self.sp_model.encode(text, out_type=str)
111
+
112
+ def _convert_token_to_id(self, token):
113
+ """Converts a token (str) in an id using the vocab."""
114
+ return self.sp_model.piece_to_id(token)
115
+
116
+ def _convert_id_to_token(self, index):
117
+ """Converts an index (integer) in a token (str) using the vocab."""
118
+ token = self.sp_model.IdToPiece(index)
119
+ return token
120
+
121
+ def convert_tokens_to_string(self, tokens):
122
+ """Converts a sequence of tokens (string) in a single string."""
123
+ zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
124
+ need_convert_punctuation=(",",";","!","?",":","(",")")
125
+ current_sub_tokens = []
126
+ out_string = ""
127
+ prev_is_special = False
128
+ for i, token in enumerate(tokens):
129
+ # make sure that special tokens are not decoded using sentencepiece model
130
+ if token in self.all_special_tokens:
131
+ if not prev_is_special and i != 0:
132
+ out_string += " "
133
+ out_string += self.sp_model.decode(current_sub_tokens) + token
134
+ prev_is_special = True
135
+ current_sub_tokens = []
136
+ if any([True if punctuation in token else False for punctuation in need_convert_punctuation]):
137
+ out_string += self.sp_model.decode(current_sub_tokens)
138
+ token=self.sp_model.decode(token)
139
+ if zhPattern.search(out_string[-20:]):
140
+ token = self.to_zh_punctuation(token)
141
+ out_string += token
142
+ current_sub_tokens = []
143
+ else:
144
+ current_sub_tokens.append(token)
145
+ prev_is_special = False
146
+ out_string += self.sp_model.decode(current_sub_tokens)
147
+ return out_string
148
+
149
+ def to_zh_punctuation(self, token):
150
+ return token.replace(",",",").replace(";",";").replace("!","!").replace("?","?").replace(":",":").replace("(","(").replace(")",")")
151
+
152
+ def save_vocabulary(
153
+ self, save_directory, filename_prefix: Optional[str] = None
154
+ ) -> Tuple[str]:
155
+ """
156
+ Save the vocabulary and special tokens file to a directory.
157
+
158
+ Args:
159
+ save_directory (`str`):
160
+ The directory in which to save the vocabulary.
161
+
162
+ Returns:
163
+ `Tuple(str)`: Paths to the files saved.
164
+ """
165
+ if not os.path.isdir(save_directory):
166
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
167
+ return
168
+ out_vocab_file = os.path.join(
169
+ save_directory,
170
+ (filename_prefix + "-" if filename_prefix else "")
171
+ + VOCAB_FILES_NAMES["vocab_file"],
172
+ )
173
+
174
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
175
+ out_vocab_file
176
+ ) and os.path.isfile(self.vocab_file):
177
+ copyfile(self.vocab_file, out_vocab_file)
178
+ elif not os.path.isfile(self.vocab_file):
179
+ with open(out_vocab_file, "wb") as fi:
180
+ content_spiece_model = self.sp_model.serialized_model_proto()
181
+ fi.write(content_spiece_model)
182
+
183
+ return (out_vocab_file,)
184
+
185
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
186
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
187
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
188
+
189
+ output = bos_token_id + token_ids_0 + eos_token_id
190
+
191
+ if token_ids_1 is not None:
192
+ output = output + bos_token_id + token_ids_1 + eos_token_id
193
+
194
+ return output
195
+
196
+ def get_special_tokens_mask(
197
+ self,
198
+ token_ids_0: List[int],
199
+ token_ids_1: Optional[List[int]] = None,
200
+ already_has_special_tokens: bool = False,
201
+ ) -> List[int]:
202
+ """
203
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
204
+ special tokens using the tokenizer `prepare_for_model` method.
205
+
206
+ Args:
207
+ token_ids_0 (`List[int]`):
208
+ List of IDs.
209
+ token_ids_1 (`List[int]`, *optional*):
210
+ Optional second list of IDs for sequence pairs.
211
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
212
+ Whether or not the token list is already formatted with special tokens for the model.
213
+
214
+ Returns:
215
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
216
+ """
217
+ if already_has_special_tokens:
218
+ return super().get_special_tokens_mask(
219
+ token_ids_0=token_ids_0,
220
+ token_ids_1=token_ids_1,
221
+ already_has_special_tokens=True,
222
+ )
223
+
224
+ bos_token_id = [1] if self.add_bos_token else []
225
+ eos_token_id = [1] if self.add_eos_token else []
226
+
227
+ if token_ids_1 is None:
228
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
229
+ return (
230
+ bos_token_id
231
+ + ([0] * len(token_ids_0))
232
+ + eos_token_id
233
+ + bos_token_id
234
+ + ([0] * len(token_ids_1))
235
+ + eos_token_id
236
+ )
237
+
238
+ def create_token_type_ids_from_sequences(
239
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
240
+ ) -> List[int]:
241
+ """
242
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
243
+ sequence pair mask has the following format:
244
+
245
+ ```
246
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
247
+ | first sequence | second sequence |
248
+ ```
249
+
250
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
251
+
252
+ Args:
253
+ token_ids_0 (`List[int]`):
254
+ List of ids.
255
+ token_ids_1 (`List[int]`, *optional*):
256
+ Optional second list of IDs for sequence pairs.
257
+
258
+ Returns:
259
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
260
+ """
261
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
262
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
263
+
264
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
265
+
266
+ if token_ids_1 is not None:
267
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
268
+
269
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ded43118b7418f56db97a4eed08a5c265c03120158229ddd4fbcc9658241d5f0
3
+ size 1520600
tokenizer_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": true,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": true,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": true,
25
+ "rstrip": false,
26
+ "single_word": true,
27
+ "special": true
28
+ }
29
+ },
30
+ "auto_map": {
31
+ "AutoTokenizer": [
32
+ "tokenization_orion.OrionTokenizer",
33
+ null
34
+ ]
35
+ },
36
+ "bos_token": "<s>",
37
+ "clean_up_tokenization_spaces": false,
38
+ "eos_token": "</s>",
39
+ "model_max_length": 4096,
40
+ "pad_token": "<unk>",
41
+ "padding_side": "right",
42
+ "sp_model_kwargs": {},
43
+ "split_special_tokens": false,
44
+ "tokenizer_class": "OrionTokenizer",
45
+ "unk_token": "<unk>"
46
+ }
trainer_state.json ADDED
@@ -0,0 +1,1092 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 3.0,
5
+ "eval_steps": 500,
6
+ "global_step": 153,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.02,
13
+ "grad_norm": 5.049024000371086,
14
+ "learning_rate": 1.8181818181818183e-06,
15
+ "loss": 1.854,
16
+ "step": 1
17
+ },
18
+ {
19
+ "epoch": 0.04,
20
+ "grad_norm": 4.758646674230607,
21
+ "learning_rate": 3.6363636363636366e-06,
22
+ "loss": 1.8589,
23
+ "step": 2
24
+ },
25
+ {
26
+ "epoch": 0.06,
27
+ "grad_norm": 4.997532808044432,
28
+ "learning_rate": 5.4545454545454545e-06,
29
+ "loss": 1.8066,
30
+ "step": 3
31
+ },
32
+ {
33
+ "epoch": 0.08,
34
+ "grad_norm": 4.658976531052129,
35
+ "learning_rate": 7.272727272727273e-06,
36
+ "loss": 1.8039,
37
+ "step": 4
38
+ },
39
+ {
40
+ "epoch": 0.1,
41
+ "grad_norm": 3.2333098053485814,
42
+ "learning_rate": 9.090909090909091e-06,
43
+ "loss": 1.6903,
44
+ "step": 5
45
+ },
46
+ {
47
+ "epoch": 0.12,
48
+ "grad_norm": 2.672741130516915,
49
+ "learning_rate": 1.0909090909090909e-05,
50
+ "loss": 1.6346,
51
+ "step": 6
52
+ },
53
+ {
54
+ "epoch": 0.14,
55
+ "grad_norm": 1.8361460465829846,
56
+ "learning_rate": 1.2727272727272728e-05,
57
+ "loss": 1.5495,
58
+ "step": 7
59
+ },
60
+ {
61
+ "epoch": 0.16,
62
+ "grad_norm": 1.7045961378249597,
63
+ "learning_rate": 1.4545454545454546e-05,
64
+ "loss": 1.5097,
65
+ "step": 8
66
+ },
67
+ {
68
+ "epoch": 0.18,
69
+ "grad_norm": 1.635826359191631,
70
+ "learning_rate": 1.6363636363636366e-05,
71
+ "loss": 1.4721,
72
+ "step": 9
73
+ },
74
+ {
75
+ "epoch": 0.2,
76
+ "grad_norm": 1.578935320707837,
77
+ "learning_rate": 1.8181818181818182e-05,
78
+ "loss": 1.4229,
79
+ "step": 10
80
+ },
81
+ {
82
+ "epoch": 0.22,
83
+ "grad_norm": 1.5221044723806934,
84
+ "learning_rate": 2e-05,
85
+ "loss": 1.3793,
86
+ "step": 11
87
+ },
88
+ {
89
+ "epoch": 0.24,
90
+ "grad_norm": 1.4000849902377055,
91
+ "learning_rate": 1.999867521457224e-05,
92
+ "loss": 1.3113,
93
+ "step": 12
94
+ },
95
+ {
96
+ "epoch": 0.25,
97
+ "grad_norm": 1.575616258826214,
98
+ "learning_rate": 1.9994701209300245e-05,
99
+ "loss": 1.2887,
100
+ "step": 13
101
+ },
102
+ {
103
+ "epoch": 0.27,
104
+ "grad_norm": 1.3392980593157788,
105
+ "learning_rate": 1.9988079037124866e-05,
106
+ "loss": 1.2279,
107
+ "step": 14
108
+ },
109
+ {
110
+ "epoch": 0.29,
111
+ "grad_norm": 1.424201738399285,
112
+ "learning_rate": 1.9978810452637544e-05,
113
+ "loss": 1.1972,
114
+ "step": 15
115
+ },
116
+ {
117
+ "epoch": 0.31,
118
+ "grad_norm": 1.4523213122657395,
119
+ "learning_rate": 1.9966897911615417e-05,
120
+ "loss": 1.1793,
121
+ "step": 16
122
+ },
123
+ {
124
+ "epoch": 0.33,
125
+ "grad_norm": 1.3820011323242407,
126
+ "learning_rate": 1.995234457037063e-05,
127
+ "loss": 1.1211,
128
+ "step": 17
129
+ },
130
+ {
131
+ "epoch": 0.35,
132
+ "grad_norm": 1.2328298047764605,
133
+ "learning_rate": 1.9935154284914063e-05,
134
+ "loss": 1.0237,
135
+ "step": 18
136
+ },
137
+ {
138
+ "epoch": 0.37,
139
+ "grad_norm": 1.4014760682876144,
140
+ "learning_rate": 1.991533160993366e-05,
141
+ "loss": 1.084,
142
+ "step": 19
143
+ },
144
+ {
145
+ "epoch": 0.39,
146
+ "grad_norm": 1.304071018054968,
147
+ "learning_rate": 1.98928817975876e-05,
148
+ "loss": 1.0577,
149
+ "step": 20
150
+ },
151
+ {
152
+ "epoch": 0.41,
153
+ "grad_norm": 1.2396816193325995,
154
+ "learning_rate": 1.9867810796112742e-05,
155
+ "loss": 1.0534,
156
+ "step": 21
157
+ },
158
+ {
159
+ "epoch": 0.43,
160
+ "grad_norm": 1.1906790092813893,
161
+ "learning_rate": 1.9840125248248564e-05,
162
+ "loss": 0.9375,
163
+ "step": 22
164
+ },
165
+ {
166
+ "epoch": 0.45,
167
+ "grad_norm": 1.2125922433431726,
168
+ "learning_rate": 1.9809832489477144e-05,
169
+ "loss": 0.907,
170
+ "step": 23
171
+ },
172
+ {
173
+ "epoch": 0.47,
174
+ "grad_norm": 1.3509732764627251,
175
+ "learning_rate": 1.9776940546079552e-05,
176
+ "loss": 0.8994,
177
+ "step": 24
178
+ },
179
+ {
180
+ "epoch": 0.49,
181
+ "grad_norm": 1.1575946721358368,
182
+ "learning_rate": 1.9741458133009258e-05,
183
+ "loss": 0.9001,
184
+ "step": 25
185
+ },
186
+ {
187
+ "epoch": 0.51,
188
+ "grad_norm": 1.0819155083735588,
189
+ "learning_rate": 1.970339465158301e-05,
190
+ "loss": 0.8853,
191
+ "step": 26
192
+ },
193
+ {
194
+ "epoch": 0.53,
195
+ "grad_norm": 1.1831054183701755,
196
+ "learning_rate": 1.9662760186989914e-05,
197
+ "loss": 0.8559,
198
+ "step": 27
199
+ },
200
+ {
201
+ "epoch": 0.55,
202
+ "grad_norm": 1.2787427328132572,
203
+ "learning_rate": 1.9619565505619288e-05,
204
+ "loss": 0.8908,
205
+ "step": 28
206
+ },
207
+ {
208
+ "epoch": 0.57,
209
+ "grad_norm": 1.1960513256280778,
210
+ "learning_rate": 1.9573822052208013e-05,
211
+ "loss": 0.8505,
212
+ "step": 29
213
+ },
214
+ {
215
+ "epoch": 0.59,
216
+ "grad_norm": 1.1882091713537735,
217
+ "learning_rate": 1.9525541946808187e-05,
218
+ "loss": 0.8252,
219
+ "step": 30
220
+ },
221
+ {
222
+ "epoch": 0.61,
223
+ "grad_norm": 1.1957026823405033,
224
+ "learning_rate": 1.9474737981575833e-05,
225
+ "loss": 0.8294,
226
+ "step": 31
227
+ },
228
+ {
229
+ "epoch": 0.63,
230
+ "grad_norm": 1.1235625302238945,
231
+ "learning_rate": 1.942142361738151e-05,
232
+ "loss": 0.7843,
233
+ "step": 32
234
+ },
235
+ {
236
+ "epoch": 0.65,
237
+ "grad_norm": 1.2129049745653777,
238
+ "learning_rate": 1.936561298024377e-05,
239
+ "loss": 0.7732,
240
+ "step": 33
241
+ },
242
+ {
243
+ "epoch": 0.67,
244
+ "grad_norm": 1.0546648941443104,
245
+ "learning_rate": 1.9307320857586377e-05,
246
+ "loss": 0.7081,
247
+ "step": 34
248
+ },
249
+ {
250
+ "epoch": 0.69,
251
+ "grad_norm": 1.099433031052361,
252
+ "learning_rate": 1.9246562694320258e-05,
253
+ "loss": 0.6877,
254
+ "step": 35
255
+ },
256
+ {
257
+ "epoch": 0.71,
258
+ "grad_norm": 1.3153258284792773,
259
+ "learning_rate": 1.9183354588751274e-05,
260
+ "loss": 0.7302,
261
+ "step": 36
262
+ },
263
+ {
264
+ "epoch": 0.73,
265
+ "grad_norm": 1.1045347116178383,
266
+ "learning_rate": 1.9117713288314864e-05,
267
+ "loss": 0.6839,
268
+ "step": 37
269
+ },
270
+ {
271
+ "epoch": 0.75,
272
+ "grad_norm": 1.1110989245435192,
273
+ "learning_rate": 1.904965618513868e-05,
274
+ "loss": 0.6519,
275
+ "step": 38
276
+ },
277
+ {
278
+ "epoch": 0.76,
279
+ "grad_norm": 1.094231744667558,
280
+ "learning_rate": 1.8979201311434434e-05,
281
+ "loss": 0.6653,
282
+ "step": 39
283
+ },
284
+ {
285
+ "epoch": 0.78,
286
+ "grad_norm": 1.1989962094861866,
287
+ "learning_rate": 1.8906367334720125e-05,
288
+ "loss": 0.664,
289
+ "step": 40
290
+ },
291
+ {
292
+ "epoch": 0.8,
293
+ "grad_norm": 2.0062427841484576,
294
+ "learning_rate": 1.8831173552873946e-05,
295
+ "loss": 0.7041,
296
+ "step": 41
297
+ },
298
+ {
299
+ "epoch": 0.82,
300
+ "grad_norm": 1.230679254842199,
301
+ "learning_rate": 1.8753639889021197e-05,
302
+ "loss": 0.6849,
303
+ "step": 42
304
+ },
305
+ {
306
+ "epoch": 0.84,
307
+ "grad_norm": 1.1625293133229038,
308
+ "learning_rate": 1.8673786886255478e-05,
309
+ "loss": 0.5871,
310
+ "step": 43
311
+ },
312
+ {
313
+ "epoch": 0.86,
314
+ "grad_norm": 1.2011252293407368,
315
+ "learning_rate": 1.8591635702195672e-05,
316
+ "loss": 0.5814,
317
+ "step": 44
318
+ },
319
+ {
320
+ "epoch": 0.88,
321
+ "grad_norm": 1.1548475575271413,
322
+ "learning_rate": 1.8507208103380093e-05,
323
+ "loss": 0.6028,
324
+ "step": 45
325
+ },
326
+ {
327
+ "epoch": 0.9,
328
+ "grad_norm": 1.3290758207520514,
329
+ "learning_rate": 1.8420526459499252e-05,
330
+ "loss": 0.5177,
331
+ "step": 46
332
+ },
333
+ {
334
+ "epoch": 0.92,
335
+ "grad_norm": 1.3961190552811622,
336
+ "learning_rate": 1.8331613737468888e-05,
337
+ "loss": 0.5327,
338
+ "step": 47
339
+ },
340
+ {
341
+ "epoch": 0.94,
342
+ "grad_norm": 1.1179664937015907,
343
+ "learning_rate": 1.8240493495344695e-05,
344
+ "loss": 0.5702,
345
+ "step": 48
346
+ },
347
+ {
348
+ "epoch": 0.96,
349
+ "grad_norm": 0.991786755708903,
350
+ "learning_rate": 1.8147189876080463e-05,
351
+ "loss": 0.5585,
352
+ "step": 49
353
+ },
354
+ {
355
+ "epoch": 0.98,
356
+ "grad_norm": 1.0511710425989889,
357
+ "learning_rate": 1.8051727601131228e-05,
358
+ "loss": 0.4897,
359
+ "step": 50
360
+ },
361
+ {
362
+ "epoch": 1.0,
363
+ "grad_norm": 0.9871728886473652,
364
+ "learning_rate": 1.7954131963903134e-05,
365
+ "loss": 0.5135,
366
+ "step": 51
367
+ },
368
+ {
369
+ "epoch": 1.02,
370
+ "grad_norm": 0.8724604948002991,
371
+ "learning_rate": 1.785442882305179e-05,
372
+ "loss": 0.3347,
373
+ "step": 52
374
+ },
375
+ {
376
+ "epoch": 1.04,
377
+ "grad_norm": 0.8838295943097,
378
+ "learning_rate": 1.775264459563081e-05,
379
+ "loss": 0.3181,
380
+ "step": 53
381
+ },
382
+ {
383
+ "epoch": 1.06,
384
+ "grad_norm": 0.9931815866970414,
385
+ "learning_rate": 1.764880625009245e-05,
386
+ "loss": 0.3026,
387
+ "step": 54
388
+ },
389
+ {
390
+ "epoch": 1.08,
391
+ "grad_norm": 1.0345742370865185,
392
+ "learning_rate": 1.7542941299142113e-05,
393
+ "loss": 0.3461,
394
+ "step": 55
395
+ },
396
+ {
397
+ "epoch": 1.1,
398
+ "grad_norm": 0.9441524354940148,
399
+ "learning_rate": 1.7435077792448666e-05,
400
+ "loss": 0.3211,
401
+ "step": 56
402
+ },
403
+ {
404
+ "epoch": 1.12,
405
+ "grad_norm": 0.8125450415231048,
406
+ "learning_rate": 1.7325244309212476e-05,
407
+ "loss": 0.276,
408
+ "step": 57
409
+ },
410
+ {
411
+ "epoch": 1.14,
412
+ "grad_norm": 0.8616036387498645,
413
+ "learning_rate": 1.7213469950593156e-05,
414
+ "loss": 0.3256,
415
+ "step": 58
416
+ },
417
+ {
418
+ "epoch": 1.16,
419
+ "grad_norm": 0.8037201705902857,
420
+ "learning_rate": 1.709978433199901e-05,
421
+ "loss": 0.2875,
422
+ "step": 59
423
+ },
424
+ {
425
+ "epoch": 1.18,
426
+ "grad_norm": 0.923293041412828,
427
+ "learning_rate": 1.6984217575240212e-05,
428
+ "loss": 0.3468,
429
+ "step": 60
430
+ },
431
+ {
432
+ "epoch": 1.2,
433
+ "grad_norm": 0.8864744076614339,
434
+ "learning_rate": 1.6866800300547814e-05,
435
+ "loss": 0.3045,
436
+ "step": 61
437
+ },
438
+ {
439
+ "epoch": 1.22,
440
+ "grad_norm": 0.8688649629779567,
441
+ "learning_rate": 1.674756361846071e-05,
442
+ "loss": 0.3243,
443
+ "step": 62
444
+ },
445
+ {
446
+ "epoch": 1.24,
447
+ "grad_norm": 0.77439697554644,
448
+ "learning_rate": 1.6626539121582687e-05,
449
+ "loss": 0.2579,
450
+ "step": 63
451
+ },
452
+ {
453
+ "epoch": 1.25,
454
+ "grad_norm": 0.8571490155577813,
455
+ "learning_rate": 1.650375887621171e-05,
456
+ "loss": 0.332,
457
+ "step": 64
458
+ },
459
+ {
460
+ "epoch": 1.27,
461
+ "grad_norm": 0.922211924907794,
462
+ "learning_rate": 1.637925541384375e-05,
463
+ "loss": 0.3416,
464
+ "step": 65
465
+ },
466
+ {
467
+ "epoch": 1.29,
468
+ "grad_norm": 0.8273052620873378,
469
+ "learning_rate": 1.6253061722553353e-05,
470
+ "loss": 0.3068,
471
+ "step": 66
472
+ },
473
+ {
474
+ "epoch": 1.31,
475
+ "grad_norm": 0.8095932095629248,
476
+ "learning_rate": 1.612521123825317e-05,
477
+ "loss": 0.3171,
478
+ "step": 67
479
+ },
480
+ {
481
+ "epoch": 1.33,
482
+ "grad_norm": 0.8019342077433093,
483
+ "learning_rate": 1.5995737835834905e-05,
484
+ "loss": 0.3117,
485
+ "step": 68
486
+ },
487
+ {
488
+ "epoch": 1.35,
489
+ "grad_norm": 0.7916383152619996,
490
+ "learning_rate": 1.586467582019392e-05,
491
+ "loss": 0.2724,
492
+ "step": 69
493
+ },
494
+ {
495
+ "epoch": 1.37,
496
+ "grad_norm": 0.8004248593606291,
497
+ "learning_rate": 1.5732059917139912e-05,
498
+ "loss": 0.2895,
499
+ "step": 70
500
+ },
501
+ {
502
+ "epoch": 1.39,
503
+ "grad_norm": 0.8986302044736728,
504
+ "learning_rate": 1.5597925264196048e-05,
505
+ "loss": 0.2968,
506
+ "step": 71
507
+ },
508
+ {
509
+ "epoch": 1.41,
510
+ "grad_norm": 0.9101368979823861,
511
+ "learning_rate": 1.546230740128904e-05,
512
+ "loss": 0.339,
513
+ "step": 72
514
+ },
515
+ {
516
+ "epoch": 1.43,
517
+ "grad_norm": 0.8045707914289225,
518
+ "learning_rate": 1.53252422613326e-05,
519
+ "loss": 0.2773,
520
+ "step": 73
521
+ },
522
+ {
523
+ "epoch": 1.45,
524
+ "grad_norm": 0.8169621304521563,
525
+ "learning_rate": 1.5186766160706738e-05,
526
+ "loss": 0.2971,
527
+ "step": 74
528
+ },
529
+ {
530
+ "epoch": 1.47,
531
+ "grad_norm": 0.7851894618359577,
532
+ "learning_rate": 1.504691578963549e-05,
533
+ "loss": 0.2505,
534
+ "step": 75
535
+ },
536
+ {
537
+ "epoch": 1.49,
538
+ "grad_norm": 0.7829032571228582,
539
+ "learning_rate": 1.4905728202465596e-05,
540
+ "loss": 0.2955,
541
+ "step": 76
542
+ },
543
+ {
544
+ "epoch": 1.51,
545
+ "grad_norm": 0.8280131066501262,
546
+ "learning_rate": 1.4763240807848667e-05,
547
+ "loss": 0.3118,
548
+ "step": 77
549
+ },
550
+ {
551
+ "epoch": 1.53,
552
+ "grad_norm": 0.7904115230357416,
553
+ "learning_rate": 1.4619491358829502e-05,
554
+ "loss": 0.2637,
555
+ "step": 78
556
+ },
557
+ {
558
+ "epoch": 1.55,
559
+ "grad_norm": 0.8576605948937364,
560
+ "learning_rate": 1.4474517942843173e-05,
561
+ "loss": 0.3111,
562
+ "step": 79
563
+ },
564
+ {
565
+ "epoch": 1.57,
566
+ "grad_norm": 0.771179138835728,
567
+ "learning_rate": 1.4328358971623455e-05,
568
+ "loss": 0.2625,
569
+ "step": 80
570
+ },
571
+ {
572
+ "epoch": 1.59,
573
+ "grad_norm": 0.7163659653314414,
574
+ "learning_rate": 1.4181053171025392e-05,
575
+ "loss": 0.2548,
576
+ "step": 81
577
+ },
578
+ {
579
+ "epoch": 1.61,
580
+ "grad_norm": 0.7449243778532777,
581
+ "learning_rate": 1.4032639570764595e-05,
582
+ "loss": 0.2548,
583
+ "step": 82
584
+ },
585
+ {
586
+ "epoch": 1.63,
587
+ "grad_norm": 0.7999629608162984,
588
+ "learning_rate": 1.3883157494076048e-05,
589
+ "loss": 0.2926,
590
+ "step": 83
591
+ },
592
+ {
593
+ "epoch": 1.65,
594
+ "grad_norm": 0.8217922125483811,
595
+ "learning_rate": 1.3732646547295128e-05,
596
+ "loss": 0.2938,
597
+ "step": 84
598
+ },
599
+ {
600
+ "epoch": 1.67,
601
+ "grad_norm": 0.8086828652630952,
602
+ "learning_rate": 1.358114660936364e-05,
603
+ "loss": 0.297,
604
+ "step": 85
605
+ },
606
+ {
607
+ "epoch": 1.69,
608
+ "grad_norm": 0.8194748734537538,
609
+ "learning_rate": 1.34286978212636e-05,
610
+ "loss": 0.2856,
611
+ "step": 86
612
+ },
613
+ {
614
+ "epoch": 1.71,
615
+ "grad_norm": 0.7858003470117391,
616
+ "learning_rate": 1.32753405753816e-05,
617
+ "loss": 0.2543,
618
+ "step": 87
619
+ },
620
+ {
621
+ "epoch": 1.73,
622
+ "grad_norm": 0.7826963768753953,
623
+ "learning_rate": 1.3121115504806554e-05,
624
+ "loss": 0.2677,
625
+ "step": 88
626
+ },
627
+ {
628
+ "epoch": 1.75,
629
+ "grad_norm": 0.7729735090495947,
630
+ "learning_rate": 1.2966063472563686e-05,
631
+ "loss": 0.2276,
632
+ "step": 89
633
+ },
634
+ {
635
+ "epoch": 1.76,
636
+ "grad_norm": 0.7157613149688595,
637
+ "learning_rate": 1.2810225560787561e-05,
638
+ "loss": 0.2236,
639
+ "step": 90
640
+ },
641
+ {
642
+ "epoch": 1.78,
643
+ "grad_norm": 0.8637010063044507,
644
+ "learning_rate": 1.2653643059837109e-05,
645
+ "loss": 0.2915,
646
+ "step": 91
647
+ },
648
+ {
649
+ "epoch": 1.8,
650
+ "grad_norm": 0.7449248979464137,
651
+ "learning_rate": 1.2496357457355423e-05,
652
+ "loss": 0.2476,
653
+ "step": 92
654
+ },
655
+ {
656
+ "epoch": 1.82,
657
+ "grad_norm": 0.7456800901872752,
658
+ "learning_rate": 1.2338410427277342e-05,
659
+ "loss": 0.276,
660
+ "step": 93
661
+ },
662
+ {
663
+ "epoch": 1.84,
664
+ "grad_norm": 0.6931855319587382,
665
+ "learning_rate": 1.2179843818787625e-05,
666
+ "loss": 0.2291,
667
+ "step": 94
668
+ },
669
+ {
670
+ "epoch": 1.86,
671
+ "grad_norm": 0.748062571866356,
672
+ "learning_rate": 1.202069964523272e-05,
673
+ "loss": 0.2484,
674
+ "step": 95
675
+ },
676
+ {
677
+ "epoch": 1.88,
678
+ "grad_norm": 0.7159809176976305,
679
+ "learning_rate": 1.186102007298904e-05,
680
+ "loss": 0.264,
681
+ "step": 96
682
+ },
683
+ {
684
+ "epoch": 1.9,
685
+ "grad_norm": 0.6999413576425992,
686
+ "learning_rate": 1.1700847410290667e-05,
687
+ "loss": 0.2569,
688
+ "step": 97
689
+ },
690
+ {
691
+ "epoch": 1.92,
692
+ "grad_norm": 0.7184171735319789,
693
+ "learning_rate": 1.1540224096019495e-05,
694
+ "loss": 0.2533,
695
+ "step": 98
696
+ },
697
+ {
698
+ "epoch": 1.94,
699
+ "grad_norm": 0.7498351154279366,
700
+ "learning_rate": 1.137919268846074e-05,
701
+ "loss": 0.2625,
702
+ "step": 99
703
+ },
704
+ {
705
+ "epoch": 1.96,
706
+ "grad_norm": 0.8195036397088564,
707
+ "learning_rate": 1.121779585402684e-05,
708
+ "loss": 0.2872,
709
+ "step": 100
710
+ },
711
+ {
712
+ "epoch": 1.98,
713
+ "grad_norm": 0.7239230213655573,
714
+ "learning_rate": 1.105607635595266e-05,
715
+ "loss": 0.2138,
716
+ "step": 101
717
+ },
718
+ {
719
+ "epoch": 2.0,
720
+ "grad_norm": 0.5927611951490782,
721
+ "learning_rate": 1.0894077042965084e-05,
722
+ "loss": 0.1527,
723
+ "step": 102
724
+ },
725
+ {
726
+ "epoch": 2.02,
727
+ "grad_norm": 0.5812390972468515,
728
+ "learning_rate": 1.0731840837929946e-05,
729
+ "loss": 0.0943,
730
+ "step": 103
731
+ },
732
+ {
733
+ "epoch": 2.04,
734
+ "grad_norm": 0.6457949647478547,
735
+ "learning_rate": 1.0569410726479301e-05,
736
+ "loss": 0.1276,
737
+ "step": 104
738
+ },
739
+ {
740
+ "epoch": 2.06,
741
+ "grad_norm": 0.6076599586709107,
742
+ "learning_rate": 1.0406829745622085e-05,
743
+ "loss": 0.1118,
744
+ "step": 105
745
+ },
746
+ {
747
+ "epoch": 2.08,
748
+ "grad_norm": 0.6580690196356788,
749
+ "learning_rate": 1.0244140972341155e-05,
750
+ "loss": 0.1266,
751
+ "step": 106
752
+ },
753
+ {
754
+ "epoch": 2.1,
755
+ "grad_norm": 0.6652391219627729,
756
+ "learning_rate": 1.008138751217973e-05,
757
+ "loss": 0.1061,
758
+ "step": 107
759
+ },
760
+ {
761
+ "epoch": 2.12,
762
+ "grad_norm": 0.8077871750305834,
763
+ "learning_rate": 9.918612487820274e-06,
764
+ "loss": 0.1372,
765
+ "step": 108
766
+ },
767
+ {
768
+ "epoch": 2.14,
769
+ "grad_norm": 0.7590982992651446,
770
+ "learning_rate": 9.755859027658848e-06,
771
+ "loss": 0.1108,
772
+ "step": 109
773
+ },
774
+ {
775
+ "epoch": 2.16,
776
+ "grad_norm": 0.8397462300303704,
777
+ "learning_rate": 9.593170254377915e-06,
778
+ "loss": 0.1289,
779
+ "step": 110
780
+ },
781
+ {
782
+ "epoch": 2.18,
783
+ "grad_norm": 0.7003906062775592,
784
+ "learning_rate": 9.430589273520704e-06,
785
+ "loss": 0.1058,
786
+ "step": 111
787
+ },
788
+ {
789
+ "epoch": 2.2,
790
+ "grad_norm": 0.7088357228372557,
791
+ "learning_rate": 9.268159162070058e-06,
792
+ "loss": 0.1135,
793
+ "step": 112
794
+ },
795
+ {
796
+ "epoch": 2.22,
797
+ "grad_norm": 0.7000401962183394,
798
+ "learning_rate": 9.105922957034921e-06,
799
+ "loss": 0.1096,
800
+ "step": 113
801
+ },
802
+ {
803
+ "epoch": 2.24,
804
+ "grad_norm": 0.5830640142754188,
805
+ "learning_rate": 8.943923644047343e-06,
806
+ "loss": 0.096,
807
+ "step": 114
808
+ },
809
+ {
810
+ "epoch": 2.25,
811
+ "grad_norm": 0.7040673193362394,
812
+ "learning_rate": 8.782204145973162e-06,
813
+ "loss": 0.126,
814
+ "step": 115
815
+ },
816
+ {
817
+ "epoch": 2.27,
818
+ "grad_norm": 0.5883035825262033,
819
+ "learning_rate": 8.620807311539258e-06,
820
+ "loss": 0.1046,
821
+ "step": 116
822
+ },
823
+ {
824
+ "epoch": 2.29,
825
+ "grad_norm": 0.5889783156569407,
826
+ "learning_rate": 8.45977590398051e-06,
827
+ "loss": 0.1099,
828
+ "step": 117
829
+ },
830
+ {
831
+ "epoch": 2.31,
832
+ "grad_norm": 0.5746493638760929,
833
+ "learning_rate": 8.299152589709336e-06,
834
+ "loss": 0.0998,
835
+ "step": 118
836
+ },
837
+ {
838
+ "epoch": 2.33,
839
+ "grad_norm": 0.5063169905997035,
840
+ "learning_rate": 8.138979927010964e-06,
841
+ "loss": 0.0829,
842
+ "step": 119
843
+ },
844
+ {
845
+ "epoch": 2.35,
846
+ "grad_norm": 0.561526728081391,
847
+ "learning_rate": 7.979300354767282e-06,
848
+ "loss": 0.099,
849
+ "step": 120
850
+ },
851
+ {
852
+ "epoch": 2.37,
853
+ "grad_norm": 0.6140392260229752,
854
+ "learning_rate": 7.82015618121238e-06,
855
+ "loss": 0.112,
856
+ "step": 121
857
+ },
858
+ {
859
+ "epoch": 2.39,
860
+ "grad_norm": 0.6024756993343563,
861
+ "learning_rate": 7.66158957272266e-06,
862
+ "loss": 0.0924,
863
+ "step": 122
864
+ },
865
+ {
866
+ "epoch": 2.41,
867
+ "grad_norm": 0.6149831107386897,
868
+ "learning_rate": 7.503642542644581e-06,
869
+ "loss": 0.1056,
870
+ "step": 123
871
+ },
872
+ {
873
+ "epoch": 2.43,
874
+ "grad_norm": 0.6268831968674875,
875
+ "learning_rate": 7.346356940162895e-06,
876
+ "loss": 0.1109,
877
+ "step": 124
878
+ },
879
+ {
880
+ "epoch": 2.45,
881
+ "grad_norm": 0.5774013268612427,
882
+ "learning_rate": 7.189774439212442e-06,
883
+ "loss": 0.095,
884
+ "step": 125
885
+ },
886
+ {
887
+ "epoch": 2.47,
888
+ "grad_norm": 0.5981672010212989,
889
+ "learning_rate": 7.033936527436318e-06,
890
+ "loss": 0.1028,
891
+ "step": 126
892
+ },
893
+ {
894
+ "epoch": 2.49,
895
+ "grad_norm": 0.6129772623459513,
896
+ "learning_rate": 6.878884495193448e-06,
897
+ "loss": 0.0945,
898
+ "step": 127
899
+ },
900
+ {
901
+ "epoch": 2.51,
902
+ "grad_norm": 0.5804441177255439,
903
+ "learning_rate": 6.724659424618401e-06,
904
+ "loss": 0.099,
905
+ "step": 128
906
+ },
907
+ {
908
+ "epoch": 2.53,
909
+ "grad_norm": 0.6592505296857643,
910
+ "learning_rate": 6.571302178736404e-06,
911
+ "loss": 0.1119,
912
+ "step": 129
913
+ },
914
+ {
915
+ "epoch": 2.55,
916
+ "grad_norm": 0.5876228001270772,
917
+ "learning_rate": 6.418853390636363e-06,
918
+ "loss": 0.1066,
919
+ "step": 130
920
+ },
921
+ {
922
+ "epoch": 2.57,
923
+ "grad_norm": 0.5711848758996622,
924
+ "learning_rate": 6.267353452704876e-06,
925
+ "loss": 0.0939,
926
+ "step": 131
927
+ },
928
+ {
929
+ "epoch": 2.59,
930
+ "grad_norm": 0.5276470301226159,
931
+ "learning_rate": 6.116842505923955e-06,
932
+ "loss": 0.086,
933
+ "step": 132
934
+ },
935
+ {
936
+ "epoch": 2.61,
937
+ "grad_norm": 0.5743382647434178,
938
+ "learning_rate": 5.967360429235407e-06,
939
+ "loss": 0.0976,
940
+ "step": 133
941
+ },
942
+ {
943
+ "epoch": 2.63,
944
+ "grad_norm": 0.5502701680994874,
945
+ "learning_rate": 5.8189468289746075e-06,
946
+ "loss": 0.0925,
947
+ "step": 134
948
+ },
949
+ {
950
+ "epoch": 2.65,
951
+ "grad_norm": 0.6137369248887328,
952
+ "learning_rate": 5.671641028376547e-06,
953
+ "loss": 0.1014,
954
+ "step": 135
955
+ },
956
+ {
957
+ "epoch": 2.67,
958
+ "grad_norm": 0.5582863288518123,
959
+ "learning_rate": 5.525482057156833e-06,
960
+ "loss": 0.0977,
961
+ "step": 136
962
+ },
963
+ {
964
+ "epoch": 2.69,
965
+ "grad_norm": 0.5454192540734187,
966
+ "learning_rate": 5.380508641170499e-06,
967
+ "loss": 0.0904,
968
+ "step": 137
969
+ },
970
+ {
971
+ "epoch": 2.71,
972
+ "grad_norm": 0.5209533902715616,
973
+ "learning_rate": 5.236759192151336e-06,
974
+ "loss": 0.0866,
975
+ "step": 138
976
+ },
977
+ {
978
+ "epoch": 2.73,
979
+ "grad_norm": 0.5717122393516525,
980
+ "learning_rate": 5.094271797534404e-06,
981
+ "loss": 0.0996,
982
+ "step": 139
983
+ },
984
+ {
985
+ "epoch": 2.75,
986
+ "grad_norm": 0.6064773526535152,
987
+ "learning_rate": 4.953084210364508e-06,
988
+ "loss": 0.104,
989
+ "step": 140
990
+ },
991
+ {
992
+ "epoch": 2.76,
993
+ "grad_norm": 0.5691234525814087,
994
+ "learning_rate": 4.813233839293265e-06,
995
+ "loss": 0.1015,
996
+ "step": 141
997
+ },
998
+ {
999
+ "epoch": 2.78,
1000
+ "grad_norm": 0.5208562146564856,
1001
+ "learning_rate": 4.674757738667405e-06,
1002
+ "loss": 0.0851,
1003
+ "step": 142
1004
+ },
1005
+ {
1006
+ "epoch": 2.8,
1007
+ "grad_norm": 0.5729654869317482,
1008
+ "learning_rate": 4.537692598710962e-06,
1009
+ "loss": 0.0999,
1010
+ "step": 143
1011
+ },
1012
+ {
1013
+ "epoch": 2.82,
1014
+ "grad_norm": 0.5098181803420644,
1015
+ "learning_rate": 4.402074735803955e-06,
1016
+ "loss": 0.0811,
1017
+ "step": 144
1018
+ },
1019
+ {
1020
+ "epoch": 2.84,
1021
+ "grad_norm": 0.5599902642629923,
1022
+ "learning_rate": 4.267940082860088e-06,
1023
+ "loss": 0.0859,
1024
+ "step": 145
1025
+ },
1026
+ {
1027
+ "epoch": 2.86,
1028
+ "grad_norm": 0.6128082395071871,
1029
+ "learning_rate": 4.135324179806079e-06,
1030
+ "loss": 0.1044,
1031
+ "step": 146
1032
+ },
1033
+ {
1034
+ "epoch": 2.88,
1035
+ "grad_norm": 0.6027252305351385,
1036
+ "learning_rate": 4.004262164165098e-06,
1037
+ "loss": 0.101,
1038
+ "step": 147
1039
+ },
1040
+ {
1041
+ "epoch": 2.9,
1042
+ "grad_norm": 0.6114396307412036,
1043
+ "learning_rate": 3.874788761746836e-06,
1044
+ "loss": 0.1008,
1045
+ "step": 148
1046
+ },
1047
+ {
1048
+ "epoch": 2.92,
1049
+ "grad_norm": 0.5382288139061067,
1050
+ "learning_rate": 3.74693827744665e-06,
1051
+ "loss": 0.0846,
1052
+ "step": 149
1053
+ },
1054
+ {
1055
+ "epoch": 2.94,
1056
+ "grad_norm": 0.680532062269904,
1057
+ "learning_rate": 3.6207445861562497e-06,
1058
+ "loss": 0.1155,
1059
+ "step": 150
1060
+ },
1061
+ {
1062
+ "epoch": 2.96,
1063
+ "grad_norm": 0.5889312810479405,
1064
+ "learning_rate": 3.4962411237882945e-06,
1065
+ "loss": 0.0916,
1066
+ "step": 151
1067
+ },
1068
+ {
1069
+ "epoch": 2.98,
1070
+ "grad_norm": 0.5564936393621064,
1071
+ "learning_rate": 3.373460878417315e-06,
1072
+ "loss": 0.0937,
1073
+ "step": 152
1074
+ },
1075
+ {
1076
+ "epoch": 3.0,
1077
+ "grad_norm": 0.4415683617442384,
1078
+ "learning_rate": 3.252436381539291e-06,
1079
+ "loss": 0.0547,
1080
+ "step": 153
1081
+ }
1082
+ ],
1083
+ "logging_steps": 1,
1084
+ "max_steps": 204,
1085
+ "num_input_tokens_seen": 0,
1086
+ "num_train_epochs": 4,
1087
+ "save_steps": 500,
1088
+ "total_flos": 37890624061440.0,
1089
+ "train_batch_size": 16,
1090
+ "trial_name": null,
1091
+ "trial_params": null
1092
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80d37d64d247213fb1d797e96d2e1dcde9aa2b701a9e0ef5ad5dbca53fa9ce03
3
+ size 6840