Lab1806 commited on
Commit
113dc8b
·
verified ·
1 Parent(s): e3c72b6

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ComplexNetLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_Fairy_plus_minus_i.ComplexNetConfig",
9
+ "AutoModelForCausalLM": "modeling_Fairy_plus_minus_i.ComplexNetLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "relu2",
14
+ "hidden_size": 1536,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 4096,
17
+ "loss_type": "ForCausalLM",
18
+ "max_position_embeddings": 2048,
19
+ "model_type": "complexnet",
20
+ "num_attention_heads": 16,
21
+ "num_hidden_layers": 24,
22
+ "num_key_value_heads": 16,
23
+ "pretraining_tp": 1,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000,
27
+ "tie_word_embeddings": false,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.52.4",
30
+ "use_cache": true,
31
+ "vocab_size": 32000
32
+ }
configuration_Fairy_plus_minus_i.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLaMA model configuration"""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
10
+
11
+
12
+ class ComplexNetConfig(PretrainedConfig):
13
+ model_type = "complexnet"
14
+ keys_to_ignore_at_inference = ["past_key_values"]
15
+
16
+ def __init__(
17
+ self,
18
+ vocab_size=32000,
19
+ hidden_size=1536,
20
+ intermediate_size=4096,
21
+ num_hidden_layers=24,
22
+ num_attention_heads=16,
23
+ num_key_value_heads=16,
24
+ hidden_act="relu2",
25
+ max_position_embeddings=2048,
26
+ initializer_range=0.02,
27
+ rms_norm_eps=1e-5,
28
+ use_cache=True,
29
+ pad_token_id=None,
30
+ bos_token_id=1,
31
+ eos_token_id=2,
32
+ pretraining_tp=1,
33
+ tie_word_embeddings=False,
34
+ rope_theta=10000,
35
+ rope_scaling=None,
36
+ attention_bias=False,
37
+ attention_dropout=0.0,
38
+ loss_type="ForCausalLM",
39
+ **kwargs,
40
+ ):
41
+ self.vocab_size = vocab_size
42
+ self.max_position_embeddings = max_position_embeddings
43
+ self.hidden_size = hidden_size
44
+ self.intermediate_size = intermediate_size
45
+ self.num_hidden_layers = num_hidden_layers
46
+ self.num_attention_heads = num_attention_heads
47
+
48
+ if num_key_value_heads is None:
49
+ num_key_value_heads = num_attention_heads
50
+
51
+ self.num_key_value_heads = num_key_value_heads
52
+ self.hidden_act = hidden_act
53
+ self.initializer_range = initializer_range
54
+ self.rms_norm_eps = rms_norm_eps
55
+ self.pretraining_tp = pretraining_tp
56
+ self.use_cache = use_cache
57
+ self.rope_theta = rope_theta
58
+ self.rope_scaling = rope_scaling
59
+ self._rope_scaling_validation()
60
+ self.attention_bias = attention_bias
61
+ self.attention_dropout = attention_dropout
62
+ self.loss_type = loss_type
63
+
64
+ super().__init__(
65
+ pad_token_id=pad_token_id,
66
+ bos_token_id=bos_token_id,
67
+ eos_token_id=eos_token_id,
68
+ tie_word_embeddings=tie_word_embeddings,
69
+ **kwargs,
70
+ )
71
+
72
+ def _rope_scaling_validation(self):
73
+ if self.rope_scaling is None:
74
+ return
75
+
76
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
77
+ raise ValueError(
78
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
79
+ f"got {self.rope_scaling}"
80
+ )
81
+ rope_scaling_type = self.rope_scaling.get("type", None)
82
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
83
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
84
+ raise ValueError(
85
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
86
+ )
87
+ if (
88
+ rope_scaling_factor is None
89
+ or not isinstance(rope_scaling_factor, float)
90
+ or rope_scaling_factor <= 1.0
91
+ ):
92
+ raise ValueError(
93
+ f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
94
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.52.4"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dbdfceb51503ba440bd405ae2552475351eabed4307eac79afae2862f32e845c
3
+ size 3112026544
modeling_Fairy_plus_minus_i.py ADDED
@@ -0,0 +1,1519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ComplexNet model with Dummy Complex Semantic
3
+ backpropogation with simple autograd
4
+ """
5
+
6
+ from typing import Optional, Tuple, Callable, Any, Dict, List
7
+ import math
8
+ from functools import partial
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch.nn import init
12
+ import torch.nn.functional as F
13
+ from transformers.cache_utils import Cache, StaticCache
14
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
15
+ from transformers.modeling_utils import PreTrainedModel
16
+
17
+ try:
18
+ from transformers.generation.utils import GenerationMixin
19
+ except ImportError:
20
+ from transformers.modeling_utils import GenerationMixin
21
+
22
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
23
+ from transformers.modeling_outputs import CausalLMOutputWithPast
24
+ from transformers.utils import (
25
+ is_flash_attn_2_available,
26
+ is_flash_attn_greater_or_equal_2_10,
27
+ logging,
28
+ )
29
+
30
+ from configuration_Fairy_plus_minus_i import ComplexNetConfig
31
+
32
+ from transformers.cache_utils import Cache
33
+
34
+ import torch
35
+ from packaging import version
36
+
37
+ from transformers.configuration_utils import PretrainedConfig
38
+ from transformers.utils import (
39
+ is_hqq_available,
40
+ is_optimum_quanto_available,
41
+ is_torchdynamo_compiling,
42
+ logging,
43
+ )
44
+ from transformers.utils.deprecation import deprecate_kwarg
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ class ComplexDynamicCache(Cache):
51
+ """
52
+ A complex cache that grows dynamically as more tokens are generated. This is the default for generative models.
53
+
54
+ It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is
55
+ `[batch_size, num_heads, seq_len, head_dim]`.
56
+
57
+ Example:
58
+
59
+ ```python
60
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
61
+
62
+ >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
63
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
64
+
65
+ >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
66
+
67
+ >>> # Prepare a cache class and pass it to model's forward
68
+ >>> past_key_values = ComplexDynamicCache()
69
+ >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
70
+ >>> outputs.past_key_values # access cache filled with key/values from generation
71
+ ComplexDynamicCache()
72
+ ```
73
+ """
74
+
75
+ @deprecate_kwarg("num_hidden_layers", version="4.47.0")
76
+ def __init__(self, num_hidden_layers: Optional[int] = None) -> None:
77
+ super().__init__()
78
+ self._seen_tokens = (
79
+ 0 # Used in `generate` to keep tally of how many tokens the cache has seen
80
+ )
81
+ self.key_real_cache: List[torch.Tensor] = []
82
+ self.key_imag_cache: List[torch.Tensor] = []
83
+ self.value_real_cache: List[torch.Tensor] = []
84
+ self.value_imag_cache: List[torch.Tensor] = []
85
+
86
+ def __getitem__(self, layer_idx: int) -> List[Tuple[torch.Tensor]]:
87
+ """
88
+ Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
89
+ sequence length.
90
+ """
91
+ if layer_idx < len(self):
92
+ return (
93
+ self.key_real_cache[layer_idx],
94
+ self.key_imag_cache[layer_idx],
95
+ self.value_real_cache[layer_idx],
96
+ self.value_imag_cache[layer_idx],
97
+ )
98
+ else:
99
+ raise KeyError(
100
+ f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}"
101
+ )
102
+
103
+ def __iter__(self):
104
+ """
105
+ Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
106
+ keys and values
107
+ """
108
+ for layer_idx in range(len(self)):
109
+ yield (
110
+ self.key_real_cache[layer_idx],
111
+ self.key_imag_cache[layer_idx],
112
+ self.value_real_cache[layer_idx],
113
+ self.value_imag_cache[layer_idx],
114
+ )
115
+
116
+ def __len__(self):
117
+ """
118
+ Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
119
+ to the number of layers in the model.
120
+ """
121
+ return len(self.key_real_cache)
122
+
123
+ def update(
124
+ self,
125
+ key_real_states: torch.Tensor,
126
+ key_imag_states: torch.Tensor,
127
+ value_real_states: torch.Tensor,
128
+ value_imag_states: torch.Tensor,
129
+ layer_idx: int,
130
+ cache_kwargs: Optional[Dict[str, Any]] = None,
131
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
132
+ """
133
+ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
134
+
135
+ Parameters:
136
+ key_states (`torch.Tensor`):
137
+ The new key states to cache.
138
+ value_states (`torch.Tensor`):
139
+ The new value states to cache.
140
+ layer_idx (`int`):
141
+ The index of the layer to cache the states for.
142
+ cache_kwargs (`Dict[str, Any]`, `optional`):
143
+ Additional arguments for the cache subclass. No additional arguments are used in `ComplexDynamicCache`.
144
+
145
+ Return:
146
+ A tuple containing the updated key and value states.
147
+ """
148
+ # Update the number of seen tokens
149
+ if layer_idx == 0:
150
+ self._seen_tokens += key_real_states.shape[-2]
151
+
152
+ # Update the cache
153
+ if key_real_states is not None:
154
+ if len(self.key_real_cache) <= layer_idx:
155
+ # There may be skipped layers, fill them with empty lists
156
+ for _ in range(len(self.key_real_cache), layer_idx):
157
+ self.key_real_cache.append([])
158
+ self.key_imag_cache.append([])
159
+ self.value_real_cache.append([])
160
+ self.value_imag_cache.append([])
161
+ self.key_real_cache.append(key_real_states)
162
+ self.key_imag_cache.append(key_imag_states)
163
+ self.value_real_cache.append(value_real_states)
164
+ self.value_imag_cache.append(value_imag_states)
165
+ elif (
166
+ len(self.key_real_cache[layer_idx]) == 0
167
+ ): # fills previously skipped layers; checking for tensor causes errors
168
+ self.key_real_cache[layer_idx] = key_real_states
169
+ self.key_imag_cache[layer_idx] = key_imag_states
170
+ self.value_real_cache[layer_idx] = value_real_states
171
+ self.value_imag_cache[layer_idx] = value_imag_states
172
+
173
+ else:
174
+ self.key_real_cache[layer_idx] = torch.cat(
175
+ [self.key_real_cache[layer_idx], key_real_states], dim=-2
176
+ )
177
+ self.key_imag_cache[layer_idx] = torch.cat([self.key_imag_cache[layer_idx], key_imag_states], dim=-2)
178
+ self.value_real_cache[layer_idx] = torch.cat(
179
+ [self.value_real_cache[layer_idx], value_real_states], dim=-2
180
+ )
181
+ self.value_imag_cache[layer_idx] = torch.cat(
182
+ [self.value_imag_cache[layer_idx], value_imag_states], dim=-2
183
+ )
184
+
185
+ return (
186
+ self.key_real_cache[layer_idx],
187
+ self.key_imag_cache[layer_idx],
188
+ self.value_real_cache[layer_idx],
189
+ self.value_imag_cache[layer_idx],
190
+ )
191
+
192
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
193
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
194
+ # TODO: deprecate this function in favor of `cache_position`
195
+ is_empty_layer = (
196
+ len(self.key_real_cache) == 0 # no cache in any layer
197
+ or len(self.key_real_cache)
198
+ <= layer_idx # skipped `layer_idx` and hasn't run a layer with cache after it
199
+ or len(self.key_real_cache[layer_idx]) == 0 # the layer has no cache
200
+ )
201
+ layer_seq_length = (
202
+ self.key_real_cache[layer_idx].shape[-2] if not is_empty_layer else 0
203
+ )
204
+ return layer_seq_length
205
+
206
+ def get_max_cache_shape(self) -> Optional[int]:
207
+ """Returns the maximum sequence length of the cache object. DynamicCache does not have a maximum length."""
208
+ return None
209
+
210
+ def to_legacy_cache(
211
+ self,
212
+ ) -> Tuple[
213
+ Tuple[torch.Tensor],
214
+ Tuple[torch.Tensor],
215
+ Tuple[torch.Tensor],
216
+ Tuple[torch.Tensor],
217
+ ]:
218
+ """Converts the `ComplexDynamicCache` instance into the its equivalent in the legacy cache format. Used for
219
+ backward compatibility."""
220
+ legacy_cache = ()
221
+ for layer_idx in range(len(self)):
222
+ legacy_cache += (
223
+ (
224
+ self.key_real_cache[layer_idx],
225
+ self.key_imag_cache[layer_idx],
226
+ self.value_real_cache[layer_idx],
227
+ self.value_imag_cache[layer_idx],
228
+ ),
229
+ )
230
+ return legacy_cache
231
+
232
+ @classmethod
233
+ @deprecate_kwarg("num_hidden_layers", version="4.47.0")
234
+ def from_legacy_cache(
235
+ cls,
236
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
237
+ num_hidden_layers: int = None,
238
+ ) -> "ComplexDynamicCache":
239
+ """Converts a cache in the legacy cache format into an equivalent `ComplexDynamicCache`. Used for
240
+ backward compatibility."""
241
+ cache = cls()
242
+ if past_key_values is not None:
243
+ for layer_idx in range(len(past_key_values)):
244
+ (
245
+ key_real_states,
246
+ key_imag_states,
247
+ value_real_states,
248
+ value_imag_states,
249
+ ) = past_key_values[layer_idx]
250
+ cache.update(
251
+ key_real_states,
252
+ key_imag_states,
253
+ value_real_states,
254
+ value_imag_states,
255
+ layer_idx,
256
+ )
257
+ return cache
258
+
259
+ def crop(self, max_length: int):
260
+ """Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
261
+ negative to remove `max_length` tokens. This is used in assisted decoding and contrastive search.
262
+ """
263
+ # In case it is negative
264
+ if max_length < 0:
265
+ max_length = self.get_seq_length() - abs(max_length)
266
+
267
+ if self.get_seq_length() <= max_length:
268
+ return
269
+
270
+ self._seen_tokens = max_length
271
+ for idx in range(len(self.key_real_cache)):
272
+ if self.key_real_cache[idx] != []:
273
+ self.key_real_cache[idx] = self.key_real_cache[idx][..., :max_length, :]
274
+ self.key_imag_cache[idx] = self.key_imag_cache[idx][..., :max_length, :]
275
+ self.value_real_cache[idx] = self.value_real_cache[idx][
276
+ ..., :max_length, :
277
+ ]
278
+ self.value_imag_cache[idx] = self.value_imag_cache[idx][
279
+ ..., :max_length, :
280
+ ]
281
+
282
+ @deprecate_kwarg("num_hidden_layers", version="4.47.0")
283
+ def batch_split(
284
+ self, full_batch_size: int, split_size: int, num_hidden_layers: int = None
285
+ ) -> List["ComplexDynamicCache"]:
286
+ """Split the current instance into a list of `ComplexDynamicCache` by the batch size. This will be used by
287
+ `_split_model_inputs()` in `generation.utils`"""
288
+ out = []
289
+ for i in range(0, full_batch_size, split_size):
290
+ current_split = ComplexDynamicCache()
291
+ current_split._seen_tokens = self._seen_tokens
292
+ current_split.key_real_cache = [
293
+ tensor[i : i + split_size] for tensor in self.key_real_cache
294
+ ]
295
+ current_split.key_imag_cache = [
296
+ tensor[i : i + split_size] for tensor in self.key_imag_cache
297
+ ]
298
+ current_split.value_real_cache = [
299
+ tensor[i : i + split_size] for tensor in self.value_real_cache
300
+ ]
301
+ current_split.value_imag_cache = [
302
+ tensor[i : i + split_size] for tensor in self.value_imag_cache
303
+ ]
304
+
305
+ out.append(current_split)
306
+ return out
307
+
308
+ @classmethod
309
+ @deprecate_kwarg("num_hidden_layers", version="4.47.0")
310
+ def from_batch_splits(
311
+ cls, splits: List["ComplexDynamicCache"], num_hidden_layers: int = None
312
+ ) -> "ComplexDynamicCache":
313
+ """This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
314
+ `generation.utils`"""
315
+ cache = cls()
316
+ for idx in range(len(splits[0])):
317
+ key_real_cache = [
318
+ current.key_real_cache[idx]
319
+ for current in splits
320
+ if current.key_real_cache[idx] != []
321
+ ]
322
+ key_imag_cache = [
323
+ current.key_imag_cache[idx]
324
+ for current in splits
325
+ if current.key_imag_cache[idx] != []
326
+ ]
327
+ value_real_cache = [
328
+ current.value_real_cache[idx]
329
+ for current in splits
330
+ if current.value_real_cache[idx] != []
331
+ ]
332
+ value_imag_cache = [
333
+ current.value_imag_cache[idx]
334
+ for current in splits
335
+ if current.value_imag_cache[idx] != []
336
+ ]
337
+
338
+ if key_real_cache != []:
339
+ layer_keys_real = torch.cat(key_real_cache, dim=0)
340
+ layer_keys_imag = torch.cat(key_imag_cache, dim=0)
341
+ layer_values_real = torch.cat(value_real_cache, dim=0)
342
+ layer_values_imag = torch.cat(value_imag_cache, dim=0)
343
+
344
+ cache.update(
345
+ layer_keys_real,
346
+ layer_keys_imag,
347
+ layer_values_real,
348
+ layer_values_imag,
349
+ idx,
350
+ )
351
+ return cache
352
+
353
+ def batch_repeat_interleave(self, repeats: int):
354
+ """Repeat the cache `repeats` times in the batch dimension. Used in contrastive search."""
355
+ for layer_idx in range(len(self)):
356
+ self.key_real_cache[layer_idx] = self.key_real_cache[
357
+ layer_idx
358
+ ].repeat_interleave(repeats, dim=0)
359
+ self.key_imag_cache[layer_idx] = self.key_imag_cache[
360
+ layer_idx
361
+ ].repeat_interleave(repeats, dim=0)
362
+ self.value_real_cache[layer_idx] = self.value_real_cache[
363
+ layer_idx
364
+ ].repeat_interleave(repeats, dim=0)
365
+ self.value_imag_cache[layer_idx] = self.value_imag_cache[
366
+ layer_idx
367
+ ].repeat_interleave(repeats, dim=0)
368
+
369
+ def batch_select_indices(self, indices: torch.Tensor):
370
+ """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
371
+ for layer_idx in range(len(self)):
372
+ self.key_real_cache[layer_idx] = self.key_real_cache[layer_idx][
373
+ indices, ...
374
+ ]
375
+ self.key_imag_cache[layer_idx] = self.key_imag_cache[layer_idx][
376
+ indices, ...
377
+ ]
378
+ self.value_real_cache[layer_idx] = self.value_real_cache[layer_idx][
379
+ indices, ...
380
+ ]
381
+ self.value_imag_cache[layer_idx] = self.value_imag_cache[layer_idx][
382
+ indices, ...
383
+ ]
384
+
385
+
386
+ if is_flash_attn_2_available():
387
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
388
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
389
+
390
+ _CONFIG_FOR_DOC = "ComplexNetConfig"
391
+
392
+
393
+ class DirectionQuantSTE(torch.autograd.Function):
394
+ @staticmethod
395
+ def forward(ctx, w_real: torch.Tensor, w_imag: torch.Tensor):
396
+ phase = torch.angle(w_real + 1j * w_imag)
397
+
398
+ real_scale = 1.0 / torch.clamp(w_real.abs().mean(), min=1e-5)
399
+ imag_scale = 1.0 / torch.clamp(w_imag.abs().mean(), min=1e-5)
400
+
401
+ w_real_scaled = w_real * real_scale
402
+ w_imag_scaled = w_imag * imag_scale
403
+
404
+ qw_real = torch.zeros_like(w_real_scaled)
405
+ qw_imag = torch.zeros_like(w_imag_scaled)
406
+
407
+ qw_real[(phase >= -torch.pi / 4) & (phase < torch.pi / 4)] = 1.0
408
+ qw_imag[(phase >= torch.pi / 4) & (phase < 3 * torch.pi / 4)] = 1.0
409
+ qw_real[(phase >= 3 * torch.pi / 4) | (phase < -3 * torch.pi / 4)] = -1.0
410
+ qw_imag[(phase >= -3 * torch.pi / 4) & (phase < -torch.pi / 4)] = -1.0
411
+
412
+ qw_real = qw_real / real_scale
413
+ qw_imag = qw_imag / imag_scale
414
+
415
+ return qw_real, qw_imag
416
+
417
+ @staticmethod
418
+ def backward(ctx, grad_real, grad_imag):
419
+ return grad_real, grad_imag
420
+
421
+
422
+ def weight_quant_qat(w_real: torch.Tensor, w_imag: torch.Tensor):
423
+ return DirectionQuantSTE.apply(w_real, w_imag)
424
+
425
+
426
+ class ComplexWeightQuantizer(nn.Module):
427
+ def __init__(self):
428
+ super().__init__()
429
+
430
+ def forward(self, w_real, w_imag):
431
+ return weight_quant_qat(w_real, w_imag)
432
+
433
+
434
+ class ActivationQuantSTE(torch.autograd.Function):
435
+ @staticmethod
436
+ def forward(ctx, x_real: torch.Tensor, x_imag: torch.Tensor):
437
+ real_scale = 127.0 / x_real.abs().max(dim=-1, keepdim=True).values.clamp_(
438
+ min=1e-5
439
+ )
440
+ imag_scale = 127.0 / x_imag.abs().max(dim=-1, keepdim=True).values.clamp_(
441
+ min=1e-5
442
+ )
443
+
444
+ qx_real = x_real * real_scale
445
+ qx_real = qx_real.contiguous()
446
+ qx_real.round_()
447
+ qx_real.clamp_(-128, 127)
448
+ qx_real.div_(real_scale)
449
+
450
+ qx_imag = x_imag * imag_scale
451
+ qx_imag = qx_imag.contiguous()
452
+ qx_imag.round_()
453
+ qx_imag.clamp_(-128, 127)
454
+ qx_imag.div_(imag_scale)
455
+
456
+ return qx_real, qx_imag
457
+
458
+ @staticmethod
459
+ def backward(ctx, grad_real, grad_imag):
460
+ # STE
461
+ return grad_real, grad_imag
462
+
463
+
464
+ def activation_quant_qat(x_real: torch.Tensor, x_imag: torch.Tensor):
465
+ return ActivationQuantSTE.apply(x_real, x_imag)
466
+
467
+
468
+ class ComplexActivationQuantizer(nn.Module):
469
+ def __init__(self):
470
+ super().__init__()
471
+
472
+ def forward(self, x_real, x_imag):
473
+ return activation_quant_qat(x_real, x_imag)
474
+
475
+
476
+ class HalfComplexLinear(nn.Module):
477
+ """
478
+ HalfComplexLinear is a linear layer that only outputs real_output.
479
+ """
480
+
481
+ def __init__(self, in_features: int, out_features: int):
482
+ super(HalfComplexLinear, self).__init__()
483
+ self.in_features = in_features
484
+ self.out_features = out_features
485
+
486
+ self.weight_real = nn.Parameter(
487
+ torch.empty(self.out_features, self.in_features)
488
+ )
489
+ self.weight_imag = nn.Parameter(
490
+ torch.empty(self.out_features, self.in_features)
491
+ )
492
+ self.act_quantizer = ComplexActivationQuantizer()
493
+ self.weight_quantizer = ComplexWeightQuantizer()
494
+ self.reset_parameters()
495
+
496
+ def reset_parameters(self):
497
+ init.kaiming_uniform_(self.weight_real, a=math.sqrt(5))
498
+ init.kaiming_uniform_(self.weight_imag, a=math.sqrt(5))
499
+
500
+ def forward(self, x_real: torch.Tensor, x_imag: torch.Tensor) -> torch.Tensor:
501
+ qw_real, qw_imag = self.weight_quantizer(self.weight_real, self.weight_imag)
502
+ qx_real, qx_imag = self.act_quantizer(x_real, x_imag)
503
+
504
+ out_real = F.linear(qx_real, qw_real) + F.linear(qx_imag, qw_imag)
505
+
506
+ return out_real
507
+
508
+
509
+ class ComplexLinear(nn.Module):
510
+ def __init__(self, in_features: int, out_features: int):
511
+ super(ComplexLinear, self).__init__()
512
+ self.in_features = in_features
513
+ self.out_features = out_features
514
+
515
+ self.weight_real = nn.Parameter(
516
+ torch.empty(self.out_features, self.in_features)
517
+ )
518
+ self.weight_imag = nn.Parameter(
519
+ torch.empty(self.out_features, self.in_features)
520
+ )
521
+ self.act_quantizer = ComplexActivationQuantizer()
522
+ self.weight_quantizer = ComplexWeightQuantizer()
523
+ self.reset_parameters()
524
+
525
+ def reset_parameters(self):
526
+ init.kaiming_uniform_(self.weight_real, a=math.sqrt(5))
527
+ init.kaiming_uniform_(self.weight_imag, a=math.sqrt(5))
528
+
529
+ def forward(self, x_real: torch.Tensor, x_imag: torch.Tensor) -> torch.Tensor:
530
+ qw_real, qw_imag = self.weight_quantizer(self.weight_real, self.weight_imag)
531
+ qx_real, qx_imag = self.act_quantizer(x_real, x_imag)
532
+
533
+ out_real = F.linear(qx_real, qw_real) + F.linear(qx_imag, qw_imag)
534
+ out_imag = F.linear(qx_real, qw_imag) - F.linear(qx_imag, qw_real)
535
+
536
+ return out_real, out_imag
537
+
538
+
539
+ class ComplexNetRMSNorm(nn.Module):
540
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
541
+ super().__init__()
542
+ self.weight_real = nn.Parameter(torch.ones(hidden_size))
543
+ self.weight_imag = nn.Parameter(torch.ones(hidden_size))
544
+ self.variance_epsilon = eps
545
+
546
+ def forward(
547
+ self, hidden_states_real: torch.Tensor, hidden_states_imag: torch.Tensor
548
+ ):
549
+ input_dtype = hidden_states_real.dtype
550
+
551
+ hidden_states_real.to(torch.float32)
552
+ hidden_states_imag.to(torch.float32)
553
+ magnitude = torch.mean(
554
+ hidden_states_real**2 + hidden_states_imag**2, dim=-1, keepdim=True
555
+ )
556
+ variance = torch.rsqrt(magnitude + self.variance_epsilon)
557
+
558
+ hidden_states_real = hidden_states_real * variance
559
+ hidden_states_imag = hidden_states_imag * variance
560
+
561
+ rmsnorm_out_real = self.weight_real * hidden_states_real
562
+ rmsnorm_out_imag = self.weight_imag * hidden_states_imag
563
+
564
+ return rmsnorm_out_real.to(input_dtype), rmsnorm_out_imag.to(input_dtype)
565
+
566
+
567
+ ALL_LAYERNORM_LAYERS.append(ComplexNetRMSNorm)
568
+
569
+
570
+ class ComplexNetMLP(nn.Module):
571
+ def __init__(self, config: ComplexNetConfig):
572
+ super().__init__()
573
+ self.config = config
574
+ self.hidden_size = self.config.hidden_size
575
+ self.im_size = self.config.intermediate_size
576
+
577
+ self.gate_proj = ComplexLinear(self.hidden_size, self.im_size)
578
+ self.up_proj = ComplexLinear(self.hidden_size, self.im_size)
579
+ self.down_proj = ComplexLinear(self.im_size, self.hidden_size)
580
+
581
+ self.ffn_layernorm = ComplexNetRMSNorm(self.im_size, eps=config.rms_norm_eps)
582
+
583
+ def complex_relu2(self, x_real: torch.Tensor, x_imag: torch.Tensor) -> torch.Tensor:
584
+ mask = torch.logical_and(x_real < 0, x_imag < 0)
585
+ x_real[mask] = 0
586
+ x_imag[mask] = 0
587
+ x_real = x_real**2
588
+ x_imag = x_imag**2
589
+ return x_real, x_imag
590
+
591
+ def forward(self, x_real: torch.Tensor, x_imag: torch.Tensor) -> torch.Tensor:
592
+ gate_proj_real, gate_proj_imag = self.gate_proj(x_real, x_imag)
593
+ activated_real, activated_imag = self.complex_relu2(
594
+ gate_proj_real, gate_proj_imag
595
+ )
596
+ up_proj_real, up_proj_imag = self.up_proj(x_real, x_imag)
597
+
598
+ up_proj_activated_real = (
599
+ activated_real * up_proj_real + activated_imag * up_proj_imag
600
+ )
601
+ up_proj_activated_imag = (
602
+ activated_real * up_proj_imag - activated_imag * up_proj_real
603
+ )
604
+
605
+ ln_real, ln_imag = self.ffn_layernorm(
606
+ up_proj_activated_real, up_proj_activated_imag
607
+ )
608
+ out_real, out_imag = self.down_proj(ln_real, ln_imag)
609
+ return out_real, out_imag
610
+
611
+
612
+ class ComplexNetRotaryEmbedding(nn.Module):
613
+ def __init__(self, config: ComplexNetConfig):
614
+ super().__init__()
615
+
616
+ self.config = config
617
+ self.base = self.config.rope_theta
618
+ self.hidden_size = self.config.hidden_size
619
+ self.num_attention_heads = self.config.num_attention_heads
620
+ self.max_seq_len_cached = self.config.max_position_embeddings
621
+
622
+ inv_freq = self._compute_inv_freq()
623
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
624
+
625
+ def _compute_inv_freq(self):
626
+ base = self.base
627
+ head_dim = self.hidden_size // self.num_attention_heads
628
+ inv_freq = 1.0 / (
629
+ base ** (torch.arange(0, head_dim, dtype=torch.int64) / head_dim)
630
+ )
631
+ return inv_freq
632
+
633
+ @torch.no_grad()
634
+ def forward(
635
+ self, position_ids: torch.Tensor, hidden_states_type: torch.dtype
636
+ ) -> tuple:
637
+ batch_size = position_ids.shape[0]
638
+ position_ids = position_ids[:, None, :].to(torch.float32)
639
+ if self.inv_freq.dim() == 1:
640
+ self.inv_freq = (
641
+ self.inv_freq[None, :, None]
642
+ .expand(batch_size, -1, 1)
643
+ .to(position_ids.device)
644
+ )
645
+
646
+ if position_ids.shape[0] > self.max_seq_len_cached:
647
+ print(f"Truncate position_ids within max_seq_len_cached.")
648
+ position_ids = position_ids[: self.max_seq_len_cached]
649
+ theta = (self.inv_freq.to(position_ids.dtype) @ position_ids).transpose(1, 2)
650
+ cos_emb = torch.cos(theta).to(hidden_states_type)
651
+ sin_emb = torch.sin(theta).to(hidden_states_type)
652
+
653
+ return cos_emb, sin_emb
654
+
655
+
656
+ def _apply_rotary_pos_emb(
657
+ q_real: torch.Tensor,
658
+ q_imag: torch.Tensor,
659
+ k_real: torch.Tensor,
660
+ k_imag: torch.Tensor,
661
+ cos_emb: torch.Tensor,
662
+ sin_emb: torch.Tensor,
663
+ ) -> tuple:
664
+
665
+ def _apply_rotation(
666
+ x_real: torch.Tensor,
667
+ x_imag: torch.Tensor,
668
+ cos_emb: torch.Tensor,
669
+ sin_emb: torch.Tensor,
670
+ ) -> torch.Tensor:
671
+ cos_emb = cos_emb.unsqueeze(1)
672
+ sin_emb = sin_emb.unsqueeze(1)
673
+
674
+ rotated_x_real = x_real * cos_emb - x_imag * sin_emb
675
+ rotated_x_imag = x_real * sin_emb + x_imag * cos_emb
676
+
677
+ return rotated_x_real, rotated_x_imag
678
+
679
+ rotated_q_real, rotated_q_imag = _apply_rotation(q_real, q_imag, cos_emb, sin_emb)
680
+ rotated_k_real, rotated_k_imag = _apply_rotation(k_real, k_imag, cos_emb, sin_emb)
681
+
682
+ return rotated_q_real, rotated_q_imag, rotated_k_real, rotated_k_imag
683
+
684
+
685
+ def repeat_kv(
686
+ hidden_states_real: torch.Tensor,
687
+ hidden_states_imag: torch.Tensor,
688
+ num_key_value_groups: int,
689
+ ) -> torch.Tensor:
690
+ batch_size, num_key_value_heads, seq_length, head_dim = hidden_states_real.shape
691
+
692
+ if num_key_value_groups == 1:
693
+ return hidden_states_real, hidden_states_imag
694
+
695
+ hidden_states_real = hidden_states_real[:, :, None, :, :].expand(
696
+ batch_size, num_key_value_heads, num_key_value_groups, seq_length, head_dim
697
+ )
698
+ hidden_states_imag = hidden_states_imag[:, :, None, :, :].expand(
699
+ batch_size, num_key_value_heads, num_key_value_groups, seq_length, head_dim
700
+ )
701
+
702
+ hidden_states_real = hidden_states_real.reshape(
703
+ batch_size, num_key_value_heads * num_key_value_groups, seq_length, head_dim
704
+ )
705
+ hidden_states_imag = hidden_states_imag.reshape(
706
+ batch_size, num_key_value_heads * num_key_value_groups, seq_length, head_dim
707
+ )
708
+ return hidden_states_real, hidden_states_imag
709
+
710
+
711
+ def repeat_kv_for_real(
712
+ hidden_states_real: torch.Tensor,
713
+ num_key_value_groups: int,
714
+ ) -> torch.Tensor:
715
+ batch_size, num_key_value_heads, seq_length, head_dim = hidden_states_real.shape
716
+
717
+ if num_key_value_groups == 1:
718
+ return hidden_states_real
719
+
720
+ hidden_states_real = hidden_states_real[:, :, None, :, :].expand(
721
+ batch_size, num_key_value_heads, num_key_value_groups, seq_length, head_dim
722
+ )
723
+
724
+ hidden_states_real = hidden_states_real.reshape(
725
+ batch_size, num_key_value_heads * num_key_value_groups, seq_length, head_dim
726
+ )
727
+ return hidden_states_real
728
+
729
+
730
+ def _rotate_half(x):
731
+ """Rotates half the hidden dims of the input."""
732
+ x1 = x[..., : x.shape[-1] // 2]
733
+ x2 = x[..., x.shape[-1] // 2 :]
734
+ return torch.cat((-x2, x1), dim=-1)
735
+
736
+
737
+ def _apply_rotary_pos_emb_only_for_real(
738
+ q_real: torch.Tensor,
739
+ k_real: torch.Tensor,
740
+ cos_emb: torch.Tensor,
741
+ sin_emb: torch.Tensor,
742
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
743
+ cos_emb = cos_emb.unsqueeze(1)
744
+ sin_emb = sin_emb.unsqueeze(1)
745
+ q_embed = (q_real * cos_emb) + (_rotate_half(q_real) * sin_emb)
746
+ k_embed = (k_real * cos_emb) + (_rotate_half(k_real) * sin_emb)
747
+ return q_embed, k_embed
748
+
749
+
750
+ class ComplexNetAttentionBase(nn.Module):
751
+ def __init__(self, config: ComplexNetConfig, layer_idx: int):
752
+ super().__init__()
753
+ self.config = config
754
+ self.layer_idx = layer_idx
755
+
756
+ self.attn_dropout = self.config.attention_dropout
757
+
758
+ self.hidden_size = self.config.hidden_size
759
+ self.num_attn_heads = self.config.num_attention_heads
760
+ self.head_dim = self.hidden_size // self.num_attn_heads
761
+
762
+ self.num_key_value_heads = self.config.num_key_value_heads
763
+ self.num_key_value_groups = (
764
+ self.num_attn_heads // self.config.num_key_value_heads
765
+ )
766
+
767
+ self.max_position_embeddings = self.config.max_position_embeddings
768
+ self.rope_theta = self.config.rope_theta
769
+
770
+ self.scaling = self.head_dim**-0.5
771
+
772
+ self.is_causal = True
773
+ self.rms_norm_eps = self.config.rms_norm_eps
774
+
775
+ self.q_proj = ComplexLinear(
776
+ self.hidden_size, self.num_attn_heads * self.head_dim
777
+ )
778
+ self.k_proj = ComplexLinear(
779
+ self.hidden_size, self.num_key_value_heads * self.head_dim
780
+ )
781
+ self.v_proj = ComplexLinear(
782
+ self.hidden_size, self.num_key_value_heads * self.head_dim
783
+ )
784
+ self.o_proj = ComplexLinear(self.hidden_size, self.hidden_size)
785
+
786
+ self.rotary_emb = ComplexNetRotaryEmbedding(self.config)
787
+ self.attn_layernorm = ComplexNetRMSNorm(self.hidden_size, eps=self.rms_norm_eps)
788
+
789
+ def forward(
790
+ self,
791
+ hidden_states_real: torch.Tensor,
792
+ hidden_states_imag: torch.Tensor,
793
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
794
+ attn_mask_real: Optional[torch.Tensor] = None,
795
+ attn_mask_imag: Optional[torch.Tensor] = None,
796
+ past_key_value: Optional[ComplexDynamicCache] = None,
797
+ cache_position: Optional[torch.LongTensor] = None,
798
+ **kwargs,
799
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
800
+ input_shape = hidden_states_real.shape[:-1]
801
+ q_shape = (*input_shape, self.num_attn_heads, self.head_dim)
802
+ kv_shape = (*input_shape, self.num_key_value_heads, self.head_dim)
803
+
804
+ q_real = self.q_proj(hidden_states_real, hidden_states_imag)
805
+ q_real = q_real.view(q_shape).transpose(1, 2)
806
+
807
+ k_real = self.k_proj(hidden_states_real, hidden_states_imag)
808
+ k_imag = None
809
+ k_real = k_real.view(kv_shape).transpose(1, 2)
810
+
811
+ v_real, v_imag = self.v_proj(hidden_states_real, hidden_states_imag)
812
+ v_real = v_real.view(kv_shape).transpose(1, 2)
813
+ v_imag = v_imag.view(kv_shape).transpose(1, 2)
814
+
815
+ cos_emb, sin_emb = position_embeddings
816
+ q_real, k_real = _apply_rotary_pos_emb_only_for_real(
817
+ q_real, k_real, cos_emb, sin_emb
818
+ )
819
+
820
+ if past_key_value is not None:
821
+ cache_kwargs = {
822
+ "sin": sin_emb,
823
+ "cos": cos_emb,
824
+ "cache_position": cache_position,
825
+ }
826
+ k_real, k_imag, v_real, v_imag = past_key_value.update(
827
+ k_real, k_imag, v_real, v_imag, self.layer_idx, cache_kwargs
828
+ )
829
+
830
+ k_real = repeat_kv_for_real(k_real, self.num_key_value_groups)
831
+ v_real, v_imag = repeat_kv(v_real, v_imag, self.num_key_value_groups)
832
+
833
+ attn_weights_real = (q_real @ k_real.transpose(2, 3)) * self.scaling
834
+ if attn_mask_real is not None:
835
+ causal_mask_real = attn_mask_real[:, :, :, : k_real.shape[-2]]
836
+ attn_weights_real = attn_weights_real + causal_mask_real
837
+
838
+ attn_weights = attn_weights_real
839
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
840
+ q_real.dtype
841
+ )
842
+ attn_weights = F.dropout(
843
+ attn_weights, p=self.attn_dropout, training=self.training
844
+ )
845
+ attn_output_real = (
846
+ torch.matmul(attn_weights, v_real)
847
+ .transpose(1, 2)
848
+ .contiguous()
849
+ .reshape(input_shape[0], input_shape[1], self.hidden_size)
850
+ )
851
+ attn_output_imag = (
852
+ torch.matmul(attn_weights, v_imag)
853
+ .transpose(1, 2)
854
+ .contiguous()
855
+ .reshape(input_shape[0], input_shape[1], self.hidden_size)
856
+ )
857
+
858
+ attn_output_real, attn_output_imag = self.attn_layernorm(
859
+ attn_output_real, attn_output_imag
860
+ )
861
+ attn_output_real, attn_output_imag = self.o_proj(
862
+ attn_output_real, attn_output_imag
863
+ )
864
+
865
+ return (
866
+ attn_output_real,
867
+ attn_output_imag,
868
+ attn_weights_real,
869
+ None, # attn_weights_imag
870
+ past_key_value,
871
+ )
872
+
873
+
874
+ def _get_unpad_data(attention_mask):
875
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
876
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
877
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
878
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
879
+ return (
880
+ indices,
881
+ cu_seqlens,
882
+ max_seqlen_in_batch,
883
+ )
884
+
885
+
886
+ def _upad_input(
887
+ module,
888
+ query_layer,
889
+ key_layer,
890
+ value_layer,
891
+ attention_mask,
892
+ query_length,
893
+ ):
894
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
895
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
896
+
897
+ key_layer = index_first_axis(
898
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
899
+ indices_k,
900
+ )
901
+ value_layer = index_first_axis(
902
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
903
+ indices_k,
904
+ )
905
+
906
+ if query_length == kv_seq_len:
907
+ query_layer = index_first_axis(
908
+ query_layer.reshape(
909
+ batch_size * kv_seq_len, module.num_attn_heads, head_dim
910
+ ),
911
+ indices_k,
912
+ )
913
+ cu_seqlens_q = cu_seqlens_k
914
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
915
+ indices_q = indices_k
916
+ elif query_length == 1:
917
+ max_seqlen_in_batch_q = 1
918
+ cu_seqlens_q = torch.arange(
919
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
920
+ )
921
+ indices_q = cu_seqlens_q[:-1]
922
+ query_layer = query_layer.squeeze(1)
923
+ else:
924
+ attention_mask = attention_mask[:, -query_length:]
925
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
926
+ query_layer, attention_mask
927
+ )
928
+
929
+ return (
930
+ query_layer,
931
+ key_layer,
932
+ value_layer,
933
+ indices_q,
934
+ (cu_seqlens_q, cu_seqlens_k),
935
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
936
+ )
937
+
938
+
939
+ def eager_attention_forward(
940
+ module: nn.Module,
941
+ q_cat: torch.Tensor,
942
+ k_cat: torch.Tensor,
943
+ v_cat: torch.Tensor,
944
+ attn_mask: Optional[torch.Tensor],
945
+ scaling: float,
946
+ dropout: float = 0.0,
947
+ **kwargs,
948
+ ):
949
+ # for_real func only handle one input
950
+ k_cat = repeat_kv_for_real(k_cat, module.num_key_value_groups)
951
+ v_cat = repeat_kv_for_real(v_cat, module.num_key_value_groups)
952
+
953
+ attn_weights_real = (q_cat @ k_cat.transpose(2, 3)) * scaling
954
+ if attn_mask is not None:
955
+ causal_mask_real = attn_mask[:, :, :, : k_cat.shape[-2]]
956
+ attn_weights_real = attn_weights_real + causal_mask_real
957
+
958
+ attn_weights = attn_weights_real
959
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
960
+ q_cat.dtype
961
+ )
962
+
963
+ attn_weights = F.dropout(attn_weights, p=dropout, training=module.training)
964
+ attn_output = torch.matmul(attn_weights, v_cat).transpose(1, 2).contiguous()
965
+
966
+ return attn_output, None, None
967
+
968
+
969
+ def flash_attention_forward(
970
+ module: nn.Module,
971
+ q_cat: torch.Tensor,
972
+ k_cat: torch.Tensor,
973
+ v_cat: torch.Tensor,
974
+ attn_mask: Optional[torch.Tensor],
975
+ scaling: float,
976
+ dropout: float = 0.0,
977
+ softmax_scale: Optional[float] = None,
978
+ **kwargs,
979
+ ):
980
+ def transpose_hidden_states(*hidden_states: torch.Tensor):
981
+ return [tensor.transpose(1, 2) for tensor in hidden_states]
982
+
983
+ (q_cat, k_cat, v_cat) = transpose_hidden_states(q_cat, k_cat, v_cat)
984
+ query_len = 1
985
+ query_len = q_cat.shape[1]
986
+ input_dtype = q_cat.dtype
987
+ if input_dtype == torch.float32:
988
+ if torch.is_autocast_enabled():
989
+ target_dtype = torch.get_autocast_gpu_dtype()
990
+ elif hasattr(module.config, "_pre_quantization_dtype"):
991
+ target_dtype = module.config._pre_quantization_dtype
992
+ else:
993
+ target_dtype = module.q_proj.weight_real.dtype
994
+
995
+ def dtype_cast(*tensors: torch.Tensor):
996
+ return [tensor.to(target_dtype) for tensor in tensors]
997
+
998
+ (q_cat, k_cat, v_cat) = dtype_cast(q_cat, k_cat, v_cat)
999
+ if not module._flash_attn_uses_top_left_mask:
1000
+ causal = module.is_causal
1001
+ else:
1002
+ causal = module.is_causal and query_len != 1
1003
+
1004
+ if attn_mask is not None:
1005
+ batch_size = q_cat.shape[0]
1006
+ (
1007
+ q_cat,
1008
+ k_cat,
1009
+ v_cat,
1010
+ indices_q,
1011
+ cu_seq_lens,
1012
+ max_seq_lens,
1013
+ ) = _upad_input(
1014
+ module,
1015
+ q_cat,
1016
+ k_cat,
1017
+ v_cat,
1018
+ attn_mask,
1019
+ query_len,
1020
+ )
1021
+
1022
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1023
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1024
+
1025
+ def mask_complex_flash_attn(q, k, v):
1026
+ return flash_attn_varlen_func(
1027
+ q,
1028
+ k,
1029
+ v,
1030
+ cu_seqlens_q=cu_seqlens_q,
1031
+ cu_seqlens_k=cu_seqlens_k,
1032
+ max_seqlen_q=max_seqlen_in_batch_q,
1033
+ max_seqlen_k=max_seqlen_in_batch_k,
1034
+ dropout_p=dropout,
1035
+ softmax_scale=softmax_scale,
1036
+ causal=causal,
1037
+ )
1038
+
1039
+
1040
+ attn_output_unpad = mask_complex_flash_attn(q_cat, k_cat, v_cat)
1041
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_len)
1042
+ else:
1043
+
1044
+ def unmask_complex_flash_attn(q, k, v):
1045
+ return flash_attn_func(
1046
+ q,
1047
+ k,
1048
+ v,
1049
+ dropout_p=dropout,
1050
+ softmax_scale=softmax_scale,
1051
+ causal=causal,
1052
+ )
1053
+
1054
+ attn_output = unmask_complex_flash_attn(q_cat, k_cat, v_cat)
1055
+ return attn_output, None, None
1056
+
1057
+
1058
+ ALL_ATTENTION_FUNCTIONS = {
1059
+ "eager": eager_attention_forward,
1060
+ "flash_attention_2": flash_attention_forward,
1061
+ }
1062
+
1063
+
1064
+ class ComplexNetAttention(ComplexNetAttentionBase):
1065
+ def __init__(self, *args, **kwargs):
1066
+ super().__init__(*args, **kwargs)
1067
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1068
+
1069
+ def forward(
1070
+ self,
1071
+ hidden_states_real: torch.Tensor,
1072
+ hidden_states_imag: torch.Tensor,
1073
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
1074
+ attn_mask_real: Optional[torch.Tensor] = None,
1075
+ attn_mask_imag: Optional[torch.Tensor] = None,
1076
+ past_key_value: Optional[Cache] = None,
1077
+ output_attentions: bool = False,
1078
+ use_cache: bool = False,
1079
+ cache_position: Optional[torch.LongTensor] = None,
1080
+ **kwargs,
1081
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1082
+ input_shape = hidden_states_real.shape[:-1]
1083
+ q_shape = (*input_shape, self.num_attn_heads, self.head_dim)
1084
+ kv_shape = (*input_shape, self.num_key_value_heads, self.head_dim)
1085
+
1086
+ def transpose_hidden_states(*hidden_states: torch.Tensor):
1087
+ return [tensor.transpose(1, 2) for tensor in hidden_states]
1088
+
1089
+ q_real, q_imag = self.q_proj(hidden_states_real, hidden_states_imag)
1090
+ k_real, k_imag = self.k_proj(hidden_states_real, hidden_states_imag)
1091
+ v_real, v_imag = self.v_proj(hidden_states_real, hidden_states_imag)
1092
+ (q_real, q_imag, k_real, k_imag, v_real, v_imag) = transpose_hidden_states(
1093
+ q_real.view(q_shape),
1094
+ q_imag.view(q_shape),
1095
+ k_real.view(kv_shape),
1096
+ k_imag.view(kv_shape),
1097
+ v_real.view(kv_shape),
1098
+ v_imag.view(kv_shape),
1099
+ )
1100
+
1101
+ cos_emb, sin_emb = position_embeddings
1102
+
1103
+ q_real, q_imag, k_real, k_imag = _apply_rotary_pos_emb(
1104
+ q_real, q_imag, k_real, k_imag, cos_emb, sin_emb
1105
+ )
1106
+
1107
+ past_key_value = getattr(self, "past_key_value", past_key_value)
1108
+ if past_key_value is not None:
1109
+ cache_kwargs = {
1110
+ "sin": sin_emb,
1111
+ "cos": cos_emb,
1112
+ "cache_position": cache_position,
1113
+ }
1114
+ k_real, k_imag, v_real, v_imag = past_key_value.update(
1115
+ k_real, k_imag, v_real, v_imag, self.layer_idx, cache_kwargs
1116
+ )
1117
+ attention_interface: Callable = eager_attention_forward
1118
+
1119
+ if self.config._attn_implementation != "eager":
1120
+ if self.config._attn_implementation == "sdpa" and kwargs.get(
1121
+ "output_attentions", False
1122
+ ):
1123
+ logger.warning_once(
1124
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
1125
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1126
+ )
1127
+ raise ValueError(
1128
+ f"Unsupported attention implementation: {self.config._attn_implementation}. Supported implementations are: {list(ALL_ATTENTION_FUNCTIONS.keys())}."
1129
+ )
1130
+ elif self.config._attn_implementation == "flash_attention_2":
1131
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
1132
+ self.config._attn_implementation
1133
+ ]
1134
+ else:
1135
+ raise ValueError(
1136
+ f"Unsupported attention implementation: {self.config._attn_implementation}. Supported implementations are: {list(ALL_ATTENTION_FUNCTIONS.keys())}."
1137
+ )
1138
+ cat_q = torch.cat([q_real, q_imag], dim=-1).reshape(
1139
+ input_shape[0], self.num_attn_heads, input_shape[1], 2 * self.head_dim
1140
+ )
1141
+ cat_k = torch.cat([k_real, k_imag], dim=-1).reshape(
1142
+ input_shape[0], self.num_key_value_heads, input_shape[1], 2 * self.head_dim
1143
+ )
1144
+ cat_v = torch.cat([v_real, v_imag], dim=-1).reshape(
1145
+ input_shape[0], self.num_key_value_heads, input_shape[1], 2 * self.head_dim
1146
+ )
1147
+ attn_output, attn_weights_real, attn_weights_imag = attention_interface(
1148
+ self,
1149
+ cat_q,
1150
+ cat_k,
1151
+ cat_v,
1152
+ attn_mask_real,
1153
+ scaling=self.scaling,
1154
+ dropout=self.attn_dropout if self.training else 0.0,
1155
+ **kwargs,
1156
+ )
1157
+ attn_output_real, attn_output_imag = torch.chunk(attn_output, 2, dim=-1)
1158
+ attn_output_real = attn_output_real.reshape(
1159
+ input_shape[0], input_shape[1], self.hidden_size
1160
+ ).contiguous()
1161
+ attn_output_imag = attn_output_imag.reshape(
1162
+ input_shape[0], input_shape[1], self.hidden_size
1163
+ ).contiguous()
1164
+
1165
+ attn_output_real, attn_output_imag = self.attn_layernorm(
1166
+ attn_output_real, attn_output_imag
1167
+ )
1168
+ attn_output_real, attn_output_imag = self.o_proj(
1169
+ attn_output_real, attn_output_imag
1170
+ )
1171
+
1172
+ if not output_attentions:
1173
+ attn_weights_real = None
1174
+ attn_weights_imag = None
1175
+
1176
+ return (
1177
+ attn_output_real,
1178
+ attn_output_imag,
1179
+ attn_weights_real,
1180
+ attn_weights_imag,
1181
+ past_key_value,
1182
+ )
1183
+
1184
+
1185
+ class ComplexNetDecoderLayer(nn.Module):
1186
+ def __init__(self, config: ComplexNetConfig, layer_idx: int):
1187
+ super().__init__()
1188
+ self.config = config
1189
+ self.hidden_size = self.config.hidden_size
1190
+
1191
+ self.self_attn = ComplexNetAttention(config=config, layer_idx=layer_idx)
1192
+ self.mlp = ComplexNetMLP(config)
1193
+ self.pre_layernorm = ComplexNetRMSNorm(
1194
+ config.hidden_size, eps=config.rms_norm_eps
1195
+ )
1196
+ self.post_layernorm = ComplexNetRMSNorm(
1197
+ config.hidden_size, eps=config.rms_norm_eps
1198
+ )
1199
+
1200
+ def forward(
1201
+ self,
1202
+ hidden_states_real: torch.Tensor,
1203
+ hidden_states_imag: torch.Tensor,
1204
+ attention_mask_real: Optional[torch.Tensor] = None,
1205
+ attention_mask_imag: Optional[torch.Tensor] = None,
1206
+ past_key_value: Optional[Cache] = None,
1207
+ output_attentions: Optional[bool] = False,
1208
+ use_cache: Optional[bool] = False,
1209
+ cache_position: Optional[torch.LongTensor] = None,
1210
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
1211
+ **kwargs,
1212
+ ) -> Tuple[
1213
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1214
+ ]:
1215
+
1216
+ residual_real = hidden_states_real
1217
+ residual_imag = hidden_states_imag
1218
+
1219
+ hidden_states_real, hidden_states_imag = self.pre_layernorm(
1220
+ hidden_states_real, hidden_states_imag
1221
+ )
1222
+ (
1223
+ hidden_states_real,
1224
+ hidden_states_imag,
1225
+ attn_weights_real,
1226
+ attn_weights_imag,
1227
+ present_key_value,
1228
+ ) = self.self_attn(
1229
+ hidden_states_real=hidden_states_real,
1230
+ hidden_states_imag=hidden_states_imag,
1231
+ position_embeddings=position_embeddings,
1232
+ attn_mask_real=attention_mask_real,
1233
+ attn_mask_imag=attention_mask_imag,
1234
+ past_key_value=past_key_value,
1235
+ output_attentions=output_attentions,
1236
+ use_cache=use_cache,
1237
+ cache_position=cache_position,
1238
+ **kwargs,
1239
+ )
1240
+
1241
+ hidden_states_real = residual_real + hidden_states_real
1242
+ hidden_states_imag = residual_imag + hidden_states_imag
1243
+
1244
+ residual_real = hidden_states_real
1245
+ residual_imag = hidden_states_imag
1246
+ hidden_states_real, hidden_states_imag = self.post_layernorm(
1247
+ hidden_states_real, hidden_states_imag
1248
+ )
1249
+ hidden_states_real, hidden_states_imag = self.mlp(
1250
+ hidden_states_real, hidden_states_imag
1251
+ )
1252
+ hidden_states_real = residual_real + hidden_states_real
1253
+ hidden_states_imag = residual_imag + hidden_states_imag
1254
+
1255
+ outputs = (
1256
+ hidden_states_real,
1257
+ hidden_states_imag,
1258
+ )
1259
+
1260
+ if output_attentions:
1261
+ outputs += (
1262
+ attn_weights_real,
1263
+ attn_weights_imag,
1264
+ )
1265
+
1266
+ if use_cache:
1267
+ outputs += (present_key_value,)
1268
+
1269
+ return outputs
1270
+
1271
+
1272
+ logger = logging.get_logger(__name__)
1273
+
1274
+
1275
+ class ComplexNetLM(PreTrainedModel, GenerationMixin):
1276
+ config_class = ComplexNetConfig
1277
+ supports_gradient_checkpointing = True
1278
+ _supports_flash_attn_2 = True
1279
+
1280
+ def __init__(self, config: ComplexNetConfig):
1281
+ super().__init__(config=config)
1282
+ self.config = config
1283
+ self.n_vocab = self.config.vocab_size
1284
+ self.max_position_embeddings = self.config.max_position_embeddings
1285
+ self.hidden_size = self.config.hidden_size
1286
+ self.num_hidden_layers = self.config.num_hidden_layers
1287
+ self.use_cache = self.config.use_cache
1288
+ self.token_embeddings_real = nn.Embedding(self.n_vocab, self.hidden_size)
1289
+ self.token_embeddings_imag = nn.Embedding(self.n_vocab, self.hidden_size)
1290
+ self.final_norm = ComplexNetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1291
+ self.layer = nn.ModuleList(
1292
+ [
1293
+ ComplexNetDecoderLayer(config, layer_idx)
1294
+ for layer_idx in range(self.num_hidden_layers)
1295
+ ]
1296
+ )
1297
+ self.gradient_checkpointing = False
1298
+ self.rotary_emb = ComplexNetRotaryEmbedding(self.config)
1299
+ self.lm_head = nn.Linear(self.hidden_size * 2, self.n_vocab, bias=False)
1300
+ self.apply(self._init_weights)
1301
+
1302
+ def _init_weights(self, module):
1303
+ std = self.config.initializer_range
1304
+ if isinstance(module, nn.Linear):
1305
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
1306
+ if module.bias is not None:
1307
+ torch.nn.init.zeros_(module.bias)
1308
+ elif isinstance(module, nn.Embedding):
1309
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
1310
+ elif isinstance(module, ComplexLinear):
1311
+ std = std / math.sqrt(2)
1312
+ torch.nn.init.normal_(module.weight_real, mean=0.0, std=std)
1313
+ torch.nn.init.normal_(module.weight_imag, mean=0.0, std=std)
1314
+
1315
+ def embed(
1316
+ self,
1317
+ input_ids: torch.LongTensor,
1318
+ attention_mask: Optional[torch.Tensor] = None,
1319
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
1320
+
1321
+ token_embeddings_real = self.token_embeddings_real(input_ids)
1322
+ token_embeddings_imag = self.token_embeddings_imag(input_ids)
1323
+
1324
+ return token_embeddings_real, token_embeddings_imag
1325
+
1326
+ def token_logits(
1327
+ self,
1328
+ x_real: torch.FloatTensor,
1329
+ x_imag: torch.FloatTensor,
1330
+ ) -> torch.FloatTensor:
1331
+ # catenate the real and imaginary parts
1332
+ x_cat = torch.cat([x_real, x_imag], dim=-1)
1333
+ logits = self.lm_head(x_cat)
1334
+ return logits
1335
+
1336
+ def forward(
1337
+ self,
1338
+ input_ids: torch.LongTensor,
1339
+ attention_mask: Optional[torch.Tensor] = None,
1340
+ labels=None,
1341
+ position_ids: Optional[torch.LongTensor] = None,
1342
+ past_key_values: Optional[Cache] = None,
1343
+ output_attentions: Optional[bool] = False,
1344
+ use_cache: Optional[bool] = False,
1345
+ cache_position: Optional[torch.LongTensor] = None,
1346
+ **kwargs,
1347
+ ) -> dict:
1348
+ output_attentions = (
1349
+ output_attentions
1350
+ if output_attentions is not None
1351
+ else self.config.output_attentions
1352
+ )
1353
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1354
+ if self.gradient_checkpointing and self.training and use_cache:
1355
+ logger.warning_once(
1356
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1357
+ )
1358
+ use_cache = False
1359
+
1360
+ if not isinstance(past_key_values, (type(None), Cache)):
1361
+ raise ValueError(
1362
+ "The `past_key_values` should be either a `Cache` object or `None`."
1363
+ )
1364
+ batch_size, seq_len = input_ids.shape
1365
+ device = input_ids.device
1366
+ x_real, x_imag = self.embed(input_ids, attention_mask)
1367
+ if use_cache and past_key_values is None:
1368
+ past_key_values = ComplexDynamicCache()
1369
+ if cache_position is None:
1370
+ past_seen_tokens = (
1371
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1372
+ )
1373
+ cache_position = torch.arange(
1374
+ past_seen_tokens,
1375
+ past_seen_tokens + x_real.shape[1],
1376
+ device=x_real.device,
1377
+ )
1378
+ if position_ids is None:
1379
+ position_ids = cache_position.unsqueeze(0)
1380
+ causal_mask = self._update_causal_mask(
1381
+ attention_mask, x_real, cache_position, past_key_values, output_attentions
1382
+ )
1383
+ position_embeddings = self.rotary_emb(position_ids, x_real.dtype)
1384
+ all_hidden_states_real = []
1385
+ all_hidden_states_imag = []
1386
+ for i, layer_module in enumerate(self.layer):
1387
+ if self.gradient_checkpointing and self.training:
1388
+ layer_outputs = self._gradient_checkpointing_func(
1389
+ partial(layer_module.__call__, **kwargs),
1390
+ x_real,
1391
+ x_imag,
1392
+ causal_mask,
1393
+ causal_mask,
1394
+ past_key_values,
1395
+ output_attentions,
1396
+ use_cache,
1397
+ cache_position,
1398
+ position_embeddings,
1399
+ )
1400
+ else:
1401
+ layer_outputs = layer_module(
1402
+ hidden_states_real=x_real,
1403
+ hidden_states_imag=x_imag,
1404
+ attention_mask_real=causal_mask,
1405
+ attention_mask_imag=causal_mask,
1406
+ past_key_value=past_key_values,
1407
+ output_attentions=output_attentions,
1408
+ use_cache=use_cache,
1409
+ cache_position=cache_position,
1410
+ position_embeddings=position_embeddings,
1411
+ **kwargs,
1412
+ )
1413
+
1414
+ x_real, x_imag = layer_outputs[:2]
1415
+
1416
+ if output_attentions:
1417
+ all_hidden_states_real.append(layer_outputs[2])
1418
+ all_hidden_states_imag.append(layer_outputs[3])
1419
+
1420
+ x_real, x_imag = self.final_norm(x_real, x_imag)
1421
+ logits = self.token_logits(x_real, x_imag)
1422
+ loss = None
1423
+ if labels is not None:
1424
+ loss = self.loss_function(
1425
+ logits=logits,
1426
+ labels=labels,
1427
+ vocab_size=self.config.vocab_size,
1428
+ **kwargs,
1429
+ )
1430
+
1431
+ return CausalLMOutputWithPast(
1432
+ loss=loss,
1433
+ logits=logits,
1434
+ past_key_values=past_key_values,
1435
+ )
1436
+
1437
+ def _update_causal_mask(
1438
+ self,
1439
+ attention_mask: torch.Tensor,
1440
+ input_tensor: torch.Tensor,
1441
+ cache_position: torch.Tensor,
1442
+ past_key_values: Cache,
1443
+ output_attentions: bool = False,
1444
+ ):
1445
+ if self.config._attn_implementation == "flash_attention_2":
1446
+ if attention_mask is not None and (attention_mask == 0.0).any():
1447
+ return attention_mask
1448
+ return None
1449
+ past_seen_tokens = (
1450
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1451
+ )
1452
+ using_static_cache = isinstance(past_key_values, StaticCache)
1453
+
1454
+ dtype, device = input_tensor.dtype, input_tensor.device
1455
+ sequence_length = input_tensor.shape[1]
1456
+ if using_static_cache:
1457
+ target_length = past_key_values.get_max_cache_shape()
1458
+ else:
1459
+ target_length = (
1460
+ attention_mask.shape[-1]
1461
+ if isinstance(attention_mask, torch.Tensor)
1462
+ else past_seen_tokens + sequence_length + 1
1463
+ )
1464
+
1465
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1466
+ attention_mask=attention_mask,
1467
+ sequence_length=sequence_length,
1468
+ target_length=target_length,
1469
+ dtype=dtype,
1470
+ device=device,
1471
+ cache_position=cache_position,
1472
+ batch_size=input_tensor.shape[0],
1473
+ )
1474
+
1475
+ return causal_mask
1476
+
1477
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1478
+ self,
1479
+ attention_mask: torch.Tensor,
1480
+ sequence_length: int,
1481
+ target_length: int,
1482
+ dtype: torch.dtype,
1483
+ device: torch.device,
1484
+ cache_position: torch.Tensor,
1485
+ batch_size: int,
1486
+ **kwargs,
1487
+ ):
1488
+
1489
+ if attention_mask is not None and attention_mask.dim() == 4:
1490
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1491
+ causal_mask = attention_mask
1492
+ else:
1493
+ min_dtype = torch.finfo(dtype).min
1494
+ causal_mask = torch.full(
1495
+ (sequence_length, target_length),
1496
+ fill_value=min_dtype,
1497
+ dtype=dtype,
1498
+ device=device,
1499
+ )
1500
+ if sequence_length != 1:
1501
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1502
+ causal_mask *= torch.arange(
1503
+ target_length, device=device
1504
+ ) > cache_position.reshape(-1, 1)
1505
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1506
+ if attention_mask is not None:
1507
+ causal_mask = (
1508
+ causal_mask.clone()
1509
+ ) # copy to contiguous memory for in-place edit
1510
+ mask_length = attention_mask.shape[-1]
1511
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[
1512
+ :, None, None, :
1513
+ ].to(causal_mask.device)
1514
+ padding_mask = padding_mask == 0
1515
+ causal_mask[:, :, :, :mask_length] = causal_mask[
1516
+ :, :, :, :mask_length
1517
+ ].masked_fill(padding_mask, min_dtype)
1518
+
1519
+ return causal_mask
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "extra_special_tokens": {},
35
+ "legacy": false,
36
+ "model_max_length": 1000000000000000019884624838656,
37
+ "pad_token": "</s>",
38
+ "padding_side": "right",
39
+ "sp_model_kwargs": {},
40
+ "tokenizer_class": "LlamaTokenizerFast",
41
+ "unk_token": "<unk>",
42
+ "use_default_system_prompt": false
43
+ }