AoiKazama commited on
Commit
6a8d5c3
1 Parent(s): b3ab66f

Upload Kinoe-7B

Browse files
README.md CHANGED
@@ -1,3 +1,4 @@
1
  ---
2
  license: apache-2.0
3
  ---
 
 
1
  ---
2
  license: apache-2.0
3
  ---
4
+ Copy from https://huggingface.co/GENIAC-team-haijima/mistral_9B_global_step63579
__init__.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 weblab. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from typing import TYPE_CHECKING
16
+
17
+ from transformers.utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_torch_available,
21
+ )
22
+
23
+ _import_structure = {
24
+ "configuration_kinoe": ["KinoeConfig"],
25
+ }
26
+
27
+ try:
28
+ if not is_torch_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["modeling_kinoe"] = [
34
+ "KinoeForCausalLM",
35
+ "KinoeModel",
36
+ "KinoePreTrainedModel",
37
+ "KinoeForSequenceClassification",
38
+ "KinoeForTokenClassification",
39
+ ]
40
+
41
+ if TYPE_CHECKING:
42
+ from .configuration_kinoe import KinoeConfig
43
+
44
+ try:
45
+ if not is_torch_available():
46
+ raise OptionalDependencyNotAvailable()
47
+ except OptionalDependencyNotAvailable:
48
+ pass
49
+ else:
50
+ from .modeling_kinoe import (
51
+ KinoeForCausalLM,
52
+ KinoeForSequenceClassification,
53
+ KinoeForTokenClassification,
54
+ KinoeModel,
55
+ KinoePreTrainedModel,
56
+ )
57
+
58
+ else:
59
+ import sys
60
+
61
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
config.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "KinoeForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_kinoe.KinoeConfig",
7
+ "AutoModelForImageClassification": "modeling_kinoe.KinoeForCausalLM"
8
+ },
9
+ "vocab_size": 55424,
10
+ "max_position_embeddings": 37268,
11
+ "hidden_size": 5120,
12
+ "intermediate_size": 14336,
13
+ "num_hidden_layers": 24,
14
+ "num_attention_heads": 40,
15
+ "sliding_window": 1024,
16
+ "num_key_value_heads": 10,
17
+ "hidden_act": "silu",
18
+ "initializer_range": 0.02,
19
+ "rms_norm_eps": 1e-06,
20
+ "use_cache": true,
21
+ "rope_theta": 10000.0,
22
+ "attention_dropout": 0.0,
23
+ "return_dict": true,
24
+ "output_hidden_states": false,
25
+ "output_attentions": false,
26
+ "torchscript": false,
27
+ "torch_dtype": "bfloat16",
28
+ "use_bfloat16": false,
29
+ "tf_legacy_loss": false,
30
+ "pruned_heads": {},
31
+ "tie_word_embeddings": false,
32
+ "chunk_size_feed_forward": 0,
33
+ "is_encoder_decoder": false,
34
+ "is_decoder": false,
35
+ "cross_attention_hidden_size": null,
36
+ "add_cross_attention": false,
37
+ "tie_encoder_decoder": false,
38
+ "max_length": 20,
39
+ "min_length": 0,
40
+ "do_sample": false,
41
+ "early_stopping": false,
42
+ "num_beams": 1,
43
+ "num_beam_groups": 1,
44
+ "diversity_penalty": 0.0,
45
+ "temperature": 1.0,
46
+ "top_k": 50,
47
+ "top_p": 1.0,
48
+ "typical_p": 1.0,
49
+ "repetition_penalty": 1.0,
50
+ "length_penalty": 1.0,
51
+ "no_repeat_ngram_size": 0,
52
+ "encoder_no_repeat_ngram_size": 0,
53
+ "bad_words_ids": null,
54
+ "num_return_sequences": 1,
55
+ "output_scores": false,
56
+ "return_dict_in_generate": false,
57
+ "forced_bos_token_id": null,
58
+ "forced_eos_token_id": null,
59
+ "remove_invalid_values": false,
60
+ "exponential_decay_length_penalty": null,
61
+ "suppress_tokens": null,
62
+ "begin_suppress_tokens": null,
63
+ "finetuning_task": null,
64
+ "id2label": {
65
+ "0": "LABEL_0",
66
+ "1": "LABEL_1"
67
+ },
68
+ "label2id": {
69
+ "LABEL_0": 0,
70
+ "LABEL_1": 1
71
+ },
72
+ "tokenizer_class": null,
73
+ "prefix": null,
74
+ "bos_token_id": 1,
75
+ "eos_token_id": 2,
76
+ "transformers_version": "4.40.2",
77
+ "intermeditate_size": 14336,
78
+ "max_sequence_length": 2048,
79
+ "model_type": "kinoe"
80
+ }
config.json.bak ADDED
@@ -0,0 +1 @@
 
 
1
+ {"vocab_size": 55424, "max_position_embeddings": 37268, "hidden_size": 5120, "intermediate_size": 14336, "num_hidden_layers": 24, "num_attention_heads": 40, "sliding_window": 1024, "num_key_value_heads": 10, "hidden_act": "silu", "initializer_range": 0.02, "rms_norm_eps": 1e-06, "use_cache": true, "rope_theta": 10000, "attention_dropout": 0.0, "return_dict": true, "output_hidden_states": false, "output_attentions": false, "torchscript": false, "torch_dtype": "bfloat16", "use_bfloat16": false, "tf_legacy_loss": false, "pruned_heads": {}, "tie_word_embeddings": false, "chunk_size_feed_forward": 0, "is_encoder_decoder": false, "is_decoder": false, "cross_attention_hidden_size": null, "add_cross_attention": false, "tie_encoder_decoder": false, "max_length": 20, "min_length": 0, "do_sample": false, "early_stopping": false, "num_beams": 1, "num_beam_groups": 1, "diversity_penalty": 0.0, "temperature": 1.0, "top_k": 50, "top_p": 1.0, "typical_p": 1.0, "repetition_penalty": 1.0, "length_penalty": 1.0, "no_repeat_ngram_size": 0, "encoder_no_repeat_ngram_size": 0, "bad_words_ids": null, "num_return_sequences": 1, "output_scores": false, "return_dict_in_generate": false, "forced_bos_token_id": null, "forced_eos_token_id": null, "remove_invalid_values": false, "exponential_decay_length_penalty": null, "suppress_tokens": null, "begin_suppress_tokens": null, "architectures": ["MistralForCausalLM"], "finetuning_task": null, "id2label": {"0": "LABEL_0", "1": "LABEL_1"}, "label2id": {"LABEL_0": 0, "LABEL_1": 1}, "tokenizer_class": null, "prefix": null, "bos_token_id": 1, "pad_token_id": null, "eos_token_id": 2, "sep_token_id": null, "decoder_start_token_id": null, "task_specific_params": null, "problem_type": null, "_name_or_path": "", "transformers_version": "4.40.2", "intermeditate_size": 14336, "max_sequence_length": 2048, "model_type": "mistral"}
configuration_kinoe.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 weblab. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Kinoe model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class KinoeConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`KinoeModel`]. It is used to instantiate an
27
+ Kinoe model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the Mistral-7B-v0.1 or Mistral-7B-Instruct-v0.1.
29
+
30
+ [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1)
31
+ [mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the Kinoe model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`KinoeModel`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 14336):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*, defaults to 8):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
+ The non-linear activation function (function or string) in the decoder.
58
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
59
+ The maximum sequence length that this model might ever be used with. Kinoe's sliding window attention
60
+ allows sequence of up to 4096*32 tokens.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ pad_token_id (`int`, *optional*):
69
+ The id of the padding token.
70
+ bos_token_id (`int`, *optional*, defaults to 1):
71
+ The id of the "beginning-of-sequence" token.
72
+ eos_token_id (`int`, *optional*, defaults to 2):
73
+ The id of the "end-of-sequence" token.
74
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
75
+ Whether the model's input and output word embeddings should be tied.
76
+ rope_theta (`float`, *optional*, defaults to 10000.0):
77
+ The base period of the RoPE embeddings.
78
+ sliding_window (`int`, *optional*, defaults to 4096):
79
+ Sliding window attention window size. If not specified, will default to `4096`.
80
+ attention_dropout (`float`, *optional*, defaults to 0.0):
81
+ The dropout ratio for the attention probabilities.
82
+
83
+ ```python
84
+ >>> from transformers import KinoeModel, KinoeConfig
85
+
86
+ >>> # Initializing a Kinoe 7B style configuration
87
+ >>> configuration = KinoeConfig()
88
+
89
+ >>> # Initializing a model from the Kinoe 7B style configuration
90
+ >>> model = KinoeModel(configuration)
91
+
92
+ >>> # Accessing the model configuration
93
+ >>> configuration = model.config
94
+ ```"""
95
+
96
+ model_type = "kinoe"
97
+ keys_to_ignore_at_inference = ["past_key_values"]
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_size=55424,
102
+ hidden_size=5120,
103
+ intermediate_size=14336,
104
+ num_hidden_layers=24,
105
+ num_attention_heads=40,
106
+ num_key_value_heads=10,
107
+ hidden_act="silu",
108
+ max_position_embeddings=32768,
109
+ initializer_range=0.02,
110
+ rms_norm_eps=1e-6,
111
+ use_cache=True,
112
+ pad_token_id=None,
113
+ bos_token_id=1,
114
+ eos_token_id=2,
115
+ tie_word_embeddings=False,
116
+ rope_theta=10000.0,
117
+ sliding_window=1024,
118
+ attention_dropout=0.0,
119
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.sliding_window = sliding_window
128
+
129
+ # for backward compatibility
130
+ if num_key_value_heads is None:
131
+ num_key_value_heads = num_attention_heads
132
+
133
+ self.num_key_value_heads = num_key_value_heads
134
+ self.hidden_act = hidden_act
135
+ self.initializer_range = initializer_range
136
+ self.rms_norm_eps = rms_norm_eps
137
+ self.use_cache = use_cache
138
+ self.rope_theta = rope_theta
139
+ self.attention_dropout = attention_dropout
140
+
141
+ super().__init__(
142
+ pad_token_id=pad_token_id,
143
+ bos_token_id=bos_token_id,
144
+ eos_token_id=eos_token_id,
145
+ tie_word_embeddings=tie_word_embeddings,
146
+ **kwargs,
147
+ )
deepspeed_to_transformers_kinoe.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import torch
5
+ import json
6
+
7
+ # from deepspeed_checkpoint import DeepSpeedCheckpoint
8
+ from deepspeed_to_megatron import _create_rank_checkpoint, parse_arguments
9
+ from typing import Dict
10
+
11
+ # the import was tested to work with this version
12
+ # https://github.com/huggingface/transformers/commit/0af901e83 if it diverges we may consider
13
+ # copying that version here instead
14
+ # from transformers.models.megatron_gpt2.convert_megatron_gpt2_checkpoint import convert_megatron_checkpoint
15
+ # from transformers import MistralConfig
16
+ from .configuration_kinoe import KinoeConfig
17
+
18
+ # ----------- temporal fix for relative import issue
19
+
20
+ ZERO_FILE_PREFIX = 'zero_pp_rank_'
21
+ LAYER_FILE_PREFIX = 'layer_'
22
+ MP_RANK_FILE_PREFIX = 'mp_rank_'
23
+ EMBEDDING_LAYER_INDEX = 0
24
+ FINAL_LAYER_NORM_INDEX = -1
25
+ ARGS_KEY = 'args'
26
+ ITERATION_KEY = 'iteration'
27
+ SEQUENTIAL_LAYERS = [
28
+ 'input_layernorm.weight', 'input_layernorm.bias',
29
+ 'self_attention.dense.bias',
30
+ 'post_attention_layernorm.weight', 'post_attention_layernorm.bias',
31
+ 'mlp.dense_4h_to_h.bias',
32
+ 'position_embeddings.weight'
33
+ ]
34
+
35
+ LAYER_CONCAT_DIM = {
36
+ 'self_attention.dense.weight': 1,
37
+ 'mlp.dense_4h_to_h.weight': 1
38
+ }
39
+
40
+ class DeepSpeedCheckpoint(object):
41
+ def __init__(self, dir, tp_degree=None, pp_degree=None, no_pp=False):
42
+ self.dir = dir
43
+ self.no_pp = no_pp
44
+ self.file_list = self._get_files(dir)
45
+ self.zero_files = self._get_files_with_prefix(self.file_list, ZERO_FILE_PREFIX)
46
+ self.layer_files = self._get_files_with_prefix(self.file_list, LAYER_FILE_PREFIX)
47
+ self.mp_rank_files = self._get_files_with_prefix(self.file_list, MP_RANK_FILE_PREFIX)
48
+ self.layer_keys = self._get_layer_keys()
49
+ self.layer_count = len(self.layer_keys)
50
+ if not self.no_pp:
51
+ self.original_tp_degree = len(self._get_files_with_prefix(self.layer_files, f'{LAYER_FILE_PREFIX}01'))
52
+ self.original_pp_degree = len(self.mp_rank_files) // self.original_tp_degree
53
+ else:
54
+ self.original_tp_degree = len(self.mp_rank_files)
55
+ self.original_pp_degree = 1
56
+ self.dp_degree = len(self.zero_files) // (self.original_pp_degree * self.original_tp_degree)
57
+ print(f"dp: {self.dp_degree}")
58
+ #self.dp_degree = 24
59
+ self.tp_degree = self.original_tp_degree if tp_degree is None else tp_degree
60
+ print(f"tp: {self.tp_degree}")
61
+ #self.tp_degree = 1
62
+ self.pp_degree = self.original_pp_degree if pp_degree is None else pp_degree
63
+ print(f"pp: {self.pp_degree}")
64
+ #self.pp_degree = 1
65
+ self.global_state = {}
66
+
67
+ self._sanity_check()
68
+ self.pp_to_transformer_map = self._build_pp_transformer_map()
69
+ self.transformer_file_map = self._build_transformer_file_map()
70
+ if not self.no_pp:
71
+ self.tp_to_embedding_map = self._build_tp_other_layer_map(EMBEDDING_LAYER_INDEX)
72
+ self.tp_to_final_norm_map = self._build_tp_other_layer_map(FINAL_LAYER_NORM_INDEX)
73
+ self._build_global_state()
74
+
75
+
76
+
77
+ def show_tp_embedding_map(self):
78
+ self._dump_mapping(self.tp_to_embedding_map, 'tp_to_embedding_layers')
79
+
80
+ def show_tp_final_norm_map(self):
81
+ self._dump_mapping(self.tp_to_final_norm_map, 'tp_to_final_norm_layers')
82
+
83
+ def show_pp_tranformer_map(self):
84
+ self._dump_mapping(self.pp_to_transformer_map, 'pp_to_tranformer_layers')
85
+
86
+ def show_transformer_file_map(self):
87
+ self._dump_mapping(self.transformer_file_map, 'rank_to_tranformer_files')
88
+
89
+ def _build_global_state(self):
90
+ sd = torch.load(self.mp_rank_files[0], map_location=torch.device('cpu'))
91
+ self.global_state[ITERATION_KEY] = sd.get(ITERATION_KEY, 0)
92
+ self.global_state[ARGS_KEY] = sd.get(ARGS_KEY, None)
93
+
94
+ def get_iteration(self):
95
+ if not ITERATION_KEY in self.global_state:
96
+ sd = torch.load(self.mp_rank_files[0], map_location=torch.device('cpu'))
97
+ self.global_state[ITERATION_KEY] = sd.get(ITERATION_KEY, 0)
98
+
99
+ return self.global_state[ITERATION_KEY]
100
+
101
+ def get_embedding_state(self, tp_index: int) -> Dict:
102
+ assert tp_index in self.tp_to_embedding_map.keys()
103
+ sd_list = [torch.load(fname, map_location=torch.device('cpu')) for fname in self.tp_to_embedding_map[tp_index]]
104
+ sd = self._merge_state_dicts(sd_list)
105
+ return sd
106
+
107
+ def get_args(self):
108
+ if not ARGS_KEY in self.global_state:
109
+ sd = torch.load(self.mp_rank_files[0], map_location=torch.device('cpu'))
110
+ self.global_state[ARGS_KEY] = sd.get(ARGS_KEY, None)
111
+
112
+ return self.global_state[ARGS_KEY]
113
+
114
+
115
+ def get_transformer_state(self, tp_index: int, pp_index: int) -> list:
116
+ assert tp_index < self.tp_degree
117
+ assert pp_index < self.pp_degree
118
+ t_list = []
119
+ for fname_list in self.transformer_file_map[(tp_index, pp_index)]:
120
+ sd_list = [torch.load(fname, map_location=torch.device('cpu')) for fname in fname_list]
121
+ sd = self._merge_state_dicts(sd_list)
122
+ t_list.append(sd)
123
+ return t_list
124
+
125
+ def get_final_norm_state(self, tp_index:int) -> Dict:
126
+ assert tp_index in self.tp_to_final_norm_map.keys()
127
+ sd = torch.load(self.tp_to_final_norm_map[tp_index][0], map_location=torch.device('cpu'))
128
+ return sd
129
+
130
+ def _build_tp_other_layer_map(self, layer_index:int):
131
+ assert layer_index < len(self.layer_files)
132
+ layer_files = self._get_files_with_prefix(self.layer_files, self.layer_keys[layer_index])
133
+ layer_file_partitions = self._partition_data(layer_files, self.tp_degree)
134
+ data_map = {i:flist for i, flist in enumerate(layer_file_partitions)}
135
+ return data_map
136
+
137
+ def _build_pp_transformer_map(self):
138
+ data_map = {}
139
+ transformer_layers = self.layer_keys[1:-1]
140
+ layers_per_pp = len(transformer_layers) // self.pp_degree
141
+ data_map = {i:transformer_layers[i*layers_per_pp:(i+1)*layers_per_pp] for i in range(0, self.pp_degree)}
142
+ return data_map
143
+
144
+ def _dump_mapping(self, data_map, map_tag = None):
145
+ if map_tag is not None:
146
+ print(f'Dump mapping: {map_tag}')
147
+ for k, v in data_map.items():
148
+ print(f'{k} = {v}')
149
+
150
+ def _build_transformer_file_map(self):
151
+ transformer_layer_keys = self.layer_keys[1:-1]
152
+ file_map = {}
153
+ layers_per_pp = len(transformer_layer_keys) // self.pp_degree
154
+ for key_index, layer_key in enumerate(transformer_layer_keys):
155
+ pp_index = key_index // layers_per_pp
156
+ layer_files = self._get_files_with_prefix(self.layer_files, layer_key)
157
+ layer_file_partitions = self._partition_data(layer_files, self.tp_degree)
158
+ for tp_index in range(self.tp_degree):
159
+ map_key = (tp_index, pp_index)
160
+ if not map_key in file_map.keys():
161
+ file_map[map_key] = []
162
+ file_map[map_key].append(layer_file_partitions[tp_index])
163
+
164
+ return file_map
165
+
166
+ def _sanity_check(self):
167
+ assert len(self.mp_rank_files) % self.tp_degree == 0
168
+ assert len(self.zero_files) % (self.pp_degree * self.tp_degree) == 0
169
+ if not self.no_pp:
170
+ assert len(self.layer_keys) > 2
171
+ assert (len(self.layer_keys) - 2) % self.pp_degree == 0
172
+
173
+ def _get_files_with_prefix(self, all_files, prefix):
174
+ file_list = []
175
+ for file_path in all_files:
176
+ _, fname = os.path.split(file_path)
177
+ if fname.startswith(prefix):
178
+ file_list.append(file_path)
179
+
180
+ return sorted(file_list)
181
+
182
+ def validate_files(self):
183
+ for file in self.file_list:
184
+ if not os.path.isfile(file):
185
+ print(f'Error: {file} is not existent')
186
+
187
+ def _get_files(self, dir):
188
+ file_list = []
189
+ for root, dirs, files in os.walk(dir):
190
+ for file in files:
191
+ file_list.append(os.path.join(root, file))
192
+ return file_list
193
+
194
+ def _get_layer_keys(self):
195
+ key_set = set()
196
+ key_len = len(LAYER_FILE_PREFIX) + 2
197
+ for file_path in self.layer_files:
198
+ _, fname = os.path.split(file_path)
199
+ key_set.add(fname[:key_len])
200
+ return sorted(list(key_set))
201
+
202
+ def _partition_data(self, data_list, num_partitions):
203
+ num_elems = len(data_list)
204
+ assert num_elems % num_partitions == 0
205
+ partition_size = num_elems // num_partitions
206
+ partitions_list = [data_list[i:i+partition_size] for i in range(0, num_elems, partition_size)]
207
+ return partitions_list
208
+
209
+ def _merge_state_dicts(self, sd_list):
210
+ merged_sd = {}
211
+ for key in sd_list[0].keys():
212
+ if not key in SEQUENTIAL_LAYERS:
213
+ cat_dim = LAYER_CONCAT_DIM.get(key, 0)
214
+ merged_sd[key] = torch.cat([sd[key] for sd in sd_list], dim=cat_dim)
215
+ else:
216
+ merged_sd[key] = sd_list[0][key]
217
+ return merged_sd
218
+
219
+ # ------------------------------
220
+
221
+ def convert_wqkv(
222
+ qkv_w: torch.Tensor, # [7680, 5120]
223
+ n_heads: int = 40,
224
+ n_heads_kv: int = 10,
225
+ tp_size: int = 1,
226
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
227
+ """
228
+ Args:
229
+ qkv_w (torch.Tensor):
230
+ layer_idx (int, optional):
231
+ n_heads (int, optional):
232
+ n_heads_kv (int, optional):
233
+
234
+ Returns:
235
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
236
+ """
237
+ n_hidden = qkv_w.size(1)
238
+ # hidden_dim: 128
239
+ hidden_dim: int = n_hidden // n_heads * tp_size
240
+ # print(f"hidden_dim: {hidden_dim}")
241
+
242
+ # n_sq_per_kv: 4
243
+ n_qs_per_kv: int = n_heads // n_heads_kv
244
+ # print(f"n_qs_per_kv {n_qs_per_kv}")
245
+ # n_groups: 10
246
+ n_groups: int = qkv_w.size(0) // hidden_dim // (n_qs_per_kv + 2)
247
+ # print(f"n_groups: {n_groups}")
248
+ qkv_w: list[torch.Tensor] = list(torch.split(qkv_w, hidden_dim, dim=0))
249
+
250
+ wq, wk, wv = [], [], []
251
+ for _ in range(n_groups):
252
+ for qs in range(n_qs_per_kv):
253
+ wq.append(qkv_w[0])
254
+ del qkv_w[0]
255
+ wk.append(qkv_w[0])
256
+ del qkv_w[0]
257
+ wv.append(qkv_w[0])
258
+ del qkv_w[0]
259
+ assert len(qkv_w) == 0
260
+
261
+ wq = torch.concat(wq, dim=0)
262
+ wk = torch.concat(wk, dim=0)
263
+ wv = torch.concat(wv, dim=0)
264
+ return wq, wk, wv
265
+
266
+
267
+ def convert_megatron_checkpoint_custom(args, input_state_dict, config):
268
+ """Custom function that converts megatron checkpoints to hf compatible ones for Mistral."""
269
+ output_state_dict = {}
270
+
271
+ # old versions did not store training args
272
+ ds_args = input_state_dict.get("args", None)
273
+
274
+ # check torch dtype
275
+ torch_dtype = torch.float32
276
+ if ds_args.bf16:
277
+ torch_dtype = torch.bfloat16
278
+ elif ds_args.fp16:
279
+ torch_dtype = torch.float16
280
+
281
+ # config の修正
282
+ if ds_args is not None:
283
+ config.torch_dtype = torch_dtype
284
+
285
+ model = input_state_dict["model"]
286
+ lm = model["language_model"]
287
+ embeddings = lm["embedding"]
288
+ encoder = lm["encoder"]
289
+
290
+ # model.embed_tokens.weight
291
+ output_state_dict["model.embed_tokens.weight"] = embeddings["word_embeddings"]['weight']
292
+
293
+ # layers
294
+ encoder_num_layers = config.num_hidden_layers
295
+ for i in range(encoder_num_layers):
296
+ # layers.{i}.input_layernorm.weight
297
+ output_state_dict[f"model.layers.{i}.input_layernorm.weight"] = encoder[f"layers.{i}.input_layernorm.weight"]
298
+
299
+ # size (7680, 5120)
300
+ qkv_weight = encoder[f"layers.{i}.self_attention.query_key_value.weight"]
301
+
302
+ q_proj, k_proj, v_proj = convert_wqkv(qkv_weight, config.num_attention_heads, config.num_key_value_heads)
303
+ # model.layers.{i}.self_attn.q_proj.weight
304
+ output_state_dict[f"model.layers.{i}.self_attn.q_proj.weight"] = q_proj
305
+ # model.layers.{i}.self_attn.k_proj.weight
306
+ output_state_dict[f"model.layers.{i}.self_attn.k_proj.weight"] = k_proj
307
+ # model.layers.{i}.self_attn.v_proj.weight
308
+ output_state_dict[f"model.layers.{i}.self_attn.v_proj.weight"] = v_proj
309
+ # model.layers.{i}.self_attn.o_proj.weight
310
+ output_state_dict[f"model.layers.{i}.self_attn.o_proj.weight"] = encoder[f"layers.{i}.self_attention.dense.weight"]
311
+
312
+ dense_h_to_4h_weight = encoder[f"layers.{i}.mlp.dense_h_to_4h.weight"]
313
+ split_size = dense_h_to_4h_weight.size(0) // 2
314
+ # model.layers.{i}.mlp.gate_proj.weight, model.layers.{i}.mlp.up_proj.weight
315
+ output_state_dict[f"model.layers.{i}.mlp.gate_proj.weight"], output_state_dict[f"model.layers.{i}.mlp.up_proj.weight"] = torch.split(dense_h_to_4h_weight, split_size, dim=0)
316
+ # model.layers.{i}.mlp.down_proj.weight
317
+ output_state_dict[f"model.layers.{i}.mlp.down_proj.weight"] = encoder[f"layers.{i}.mlp.dense_4h_to_h.weight"]
318
+
319
+ # model.layers.{i}.post_attention_layernorm.weight
320
+ output_state_dict[f"model.layers.{i}.post_attention_layernorm.weight"] = encoder[f"layers.{i}.post_attention_layernorm.weight"]
321
+
322
+ # model.norm.weight
323
+ output_state_dict["model.norm.weight"] = encoder[f"layers.{encoder_num_layers}.weight"]
324
+
325
+ # lm_head.weight
326
+ output_state_dict["lm_head.weight"] = model['word_embeddings_for_head']['weight']
327
+
328
+ return output_state_dict
329
+
330
+ #FIXME
331
+ def validate_conversion(ds_model, hf_model, dtype):
332
+ seed = 1234
333
+ tensor = torch.random((1, 2048), dtype=dtype)
334
+
335
+ # TODO
336
+ # do inference for each model
337
+ return
338
+
339
+ def load_from_hf_checkpoint(cp_path):
340
+ from transformers import AutoModelForCausalLM
341
+ model = AutoModelForCausalLM.from_pretrained(cp_path, device_map="auto")
342
+ return model
343
+
344
+
345
+ def main():
346
+
347
+ # this first part comes mainly from deepspeed_to_megatron.main
348
+ args = parse_arguments()
349
+ print(f'Converting DeepSpeed checkpoint in {args.input_folder} to HF Transformers checkpoint in {args.output_folder}')
350
+
351
+ ds_checkpoint = DeepSpeedCheckpoint(args.input_folder, args.target_tp, args.target_pp)
352
+ iteration = ds_checkpoint.get_iteration()
353
+ input_state_dict = _create_rank_checkpoint(ds_checkpoint, 0, 0, args.for_release)
354
+
355
+ # Get config wiht HF format.
356
+ config = KinoeConfig(
357
+ vocab_size=55424,
358
+ hidden_size=5120,
359
+ intermeditate_size=14336,
360
+ num_hidden_layers=24,
361
+ num_attention_heads=40,
362
+ num_key_value_heads=10,
363
+ hidden_act="silu",
364
+ max_position_embeddings=37268,
365
+ rms_norm_eps=1e-6,
366
+ use_cache=True,
367
+ tie_word_embeddings=False,
368
+ rope_theta=10000, # refer to Megatron-DeepSpeed/megatron/model/rotay_pos_embedding.py
369
+ sliding_window=1024,
370
+ attention_dropout= 0.0,
371
+ max_sequence_length=2048,
372
+ pad_token_id=None,
373
+ bos_token_id=1,
374
+ eos_token_id=2,
375
+ )
376
+
377
+ # Convert.
378
+ print("Converting to HF Checkpoint")
379
+ output_state_dict = convert_megatron_checkpoint_custom(args, input_state_dict, config)
380
+
381
+ basename = args.output_folder
382
+ os.makedirs(basename, exist_ok=True)
383
+
384
+ # Print the structure of converted state dict.
385
+ #if args.print_checkpoint_structure:
386
+ # recursive_print(None, output_state_dict)
387
+
388
+ # Store the config to file.
389
+ output_config_file = os.path.join(basename, "config.json")
390
+ output_config = config.to_dict()
391
+ output_config["architectures"] = ["KinoeForCausalLM"]
392
+ output_config["model_type"] = "gpt"
393
+ print(f'Saving config to "{output_config_file}"')
394
+ with open(output_config_file, "w") as f:
395
+ json.dump(output_config, f)
396
+
397
+ # Store the state_dict to file.
398
+ output_checkpoint_file = os.path.join(basename, "pytorch_model.bin")
399
+ print(f'Saving checkpoint to "{output_checkpoint_file}"')
400
+ torch.save(output_state_dict, output_checkpoint_file)
401
+
402
+ # load hf model
403
+ model = load_from_hf_checkpoint(basename)
404
+ print("Loaded hf model")
405
+
406
+ print("Now add tokenizer files and upload to the hub")
407
+
408
+
409
+ if __name__ == "__main__":
410
+ main()
modeling_kinoe.py ADDED
@@ -0,0 +1,1544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 weblab. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Kinoe model."""
21
+
22
+ import inspect
23
+ import math
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
34
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_kinoe import KinoeConfig
51
+
52
+
53
+ if is_flash_attn_2_available():
54
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
55
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
56
+
57
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CONFIG_FOR_DOC = "KinoeConfig"
63
+
64
+
65
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
71
+ return (
72
+ indices,
73
+ cu_seqlens,
74
+ max_seqlen_in_batch,
75
+ )
76
+
77
+
78
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Kinoe
79
+ class KinoeRMSNorm(nn.Module):
80
+ def __init__(self, hidden_size, eps=1e-6):
81
+ """
82
+ KinoeRMSNorm is equivalent to T5LayerNorm
83
+ """
84
+ super().__init__()
85
+ self.weight = nn.Parameter(torch.ones(hidden_size))
86
+ self.variance_epsilon = eps
87
+
88
+ def forward(self, hidden_states):
89
+ input_dtype = hidden_states.dtype
90
+ hidden_states = hidden_states.to(torch.float32)
91
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
92
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
93
+ return self.weight * hidden_states.to(input_dtype)
94
+
95
+
96
+ class KinoeRotaryEmbedding(nn.Module):
97
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
98
+ super().__init__()
99
+
100
+ self.dim = dim // 4
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.base = base
103
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, (self.dim), 2, dtype=torch.int64).float().to(device) / (self.dim)))
104
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
105
+
106
+ @torch.no_grad()
107
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.forward
108
+ def forward(self, x, position_ids):
109
+ # x: [bs, num_attention_heads, seq_len, head_size]
110
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
111
+ position_ids_expanded = position_ids[:, None, :].float()
112
+ # Force float32 since bfloat16 loses precision on long contexts
113
+ # See https://github.com/huggingface/transformers/pull/29285
114
+ device_type = x.device.type
115
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
116
+ with torch.autocast(device_type=device_type, enabled=False):
117
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ cos = emb.cos()
120
+ sin = emb.sin()
121
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
122
+
123
+
124
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
125
+ def rotate_half(x):
126
+ """Rotates half the hidden dims of the input."""
127
+ x1 = x[..., : x.shape[-1] // 2]
128
+ x2 = x[..., x.shape[-1] // 2 :]
129
+ return torch.cat((-x2, x1), dim=-1)
130
+
131
+
132
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
133
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
134
+ """Applies Rotary Position Embedding to the query and key tensors.
135
+
136
+ Args:
137
+ q (`torch.Tensor`): The query tensor.
138
+ k (`torch.Tensor`): The key tensor.
139
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
140
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
141
+ position_ids (`torch.Tensor`, *optional*):
142
+ Deprecated and unused.
143
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
144
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
145
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
146
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
147
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
148
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
149
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
150
+ Returns:
151
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
152
+ """
153
+ rot_dim = cos.shape[-1]
154
+ cos = cos.unsqueeze(unsqueeze_dim)
155
+ sin = sin.unsqueeze(unsqueeze_dim)
156
+ q, q_pass = q[..., :rot_dim], q[..., rot_dim:]
157
+ k, k_pass = k[..., :rot_dim], k[..., rot_dim:]
158
+ q_embed = (q * cos) + (rotate_half(q) * sin)
159
+ k_embed = (k * cos) + (rotate_half(k) * sin)
160
+ return torch.cat([q_embed, q_pass], dim=-1), torch.cat([k_embed, k_pass], dim=-1)
161
+
162
+
163
+ class KinoeMLP(nn.Module):
164
+ def __init__(self, config):
165
+ super().__init__()
166
+ self.config = config
167
+ self.hidden_size = config.hidden_size
168
+ self.intermediate_size = config.intermediate_size
169
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
170
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
171
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
172
+ self.act_fn = ACT2FN[config.hidden_act]
173
+
174
+ def forward(self, x):
175
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
176
+
177
+
178
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
179
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
180
+ """
181
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
182
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
183
+ """
184
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
185
+ if n_rep == 1:
186
+ return hidden_states
187
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
188
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
189
+
190
+
191
+ class KinoeAttention(nn.Module):
192
+ """
193
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
194
+ and "Generating Long Sequences with Sparse Transformers".
195
+ """
196
+
197
+ def __init__(self, config: KinoeConfig, layer_idx: Optional[int] = None):
198
+ super().__init__()
199
+ self.config = config
200
+ self.layer_idx = layer_idx
201
+ if layer_idx is None:
202
+ logger.warning_once(
203
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
204
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
205
+ "when creating this class."
206
+ )
207
+
208
+ self.attention_dropout = config.attention_dropout
209
+ self.hidden_size = config.hidden_size
210
+ self.num_heads = config.num_attention_heads
211
+ self.head_dim = self.hidden_size // self.num_heads
212
+ self.num_key_value_heads = config.num_key_value_heads
213
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
214
+ self.max_position_embeddings = config.max_position_embeddings
215
+ self.rope_theta = config.rope_theta
216
+ self.is_causal = True
217
+
218
+ if (self.head_dim * self.num_heads) != self.hidden_size:
219
+ raise ValueError(
220
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
221
+ f" and `num_heads`: {self.num_heads})."
222
+ )
223
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
224
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
225
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
226
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
227
+
228
+ self.rotary_emb = KinoeRotaryEmbedding(
229
+ self.head_dim,
230
+ max_position_embeddings=self.max_position_embeddings,
231
+ base=self.rope_theta,
232
+ )
233
+
234
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaAttention.forward with Gemma->Kinoe
235
+ def forward(
236
+ self,
237
+ hidden_states: torch.Tensor,
238
+ attention_mask: Optional[torch.Tensor] = None,
239
+ position_ids: Optional[torch.LongTensor] = None,
240
+ past_key_value: Optional[Cache] = None,
241
+ output_attentions: bool = False,
242
+ use_cache: bool = False,
243
+ cache_position: Optional[torch.LongTensor] = None,
244
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
245
+ bsz, q_len, _ = hidden_states.size()
246
+
247
+ query_states = self.q_proj(hidden_states)
248
+ key_states = self.k_proj(hidden_states)
249
+ value_states = self.v_proj(hidden_states)
250
+
251
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
252
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
253
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
254
+
255
+ cos, sin = self.rotary_emb(value_states, position_ids)
256
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
257
+
258
+ if past_key_value is not None:
259
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
260
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
261
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
262
+
263
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
264
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
265
+
266
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
267
+
268
+ if attention_mask is not None: # no matter the length, we just slice it
269
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
270
+ attn_weights = attn_weights + causal_mask
271
+
272
+ # upcast attention to fp32
273
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
274
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
275
+ attn_output = torch.matmul(attn_weights, value_states)
276
+
277
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
278
+ raise ValueError(
279
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
280
+ f" {attn_output.size()}"
281
+ )
282
+
283
+ attn_output = attn_output.transpose(1, 2).contiguous()
284
+
285
+ attn_output = attn_output.view(bsz, q_len, -1)
286
+ attn_output = self.o_proj(attn_output)
287
+
288
+ if not output_attentions:
289
+ attn_weights = None
290
+
291
+ return attn_output, attn_weights, past_key_value
292
+
293
+
294
+ class KinoeFlashAttention2(KinoeAttention):
295
+ """
296
+ Kinoe flash attention module. This module inherits from `KinoeAttention` as the weights of the module stays
297
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
298
+ flash attention and deal with padding tokens in case the input contains any of them.
299
+ """
300
+
301
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
302
+ def __init__(self, *args, **kwargs):
303
+ super().__init__(*args, **kwargs)
304
+
305
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
306
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
307
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
308
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ past_key_value: Optional[Cache] = None,
316
+ output_attentions: bool = False,
317
+ use_cache: bool = False,
318
+ cache_position: Optional[torch.LongTensor] = None,
319
+ ):
320
+ if isinstance(past_key_value, StaticCache):
321
+ raise ValueError(
322
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
323
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
324
+ )
325
+
326
+ output_attentions = False
327
+
328
+ bsz, q_len, _ = hidden_states.size()
329
+
330
+ query_states = self.q_proj(hidden_states)
331
+ key_states = self.k_proj(hidden_states)
332
+ value_states = self.v_proj(hidden_states)
333
+
334
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
335
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
336
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
337
+
338
+ kv_seq_len = key_states.shape[-2]
339
+ if past_key_value is not None:
340
+ kv_seq_len += cache_position[0]
341
+
342
+ cos, sin = self.rotary_emb(value_states, position_ids)
343
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
344
+
345
+ use_sliding_windows = (
346
+ _flash_supports_window_size
347
+ and getattr(self.config, "sliding_window", None) is not None
348
+ and kv_seq_len > self.config.sliding_window
349
+ )
350
+
351
+ if not _flash_supports_window_size:
352
+ logger.warning_once(
353
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
354
+ " make sure to upgrade flash-attn library."
355
+ )
356
+
357
+ if past_key_value is not None:
358
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
359
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
360
+ if (
361
+ getattr(self.config, "sliding_window", None) is not None
362
+ and kv_seq_len > self.config.sliding_window
363
+ and cache_has_contents
364
+ ):
365
+ slicing_tokens = 1 - self.config.sliding_window
366
+
367
+ past_key = past_key_value[self.layer_idx][0]
368
+ past_value = past_key_value[self.layer_idx][1]
369
+
370
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
371
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
372
+
373
+ if past_key.shape[-2] != self.config.sliding_window - 1:
374
+ raise ValueError(
375
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
376
+ f" {past_key.shape}"
377
+ )
378
+
379
+ if attention_mask is not None:
380
+ attention_mask = attention_mask[:, slicing_tokens:]
381
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
382
+
383
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
384
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
385
+
386
+ # repeat k/v heads if n_kv_heads < n_heads
387
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
388
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
389
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
390
+
391
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
392
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
393
+ # cast them back in float16 just to be sure everything works as expected.
394
+ input_dtype = query_states.dtype
395
+ if input_dtype == torch.float32:
396
+ if torch.is_autocast_enabled():
397
+ target_dtype = torch.get_autocast_gpu_dtype()
398
+ # Handle the case where the model is quantized
399
+ elif hasattr(self.config, "_pre_quantization_dtype"):
400
+ target_dtype = self.config._pre_quantization_dtype
401
+ else:
402
+ target_dtype = self.q_proj.weight.dtype
403
+
404
+ logger.warning_once(
405
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
406
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
407
+ f" {target_dtype}."
408
+ )
409
+
410
+ query_states = query_states.to(target_dtype)
411
+ key_states = key_states.to(target_dtype)
412
+ value_states = value_states.to(target_dtype)
413
+
414
+ # Reashape to the expected shape for Flash Attention
415
+ query_states = query_states.transpose(1, 2)
416
+ key_states = key_states.transpose(1, 2)
417
+ value_states = value_states.transpose(1, 2)
418
+
419
+ attn_output = self._flash_attention_forward(
420
+ query_states,
421
+ key_states,
422
+ value_states,
423
+ attention_mask,
424
+ q_len,
425
+ dropout=dropout_rate,
426
+ use_sliding_windows=use_sliding_windows,
427
+ )
428
+
429
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
430
+ attn_output = self.o_proj(attn_output)
431
+
432
+ if not output_attentions:
433
+ attn_weights = None
434
+
435
+ return attn_output, attn_weights, past_key_value
436
+
437
+ def _flash_attention_forward(
438
+ self,
439
+ query_states,
440
+ key_states,
441
+ value_states,
442
+ attention_mask,
443
+ query_length,
444
+ dropout=0.0,
445
+ softmax_scale=None,
446
+ use_sliding_windows=False,
447
+ ):
448
+ """
449
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
450
+ first unpad the input, then computes the attention scores and pad the final attention scores.
451
+
452
+ Args:
453
+ query_states (`torch.Tensor`):
454
+ Input query states to be passed to Flash Attention API
455
+ key_states (`torch.Tensor`):
456
+ Input key states to be passed to Flash Attention API
457
+ value_states (`torch.Tensor`):
458
+ Input value states to be passed to Flash Attention API
459
+ attention_mask (`torch.Tensor`):
460
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
461
+ position of padding tokens and 1 for the position of non-padding tokens.
462
+ dropout (`float`):
463
+ Attention dropout
464
+ softmax_scale (`float`, *optional*):
465
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
466
+ use_sliding_windows (`bool`, *optional*):
467
+ Whether to activate sliding window attention.
468
+ """
469
+ if not self._flash_attn_uses_top_left_mask:
470
+ causal = self.is_causal
471
+ else:
472
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
473
+ causal = self.is_causal and query_length != 1
474
+
475
+ # Contains at least one padding token in the sequence
476
+ if attention_mask is not None:
477
+ batch_size = query_states.shape[0]
478
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
479
+ query_states, key_states, value_states, attention_mask, query_length
480
+ )
481
+
482
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
483
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
484
+
485
+ if not use_sliding_windows:
486
+ attn_output_unpad = flash_attn_varlen_func(
487
+ query_states,
488
+ key_states,
489
+ value_states,
490
+ cu_seqlens_q=cu_seqlens_q,
491
+ cu_seqlens_k=cu_seqlens_k,
492
+ max_seqlen_q=max_seqlen_in_batch_q,
493
+ max_seqlen_k=max_seqlen_in_batch_k,
494
+ dropout_p=dropout,
495
+ softmax_scale=softmax_scale,
496
+ causal=causal,
497
+ )
498
+ else:
499
+ attn_output_unpad = flash_attn_varlen_func(
500
+ query_states,
501
+ key_states,
502
+ value_states,
503
+ cu_seqlens_q=cu_seqlens_q,
504
+ cu_seqlens_k=cu_seqlens_k,
505
+ max_seqlen_q=max_seqlen_in_batch_q,
506
+ max_seqlen_k=max_seqlen_in_batch_k,
507
+ dropout_p=dropout,
508
+ softmax_scale=softmax_scale,
509
+ causal=causal,
510
+ window_size=(self.config.sliding_window, self.config.sliding_window),
511
+ )
512
+
513
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
514
+ else:
515
+ if not use_sliding_windows:
516
+ attn_output = flash_attn_func(
517
+ query_states,
518
+ key_states,
519
+ value_states,
520
+ dropout,
521
+ softmax_scale=softmax_scale,
522
+ causal=causal,
523
+ )
524
+ else:
525
+ attn_output = flash_attn_func(
526
+ query_states,
527
+ key_states,
528
+ value_states,
529
+ dropout,
530
+ softmax_scale=softmax_scale,
531
+ causal=causal,
532
+ window_size=(self.config.sliding_window, self.config.sliding_window),
533
+ )
534
+
535
+ return attn_output
536
+
537
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
538
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
539
+
540
+ # On the first iteration we need to properly re-create the padding mask
541
+ # by slicing it on the proper place
542
+ if kv_seq_len != attention_mask.shape[-1]:
543
+ attention_mask_num_tokens = attention_mask.shape[-1]
544
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
545
+
546
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
547
+
548
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
549
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
550
+
551
+ if query_length == kv_seq_len:
552
+ query_layer = index_first_axis(
553
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
554
+ )
555
+ cu_seqlens_q = cu_seqlens_k
556
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
557
+ indices_q = indices_k
558
+ elif query_length == 1:
559
+ max_seqlen_in_batch_q = 1
560
+ cu_seqlens_q = torch.arange(
561
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
562
+ ) # There is a memcpy here, that is very bad.
563
+ indices_q = cu_seqlens_q[:-1]
564
+ query_layer = query_layer.squeeze(1)
565
+ else:
566
+ # The -q_len: slice assumes left padding.
567
+ attention_mask = attention_mask[:, -query_length:]
568
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
569
+
570
+ return (
571
+ query_layer,
572
+ key_layer,
573
+ value_layer,
574
+ indices_q,
575
+ (cu_seqlens_q, cu_seqlens_k),
576
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
577
+ )
578
+
579
+
580
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Kinoe
581
+ class KinoeSdpaAttention(KinoeAttention):
582
+ """
583
+ Kinoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
584
+ `KinoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
585
+ SDPA API.
586
+ """
587
+
588
+ # Adapted from KinoeAttention.forward
589
+ def forward(
590
+ self,
591
+ hidden_states: torch.Tensor,
592
+ attention_mask: Optional[torch.Tensor] = None,
593
+ position_ids: Optional[torch.LongTensor] = None,
594
+ past_key_value: Optional[Cache] = None,
595
+ output_attentions: bool = False,
596
+ use_cache: bool = False,
597
+ cache_position: Optional[torch.LongTensor] = None,
598
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
599
+ if output_attentions:
600
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
601
+ logger.warning_once(
602
+ "KinoeModel is using KinoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
603
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
604
+ )
605
+ return super().forward(
606
+ hidden_states=hidden_states,
607
+ attention_mask=attention_mask,
608
+ position_ids=position_ids,
609
+ past_key_value=past_key_value,
610
+ output_attentions=output_attentions,
611
+ use_cache=use_cache,
612
+ cache_position=cache_position,
613
+ )
614
+
615
+ bsz, q_len, _ = hidden_states.size()
616
+
617
+ query_states = self.q_proj(hidden_states)
618
+ key_states = self.k_proj(hidden_states)
619
+ value_states = self.v_proj(hidden_states)
620
+
621
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
622
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
623
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
624
+
625
+ cos, sin = self.rotary_emb(value_states, position_ids)
626
+
627
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
628
+
629
+ if past_key_value is not None:
630
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
631
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
632
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
633
+
634
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
635
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
636
+
637
+ causal_mask = attention_mask
638
+ if attention_mask is not None:
639
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
640
+
641
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
642
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
643
+ if query_states.device.type == "cuda" and causal_mask is not None:
644
+ query_states = query_states.contiguous()
645
+ key_states = key_states.contiguous()
646
+ value_states = value_states.contiguous()
647
+
648
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
649
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
650
+ is_causal = True if causal_mask is None and q_len > 1 else False
651
+
652
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
653
+ query_states,
654
+ key_states,
655
+ value_states,
656
+ attn_mask=causal_mask,
657
+ dropout_p=self.attention_dropout if self.training else 0.0,
658
+ is_causal=is_causal,
659
+ )
660
+
661
+ attn_output = attn_output.transpose(1, 2).contiguous()
662
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
663
+
664
+ attn_output = self.o_proj(attn_output)
665
+
666
+ return attn_output, None, past_key_value
667
+
668
+
669
+ KINOE_ATTENTION_CLASSES = {
670
+ "eager": KinoeAttention,
671
+ "flash_attention_2": KinoeFlashAttention2,
672
+ "sdpa": KinoeSdpaAttention,
673
+ }
674
+
675
+
676
+ # Copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with Llama->Kinoe, LLAMA->KINOE
677
+ class KinoeDecoderLayer(nn.Module):
678
+ def __init__(self, config: KinoeConfig, layer_idx: int):
679
+ super().__init__()
680
+ self.hidden_size = config.hidden_size
681
+
682
+ self.self_attn = KINOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
683
+
684
+ self.mlp = KinoeMLP(config)
685
+ self.input_layernorm = KinoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
686
+ self.post_attention_layernorm = KinoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
687
+
688
+ def forward(
689
+ self,
690
+ hidden_states: torch.Tensor,
691
+ attention_mask: Optional[torch.Tensor] = None,
692
+ position_ids: Optional[torch.LongTensor] = None,
693
+ past_key_value: Optional[Cache] = None,
694
+ output_attentions: Optional[bool] = False,
695
+ use_cache: Optional[bool] = False,
696
+ cache_position: Optional[torch.LongTensor] = None,
697
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
698
+ """
699
+ Args:
700
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
701
+ attention_mask (`torch.FloatTensor`, *optional*):
702
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
703
+ query_sequence_length, key_sequence_length)` if default attention is used.
704
+ output_attentions (`bool`, *optional*):
705
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
706
+ returned tensors for more detail.
707
+ use_cache (`bool`, *optional*):
708
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
709
+ (see `past_key_values`).
710
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
711
+ """
712
+
713
+ residual = hidden_states
714
+
715
+ hidden_states = self.input_layernorm(hidden_states)
716
+
717
+ # Self Attention
718
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
719
+ hidden_states=hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_value,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ cache_position=cache_position,
726
+ )
727
+ hidden_states = residual + hidden_states
728
+
729
+ # Fully Connected
730
+ residual = hidden_states
731
+ hidden_states = self.post_attention_layernorm(hidden_states)
732
+ hidden_states = self.mlp(hidden_states)
733
+ hidden_states = residual + hidden_states
734
+
735
+ outputs = (hidden_states,)
736
+
737
+ if output_attentions:
738
+ outputs += (self_attn_weights,)
739
+
740
+ if use_cache:
741
+ outputs += (present_key_value,)
742
+
743
+ return outputs
744
+
745
+
746
+ KINOE_START_DOCSTRING = r"""
747
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
748
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
749
+ etc.)
750
+
751
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
752
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
753
+ and behavior.
754
+
755
+ Parameters:
756
+ config ([`KinoeConfig`]):
757
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
758
+ load the weights associated with the model, only the configuration. Check out the
759
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
760
+ """
761
+
762
+
763
+ @add_start_docstrings(
764
+ "The bare Kinoe Model outputting raw hidden-states without any specific head on top.",
765
+ KINOE_START_DOCSTRING,
766
+ )
767
+ class KinoePreTrainedModel(PreTrainedModel):
768
+ config_class = KinoeConfig
769
+ base_model_prefix = "model"
770
+ supports_gradient_checkpointing = True
771
+ _no_split_modules = ["KinoeDecoderLayer"]
772
+ _skip_keys_device_placement = "past_key_values"
773
+ _supports_flash_attn_2 = True
774
+ _supports_sdpa = True
775
+ _supports_cache_class = True
776
+ _supports_static_cache = True
777
+
778
+ def _init_weights(self, module):
779
+ std = self.config.initializer_range
780
+ if isinstance(module, nn.Linear):
781
+ module.weight.data.normal_(mean=0.0, std=std)
782
+ if module.bias is not None:
783
+ module.bias.data.zero_()
784
+ elif isinstance(module, nn.Embedding):
785
+ module.weight.data.normal_(mean=0.0, std=std)
786
+ if module.padding_idx is not None:
787
+ module.weight.data[module.padding_idx].zero_()
788
+
789
+
790
+ KINOE_INPUTS_DOCSTRING = r"""
791
+ Args:
792
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
793
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
794
+ it.
795
+
796
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
797
+ [`PreTrainedTokenizer.__call__`] for details.
798
+
799
+ [What are input IDs?](../glossary#input-ids)
800
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
801
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
802
+
803
+ - 1 for tokens that are **not masked**,
804
+ - 0 for tokens that are **masked**.
805
+
806
+ [What are attention masks?](../glossary#attention-mask)
807
+
808
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
809
+ [`PreTrainedTokenizer.__call__`] for details.
810
+
811
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
812
+ `past_key_values`).
813
+
814
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
815
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
816
+ information on the default strategy.
817
+
818
+ - 1 indicates the head is **not masked**,
819
+ - 0 indicates the head is **masked**.
820
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
821
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
822
+ config.n_positions - 1]`.
823
+
824
+ [What are position IDs?](../glossary#position-ids)
825
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
826
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
827
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
828
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
829
+
830
+ Two formats are allowed:
831
+ - a [`~cache_utils.Cache`] instance;
832
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
833
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
834
+ cache format.
835
+
836
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
837
+ legacy cache format will be returned.
838
+
839
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
840
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
841
+ of shape `(batch_size, sequence_length)`.
842
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
843
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
844
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
845
+ model's internal embedding lookup matrix.
846
+ use_cache (`bool`, *optional*):
847
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
848
+ `past_key_values`).
849
+ output_attentions (`bool`, *optional*):
850
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
851
+ tensors for more detail.
852
+ output_hidden_states (`bool`, *optional*):
853
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
854
+ more detail.
855
+ return_dict (`bool`, *optional*):
856
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
857
+ """
858
+
859
+
860
+ @add_start_docstrings(
861
+ "The bare Kinoe Model outputting raw hidden-states without any specific head on top.",
862
+ KINOE_START_DOCSTRING,
863
+ )
864
+ class KinoeModel(KinoePreTrainedModel):
865
+ """
866
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`KinoeDecoderLayer`]
867
+
868
+ Args:
869
+ config: KinoeConfig
870
+ """
871
+
872
+ config_class = KinoeConfig
873
+
874
+ def __init__(self, config: KinoeConfig):
875
+ super().__init__(config)
876
+ self.padding_idx = config.pad_token_id
877
+ self.vocab_size = config.vocab_size
878
+
879
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
880
+ self.layers = nn.ModuleList(
881
+ [KinoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
882
+ )
883
+ self._attn_implementation = config._attn_implementation
884
+ self.norm = KinoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
885
+
886
+ self.gradient_checkpointing = False
887
+ # Initialize weights and apply final processing
888
+ self.post_init()
889
+
890
+ def get_input_embeddings(self):
891
+ return self.embed_tokens
892
+
893
+ def set_input_embeddings(self, value):
894
+ self.embed_tokens = value
895
+
896
+ @add_start_docstrings_to_model_forward(KINOE_INPUTS_DOCSTRING)
897
+ def forward(
898
+ self,
899
+ input_ids: torch.LongTensor = None,
900
+ attention_mask: Optional[torch.Tensor] = None,
901
+ position_ids: Optional[torch.LongTensor] = None,
902
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
903
+ inputs_embeds: Optional[torch.FloatTensor] = None,
904
+ use_cache: Optional[bool] = None,
905
+ output_attentions: Optional[bool] = None,
906
+ output_hidden_states: Optional[bool] = None,
907
+ return_dict: Optional[bool] = None,
908
+ cache_position: Optional[torch.LongTensor] = None,
909
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
910
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
911
+ output_hidden_states = (
912
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
913
+ )
914
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
915
+
916
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
917
+
918
+ # retrieve input_ids and inputs_embeds
919
+ if (input_ids is None) ^ (inputs_embeds is not None):
920
+ raise ValueError(
921
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
922
+ )
923
+
924
+ if self.gradient_checkpointing and self.training and use_cache:
925
+ logger.warning_once(
926
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
927
+ )
928
+ use_cache = False
929
+
930
+ if inputs_embeds is None:
931
+ inputs_embeds = self.embed_tokens(input_ids)
932
+
933
+ return_legacy_cache = False
934
+ if use_cache and not isinstance(past_key_values, Cache):
935
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
936
+ return_legacy_cache = True
937
+
938
+ if cache_position is None:
939
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
940
+ cache_position = torch.arange(
941
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
942
+ )
943
+
944
+ if position_ids is None:
945
+ position_ids = cache_position.unsqueeze(0)
946
+
947
+ causal_mask = self._update_causal_mask(
948
+ attention_mask, inputs_embeds, cache_position, past_key_values, use_cache, output_attentions
949
+ )
950
+
951
+ hidden_states = inputs_embeds
952
+
953
+ # decoder layers
954
+ all_hidden_states = () if output_hidden_states else None
955
+ all_self_attns = () if output_attentions else None
956
+ next_decoder_cache = None
957
+
958
+ for decoder_layer in self.layers:
959
+ if output_hidden_states:
960
+ all_hidden_states += (hidden_states,)
961
+
962
+ if self.gradient_checkpointing and self.training:
963
+ layer_outputs = self._gradient_checkpointing_func(
964
+ decoder_layer.__call__,
965
+ hidden_states,
966
+ causal_mask,
967
+ position_ids,
968
+ past_key_values,
969
+ output_attentions,
970
+ use_cache,
971
+ cache_position,
972
+ )
973
+ else:
974
+ layer_outputs = decoder_layer(
975
+ hidden_states,
976
+ attention_mask=causal_mask,
977
+ position_ids=position_ids,
978
+ past_key_value=past_key_values,
979
+ output_attentions=output_attentions,
980
+ use_cache=use_cache,
981
+ cache_position=cache_position,
982
+ )
983
+
984
+ hidden_states = layer_outputs[0]
985
+
986
+ if use_cache:
987
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
988
+
989
+ if output_attentions:
990
+ all_self_attns += (layer_outputs[1],)
991
+
992
+ hidden_states = self.norm(hidden_states)
993
+
994
+ # add hidden states from the last decoder layer
995
+ if output_hidden_states:
996
+ all_hidden_states += (hidden_states,)
997
+
998
+ next_cache = next_decoder_cache if use_cache else None
999
+ if return_legacy_cache:
1000
+ next_cache = next_cache.to_legacy_cache()
1001
+
1002
+ if not return_dict:
1003
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1004
+ return BaseModelOutputWithPast(
1005
+ last_hidden_state=hidden_states,
1006
+ past_key_values=next_cache,
1007
+ hidden_states=all_hidden_states,
1008
+ attentions=all_self_attns,
1009
+ )
1010
+
1011
+ def _update_causal_mask(
1012
+ self,
1013
+ attention_mask: torch.Tensor,
1014
+ input_tensor: torch.Tensor,
1015
+ cache_position: torch.Tensor,
1016
+ past_key_values: Cache,
1017
+ use_cache: bool,
1018
+ output_attentions: bool,
1019
+ ):
1020
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1021
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1022
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1023
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1024
+
1025
+ if self._attn_implementation == "flash_attention_2":
1026
+ if attention_mask is not None and use_cache:
1027
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
1028
+ if is_padding_right:
1029
+ raise ValueError(
1030
+ "You are attempting to perform batched generation with padding_side='right'"
1031
+ " this may lead to unexpected behaviour for Flash Attention version of Kinoe. Make sure to "
1032
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1033
+ )
1034
+ if attention_mask is not None and 0.0 in attention_mask:
1035
+ return attention_mask
1036
+ return None
1037
+
1038
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1039
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1040
+ # to infer the attention mask.
1041
+
1042
+ # cache_position must be valid here no matter which cache we use
1043
+ past_seen_tokens = cache_position[0] if past_key_values is not None else 0
1044
+ using_static_cache = isinstance(past_key_values, StaticCache)
1045
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1046
+
1047
+ if (
1048
+ self.config._attn_implementation == "sdpa"
1049
+ and not (using_static_cache or using_sliding_window_cache)
1050
+ and not output_attentions
1051
+ ):
1052
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1053
+ attention_mask,
1054
+ inputs_embeds=input_tensor,
1055
+ past_key_values_length=past_seen_tokens,
1056
+ sliding_window=self.config.sliding_window,
1057
+ is_training=self.training,
1058
+ ):
1059
+ return None
1060
+
1061
+ dtype, device = input_tensor.dtype, input_tensor.device
1062
+ min_dtype = torch.finfo(dtype).min
1063
+ sequence_length = input_tensor.shape[1]
1064
+ # SlidingWindowCache
1065
+ if using_sliding_window_cache:
1066
+ target_length = max(sequence_length, self.config.sliding_window)
1067
+ # StaticCache
1068
+ elif using_static_cache:
1069
+ target_length = past_key_values.get_max_length()
1070
+ # DynamicCache or no cache
1071
+ else:
1072
+ target_length = (
1073
+ attention_mask.shape[-1]
1074
+ if isinstance(attention_mask, torch.Tensor)
1075
+ else past_seen_tokens + sequence_length + 1
1076
+ )
1077
+
1078
+ if attention_mask is not None and attention_mask.dim() == 4:
1079
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1080
+ if attention_mask.max() != 0:
1081
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1082
+ causal_mask = attention_mask
1083
+ else:
1084
+ causal_mask = torch.full(
1085
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1086
+ )
1087
+ exclude_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1088
+ if self.config.sliding_window is not None:
1089
+ if not using_sliding_window_cache or sequence_length > self.config.sliding_window:
1090
+ exclude_mask |= torch.arange(target_length, device=device) <= (
1091
+ cache_position.reshape(-1, 1) - self.config.sliding_window
1092
+ )
1093
+ causal_mask *= exclude_mask
1094
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1095
+ if attention_mask is not None:
1096
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1097
+ if attention_mask.dim() == 2:
1098
+ mask_length = attention_mask.shape[-1]
1099
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1100
+ padding_mask = padding_mask == 0
1101
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1102
+ padding_mask, min_dtype
1103
+ )
1104
+
1105
+ if (
1106
+ self.config._attn_implementation == "sdpa"
1107
+ and attention_mask is not None
1108
+ and attention_mask.device.type == "cuda"
1109
+ and not output_attentions
1110
+ ):
1111
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1112
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1113
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1114
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1115
+
1116
+ return causal_mask
1117
+
1118
+
1119
+ class KinoeForCausalLM(KinoePreTrainedModel):
1120
+ _tied_weights_keys = ["lm_head.weight"]
1121
+
1122
+ config_class = KinoeConfig
1123
+
1124
+ def __init__(self, config):
1125
+ super().__init__(config)
1126
+ self.model = KinoeModel(config)
1127
+ self.vocab_size = config.vocab_size
1128
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1129
+
1130
+ # Initialize weights and apply final processing
1131
+ self.post_init()
1132
+
1133
+ def get_input_embeddings(self):
1134
+ return self.model.embed_tokens
1135
+
1136
+ def set_input_embeddings(self, value):
1137
+ self.model.embed_tokens = value
1138
+
1139
+ def get_output_embeddings(self):
1140
+ return self.lm_head
1141
+
1142
+ def set_output_embeddings(self, new_embeddings):
1143
+ self.lm_head = new_embeddings
1144
+
1145
+ def set_decoder(self, decoder):
1146
+ self.model = decoder
1147
+
1148
+ def get_decoder(self):
1149
+ return self.model
1150
+
1151
+ @add_start_docstrings_to_model_forward(KINOE_INPUTS_DOCSTRING)
1152
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1153
+ def forward(
1154
+ self,
1155
+ input_ids: torch.LongTensor = None,
1156
+ attention_mask: Optional[torch.Tensor] = None,
1157
+ position_ids: Optional[torch.LongTensor] = None,
1158
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1159
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1160
+ labels: Optional[torch.LongTensor] = None,
1161
+ use_cache: Optional[bool] = None,
1162
+ output_attentions: Optional[bool] = None,
1163
+ output_hidden_states: Optional[bool] = None,
1164
+ return_dict: Optional[bool] = None,
1165
+ cache_position: Optional[torch.LongTensor] = None,
1166
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1167
+ r"""
1168
+ Args:
1169
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1170
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1171
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1172
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1173
+
1174
+ Returns:
1175
+
1176
+ Example:
1177
+
1178
+ ```python
1179
+ >>> from transformers import AutoTokenizer, KinoeForCausalLM
1180
+
1181
+ >>> model = KinoeForCausalLM.from_pretrained("GENIAC-team-haijima/Kinoe-7B")
1182
+ >>> tokenizer = AutoTokenizer.from_pretrained("GENIAC-team-haijima/Kinoe-7B")
1183
+
1184
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1185
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1186
+
1187
+ >>> # Generate
1188
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1189
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1190
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1191
+ ```"""
1192
+
1193
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1194
+ output_hidden_states = (
1195
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1196
+ )
1197
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1198
+
1199
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1200
+ outputs = self.model(
1201
+ input_ids=input_ids,
1202
+ attention_mask=attention_mask,
1203
+ position_ids=position_ids,
1204
+ past_key_values=past_key_values,
1205
+ inputs_embeds=inputs_embeds,
1206
+ use_cache=use_cache,
1207
+ output_attentions=output_attentions,
1208
+ output_hidden_states=output_hidden_states,
1209
+ return_dict=return_dict,
1210
+ cache_position=cache_position,
1211
+ )
1212
+
1213
+ hidden_states = outputs[0]
1214
+ logits = self.lm_head(hidden_states)
1215
+ logits = logits.float()
1216
+
1217
+ loss = None
1218
+ if labels is not None:
1219
+ # Shift so that tokens < n predict n
1220
+ shift_logits = logits[..., :-1, :].contiguous()
1221
+ shift_labels = labels[..., 1:].contiguous()
1222
+ # Flatten the tokens
1223
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1224
+ shift_labels = shift_labels.view(-1)
1225
+ # Ensure tensors are on the same device
1226
+ shift_labels = shift_labels.to(shift_logits.device)
1227
+ loss_fct = CrossEntropyLoss()
1228
+ loss = loss_fct(shift_logits, shift_labels)
1229
+
1230
+ if not return_dict:
1231
+ output = (logits,) + outputs[1:]
1232
+ return (loss,) + output if loss is not None else output
1233
+
1234
+ return CausalLMOutputWithPast(
1235
+ loss=loss,
1236
+ logits=logits,
1237
+ past_key_values=outputs.past_key_values,
1238
+ hidden_states=outputs.hidden_states,
1239
+ attentions=outputs.attentions,
1240
+ )
1241
+
1242
+ def prepare_inputs_for_generation(
1243
+ self,
1244
+ input_ids,
1245
+ past_key_values=None,
1246
+ attention_mask=None,
1247
+ inputs_embeds=None,
1248
+ cache_position=None,
1249
+ use_cache=True,
1250
+ **kwargs,
1251
+ ):
1252
+ # Omit tokens covered by past_key_values
1253
+ past_length = 0
1254
+ if past_key_values is not None:
1255
+ if isinstance(past_key_values, Cache):
1256
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1257
+ max_cache_length = (
1258
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1259
+ if past_key_values.get_max_length() is not None
1260
+ else None
1261
+ )
1262
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1263
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1264
+ else:
1265
+ cache_length = past_length = past_key_values[0][0].shape[2]
1266
+ max_cache_length = None
1267
+
1268
+ # Keep only the unprocessed tokens:
1269
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1270
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1271
+ # input)
1272
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1273
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1274
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1275
+ # input_ids based on the past_length.
1276
+ elif past_length < input_ids.shape[1]:
1277
+ input_ids = input_ids[:, past_length:]
1278
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1279
+
1280
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1281
+ if (
1282
+ max_cache_length is not None
1283
+ and attention_mask is not None
1284
+ and cache_length + input_ids.shape[1] > max_cache_length
1285
+ ):
1286
+ attention_mask = attention_mask[:, -max_cache_length:]
1287
+
1288
+ position_ids = kwargs.get("position_ids", None)
1289
+ if attention_mask is not None and position_ids is None:
1290
+ # create position_ids on the fly for batch generation
1291
+ position_ids = attention_mask.long().cumsum(-1) - 1
1292
+ position_ids.masked_fill_(attention_mask == 0, 1)
1293
+ if past_key_values:
1294
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1295
+
1296
+ # crop the attention_mask to sliding window size during decode phase if using SlidingWindowCache
1297
+ if (
1298
+ past_length > 0
1299
+ and attention_mask is not None
1300
+ and isinstance(past_key_values, SlidingWindowCache)
1301
+ and attention_mask.shape[1] > past_key_values.sliding_window_size
1302
+ ):
1303
+ attention_mask = attention_mask[:, -past_key_values.sliding_window_size :]
1304
+
1305
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1306
+ if inputs_embeds is not None and past_key_values is None:
1307
+ model_inputs = {"inputs_embeds": inputs_embeds}
1308
+ else:
1309
+ model_inputs = {"input_ids": input_ids.contiguous()}
1310
+
1311
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1312
+ if cache_position is None:
1313
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1314
+ elif use_cache:
1315
+ cache_position = cache_position[-input_length:]
1316
+
1317
+ model_inputs.update(
1318
+ {
1319
+ "position_ids": position_ids,
1320
+ "cache_position": cache_position,
1321
+ "past_key_values": past_key_values,
1322
+ "use_cache": use_cache,
1323
+ "attention_mask": attention_mask,
1324
+ }
1325
+ )
1326
+ return model_inputs
1327
+
1328
+ @staticmethod
1329
+ def _reorder_cache(past_key_values, beam_idx):
1330
+ reordered_past = ()
1331
+ for layer_past in past_key_values:
1332
+ reordered_past += (
1333
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1334
+ )
1335
+ return reordered_past
1336
+
1337
+
1338
+ @add_start_docstrings(
1339
+ """
1340
+ The Kinoe Model transformer with a sequence classification head on top (linear layer).
1341
+
1342
+ [`KinoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1343
+ (e.g. GPT-2) do.
1344
+
1345
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1346
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1347
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1348
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1349
+ each row of the batch).
1350
+ """,
1351
+ KINOE_START_DOCSTRING,
1352
+ )
1353
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Kinoe, LLAMA->KINOE
1354
+ class KinoeForSequenceClassification(KinoePreTrainedModel):
1355
+ def __init__(self, config):
1356
+ super().__init__(config)
1357
+ self.num_labels = config.num_labels
1358
+ self.model = KinoeModel(config)
1359
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1360
+
1361
+ # Initialize weights and apply final processing
1362
+ self.post_init()
1363
+
1364
+ def get_input_embeddings(self):
1365
+ return self.model.embed_tokens
1366
+
1367
+ def set_input_embeddings(self, value):
1368
+ self.model.embed_tokens = value
1369
+
1370
+ @add_start_docstrings_to_model_forward(KINOE_INPUTS_DOCSTRING)
1371
+ def forward(
1372
+ self,
1373
+ input_ids: torch.LongTensor = None,
1374
+ attention_mask: Optional[torch.Tensor] = None,
1375
+ position_ids: Optional[torch.LongTensor] = None,
1376
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1377
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1378
+ labels: Optional[torch.LongTensor] = None,
1379
+ use_cache: Optional[bool] = None,
1380
+ output_attentions: Optional[bool] = None,
1381
+ output_hidden_states: Optional[bool] = None,
1382
+ return_dict: Optional[bool] = None,
1383
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1384
+ r"""
1385
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1386
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1387
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1388
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1389
+ """
1390
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1391
+
1392
+ transformer_outputs = self.model(
1393
+ input_ids,
1394
+ attention_mask=attention_mask,
1395
+ position_ids=position_ids,
1396
+ past_key_values=past_key_values,
1397
+ inputs_embeds=inputs_embeds,
1398
+ use_cache=use_cache,
1399
+ output_attentions=output_attentions,
1400
+ output_hidden_states=output_hidden_states,
1401
+ return_dict=return_dict,
1402
+ )
1403
+ hidden_states = transformer_outputs[0]
1404
+ logits = self.score(hidden_states)
1405
+
1406
+ if input_ids is not None:
1407
+ batch_size = input_ids.shape[0]
1408
+ else:
1409
+ batch_size = inputs_embeds.shape[0]
1410
+
1411
+ if self.config.pad_token_id is None and batch_size != 1:
1412
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1413
+ if self.config.pad_token_id is None:
1414
+ sequence_lengths = -1
1415
+ else:
1416
+ if input_ids is not None:
1417
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1418
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1419
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1420
+ sequence_lengths = sequence_lengths.to(logits.device)
1421
+ else:
1422
+ sequence_lengths = -1
1423
+
1424
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1425
+
1426
+ loss = None
1427
+ if labels is not None:
1428
+ labels = labels.to(logits.device)
1429
+ if self.config.problem_type is None:
1430
+ if self.num_labels == 1:
1431
+ self.config.problem_type = "regression"
1432
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1433
+ self.config.problem_type = "single_label_classification"
1434
+ else:
1435
+ self.config.problem_type = "multi_label_classification"
1436
+
1437
+ if self.config.problem_type == "regression":
1438
+ loss_fct = MSELoss()
1439
+ if self.num_labels == 1:
1440
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1441
+ else:
1442
+ loss = loss_fct(pooled_logits, labels)
1443
+ elif self.config.problem_type == "single_label_classification":
1444
+ loss_fct = CrossEntropyLoss()
1445
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1446
+ elif self.config.problem_type == "multi_label_classification":
1447
+ loss_fct = BCEWithLogitsLoss()
1448
+ loss = loss_fct(pooled_logits, labels)
1449
+ if not return_dict:
1450
+ output = (pooled_logits,) + transformer_outputs[1:]
1451
+ return ((loss,) + output) if loss is not None else output
1452
+
1453
+ return SequenceClassifierOutputWithPast(
1454
+ loss=loss,
1455
+ logits=pooled_logits,
1456
+ past_key_values=transformer_outputs.past_key_values,
1457
+ hidden_states=transformer_outputs.hidden_states,
1458
+ attentions=transformer_outputs.attentions,
1459
+ )
1460
+
1461
+
1462
+ @add_start_docstrings(
1463
+ """
1464
+ The Kinoe Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1465
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1466
+ """,
1467
+ KINOE_START_DOCSTRING,
1468
+ )
1469
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Kinoe, LLAMA->KINOE
1470
+ class KinoeForTokenClassification(KinoePreTrainedModel):
1471
+ def __init__(self, config):
1472
+ super().__init__(config)
1473
+ self.num_labels = config.num_labels
1474
+ self.model = KinoeModel(config)
1475
+ if getattr(config, "classifier_dropout", None) is not None:
1476
+ classifier_dropout = config.classifier_dropout
1477
+ elif getattr(config, "hidden_dropout", None) is not None:
1478
+ classifier_dropout = config.hidden_dropout
1479
+ else:
1480
+ classifier_dropout = 0.1
1481
+ self.dropout = nn.Dropout(classifier_dropout)
1482
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1483
+
1484
+ # Initialize weights and apply final processing
1485
+ self.post_init()
1486
+
1487
+ def get_input_embeddings(self):
1488
+ return self.model.embed_tokens
1489
+
1490
+ def set_input_embeddings(self, value):
1491
+ self.model.embed_tokens = value
1492
+
1493
+ @add_start_docstrings_to_model_forward(KINOE_INPUTS_DOCSTRING)
1494
+ def forward(
1495
+ self,
1496
+ input_ids: torch.LongTensor = None,
1497
+ attention_mask: Optional[torch.Tensor] = None,
1498
+ position_ids: Optional[torch.LongTensor] = None,
1499
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1500
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1501
+ labels: Optional[torch.LongTensor] = None,
1502
+ use_cache: Optional[bool] = None,
1503
+ output_attentions: Optional[bool] = None,
1504
+ output_hidden_states: Optional[bool] = None,
1505
+ return_dict: Optional[bool] = None,
1506
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1507
+ r"""
1508
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1509
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1510
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1511
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1512
+ """
1513
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1514
+
1515
+ outputs = self.model(
1516
+ input_ids,
1517
+ attention_mask=attention_mask,
1518
+ position_ids=position_ids,
1519
+ past_key_values=past_key_values,
1520
+ inputs_embeds=inputs_embeds,
1521
+ use_cache=use_cache,
1522
+ output_attentions=output_attentions,
1523
+ output_hidden_states=output_hidden_states,
1524
+ return_dict=return_dict,
1525
+ )
1526
+ sequence_output = outputs[0]
1527
+ sequence_output = self.dropout(sequence_output)
1528
+ logits = self.score(sequence_output)
1529
+
1530
+ loss = None
1531
+ if labels is not None:
1532
+ loss_fct = CrossEntropyLoss()
1533
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1534
+
1535
+ if not return_dict:
1536
+ output = (logits,) + outputs[2:]
1537
+ return ((loss,) + output) if loss is not None else output
1538
+
1539
+ return TokenClassifierOutput(
1540
+ loss=loss,
1541
+ logits=logits,
1542
+ hidden_states=outputs.hidden_states,
1543
+ attentions=outputs.attentions,
1544
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eff65de1c7e7a37c6bbeefed0b15cff8a530409c45ae5344cb34e3f7fff0ed20
3
+ size 14283485222
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "</s|LLM-jp>"
4
+ ],
5
+ "bos_token": {
6
+ "content": "<s|LLM-jp>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "cls_token": "<CLS|LLM-jp>",
13
+ "eos_token": "<EOD|LLM-jp>",
14
+ "mask_token": "<mask|LLM-jp>",
15
+ "pad_token": "<pad|LLM-jp>",
16
+ "sep_token": "<SEP|LLM-jp>",
17
+ "unk_token": {
18
+ "content": "<unk|LLM-jp>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<unk|LLM-jp>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<s|LLM-jp>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s|LLM-jp>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "55392": {
28
+ "content": "<EOD|LLM-jp>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "55393": {
36
+ "content": "<SEP|LLM-jp>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "55394": {
44
+ "content": "<pad|LLM-jp>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "55395": {
52
+ "content": "<CLS|LLM-jp>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "55396": {
60
+ "content": "<mask|LLM-jp>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ }
67
+ },
68
+ "additional_special_tokens": [
69
+ "</s|LLM-jp>"
70
+ ],
71
+ "bos_token": "<s|LLM-jp>",
72
+ "clean_up_tokenization_spaces": false,
73
+ "cls_token": "<CLS|LLM-jp>",
74
+ "eod_token": "<EOD|LLM-jp>",
75
+ "eos_token": "<EOD|LLM-jp>",
76
+ "extra_ids": 0,
77
+ "mask_token": "<mask|LLM-jp>",
78
+ "model_max_length": 1000000000000000019884624838656,
79
+ "pad_token": "<pad|LLM-jp>",
80
+ "sep_token": "<SEP|LLM-jp>",
81
+ "sp_model_kwargs": {},
82
+ "tokenizer_class": "PreTrainedTokenizerFast",
83
+ "unk_token": "<unk|LLM-jp>"
84
+ }