jmvcoelho commited on
Commit
9e24ace
·
verified ·
1 Parent(s): 96d6e49

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": ".",
3
+ "architectures": [
4
+ "Qwen2BAForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoModel": "modeling_qwen2_ba.Qwen2ModelBA",
8
+ "AutoModelForCausalLM": "modeling_qwen2_ba.Qwen2ForCausalLMBA",
9
+ "AutoConfig": "configuration_qwen2ba.Qwen2BAConfig"
10
+ },
11
+ "attention_dropout": 0.0,
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151643,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 896,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 4864,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 24,
20
+ "model_type": "qwen2ba",
21
+ "num_attention_heads": 14,
22
+ "num_hidden_layers": 24,
23
+ "num_key_value_heads": 2,
24
+ "rms_norm_eps": 1e-06,
25
+ "rope_theta": 1000000.0,
26
+ "sliding_window": null,
27
+ "tie_word_embeddings": true,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.44.2",
30
+ "use_cache": true,
31
+ "use_mrope": false,
32
+ "use_sliding_window": false,
33
+ "vocab_size": 151936,
34
+ "output_attentions": false
35
+ }
configuration_qwen2ba.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. 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
+ """Qwen2 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 Qwen2BAConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
27
+ Qwen2 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
29
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen2Model`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 22016):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 32):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
70
+ Whether to use sliding window attention.
71
+ sliding_window (`int`, *optional*, defaults to 4096):
72
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
73
+ max_window_layers (`int`, *optional*, defaults to 28):
74
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
75
+ attention_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for the attention probabilities.
77
+
78
+ ```python
79
+ >>> from transformers import Qwen2Model, Qwen2Config
80
+
81
+ >>> # Initializing a Qwen2 style configuration
82
+ >>> configuration = Qwen2Config()
83
+
84
+ >>> # Initializing a model from the Qwen2-7B style configuration
85
+ >>> model = Qwen2Model(configuration)
86
+
87
+ >>> # Accessing the model configuration
88
+ >>> configuration = model.config
89
+ ```"""
90
+
91
+ model_type = "qwen2ba"
92
+ keys_to_ignore_at_inference = ["past_key_values"]
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=151936,
97
+ hidden_size=4096,
98
+ intermediate_size=22016,
99
+ num_hidden_layers=32,
100
+ num_attention_heads=32,
101
+ num_key_value_heads=32,
102
+ hidden_act="silu",
103
+ max_position_embeddings=32768,
104
+ initializer_range=0.02,
105
+ rms_norm_eps=1e-6,
106
+ use_cache=True,
107
+ tie_word_embeddings=False,
108
+ rope_theta=10000.0,
109
+ use_sliding_window=False,
110
+ sliding_window=4096,
111
+ max_window_layers=28,
112
+ attention_dropout=0.0,
113
+ **kwargs,
114
+ ):
115
+ self.vocab_size = vocab_size
116
+ self.max_position_embeddings = max_position_embeddings
117
+ self.hidden_size = hidden_size
118
+ self.intermediate_size = intermediate_size
119
+ self.num_hidden_layers = num_hidden_layers
120
+ self.num_attention_heads = num_attention_heads
121
+ self.use_sliding_window = use_sliding_window
122
+ self.sliding_window = sliding_window if use_sliding_window else None
123
+ self.max_window_layers = max_window_layers
124
+
125
+ # for backward compatibility
126
+ if num_key_value_heads is None:
127
+ num_key_value_heads = num_attention_heads
128
+
129
+ self.num_key_value_heads = num_key_value_heads
130
+ self.hidden_act = hidden_act
131
+ self.initializer_range = initializer_range
132
+ self.rms_norm_eps = rms_norm_eps
133
+ self.use_cache = use_cache
134
+ self.rope_theta = rope_theta
135
+ self.attention_dropout = attention_dropout
136
+
137
+ super().__init__(
138
+ tie_word_embeddings=tie_word_embeddings,
139
+ **kwargs,
140
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": false,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 2048,
6
+ "transformers_version": "4.37.0"
7
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88c142557820ccad55bb59756bfcfcf891de9cc6202816bd346445188a0ed342
3
+ size 988097824
modeling_qwen2_ba.py ADDED
@@ -0,0 +1,1433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. 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 Qwen2 model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_qwen2ba import Qwen2BAConfig as Qwen2Config
49
+
50
+
51
+ if is_flash_attn_2_available():
52
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
59
+ _CONFIG_FOR_DOC = "Qwen2Config"
60
+
61
+
62
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
63
+ def _prepare_4d_causal_attention_mask_with_cache_position(
64
+ attention_mask: torch.Tensor,
65
+ sequence_length: int,
66
+ target_length: int,
67
+ dtype: torch.dtype,
68
+ device: torch.device,
69
+ min_dtype: float,
70
+ cache_position: torch.Tensor,
71
+ batch_size: int,
72
+ ):
73
+ """
74
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
75
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
76
+
77
+ Args:
78
+ attention_mask (`torch.Tensor`):
79
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
80
+ sequence_length (`int`):
81
+ The sequence length being processed.
82
+ target_length (`int`):
83
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
84
+ dtype (`torch.dtype`):
85
+ The dtype to use for the 4D attention mask.
86
+ device (`torch.device`):
87
+ The device to plcae the 4D attention mask on.
88
+ min_dtype (`float`):
89
+ The minimum value representable with the dtype `dtype`.
90
+ cache_position (`torch.Tensor`):
91
+ Indices depicting the position of the input sequence tokens in the sequence.
92
+ batch_size (`torch.Tensor`):
93
+ Batch size.
94
+ """
95
+ if attention_mask is not None and attention_mask.dim() == 4:
96
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
97
+ causal_mask = attention_mask
98
+ else:
99
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
100
+ if sequence_length != 1:
101
+ causal_mask = torch.triu(causal_mask, diagonal=1)
102
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
103
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
104
+ if attention_mask is not None:
105
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
106
+ mask_length = attention_mask.shape[-1]
107
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
108
+ padding_mask = padding_mask == 0
109
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
110
+ padding_mask, min_dtype
111
+ )
112
+
113
+ return causal_mask
114
+
115
+
116
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
117
+ class Qwen2RMSNorm(nn.Module):
118
+ def __init__(self, hidden_size, eps=1e-6):
119
+ """
120
+ Qwen2RMSNorm is equivalent to T5LayerNorm
121
+ """
122
+ super().__init__()
123
+ self.weight = nn.Parameter(torch.ones(hidden_size))
124
+ self.variance_epsilon = eps
125
+
126
+ def forward(self, hidden_states):
127
+ input_dtype = hidden_states.dtype
128
+ hidden_states = hidden_states.to(torch.float32)
129
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
130
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
131
+ return self.weight * hidden_states.to(input_dtype)
132
+
133
+ def extra_repr(self):
134
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
135
+
136
+
137
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2
138
+ class Qwen2RotaryEmbedding(nn.Module):
139
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
140
+ super().__init__()
141
+
142
+ self.dim = dim
143
+ self.max_position_embeddings = max_position_embeddings
144
+ self.base = base
145
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
146
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
147
+
148
+ # Build here to make `torch.jit.trace` work.
149
+ self._set_cos_sin_cache(
150
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
151
+ )
152
+
153
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
154
+ self.max_seq_len_cached = seq_len
155
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
156
+
157
+ freqs = torch.outer(t, self.inv_freq)
158
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
159
+ emb = torch.cat((freqs, freqs), dim=-1)
160
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
161
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
162
+
163
+ def forward(self, x, seq_len=None):
164
+ # x: [bs, num_attention_heads, seq_len, head_size]
165
+ if seq_len > self.max_seq_len_cached:
166
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
167
+
168
+ return (
169
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
170
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
171
+ )
172
+
173
+
174
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
175
+ def rotate_half(x):
176
+ """Rotates half the hidden dims of the input."""
177
+ x1 = x[..., : x.shape[-1] // 2]
178
+ x2 = x[..., x.shape[-1] // 2 :]
179
+ return torch.cat((-x2, x1), dim=-1)
180
+
181
+
182
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
183
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
184
+ """Applies Rotary Position Embedding to the query and key tensors.
185
+
186
+ Args:
187
+ q (`torch.Tensor`): The query tensor.
188
+ k (`torch.Tensor`): The key tensor.
189
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
190
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
191
+ position_ids (`torch.Tensor`):
192
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
193
+ used to pass offsetted position ids when working with a KV-cache.
194
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
195
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
196
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
197
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
198
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
199
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
200
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
201
+ Returns:
202
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
203
+ """
204
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
205
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
206
+ q_embed = (q * cos) + (rotate_half(q) * sin)
207
+ k_embed = (k * cos) + (rotate_half(k) * sin)
208
+ return q_embed, k_embed
209
+
210
+
211
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
212
+ class Qwen2MLP(nn.Module):
213
+ def __init__(self, config):
214
+ super().__init__()
215
+ self.hidden_size = config.hidden_size
216
+ self.intermediate_size = config.intermediate_size
217
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
218
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
219
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
220
+ self.act_fn = ACT2FN[config.hidden_act]
221
+
222
+ def forward(self, hidden_state):
223
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
224
+
225
+
226
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
227
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
228
+ """
229
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
230
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
231
+ """
232
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
233
+ if n_rep == 1:
234
+ return hidden_states
235
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
236
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
237
+
238
+
239
+ class Qwen2Attention(nn.Module):
240
+ """
241
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
242
+ and "Generating Long Sequences with Sparse Transformers".
243
+ """
244
+
245
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
246
+ super().__init__()
247
+ self.config = config
248
+ self.layer_idx = layer_idx
249
+ if layer_idx is None:
250
+ logger.warning_once(
251
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
252
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
253
+ "when creating this class."
254
+ )
255
+
256
+ self.hidden_size = config.hidden_size
257
+ self.num_heads = config.num_attention_heads
258
+ self.head_dim = self.hidden_size // self.num_heads
259
+ self.num_key_value_heads = config.num_key_value_heads
260
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
261
+ self.max_position_embeddings = config.max_position_embeddings
262
+ self.rope_theta = config.rope_theta
263
+ self.is_causal = False
264
+ self.attention_dropout = config.attention_dropout
265
+
266
+ print(f"Is causal: {self.is_causal}")
267
+ if (self.head_dim * self.num_heads) != self.hidden_size:
268
+ raise ValueError(
269
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
270
+ f" and `num_heads`: {self.num_heads})."
271
+ )
272
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
273
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
274
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
275
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
276
+
277
+ self.rotary_emb = Qwen2RotaryEmbedding(
278
+ self.head_dim,
279
+ max_position_embeddings=self.max_position_embeddings,
280
+ base=self.rope_theta,
281
+ )
282
+
283
+ def forward(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ attention_mask: Optional[torch.Tensor] = None,
287
+ position_ids: Optional[torch.LongTensor] = None,
288
+ past_key_value: Optional[Cache] = None,
289
+ output_attentions: bool = False,
290
+ use_cache: bool = False,
291
+ cache_position: Optional[torch.LongTensor] = None,
292
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
293
+ bsz, q_len, _ = hidden_states.size()
294
+
295
+ query_states = self.q_proj(hidden_states)
296
+ key_states = self.k_proj(hidden_states)
297
+ value_states = self.v_proj(hidden_states)
298
+
299
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
300
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
301
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
302
+
303
+ kv_seq_len = key_states.shape[-2]
304
+ if past_key_value is not None:
305
+ if self.layer_idx is None:
306
+ raise ValueError(
307
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
308
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
309
+ "with a layer index."
310
+ )
311
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
312
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
313
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
314
+
315
+ if past_key_value is not None:
316
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
317
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
318
+
319
+ # repeat k/v heads if n_kv_heads < n_heads
320
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
321
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
322
+
323
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
324
+
325
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
326
+ raise ValueError(
327
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
328
+ f" {attn_weights.size()}"
329
+ )
330
+
331
+ if attention_mask is not None: # no matter the length, we just slice it
332
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
333
+ attn_weights = attn_weights + causal_mask
334
+
335
+ # upcast attention to fp32
336
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
337
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
338
+ attn_output = torch.matmul(attn_weights, value_states)
339
+
340
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
341
+ raise ValueError(
342
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
343
+ f" {attn_output.size()}"
344
+ )
345
+
346
+ attn_output = attn_output.transpose(1, 2).contiguous()
347
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
348
+
349
+ attn_output = self.o_proj(attn_output)
350
+
351
+ if not output_attentions:
352
+ attn_weights = None
353
+
354
+ return attn_output, attn_weights, past_key_value
355
+
356
+
357
+ class Qwen2FlashAttention2(Qwen2Attention):
358
+ """
359
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
360
+ as the weights of the module stays untouched. The only required change would be on the forward pass
361
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
362
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
363
+ config.max_window_layers layers.
364
+ """
365
+
366
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
367
+ def __init__(self, *args, **kwargs):
368
+ super().__init__(*args, **kwargs)
369
+
370
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
371
+ # 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.
372
+ # 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).
373
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
374
+
375
+ def forward(
376
+ self,
377
+ hidden_states: torch.Tensor,
378
+ attention_mask: Optional[torch.Tensor] = None,
379
+ position_ids: Optional[torch.LongTensor] = None,
380
+ past_key_value: Optional[Cache] = None,
381
+ output_attentions: bool = False,
382
+ use_cache: bool = False,
383
+ cache_position: Optional[torch.LongTensor] = None,
384
+ ):
385
+ bsz, q_len, _ = hidden_states.size()
386
+
387
+ query_states = self.q_proj(hidden_states)
388
+ key_states = self.k_proj(hidden_states)
389
+ value_states = self.v_proj(hidden_states)
390
+
391
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
392
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
393
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
394
+
395
+ kv_seq_len = key_states.shape[-2]
396
+ if past_key_value is not None:
397
+ if self.layer_idx is None:
398
+ raise ValueError(
399
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
400
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
401
+ "with a layer index."
402
+ )
403
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
404
+
405
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
406
+ rotary_seq_len = (
407
+ max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
408
+ )
409
+
410
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
411
+
412
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
413
+
414
+ if past_key_value is not None:
415
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
416
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
417
+ if (
418
+ getattr(self.config, "sliding_window", None) is not None
419
+ and kv_seq_len > self.config.sliding_window
420
+ and cache_has_contents
421
+ ):
422
+ slicing_tokens = 1 - self.config.sliding_window
423
+
424
+ past_key = past_key_value[self.layer_idx][0]
425
+ past_value = past_key_value[self.layer_idx][1]
426
+
427
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
428
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
429
+
430
+ if past_key.shape[-2] != self.config.sliding_window - 1:
431
+ raise ValueError(
432
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
433
+ f" {past_key.shape}"
434
+ )
435
+
436
+ if attention_mask is not None:
437
+ attention_mask = attention_mask[:, slicing_tokens:]
438
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
439
+
440
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
441
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
442
+
443
+ # repeat k/v heads if n_kv_heads < n_heads
444
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
445
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
446
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
447
+
448
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
449
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
450
+ # cast them back in float16 just to be sure everything works as expected.
451
+ input_dtype = query_states.dtype
452
+ if input_dtype == torch.float32:
453
+ if torch.is_autocast_enabled():
454
+ target_dtype = torch.get_autocast_gpu_dtype()
455
+ # Handle the case where the model is quantized
456
+ elif hasattr(self.config, "_pre_quantization_dtype"):
457
+ target_dtype = self.config._pre_quantization_dtype
458
+ else:
459
+ target_dtype = self.q_proj.weight.dtype
460
+
461
+ logger.warning_once(
462
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
463
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
464
+ f" {target_dtype}."
465
+ )
466
+
467
+ query_states = query_states.to(target_dtype)
468
+ key_states = key_states.to(target_dtype)
469
+ value_states = value_states.to(target_dtype)
470
+
471
+ # Reashape to the expected shape for Flash Attention
472
+ query_states = query_states.transpose(1, 2)
473
+ key_states = key_states.transpose(1, 2)
474
+ value_states = value_states.transpose(1, 2)
475
+
476
+ if (
477
+ self.config.use_sliding_window
478
+ and getattr(self.config, "sliding_window", None) is not None
479
+ and self.layer_idx >= self.config.max_window_layers
480
+ ):
481
+ sliding_window = self.config.sliding_window
482
+ else:
483
+ sliding_window = None
484
+
485
+ attn_output = _flash_attention_forward(
486
+ query_states,
487
+ key_states,
488
+ value_states,
489
+ attention_mask,
490
+ q_len,
491
+ position_ids=position_ids,
492
+ dropout=dropout_rate,
493
+ sliding_window=sliding_window,
494
+ is_causal=self.is_causal,
495
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
496
+ )
497
+
498
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
499
+ attn_output = self.o_proj(attn_output)
500
+
501
+ if not output_attentions:
502
+ attn_weights = None
503
+
504
+ return attn_output, attn_weights, past_key_value
505
+
506
+
507
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralSdpaAttention with Mixtral->Qwen2
508
+ class Qwen2SdpaAttention(Qwen2Attention):
509
+ """
510
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
511
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
512
+ SDPA API.
513
+ """
514
+
515
+ # Adapted from Qwen2Attention.forward
516
+ def forward(
517
+ self,
518
+ hidden_states: torch.Tensor,
519
+ attention_mask: Optional[torch.Tensor] = None,
520
+ position_ids: Optional[torch.LongTensor] = None,
521
+ past_key_value: Optional[Cache] = None,
522
+ output_attentions: bool = False,
523
+ use_cache: bool = False,
524
+ cache_position: Optional[torch.LongTensor] = None,
525
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
526
+ if output_attentions:
527
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
528
+ logger.warning_once(
529
+ "Qwen2ModelBA is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
530
+ '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.'
531
+ )
532
+ return super().forward(
533
+ hidden_states=hidden_states,
534
+ attention_mask=attention_mask,
535
+ position_ids=position_ids,
536
+ past_key_value=past_key_value,
537
+ output_attentions=output_attentions,
538
+ use_cache=use_cache,
539
+ )
540
+
541
+ bsz, q_len, _ = hidden_states.size()
542
+
543
+ query_states = self.q_proj(hidden_states)
544
+ key_states = self.k_proj(hidden_states)
545
+ value_states = self.v_proj(hidden_states)
546
+
547
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
548
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
549
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
550
+
551
+ kv_seq_len = key_states.shape[-2]
552
+ if past_key_value is not None:
553
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
554
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
555
+
556
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
557
+
558
+ if past_key_value is not None:
559
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
560
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
561
+
562
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
563
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
564
+
565
+ causal_mask = attention_mask
566
+ if attention_mask is not None: # no matter the length, we just slice it
567
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
568
+
569
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
570
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
571
+ if query_states.device.type == "cuda" and attention_mask is not None:
572
+ query_states = query_states.contiguous()
573
+ key_states = key_states.contiguous()
574
+ value_states = value_states.contiguous()
575
+
576
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
577
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
578
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
579
+ is_causal = True if causal_mask is None and q_len > 1 else False
580
+
581
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
582
+ query_states,
583
+ key_states,
584
+ value_states,
585
+ attn_mask=causal_mask,
586
+ dropout_p=self.attention_dropout if self.training else 0.0,
587
+ is_causal=is_causal,
588
+ )
589
+
590
+ attn_output = attn_output.transpose(1, 2).contiguous()
591
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
592
+
593
+ attn_output = self.o_proj(attn_output)
594
+
595
+ return attn_output, None, past_key_value
596
+
597
+
598
+ QWEN2_ATTENTION_CLASSES = {
599
+ "eager": Qwen2Attention,
600
+ "flash_attention_2": Qwen2FlashAttention2,
601
+ "sdpa": Qwen2SdpaAttention,
602
+ }
603
+
604
+
605
+ class Qwen2DecoderLayer(nn.Module):
606
+ def __init__(self, config: Qwen2Config, layer_idx: int):
607
+ super().__init__()
608
+ self.hidden_size = config.hidden_size
609
+
610
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
611
+ logger.warning_once(
612
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
613
+ "unexpected results may be encountered."
614
+ )
615
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
616
+
617
+ self.mlp = Qwen2MLP(config)
618
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
619
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
620
+
621
+ def forward(
622
+ self,
623
+ hidden_states: torch.Tensor,
624
+ attention_mask: Optional[torch.Tensor] = None,
625
+ position_ids: Optional[torch.LongTensor] = None,
626
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
627
+ output_attentions: Optional[bool] = False,
628
+ use_cache: Optional[bool] = False,
629
+ cache_position: Optional[torch.LongTensor] = None,
630
+ **kwargs,
631
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
632
+ """
633
+ Args:
634
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
635
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
636
+ `(batch, sequence_length)` where padding elements are indicated by 0.
637
+ output_attentions (`bool`, *optional*):
638
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
639
+ returned tensors for more detail.
640
+ use_cache (`bool`, *optional*):
641
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
642
+ (see `past_key_values`).
643
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
644
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
645
+ Indices depicting the position of the input sequence tokens in the sequence.
646
+ kwargs (`dict`, *optional*):
647
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
648
+ into the model
649
+ """
650
+
651
+ residual = hidden_states
652
+
653
+ hidden_states = self.input_layernorm(hidden_states)
654
+
655
+ # Self Attention
656
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
657
+ hidden_states=hidden_states,
658
+ attention_mask=attention_mask,
659
+ position_ids=position_ids,
660
+ past_key_value=past_key_value,
661
+ output_attentions=output_attentions,
662
+ use_cache=use_cache,
663
+ cache_position=cache_position,
664
+ )
665
+ hidden_states = residual + hidden_states
666
+
667
+ # Fully Connected
668
+ residual = hidden_states
669
+ hidden_states = self.post_attention_layernorm(hidden_states)
670
+ hidden_states = self.mlp(hidden_states)
671
+ hidden_states = residual + hidden_states
672
+
673
+ outputs = (hidden_states,)
674
+
675
+ if output_attentions:
676
+ outputs += (self_attn_weights,)
677
+
678
+ if use_cache:
679
+ outputs += (present_key_value,)
680
+
681
+ return outputs
682
+
683
+
684
+ QWEN2_START_DOCSTRING = r"""
685
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
686
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
687
+ etc.)
688
+
689
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
690
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
691
+ and behavior.
692
+
693
+ Parameters:
694
+ config ([`Qwen2Config`]):
695
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
696
+ load the weights associated with the model, only the configuration. Check out the
697
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
698
+ """
699
+
700
+
701
+ @add_start_docstrings(
702
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
703
+ QWEN2_START_DOCSTRING,
704
+ )
705
+ class Qwen2PreTrainedModel(PreTrainedModel):
706
+ config_class = Qwen2Config
707
+ base_model_prefix = "model"
708
+ supports_gradient_checkpointing = True
709
+ _no_split_modules = ["Qwen2DecoderLayer"]
710
+ _skip_keys_device_placement = "past_key_values"
711
+ _supports_flash_attn_2 = True
712
+ _supports_sdpa = True
713
+ _supports_cache_class = True
714
+
715
+ def _init_weights(self, module):
716
+ std = self.config.initializer_range
717
+ if isinstance(module, nn.Linear):
718
+ module.weight.data.normal_(mean=0.0, std=std)
719
+ if module.bias is not None:
720
+ module.bias.data.zero_()
721
+ elif isinstance(module, nn.Embedding):
722
+ module.weight.data.normal_(mean=0.0, std=std)
723
+ if module.padding_idx is not None:
724
+ module.weight.data[module.padding_idx].zero_()
725
+
726
+
727
+ QWEN2_INPUTS_DOCSTRING = r"""
728
+ Args:
729
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
730
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
731
+ it.
732
+
733
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
734
+ [`PreTrainedTokenizer.__call__`] for details.
735
+
736
+ [What are input IDs?](../glossary#input-ids)
737
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
738
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
739
+
740
+ - 1 for tokens that are **not masked**,
741
+ - 0 for tokens that are **masked**.
742
+
743
+ [What are attention masks?](../glossary#attention-mask)
744
+
745
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
746
+ [`PreTrainedTokenizer.__call__`] for details.
747
+
748
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
749
+ `past_key_values`).
750
+
751
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
752
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
753
+ information on the default strategy.
754
+
755
+ - 1 indicates the head is **not masked**,
756
+ - 0 indicates the head is **masked**.
757
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
758
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
759
+ config.n_positions - 1]`.
760
+
761
+ [What are position IDs?](../glossary#position-ids)
762
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
763
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
764
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
765
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
766
+
767
+ Two formats are allowed:
768
+ - a [`~cache_utils.Cache`] instance;
769
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
770
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
771
+ cache format.
772
+
773
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
774
+ legacy cache format will be returned.
775
+
776
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
777
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
778
+ of shape `(batch_size, sequence_length)`.
779
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
780
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
781
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
782
+ model's internal embedding lookup matrix.
783
+ use_cache (`bool`, *optional*):
784
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
785
+ `past_key_values`).
786
+ output_attentions (`bool`, *optional*):
787
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
788
+ tensors for more detail.
789
+ output_hidden_states (`bool`, *optional*):
790
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
791
+ more detail.
792
+ return_dict (`bool`, *optional*):
793
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
794
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
795
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
796
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
797
+ the complete sequence length.
798
+ """
799
+
800
+
801
+ @add_start_docstrings(
802
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
803
+ QWEN2_START_DOCSTRING,
804
+ )
805
+ class Qwen2ModelBA(Qwen2PreTrainedModel):
806
+ """
807
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
808
+
809
+ Args:
810
+ config: Qwen2Config
811
+ """
812
+
813
+ def __init__(self, config: Qwen2Config):
814
+ super().__init__(config)
815
+ self.padding_idx = config.pad_token_id
816
+ self.vocab_size = config.vocab_size
817
+
818
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
819
+ self.layers = nn.ModuleList(
820
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
821
+ )
822
+ self._attn_implementation = config._attn_implementation
823
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
824
+
825
+ self.gradient_checkpointing = False
826
+ # Initialize weights and apply final processing
827
+ self.post_init()
828
+
829
+ def get_input_embeddings(self):
830
+ return self.embed_tokens
831
+
832
+ def set_input_embeddings(self, value):
833
+ self.embed_tokens = value
834
+
835
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
836
+ def forward(
837
+ self,
838
+ input_ids: torch.LongTensor = None,
839
+ attention_mask: Optional[torch.Tensor] = None,
840
+ position_ids: Optional[torch.LongTensor] = None,
841
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
842
+ inputs_embeds: Optional[torch.FloatTensor] = None,
843
+ use_cache: Optional[bool] = None,
844
+ output_attentions: Optional[bool] = None,
845
+ output_hidden_states: Optional[bool] = None,
846
+ return_dict: Optional[bool] = None,
847
+ cache_position: Optional[torch.LongTensor] = None,
848
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
849
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
850
+
851
+ output_hidden_states = (
852
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
853
+ )
854
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
855
+
856
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
857
+
858
+ if (input_ids is None) ^ (inputs_embeds is not None):
859
+ raise ValueError(
860
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
861
+ )
862
+
863
+ if self.gradient_checkpointing and self.training:
864
+ if use_cache:
865
+ logger.warning_once(
866
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
867
+ )
868
+ use_cache = False
869
+
870
+ use_legacy_cache = False
871
+ if use_cache and not isinstance(past_key_values, Cache) and not self.training:
872
+ use_legacy_cache = True
873
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
874
+ logger.warning_once(
875
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
876
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
877
+ )
878
+
879
+ if inputs_embeds is None:
880
+ inputs_embeds = self.embed_tokens(input_ids)
881
+
882
+ _attention_mask = attention_mask
883
+
884
+ if cache_position is None:
885
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
886
+ cache_position = torch.arange(
887
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
888
+ )
889
+ if position_ids is None:
890
+ position_ids = cache_position.unsqueeze(0)
891
+
892
+ causal_mask = self._update_causal_mask(
893
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
894
+ )
895
+
896
+ hidden_states = inputs_embeds
897
+
898
+ # decoder layers
899
+ all_hidden_states = () if output_hidden_states else None
900
+ all_self_attns = () if output_attentions else None
901
+ next_decoder_cache = None
902
+
903
+ for decoder_layer in self.layers:
904
+ if output_hidden_states:
905
+ all_hidden_states += (hidden_states,)
906
+
907
+ if self.gradient_checkpointing and self.training:
908
+ layer_outputs = self._gradient_checkpointing_func(
909
+ decoder_layer.__call__,
910
+ hidden_states,
911
+ causal_mask,
912
+ position_ids,
913
+ past_key_values,
914
+ output_attentions,
915
+ use_cache,
916
+ cache_position,
917
+ )
918
+ else:
919
+ layer_outputs = decoder_layer(
920
+ hidden_states,
921
+ attention_mask=causal_mask,
922
+ position_ids=position_ids,
923
+ past_key_value=past_key_values,
924
+ output_attentions=output_attentions,
925
+ use_cache=use_cache,
926
+ cache_position=cache_position,
927
+ )
928
+
929
+ hidden_states = layer_outputs[0]
930
+
931
+ if use_cache:
932
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
933
+
934
+ if output_attentions:
935
+ all_self_attns += (layer_outputs[1],)
936
+
937
+ hidden_states = self.norm(hidden_states)
938
+
939
+ # add hidden states from the last decoder layer
940
+ if output_hidden_states:
941
+ all_hidden_states += (hidden_states,)
942
+
943
+ # attention_mask_ = _attention_mask * _attention_mask.cumsum(dim=1)
944
+ # s = hidden_states * attention_mask_.unsqueeze(-1).float()
945
+ # d = attention_mask_.sum(dim=1, keepdim=True).unsqueeze(1).float() /_attention_mask.sum(dim=1, keepdim=True).unsqueeze(1).float()
946
+
947
+ # hidden_states = s / d
948
+
949
+ next_cache = None
950
+ if use_cache:
951
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
952
+
953
+ if not return_dict:
954
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
955
+ return BaseModelOutputWithPast(
956
+ last_hidden_state=hidden_states,
957
+ past_key_values=next_cache,
958
+ hidden_states=all_hidden_states,
959
+ attentions=all_self_attns,
960
+ )
961
+
962
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
963
+ def _update_causal_mask(
964
+ self,
965
+ attention_mask: torch.Tensor,
966
+ input_tensor: torch.Tensor,
967
+ cache_position: torch.Tensor,
968
+ past_key_values: Cache,
969
+ output_attentions: bool,
970
+ ):
971
+ # 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
972
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
973
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
974
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
975
+
976
+ if self.config._attn_implementation == "flash_attention_2":
977
+ if attention_mask is not None and 0.0 in attention_mask:
978
+ return attention_mask
979
+ return None
980
+
981
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
982
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
983
+ # to infer the attention mask.
984
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
985
+ using_static_cache = isinstance(past_key_values, StaticCache)
986
+
987
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
988
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
989
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
990
+ attention_mask,
991
+ inputs_embeds=input_tensor,
992
+ past_key_values_length=past_seen_tokens,
993
+ is_training=self.training,
994
+ ):
995
+ return None
996
+
997
+ dtype, device = input_tensor.dtype, input_tensor.device
998
+ min_dtype = torch.finfo(dtype).min
999
+ sequence_length = input_tensor.shape[1]
1000
+ if using_static_cache:
1001
+ target_length = past_key_values.get_max_length()
1002
+ else:
1003
+ target_length = (
1004
+ attention_mask.shape[-1]
1005
+ if isinstance(attention_mask, torch.Tensor)
1006
+ else past_seen_tokens + sequence_length + 1
1007
+ )
1008
+
1009
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1010
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1011
+ attention_mask,
1012
+ sequence_length=sequence_length,
1013
+ target_length=target_length,
1014
+ dtype=dtype,
1015
+ device=device,
1016
+ min_dtype=min_dtype,
1017
+ cache_position=cache_position,
1018
+ batch_size=input_tensor.shape[0],
1019
+ )
1020
+
1021
+ if (
1022
+ self.config._attn_implementation == "sdpa"
1023
+ and attention_mask is not None
1024
+ and attention_mask.device.type == "cuda"
1025
+ and not output_attentions
1026
+ ):
1027
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1028
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1029
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1030
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1031
+
1032
+ return causal_mask
1033
+
1034
+
1035
+ class Qwen2ForCausalLMBA(Qwen2PreTrainedModel):
1036
+ _tied_weights_keys = ["lm_head.weight"]
1037
+
1038
+ def __init__(self, config):
1039
+ super().__init__(config)
1040
+ self.model = Qwen2ModelBA(config)
1041
+ self.vocab_size = config.vocab_size
1042
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1043
+
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ def get_input_embeddings(self):
1048
+ return self.model.embed_tokens
1049
+
1050
+ def set_input_embeddings(self, value):
1051
+ self.model.embed_tokens = value
1052
+
1053
+ def get_output_embeddings(self):
1054
+ return self.lm_head
1055
+
1056
+ def set_output_embeddings(self, new_embeddings):
1057
+ self.lm_head = new_embeddings
1058
+
1059
+ def set_decoder(self, decoder):
1060
+ self.model = decoder
1061
+
1062
+ def get_decoder(self):
1063
+ return self.model
1064
+
1065
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1066
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1067
+ def forward(
1068
+ self,
1069
+ input_ids: torch.LongTensor = None,
1070
+ attention_mask: Optional[torch.Tensor] = None,
1071
+ position_ids: Optional[torch.LongTensor] = None,
1072
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1073
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1074
+ labels: Optional[torch.LongTensor] = None,
1075
+ use_cache: Optional[bool] = None,
1076
+ output_attentions: Optional[bool] = None,
1077
+ output_hidden_states: Optional[bool] = None,
1078
+ return_dict: Optional[bool] = None,
1079
+ cache_position: Optional[torch.LongTensor] = None,
1080
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1081
+ r"""
1082
+ Args:
1083
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1084
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1085
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1086
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1087
+
1088
+ Returns:
1089
+
1090
+ Example:
1091
+
1092
+ ```python
1093
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1094
+
1095
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1096
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1097
+
1098
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1099
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1100
+
1101
+ >>> # Generate
1102
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1103
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1104
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1105
+ ```"""
1106
+
1107
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1108
+ output_hidden_states = (
1109
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1110
+ )
1111
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1112
+
1113
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1114
+ outputs = self.model(
1115
+ input_ids=input_ids,
1116
+ attention_mask=attention_mask,
1117
+ position_ids=position_ids,
1118
+ past_key_values=past_key_values,
1119
+ inputs_embeds=inputs_embeds,
1120
+ use_cache=use_cache,
1121
+ output_attentions=output_attentions,
1122
+ output_hidden_states=output_hidden_states,
1123
+ return_dict=return_dict,
1124
+ cache_position=cache_position,
1125
+ )
1126
+
1127
+ hidden_states = outputs[0]
1128
+ logits = self.lm_head(hidden_states)
1129
+ logits = logits.float()
1130
+
1131
+ loss = None
1132
+ if labels is not None:
1133
+ # Shift so that tokens < n predict n
1134
+ shift_logits = logits[..., :-1, :].contiguous()
1135
+ shift_labels = labels[..., 1:].contiguous()
1136
+ # Flatten the tokens
1137
+ loss_fct = CrossEntropyLoss()
1138
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1139
+ shift_labels = shift_labels.view(-1)
1140
+ # Enable model parallelism
1141
+ shift_labels = shift_labels.to(shift_logits.device)
1142
+ loss = loss_fct(shift_logits, shift_labels)
1143
+
1144
+ if not return_dict:
1145
+ output = (logits,) + outputs[1:]
1146
+ return (loss,) + output if loss is not None else output
1147
+
1148
+ return CausalLMOutputWithPast(
1149
+ loss=loss,
1150
+ logits=logits,
1151
+ past_key_values=outputs.past_key_values,
1152
+ hidden_states=outputs.hidden_states,
1153
+ attentions=outputs.attentions,
1154
+ )
1155
+
1156
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1157
+ def prepare_inputs_for_generation(
1158
+ self,
1159
+ input_ids,
1160
+ past_key_values=None,
1161
+ attention_mask=None,
1162
+ inputs_embeds=None,
1163
+ cache_position=None,
1164
+ position_ids=None,
1165
+ use_cache=True,
1166
+ **kwargs,
1167
+ ):
1168
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1169
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1170
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1171
+ if past_key_values is not None:
1172
+ if inputs_embeds is not None: # Exception 1
1173
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1174
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1175
+ input_ids = input_ids[:, cache_position]
1176
+
1177
+ if attention_mask is not None and position_ids is None:
1178
+ # create position_ids on the fly for batch generation
1179
+ position_ids = attention_mask.long().cumsum(-1) - 1
1180
+ position_ids.masked_fill_(attention_mask == 0, 1)
1181
+ if past_key_values:
1182
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1183
+
1184
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1185
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1186
+
1187
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1188
+ if inputs_embeds is not None and cache_position[0] == 0:
1189
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1190
+ else:
1191
+ # The clone here is for the same reason as for `position_ids`.
1192
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1193
+
1194
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1195
+ if model_inputs["inputs_embeds"] is not None:
1196
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1197
+ device = model_inputs["inputs_embeds"].device
1198
+ else:
1199
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1200
+ device = model_inputs["input_ids"].device
1201
+
1202
+ dtype = self.lm_head.weight.dtype
1203
+ min_dtype = torch.finfo(dtype).min
1204
+
1205
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1206
+ attention_mask,
1207
+ sequence_length=sequence_length,
1208
+ target_length=past_key_values.get_max_length(),
1209
+ dtype=dtype,
1210
+ device=device,
1211
+ min_dtype=min_dtype,
1212
+ cache_position=cache_position,
1213
+ batch_size=batch_size,
1214
+ )
1215
+
1216
+ model_inputs.update(
1217
+ {
1218
+ "position_ids": position_ids,
1219
+ "cache_position": cache_position,
1220
+ "past_key_values": past_key_values,
1221
+ "use_cache": use_cache,
1222
+ "attention_mask": attention_mask,
1223
+ }
1224
+ )
1225
+ return model_inputs
1226
+
1227
+
1228
+ @add_start_docstrings(
1229
+ """
1230
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1231
+
1232
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1233
+ (e.g. GPT-2) do.
1234
+
1235
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1236
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1237
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1238
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1239
+ each row of the batch).
1240
+ """,
1241
+ QWEN2_START_DOCSTRING,
1242
+ )
1243
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1244
+ def __init__(self, config):
1245
+ super().__init__(config)
1246
+ self.num_labels = config.num_labels
1247
+ self.model = Qwen2ModelBA(config)
1248
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1249
+
1250
+ # Initialize weights and apply final processing
1251
+ self.post_init()
1252
+
1253
+ def get_input_embeddings(self):
1254
+ return self.model.embed_tokens
1255
+
1256
+ def set_input_embeddings(self, value):
1257
+ self.model.embed_tokens = value
1258
+
1259
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1260
+ def forward(
1261
+ self,
1262
+ input_ids: torch.LongTensor = None,
1263
+ attention_mask: Optional[torch.Tensor] = None,
1264
+ position_ids: Optional[torch.LongTensor] = None,
1265
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1266
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1267
+ labels: Optional[torch.LongTensor] = None,
1268
+ use_cache: Optional[bool] = None,
1269
+ output_attentions: Optional[bool] = None,
1270
+ output_hidden_states: Optional[bool] = None,
1271
+ return_dict: Optional[bool] = None,
1272
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1273
+ r"""
1274
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1275
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1276
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1277
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1278
+ """
1279
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1280
+
1281
+ transformer_outputs = self.model(
1282
+ input_ids,
1283
+ attention_mask=attention_mask,
1284
+ position_ids=position_ids,
1285
+ past_key_values=past_key_values,
1286
+ inputs_embeds=inputs_embeds,
1287
+ use_cache=use_cache,
1288
+ output_attentions=output_attentions,
1289
+ output_hidden_states=output_hidden_states,
1290
+ return_dict=return_dict,
1291
+ )
1292
+ hidden_states = transformer_outputs[0]
1293
+ logits = self.score(hidden_states)
1294
+
1295
+ if input_ids is not None:
1296
+ batch_size = input_ids.shape[0]
1297
+ else:
1298
+ batch_size = inputs_embeds.shape[0]
1299
+
1300
+ if self.config.pad_token_id is None and batch_size != 1:
1301
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1302
+ if self.config.pad_token_id is None:
1303
+ sequence_lengths = -1
1304
+ else:
1305
+ if input_ids is not None:
1306
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1307
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1308
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1309
+ sequence_lengths = sequence_lengths.to(logits.device)
1310
+ else:
1311
+ sequence_lengths = -1
1312
+
1313
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1314
+
1315
+ loss = None
1316
+ if labels is not None:
1317
+ labels = labels.to(logits.device)
1318
+ if self.config.problem_type is None:
1319
+ if self.num_labels == 1:
1320
+ self.config.problem_type = "regression"
1321
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1322
+ self.config.problem_type = "single_label_classification"
1323
+ else:
1324
+ self.config.problem_type = "multi_label_classification"
1325
+
1326
+ if self.config.problem_type == "regression":
1327
+ loss_fct = MSELoss()
1328
+ if self.num_labels == 1:
1329
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1330
+ else:
1331
+ loss = loss_fct(pooled_logits, labels)
1332
+ elif self.config.problem_type == "single_label_classification":
1333
+ loss_fct = CrossEntropyLoss()
1334
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1335
+ elif self.config.problem_type == "multi_label_classification":
1336
+ loss_fct = BCEWithLogitsLoss()
1337
+ loss = loss_fct(pooled_logits, labels)
1338
+ if not return_dict:
1339
+ output = (pooled_logits,) + transformer_outputs[1:]
1340
+ return ((loss,) + output) if loss is not None else output
1341
+
1342
+ return SequenceClassifierOutputWithPast(
1343
+ loss=loss,
1344
+ logits=pooled_logits,
1345
+ past_key_values=transformer_outputs.past_key_values,
1346
+ hidden_states=transformer_outputs.hidden_states,
1347
+ attentions=transformer_outputs.attentions,
1348
+ )
1349
+
1350
+
1351
+ @add_start_docstrings(
1352
+ """
1353
+ The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1354
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1355
+ """,
1356
+ QWEN2_START_DOCSTRING,
1357
+ )
1358
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Qwen2, LLAMA->QWEN2
1359
+ class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
1360
+ def __init__(self, config):
1361
+ super().__init__(config)
1362
+ self.num_labels = config.num_labels
1363
+ self.model = Qwen2ModelBA(config)
1364
+ if getattr(config, "classifier_dropout", None) is not None:
1365
+ classifier_dropout = config.classifier_dropout
1366
+ elif getattr(config, "hidden_dropout", None) is not None:
1367
+ classifier_dropout = config.hidden_dropout
1368
+ else:
1369
+ classifier_dropout = 0.1
1370
+ self.dropout = nn.Dropout(classifier_dropout)
1371
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1372
+
1373
+ # Initialize weights and apply final processing
1374
+ self.post_init()
1375
+
1376
+ def get_input_embeddings(self):
1377
+ return self.model.embed_tokens
1378
+
1379
+ def set_input_embeddings(self, value):
1380
+ self.model.embed_tokens = value
1381
+
1382
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1383
+ def forward(
1384
+ self,
1385
+ input_ids: Optional[torch.LongTensor] = None,
1386
+ attention_mask: Optional[torch.Tensor] = None,
1387
+ position_ids: Optional[torch.LongTensor] = None,
1388
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1389
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1390
+ labels: Optional[torch.LongTensor] = None,
1391
+ use_cache: Optional[bool] = None,
1392
+ output_attentions: Optional[bool] = None,
1393
+ output_hidden_states: Optional[bool] = None,
1394
+ return_dict: Optional[bool] = None,
1395
+ ) -> Union[Tuple, TokenClassifierOutput]:
1396
+ r"""
1397
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1398
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1399
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1400
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1401
+ """
1402
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1403
+
1404
+ outputs = self.model(
1405
+ input_ids,
1406
+ attention_mask=attention_mask,
1407
+ position_ids=position_ids,
1408
+ past_key_values=past_key_values,
1409
+ inputs_embeds=inputs_embeds,
1410
+ use_cache=use_cache,
1411
+ output_attentions=output_attentions,
1412
+ output_hidden_states=output_hidden_states,
1413
+ return_dict=return_dict,
1414
+ )
1415
+ sequence_output = outputs[0]
1416
+ sequence_output = self.dropout(sequence_output)
1417
+ logits = self.score(sequence_output)
1418
+
1419
+ loss = None
1420
+ if labels is not None:
1421
+ loss_fct = CrossEntropyLoss()
1422
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1423
+
1424
+ if not return_dict:
1425
+ output = (logits,) + outputs[2:]
1426
+ return ((loss,) + output) if loss is not None else output
1427
+
1428
+ return TokenClassifierOutput(
1429
+ loss=loss,
1430
+ logits=logits,
1431
+ hidden_states=outputs.hidden_states,
1432
+ attentions=outputs.attentions,
1433
+ )
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|endoftext|>",
201
+ "errors": "replace",
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff