DachengZhang commited on
Commit
3700444
1 Parent(s): c115fb7
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/llmmodel/Orion-14B-Base/",
3
+ "architectures": [
4
+ "OrionForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_orion.OrionConfig",
9
+ "AutoModelForCausalLM": "modeling_orion.OrionForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 5120,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 15360,
17
+ "max_position_embeddings": 4096,
18
+ "max_sequence_length": 4096,
19
+ "model_type": "orion",
20
+ "num_attention_heads": 40,
21
+ "num_hidden_layers": 40,
22
+ "num_key_value_heads": 40,
23
+ "pad_token_id": 0,
24
+ "pretraining_tp": 1,
25
+ "quantization_config": {
26
+ "bits": 4,
27
+ "group_size": 128,
28
+ "modules_to_not_convert": null,
29
+ "quant_method": "awq",
30
+ "version": "gemm",
31
+ "zero_point": true
32
+ },
33
+ "rms_norm_eps": 1e-05,
34
+ "rope_scaling": null,
35
+ "rope_theta": 10000.0,
36
+ "tie_word_embeddings": false,
37
+ "torch_dtype": "float16",
38
+ "transformers_version": "4.36.2",
39
+ "use_cache": true,
40
+ "vocab_size": 84608
41
+ }
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.36.2"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0404ac443c386e147cd31e68525d96c61db92c80377c7b45b664841ae96b7196
3
+ size 8816528952
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
+
quant_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "zero_point": true,
3
+ "q_group_size": 128,
4
+ "w_bit": 4,
5
+ "version": "GEMM",
6
+ "modules_to_not_convert": null
7
+ }
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,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ import sentencepiece as spm
8
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
9
+
10
+
11
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
12
+
13
+ PRETRAINED_VOCAB_FILES_MAP = {
14
+ "vocab_file": {},
15
+ "tokenizer_file": {},
16
+ }
17
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
18
+
19
+
20
+ class OrionTokenizer(PreTrainedTokenizer):
21
+ """
22
+ Construct a Orion tokenizer. Based on byte-level Byte-Pair-Encoding.
23
+
24
+ Args:
25
+ vocab_file (`str`):
26
+ Path to the vocabulary file.
27
+ """
28
+
29
+ vocab_files_names = VOCAB_FILES_NAMES
30
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
31
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
32
+ model_input_names = ["input_ids", "attention_mask"]
33
+
34
+ def __init__(
35
+ self,
36
+ vocab_file,
37
+ unk_token="<unk>",
38
+ bos_token="<s>",
39
+ eos_token="</s>",
40
+ pad_token=None,
41
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
42
+ add_bos_token=True,
43
+ add_eos_token=False,
44
+ clean_up_tokenization_spaces=False,
45
+ **kwargs,
46
+ ):
47
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
48
+ bos_token = (
49
+ AddedToken(bos_token, lstrip=False, rstrip=False)
50
+ if isinstance(bos_token, str)
51
+ else bos_token
52
+ )
53
+ eos_token = (
54
+ AddedToken(eos_token, lstrip=False, rstrip=False)
55
+ if isinstance(eos_token, str)
56
+ else eos_token
57
+ )
58
+ unk_token = (
59
+ AddedToken(unk_token, lstrip=False, rstrip=False)
60
+ if isinstance(unk_token, str)
61
+ else unk_token
62
+ )
63
+ pad_token = (
64
+ AddedToken(pad_token, lstrip=False, rstrip=False)
65
+ if isinstance(pad_token, str)
66
+ else pad_token
67
+ )
68
+ self.vocab_file = vocab_file
69
+ self.add_bos_token = add_bos_token
70
+ self.add_eos_token = add_eos_token
71
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
72
+ self.sp_model.Load(vocab_file)
73
+ super().__init__(
74
+ bos_token=bos_token,
75
+ eos_token=eos_token,
76
+ unk_token=unk_token,
77
+ pad_token=pad_token,
78
+ add_bos_token=add_bos_token,
79
+ add_eos_token=add_eos_token,
80
+ sp_model_kwargs=self.sp_model_kwargs,
81
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
82
+ **kwargs,
83
+ )
84
+
85
+ def __getstate__(self):
86
+ state = self.__dict__.copy()
87
+ state["sp_model"] = None
88
+ return state
89
+
90
+ def __setstate__(self, d):
91
+ self.__dict__ = d
92
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
93
+ self.sp_model.Load(self.vocab_file)
94
+
95
+ @property
96
+ def vocab_size(self):
97
+ """Returns vocab size"""
98
+ return self.sp_model.get_piece_size()
99
+
100
+ def get_vocab(self):
101
+ """Returns vocab as a dict"""
102
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
103
+ vocab.update(self.added_tokens_encoder)
104
+ return vocab
105
+
106
+ def _tokenize(self, text):
107
+ """Returns a tokenized string."""
108
+ return self.sp_model.encode(text, out_type=str)
109
+
110
+ def _convert_token_to_id(self, token):
111
+ """Converts a token (str) in an id using the vocab."""
112
+ return self.sp_model.piece_to_id(token)
113
+
114
+ def _convert_id_to_token(self, index):
115
+ """Converts an index (integer) in a token (str) using the vocab."""
116
+ token = self.sp_model.IdToPiece(index)
117
+ return token
118
+
119
+ def convert_tokens_to_string(self, tokens):
120
+ """Converts a sequence of tokens (string) in a single string."""
121
+ current_sub_tokens = []
122
+ out_string = ""
123
+ prev_is_special = False
124
+ for i, token in enumerate(tokens):
125
+ # make sure that special tokens are not decoded using sentencepiece model
126
+ if token in self.all_special_tokens:
127
+ if not prev_is_special and i != 0:
128
+ out_string += " "
129
+ out_string += self.sp_model.decode(current_sub_tokens) + token
130
+ prev_is_special = True
131
+ current_sub_tokens = []
132
+ else:
133
+ current_sub_tokens.append(token)
134
+ prev_is_special = False
135
+ out_string += self.sp_model.decode(current_sub_tokens)
136
+ return out_string
137
+
138
+ def save_vocabulary(
139
+ self, save_directory, filename_prefix: Optional[str] = None
140
+ ) -> Tuple[str]:
141
+ """
142
+ Save the vocabulary and special tokens file to a directory.
143
+
144
+ Args:
145
+ save_directory (`str`):
146
+ The directory in which to save the vocabulary.
147
+
148
+ Returns:
149
+ `Tuple(str)`: Paths to the files saved.
150
+ """
151
+ if not os.path.isdir(save_directory):
152
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
153
+ return
154
+ out_vocab_file = os.path.join(
155
+ save_directory,
156
+ (filename_prefix + "-" if filename_prefix else "")
157
+ + VOCAB_FILES_NAMES["vocab_file"],
158
+ )
159
+
160
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
161
+ out_vocab_file
162
+ ) and os.path.isfile(self.vocab_file):
163
+ copyfile(self.vocab_file, out_vocab_file)
164
+ elif not os.path.isfile(self.vocab_file):
165
+ with open(out_vocab_file, "wb") as fi:
166
+ content_spiece_model = self.sp_model.serialized_model_proto()
167
+ fi.write(content_spiece_model)
168
+
169
+ return (out_vocab_file,)
170
+
171
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
172
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
173
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
174
+
175
+ output = bos_token_id + token_ids_0 + eos_token_id
176
+
177
+ if token_ids_1 is not None:
178
+ output = output + bos_token_id + token_ids_1 + eos_token_id
179
+
180
+ return output
181
+
182
+ def get_special_tokens_mask(
183
+ self,
184
+ token_ids_0: List[int],
185
+ token_ids_1: Optional[List[int]] = None,
186
+ already_has_special_tokens: bool = False,
187
+ ) -> List[int]:
188
+ """
189
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
190
+ special tokens using the tokenizer `prepare_for_model` method.
191
+
192
+ Args:
193
+ token_ids_0 (`List[int]`):
194
+ List of IDs.
195
+ token_ids_1 (`List[int]`, *optional*):
196
+ Optional second list of IDs for sequence pairs.
197
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
198
+ Whether or not the token list is already formatted with special tokens for the model.
199
+
200
+ Returns:
201
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
202
+ """
203
+ if already_has_special_tokens:
204
+ return super().get_special_tokens_mask(
205
+ token_ids_0=token_ids_0,
206
+ token_ids_1=token_ids_1,
207
+ already_has_special_tokens=True,
208
+ )
209
+
210
+ bos_token_id = [1] if self.add_bos_token else []
211
+ eos_token_id = [1] if self.add_eos_token else []
212
+
213
+ if token_ids_1 is None:
214
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
215
+ return (
216
+ bos_token_id
217
+ + ([0] * len(token_ids_0))
218
+ + eos_token_id
219
+ + bos_token_id
220
+ + ([0] * len(token_ids_1))
221
+ + eos_token_id
222
+ )
223
+
224
+ def create_token_type_ids_from_sequences(
225
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
226
+ ) -> List[int]:
227
+ """
228
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
229
+ sequence pair mask has the following format:
230
+
231
+ ```
232
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
233
+ | first sequence | second sequence |
234
+ ```
235
+
236
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
237
+
238
+ Args:
239
+ token_ids_0 (`List[int]`):
240
+ List of ids.
241
+ token_ids_1 (`List[int]`, *optional*):
242
+ Optional second list of IDs for sequence pairs.
243
+
244
+ Returns:
245
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
246
+ """
247
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
248
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
249
+
250
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
251
+
252
+ if token_ids_1 is not None:
253
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
254
+
255
+ 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,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "sp_model_kwargs": {},
42
+ "tokenizer_class": "OrionTokenizer",
43
+ "unk_token": "<unk>"
44
+ }