jacksonkek commited on
Commit
52086c1
·
verified ·
1 Parent(s): e9b512f

Upload 6 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
chunk_cache.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.cache_utils import Cache
2
+ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from transformers.utils import logging
6
+ from transformers.configuration_utils import PretrainedConfig
7
+ logger = logging.get_logger(__name__)
8
+
9
+
10
+ class HybridCache(Cache):
11
+ """
12
+ Hybrid Cache class to be used with `torch.compile` for Gemma2 models that alternate between a local sliding window attention
13
+ and global attention in every other layer. Under the hood, Hybrid Cache leverages ["SlidingWindowCache"] for sliding window attention
14
+ and ["StaticCache"] for global attention. For more information, see the documentation of each subcomponeent cache class.
15
+
16
+ Parameters:
17
+ config (`PretrainedConfig):
18
+ The configuration file defining the shape-related attributes required to initialize the static cache.
19
+ batch_size (`int`):
20
+ The batch size with which the model will be used. Note that a new instance must be instantiated if a
21
+ smaller batch size is used.
22
+ max_cache_len (`int`):
23
+ The maximum sequence length with which the model will be used.
24
+ device (`torch.device` or `str`, *optional*):
25
+ The device on which the cache should be initialized. If you're using more than 1 computation device, you
26
+ should pass the `layer_device_map` argument instead.
27
+ dtype (torch.dtype, *optional*, defaults to `torch.float32`):
28
+ The default `dtype` to use when initializing the layer.
29
+ layer_device_map(`Dict[int, Union[str, torch.device, int]]]`, `optional`):
30
+ Mapping between the layers and its device. This is required when you are manually initializing the cache
31
+ and the model is splitted between differents gpus. You can know which layers mapped to which device by
32
+ checking the associated device_map: `model.hf_device_map`.
33
+
34
+ Example:
35
+
36
+ ```python
37
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, HybridCache
38
+
39
+ >>> model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b")
40
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b")
41
+
42
+ >>> inputs = tokenizer(text="My name is Gemma", return_tensors="pt")
43
+
44
+ >>> # Prepare a cache class and pass it to model's forward
45
+ >>> # Leave empty space for 10 new tokens, which can be used when calling forward iteratively 10 times to generate
46
+ >>> max_generated_length = inputs.input_ids.shape[1] + 10
47
+ >>> past_key_values = HybridCache(config=model.config, batch_size=1, max_cache_len=max_generated_length, device=model.device, dtype=model.dtype)
48
+ >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
49
+ >>> outputs.past_key_values # access cache filled with key/values from generation
50
+ HybridCache()
51
+ ```
52
+ """
53
+
54
+ # TODO (joao): dive deeper into gemma2 and paligemma -- there are reports of speed loss with compilation. Revert
55
+ # ALL changes from the PR that commented the line below when reactivating it.
56
+ # is_compileable = True
57
+
58
+ # TODO (joao): remove `=None` in non-optional arguments in v4.46. Remove from `OBJECTS_TO_IGNORE` as well.
59
+ def __init__(
60
+ self,
61
+ config: PretrainedConfig,
62
+ batch_size: int = None,
63
+ max_cache_len: int = None,
64
+ device: Union[torch.device, str] = None,
65
+ dtype: torch.dtype = torch.float32,
66
+ max_batch_size: Optional[int] = None,
67
+ layer_device_map: Optional[Dict[int, Union[str, torch.device, int]]] = None,
68
+ ) -> None:
69
+ super().__init__()
70
+ if batch_size is not None:
71
+ logger.warning_once(
72
+ f"The 'batch_size' argument of {self.__class__.__name__} is deprecated and will be removed in "
73
+ "v4.49. Use the more precisely named 'max_batch_size' argument instead."
74
+ )
75
+ if not hasattr(config, "sliding_window") or config.sliding_window is None:
76
+ raise ValueError(
77
+ "Setting `cache_implementation` to 'sliding_window' requires the model config supporting "
78
+ "sliding window attention, please check if there is a `sliding_window` field in the model "
79
+ "config and it's not set to None."
80
+ )
81
+ self.max_cache_len = max_cache_len
82
+ self.max_batch_size = batch_size or max_batch_size
83
+ # Some model define a custom `head_dim` != config.hidden_size // config.num_attention_heads
84
+ self.head_dim = (
85
+ config.head_dim if hasattr(config, "head_dim") else config.hidden_size // config.num_attention_heads
86
+ )
87
+
88
+ self.dtype = dtype
89
+ self.num_key_value_heads = (
90
+ config.num_attention_heads if config.num_key_value_heads is None else config.num_key_value_heads
91
+ )
92
+
93
+ layer_switch = config.sliding_window_pattern if hasattr(config, "sliding_window_pattern") else 2 # 2 is for BC
94
+ self.is_sliding = torch.tensor(
95
+ [bool((i + 1) % layer_switch) for i in range(config.num_hidden_layers)], dtype=torch.bool
96
+ )
97
+ self.key_cache: List[torch.Tensor] = []
98
+ self.value_cache: List[torch.Tensor] = []
99
+ self.chunk_cache = {}
100
+ global_cache_shape = (self.max_batch_size, self.num_key_value_heads, max_cache_len, self.head_dim)
101
+ sliding_cache_shape = (
102
+ self.max_batch_size,
103
+ self.num_key_value_heads,
104
+ min(config.sliding_window, max_cache_len),
105
+ self.head_dim,
106
+ )
107
+ device = torch.device(device) if device is not None else None
108
+ for i in range(config.num_hidden_layers):
109
+ if layer_device_map is not None:
110
+ layer_device = layer_device_map[i]
111
+ else:
112
+ layer_device = device
113
+ # Note: `mark_static_address` is used to tag the cache as an fixed data pointer, preventing cuda graph
114
+ # breaks when updating the cache.
115
+ cache_shape = global_cache_shape if not self.is_sliding[i] else sliding_cache_shape
116
+ new_layer_key_cache = torch.zeros(cache_shape, dtype=self.dtype, device=layer_device)
117
+ new_layer_value_cache = torch.zeros(cache_shape, dtype=self.dtype, device=layer_device)
118
+ torch._dynamo.mark_static_address(new_layer_key_cache)
119
+ torch._dynamo.mark_static_address(new_layer_value_cache)
120
+ self.key_cache.append(new_layer_key_cache)
121
+ self.value_cache.append(new_layer_value_cache)
122
+
123
+ def _sliding_update(self, cache_position, layer_idx, key_states, value_states, k_out, v_out, max_cache_len):
124
+ if cache_position.shape[0] > max_cache_len:
125
+ k_out = key_states[:, :, -max_cache_len:, :]
126
+ v_out = value_states[:, :, -max_cache_len:, :]
127
+ # Assumption: caches are all zeros at this point, `+=` is equivalent to `=` but compile-friendly
128
+ self.key_cache[layer_idx] += k_out
129
+ self.value_cache[layer_idx] += v_out
130
+ # we should return the whole states instead of k_out, v_out to take the whole prompt
131
+ # into consideration when building kv cache instead of just throwing away tokens outside of the window
132
+ return key_states, value_states
133
+
134
+ slicing = torch.ones(max_cache_len, dtype=torch.long, device=value_states.device).cumsum(0)
135
+ cache_position = cache_position.clamp(0, max_cache_len - 1)
136
+ to_shift = cache_position >= max_cache_len - 1
137
+ indices = (slicing + to_shift[-1].int() - 1) % max_cache_len
138
+ k_out = k_out[:, :, indices]
139
+ v_out = v_out[:, :, indices]
140
+
141
+ k_out[:, :, cache_position] = key_states
142
+ v_out[:, :, cache_position] = value_states
143
+ # `_.zero()` followed by `+=` is equivalent `=`, but compile-friendly (without graph breaks due to assignment)
144
+ self.key_cache[layer_idx].zero_()
145
+ self.value_cache[layer_idx].zero_()
146
+
147
+ self.key_cache[layer_idx] += k_out
148
+ self.value_cache[layer_idx] += v_out
149
+ return k_out, v_out
150
+
151
+ def _static_update(self, layer_idx,cache):
152
+ self.chunk_cache[layer_idx] = cache
153
+ return
154
+
155
+ def _get_chunk_cache(self,layer_idx):
156
+ self.chunk_cache.setdefault(layer_idx,None)
157
+ return self.chunk_cache[layer_idx]
158
+
159
+ def update(
160
+ self,
161
+ key_states: torch.Tensor,
162
+ value_states: torch.Tensor,
163
+ layer_idx: int,
164
+ cache_kwargs: Optional[Dict[str, Any]] = None,
165
+ ) -> Tuple[torch.Tensor]:
166
+ cache_position = cache_kwargs.get("cache_position")
167
+ sliding_window = cache_kwargs.get("sliding_window")
168
+
169
+ # These two `if` blocks are only reached in multigpu and if `layer_device_map` is not passed. They are used
170
+ # when the cache is initialized in the forward pass (e.g. Gemma2)
171
+ if self.key_cache[layer_idx].device != key_states.device:
172
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].to(key_states.device)
173
+ if self.value_cache[layer_idx].device != value_states.device:
174
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].to(value_states.device)
175
+
176
+ k_out = self.key_cache[layer_idx]
177
+ v_out = self.value_cache[layer_idx]
178
+ key_states = key_states.to(k_out.dtype)
179
+ value_states = value_states.to(v_out.dtype)
180
+
181
+ if sliding_window:
182
+ update_fn = self._sliding_update
183
+ else:
184
+ update_fn = self._static_update
185
+
186
+ return update_fn(
187
+ cache_position,
188
+ layer_idx,
189
+ key_states,
190
+ value_states,
191
+ k_out,
192
+ v_out,
193
+ k_out.shape[2],
194
+ )
195
+
196
+ def get_max_cache_shape(self) -> Optional[int]:
197
+ return self.max_cache_len
198
+
199
+ def get_seq_length(self, layer_idx: Optional[int] = 0):
200
+ # Occupied cache == any slot in the 3rd dim (sequence length) holds a non-zero value. To save on compute, let's
201
+ # limit the check to the first batch member and head dimension.
202
+ # TODO: deprecate this function in favor of `cache_position`
203
+ if layer_idx != 0:
204
+ raise ValueError(
205
+ "`get_seq_length` on `HybridCache` may get inconsistent results depending on the layer index. "
206
+ "Using the `layer_idx` argument is not supported."
207
+ )
208
+ return (self.key_cache[layer_idx][0, 0].any(dim=-1)).sum()
209
+
210
+ def reset(self):
211
+ """Resets the cache values while preserving the objects"""
212
+ for layer_idx in range(len(self.key_cache)):
213
+ # In-place ops prevent breaking the static address
214
+ self.key_cache[layer_idx].zero_()
215
+ self.value_cache[layer_idx].zero_()
216
+
217
+ @property
218
+ def batch_size(self):
219
+ logger.warning_once(
220
+ f"The 'batch_size' attribute of {self.__class__.__name__} is deprecated and will be removed in "
221
+ "v4.49. Use the more precisely named 'self.max_batch_size' attribute instead."
222
+ )
223
+ return self.max_batch_size
modeling_gelinear.py ADDED
@@ -0,0 +1,1198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma2/modular_gemma2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gemma2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Callable, List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, StaticCache
29
+ from transformers.generation import GenerationMixin
30
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
38
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from transformers.processing_utils import Unpack
40
+ from transformers.utils import (
41
+ add_code_sample_docstrings,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from transformers.utils.deprecation import deprecate_kwarg
48
+ from transformers.models.gemma2.configuration_gemma2 import Gemma2Config
49
+ from einops import rearrange
50
+ from .chunk_cache import HybridCache
51
+ import gc
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ _CHECKPOINT_FOR_DOC = "google/gemma2-7b"
56
+ _CONFIG_FOR_DOC = "Gemma2Config"
57
+
58
+ class HedgehogFeatureMap(nn.Module):
59
+ def __init__(
60
+ self,
61
+ num_heads: int,
62
+ head_dim: int, # input dim
63
+ feature_dim: int, # output dim
64
+ # dtype: torch.dtype,
65
+ # device: torch.device,
66
+ bias: bool = False,
67
+ eps: float = 1e-12,
68
+ ):
69
+ super().__init__()
70
+
71
+ self.layer = nn.Parameter(
72
+ torch.zeros(
73
+ (num_heads, head_dim, feature_dim),
74
+ # dtype=dtype,
75
+ # device=device,
76
+ )
77
+ )
78
+ nn.init.kaiming_uniform_(self.layer)
79
+ if bias:
80
+ self.bias = nn.Parameter(
81
+ torch.zeros(
82
+ (1, num_heads, 1, 1),
83
+ # dtype=dtype,
84
+ # device=device,
85
+ )
86
+ )
87
+ nn.init.kaiming_uniform_(self.bias)
88
+ else:
89
+ self.bias = 0.0 # hack
90
+ self.eps = eps
91
+
92
+ def forward(self, x: torch.Tensor):
93
+ """
94
+ x = (batch_size, num_heads, seq_len, head_dim)
95
+ """
96
+ output = torch.einsum("hdf,bhld->bhlf", self.layer, x) + self.bias
97
+ output = torch.cat(
98
+ [torch.softmax(output, dim=-1), torch.softmax(-output, dim=-1)], dim=-1
99
+ ).clamp(min=self.eps)
100
+ return output
101
+
102
+ def pad(x, chunk_size=64):
103
+ T = x.shape[-2]
104
+ padded_seq_len = ceildiv(T, chunk_size) * chunk_size
105
+ if x.shape[-2] % chunk_size != 0:
106
+ x = F.pad(x, (0, 0, 0, padded_seq_len - T))
107
+
108
+ return x
109
+
110
+
111
+ def ceildiv(a, b):
112
+ return -(a // -b)
113
+
114
+
115
+ # def chunk_linear_attn(q, k, v, chunk_size=64, cached_kv=None):
116
+ # q, k, v = map(lambda x: pad(x), [q, k, v])
117
+ # q = rearrange(q, "b h (n c) d -> b h n c d", c=chunk_size) * (q.shape[-1] ** -0.5)
118
+ # k = rearrange(k, "b h (n c) d -> b h n c d", c=chunk_size)
119
+ # v = rearrange(v, "b h (n c) d -> b h n c d", c=chunk_size)
120
+ # kv = k.transpose(-1, -2) @ v
121
+ # kv = kv.cumsum(2)
122
+ # if cached_kv is not None:
123
+ # kv += cached_kv
124
+ # kv = torch.cat([torch.zeros_like(kv[:, :, :1]), kv[:, :, :-1]], dim=2)
125
+ # inter = q @ kv # (b, h, n, c, d) @ (b, h, n, d, d) -> (b, h, n, c, d)
126
+ # intra = (
127
+ # (q @ k.transpose(-1, -2)).masked_fill_(
128
+ # torch.triu(
129
+ # torch.ones(chunk_size, chunk_size, dtype=bool, device=q.device),
130
+ # diagonal=1,
131
+ # ),
132
+ # 0,
133
+ # )
134
+ # ) @ v
135
+ # o = inter + intra
136
+ # return rearrange(o, "b h n c d -> b h (n c) d")
137
+
138
+
139
+ def chunk_linear_attn(q, k, v, chunk_size=64, cached_kv=None):
140
+ q, k, v = map(lambda x: pad(x,chunk_size=chunk_size), [q, k, v])
141
+ q = rearrange(q, "b h (n c) d -> b h n c d", c=chunk_size) * (q.shape[-1] ** -0.5)
142
+ k = rearrange(k, "b h (n c) d -> b h n c d", c=chunk_size)
143
+ v = rearrange(v, "b h (n c) d -> b h n c d", c=chunk_size)
144
+ kv = k.transpose(-1, -2) @ v
145
+ if cached_kv is None:
146
+ kv = kv.cumsum(2)
147
+ cached_kv = kv[:,:,-1:,...]
148
+ kv = torch.cat([torch.zeros_like(kv[:, :, :1]), kv[:, :, :-1]], dim=2)
149
+ inter = q @ kv # (b, h, n, c, d) @ (b, h, n, d, d) -> (b, h, n, c, d)
150
+ intra = (
151
+ (q @ k.transpose(-1, -2)).masked_fill_(
152
+ torch.triu(
153
+ torch.ones(chunk_size, chunk_size, dtype=bool, device=q.device),
154
+ diagonal=1,
155
+ ),
156
+ 0,
157
+ )
158
+ ) @ v
159
+ o = inter + intra
160
+ elif cached_kv is not None:
161
+ kv += cached_kv
162
+ cached_kv = kv
163
+ o = q @ kv
164
+ return rearrange(o, "b h n c d -> b h (n c) d"), cached_kv
165
+
166
+
167
+ class Gemma2LinearAttention(nn.Module):
168
+ def __init__(self, config: Gemma2Config, layer_idx: int):
169
+ super().__init__()
170
+ self.config = config
171
+ self.layer_idx = layer_idx
172
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
173
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
174
+ self.scaling = config.query_pre_attn_scalar**-0.5
175
+ self.attention_dropout = self.config.attention_dropout
176
+ self.is_causal = True
177
+
178
+ self.q_proj = nn.Linear(
179
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
180
+ )
181
+ self.k_proj = nn.Linear(
182
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
183
+ )
184
+ self.v_proj = nn.Linear(
185
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
186
+ )
187
+ self.o_proj = nn.Linear(
188
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
189
+ )
190
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
191
+ self.feature_dim = config.feature_dim
192
+ self.sliding_window = config.sliding_window if not bool(layer_idx % 2) else None
193
+ self.feature_map_q = HedgehogFeatureMap(
194
+ num_heads=config.num_attention_heads,
195
+ head_dim=self.head_dim,
196
+ feature_dim=self.feature_dim,
197
+ )
198
+ self.feature_map_k = HedgehogFeatureMap(
199
+ num_heads=config.num_attention_heads,
200
+ head_dim=self.head_dim,
201
+ feature_dim=self.feature_dim,
202
+ )
203
+
204
+ def forward(
205
+ self,
206
+ hidden_states: torch.Tensor,
207
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
208
+ attention_mask: Optional[torch.Tensor],
209
+ past_key_value: Optional[Cache] = None,
210
+ cache_position: Optional[torch.LongTensor] = None,
211
+ **kwargs: Unpack[FlashAttentionKwargs],
212
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
213
+ input_shape = hidden_states.shape[:-1]
214
+ hidden_shape = (*input_shape, -1, self.head_dim)
215
+ batch_size = hidden_states.shape[0]
216
+ seq_len = hidden_states.shape[1]
217
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
218
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
219
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
220
+
221
+ cos, sin = position_embeddings
222
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
223
+
224
+
225
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
226
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
227
+
228
+ query_states = self.feature_map_q(query_states)
229
+ key_states = self.feature_map_k(key_states)
230
+ chunk_size = 64
231
+ cache = None
232
+ if past_key_value is not None:
233
+ if past_key_value._get_chunk_cache(self.layer_idx) is not None:
234
+ cache = past_key_value._get_chunk_cache(self.layer_idx)
235
+ chunk_size = 1
236
+ output, cache = chunk_linear_attn(query_states, key_states, value_states,chunk_size=chunk_size, cached_kv=cache)
237
+ past_key_value._static_update(self.layer_idx,cache)
238
+
239
+ output = (
240
+ output.transpose(1, 2)
241
+ .contiguous()[:, :seq_len, ...]
242
+ .view(batch_size, seq_len, -1)
243
+ )
244
+ attn_output = self.o_proj(output)
245
+ return attn_output, output
246
+
247
+
248
+ class Gemma2RMSNorm(nn.Module):
249
+ def __init__(self, dim: int, eps: float = 1e-6):
250
+ super().__init__()
251
+ self.eps = eps
252
+ self.weight = nn.Parameter(torch.zeros(dim))
253
+
254
+ def _norm(self, x):
255
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
256
+
257
+ def forward(self, x):
258
+ output = self._norm(x.float())
259
+ # Llama does x.to(float16) * w whilst Gemma2 is (x * w).to(float16)
260
+ # See https://github.com/huggingface/transformers/pull/29402
261
+ output = output * (1.0 + self.weight.float())
262
+ return output.type_as(x)
263
+
264
+ def extra_repr(self):
265
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
266
+
267
+
268
+ class Gemma2MLP(nn.Module):
269
+ def __init__(self, config):
270
+ super().__init__()
271
+ self.config = config
272
+ self.hidden_size = config.hidden_size
273
+ self.intermediate_size = config.intermediate_size
274
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
275
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
276
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
277
+ self.act_fn = ACT2FN[config.hidden_activation]
278
+
279
+ def forward(self, x):
280
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
281
+ return down_proj
282
+
283
+
284
+ def rotate_half(x):
285
+ """Rotates half the hidden dims of the input."""
286
+ x1 = x[..., : x.shape[-1] // 2]
287
+ x2 = x[..., x.shape[-1] // 2 :]
288
+ return torch.cat((-x2, x1), dim=-1)
289
+
290
+
291
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
292
+ """Applies Rotary Position Embedding to the query and key tensors.
293
+
294
+ Args:
295
+ q (`torch.Tensor`): The query tensor.
296
+ k (`torch.Tensor`): The key tensor.
297
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
298
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
299
+ position_ids (`torch.Tensor`, *optional*):
300
+ Deprecated and unused.
301
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
302
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
303
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
304
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
305
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
306
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
307
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
308
+ Returns:
309
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
310
+ """
311
+ cos = cos.unsqueeze(unsqueeze_dim)
312
+ sin = sin.unsqueeze(unsqueeze_dim)
313
+ q_embed = (q * cos) + (rotate_half(q) * sin)
314
+ k_embed = (k * cos) + (rotate_half(k) * sin)
315
+ return q_embed, k_embed
316
+
317
+
318
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
319
+ """
320
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
321
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
322
+ """
323
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
324
+ if n_rep == 1:
325
+ return hidden_states
326
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
327
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
328
+
329
+
330
+ def eager_attention_forward(
331
+ module: nn.Module,
332
+ query: torch.Tensor,
333
+ key: torch.Tensor,
334
+ value: torch.Tensor,
335
+ attention_mask: Optional[torch.Tensor],
336
+ dropout: float = 0.0,
337
+ scaling: Optional[float] = None,
338
+ softcap: Optional[float] = None,
339
+ **kwargs,
340
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
341
+ if scaling is None:
342
+ scaling = module.head_dim**-0.5
343
+
344
+ key_states = repeat_kv(key, module.num_key_value_groups)
345
+ value_states = repeat_kv(value, module.num_key_value_groups)
346
+
347
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
348
+
349
+ if softcap is not None:
350
+ attn_weights = attn_weights / softcap
351
+ attn_weights = torch.tanh(attn_weights)
352
+ attn_weights = attn_weights * softcap
353
+ if attention_mask is not None: # no matter the length, we just slice it
354
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
355
+ attn_weights = attn_weights + causal_mask
356
+
357
+ # upcast attention to fp32
358
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
359
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
360
+ attn_output = torch.matmul(attn_weights, value_states)
361
+ attn_output = attn_output.transpose(1, 2).contiguous()
362
+ return attn_output, attn_weights
363
+
364
+
365
+ class Gemma2Attention(nn.Module):
366
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
367
+
368
+ def __init__(self, config: Gemma2Config, layer_idx: int):
369
+ super().__init__()
370
+ self.config = config
371
+ self.layer_idx = layer_idx
372
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
373
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
374
+ self.scaling = config.query_pre_attn_scalar**-0.5
375
+ self.attention_dropout = self.config.attention_dropout
376
+ self.is_causal = True
377
+
378
+ self.q_proj = nn.Linear(
379
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
380
+ )
381
+ self.k_proj = nn.Linear(
382
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
383
+ )
384
+ self.v_proj = nn.Linear(
385
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
386
+ )
387
+ self.o_proj = nn.Linear(
388
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
389
+ )
390
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
391
+ self.sliding_window = config.sliding_window if not bool(layer_idx % 2) else None
392
+
393
+ def forward(
394
+ self,
395
+ hidden_states: torch.Tensor,
396
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
397
+ attention_mask: Optional[torch.Tensor],
398
+ past_key_value: Optional[Cache] = None,
399
+ cache_position: Optional[torch.LongTensor] = None,
400
+ **kwargs: Unpack[FlashAttentionKwargs],
401
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
402
+ input_shape = hidden_states.shape[:-1]
403
+ hidden_shape = (*input_shape, -1, self.head_dim)
404
+
405
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
406
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
407
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
408
+
409
+ cos, sin = position_embeddings
410
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
411
+
412
+ if past_key_value is not None:
413
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
414
+ cache_kwargs = {
415
+ "sin": sin,
416
+ "cos": cos,
417
+ "cache_position": cache_position,
418
+ "sliding_window": self.sliding_window,
419
+ }
420
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
421
+
422
+ # Here we need to slice as we use a static cache by default, but FA2 does not support it
423
+ if attention_mask is not None and self.config._attn_implementation == "flash_attention_2":
424
+ seq_len = attention_mask.shape[-1]
425
+ key_states, value_states = key_states[:, :, :seq_len, :], value_states[:, :, :seq_len, :]
426
+
427
+ attention_interface: Callable = eager_attention_forward
428
+ if self.config._attn_implementation != "eager":
429
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
430
+ logger.warning_once(
431
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
432
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
433
+ )
434
+ else:
435
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
436
+
437
+ attn_output, attn_weights = attention_interface(
438
+ self,
439
+ query_states,
440
+ key_states,
441
+ value_states,
442
+ attention_mask,
443
+ dropout=self.attention_dropout if self.training else 0.0,
444
+ scaling=self.scaling,
445
+ sliding_window=self.sliding_window,
446
+ softcap=self.attn_logit_softcapping,
447
+ **kwargs,
448
+ )
449
+
450
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
451
+ attn_output = self.o_proj(attn_output)
452
+ return attn_output, attn_weights
453
+
454
+
455
+ class Gemma2DecoderLayer(nn.Module):
456
+ def __init__(self, config: Gemma2Config, layer_idx: int):
457
+ super().__init__()
458
+ self.hidden_size = config.hidden_size
459
+ self.config = config
460
+ self.is_sliding = not bool(layer_idx % 2)
461
+ if self.is_sliding:
462
+ self.self_attn = Gemma2Attention(config=config, layer_idx=layer_idx)
463
+ else:
464
+ self.self_attn = Gemma2LinearAttention(config=config, layer_idx=layer_idx)
465
+ self.mlp = Gemma2MLP(config)
466
+ self.input_layernorm = Gemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
467
+ self.post_attention_layernorm = Gemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
468
+
469
+ self.pre_feedforward_layernorm = Gemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
470
+ self.post_feedforward_layernorm = Gemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
471
+ self.sliding_window = config.sliding_window
472
+
473
+ def forward(
474
+ self,
475
+ hidden_states: torch.Tensor,
476
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
477
+ attention_mask: Optional[torch.Tensor] = None,
478
+ position_ids: Optional[torch.LongTensor] = None,
479
+ past_key_value: Optional[Cache] = None,
480
+ output_attentions: Optional[bool] = False,
481
+ use_cache: Optional[bool] = False,
482
+ cache_position: Optional[torch.LongTensor] = None,
483
+ last_cache_position: int = 0,
484
+ **kwargs,
485
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
486
+ if self.is_sliding and attention_mask is not None: # efficient SDPA and no padding
487
+ # In prefill, we may be larger than sliding window
488
+ effective_seq_len = max(cache_position.shape[0], self.sliding_window)
489
+ # For FA2, the mask is 2D and is of shape [bs, processed_tokens] (not [bs, max_cache_len]),
490
+ # thus we must slice from the right (at most `effective_seq_len` elements)
491
+ if self.config._attn_implementation == "flash_attention_2":
492
+ attention_mask = attention_mask[:, -effective_seq_len:]
493
+ # Otherwise, the mask is 4D of shape [bs, 1, query_len, max_cache_len] thus we must slice
494
+ # from the left, with an offset if we are beyond the sliding window
495
+ else:
496
+ min_dtype = torch.finfo(attention_mask.dtype).min
497
+ sliding_window_mask = torch.tril(
498
+ torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-self.sliding_window
499
+ )
500
+ attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
501
+ # In case we are beyond the sliding window, we need to correctly offset the mask slicing
502
+ # `last_cache_position` is equivalent to `cache_position[-1]` but without breaking dynamo
503
+ offset = last_cache_position - effective_seq_len
504
+ # Should only be used when beyond the sliding window (i.e. offset > 0)
505
+ offset = max(0, offset)
506
+ attention_mask = attention_mask[:, :, :, offset : offset + effective_seq_len]
507
+
508
+ residual = hidden_states
509
+
510
+ hidden_states = self.input_layernorm(hidden_states)
511
+
512
+ # Self Attention
513
+ hidden_states, self_attn_weights = self.self_attn(
514
+ hidden_states=hidden_states,
515
+ position_embeddings=position_embeddings,
516
+ attention_mask=attention_mask,
517
+ position_ids=position_ids,
518
+ past_key_value=past_key_value,
519
+ output_attentions=output_attentions,
520
+ use_cache=use_cache,
521
+ cache_position=cache_position,
522
+ **kwargs,
523
+ )
524
+ hidden_states = self.post_attention_layernorm(hidden_states)
525
+ hidden_states = residual + hidden_states
526
+
527
+ residual = hidden_states
528
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
529
+ hidden_states = self.mlp(hidden_states)
530
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
531
+ hidden_states = residual + hidden_states
532
+
533
+ outputs = (hidden_states,)
534
+
535
+ if output_attentions:
536
+ outputs += (self_attn_weights,)
537
+
538
+ return outputs
539
+
540
+
541
+ class Gemma2RotaryEmbedding(nn.Module):
542
+ def __init__(self, config: Gemma2Config, device=None):
543
+ super().__init__()
544
+ # BC: "rope_type" was originally "type"
545
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
546
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
547
+ else:
548
+ self.rope_type = "default"
549
+ self.max_seq_len_cached = config.max_position_embeddings
550
+ self.original_max_seq_len = config.max_position_embeddings
551
+
552
+ self.config = config
553
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
554
+
555
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
556
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
557
+ self.original_inv_freq = self.inv_freq
558
+
559
+ def _dynamic_frequency_update(self, position_ids, device):
560
+ """
561
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
562
+ 1 - growing beyond the cached sequence length (allow scaling)
563
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
564
+ """
565
+ seq_len = torch.max(position_ids) + 1
566
+ if seq_len > self.max_seq_len_cached: # growth
567
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
568
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
569
+ self.max_seq_len_cached = seq_len
570
+
571
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
572
+ # This .to() is needed if the model has been moved to a device after being initialized (because
573
+ # the buffer is automatically moved, but not the original copy)
574
+ self.original_inv_freq = self.original_inv_freq.to(device)
575
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
576
+ self.max_seq_len_cached = self.original_max_seq_len
577
+
578
+ @torch.no_grad()
579
+ def forward(self, x, position_ids):
580
+ if "dynamic" in self.rope_type:
581
+ self._dynamic_frequency_update(position_ids, device=x.device)
582
+
583
+ # Core RoPE block
584
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
585
+ position_ids_expanded = position_ids[:, None, :].float()
586
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
587
+ device_type = x.device.type
588
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
589
+ with torch.autocast(device_type=device_type, enabled=False):
590
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
591
+ emb = torch.cat((freqs, freqs), dim=-1)
592
+ cos = emb.cos()
593
+ sin = emb.sin()
594
+
595
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
596
+ cos = cos * self.attention_scaling
597
+ sin = sin * self.attention_scaling
598
+
599
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
600
+
601
+
602
+ GEMMA2_START_DOCSTRING = r"""
603
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
604
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
605
+ etc.)
606
+
607
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
608
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
609
+ and behavior.
610
+
611
+ Parameters:
612
+ config ([`Gemma2Config`]):
613
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
614
+ load the weights associated with the model, only the configuration. Check out the
615
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
616
+ """
617
+
618
+
619
+ @add_start_docstrings(
620
+ "The bare Gemma2 Model outputting raw hidden-states without any specific head on top.",
621
+ GEMMA2_START_DOCSTRING,
622
+ )
623
+ class Gemma2PreTrainedModel(PreTrainedModel):
624
+ config_class = Gemma2Config
625
+ base_model_prefix = "model"
626
+ supports_gradient_checkpointing = True
627
+ _no_split_modules = ["Gemma2DecoderLayer"]
628
+ _skip_keys_device_placement = ["past_key_values"]
629
+ _supports_flash_attn_2 = True
630
+ _supports_sdpa = True
631
+ _supports_flex_attn = True
632
+ _supports_cache_class = True
633
+ _supports_quantized_cache = True
634
+ _supports_static_cache = True
635
+ _supports_attention_backend = True
636
+
637
+ def _init_weights(self, module):
638
+ std = self.config.initializer_range
639
+ if isinstance(module, nn.Linear):
640
+ module.weight.data.normal_(mean=0.0, std=std)
641
+ if module.bias is not None:
642
+ module.bias.data.zero_()
643
+ elif isinstance(module, nn.Embedding):
644
+ module.weight.data.normal_(mean=0.0, std=std)
645
+ if module.padding_idx is not None:
646
+ module.weight.data[module.padding_idx].zero_()
647
+
648
+
649
+ GEMMA2_INPUTS_DOCSTRING = r"""
650
+ Args:
651
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
652
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
653
+ it.
654
+
655
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
656
+ [`PreTrainedTokenizer.__call__`] for details.
657
+
658
+ [What are input IDs?](../glossary#input-ids)
659
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
660
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
661
+
662
+ - 1 for tokens that are **not masked**,
663
+ - 0 for tokens that are **masked**.
664
+
665
+ [What are attention masks?](../glossary#attention-mask)
666
+
667
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
668
+ [`PreTrainedTokenizer.__call__`] for details.
669
+
670
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
671
+ `past_key_values`).
672
+
673
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
674
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
675
+ information on the default strategy.
676
+
677
+ - 1 indicates the head is **not masked**,
678
+ - 0 indicates the head is **masked**.
679
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
680
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
681
+ config.n_positions - 1]`.
682
+
683
+ [What are position IDs?](../glossary#position-ids)
684
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
685
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
686
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
687
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
688
+
689
+ Two formats are allowed:
690
+ - a [`~cache_utils.Cache`] instance, see our
691
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
692
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
693
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
694
+ cache format.
695
+
696
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
697
+ legacy cache format will be returned.
698
+
699
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
700
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
701
+ of shape `(batch_size, sequence_length)`.
702
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
703
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
704
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
705
+ model's internal embedding lookup matrix.
706
+ use_cache (`bool`, *optional*):
707
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
708
+ `past_key_values`).
709
+ output_attentions (`bool`, *optional*):
710
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
711
+ tensors for more detail.
712
+ output_hidden_states (`bool`, *optional*):
713
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
714
+ more detail.
715
+ return_dict (`bool`, *optional*):
716
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
717
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
718
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
719
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
720
+ the complete sequence length.
721
+ """
722
+
723
+
724
+ @add_start_docstrings(
725
+ "The bare Gemma2 Model outputting raw hidden-states without any specific head on top.",
726
+ GEMMA2_START_DOCSTRING,
727
+ )
728
+ class Gemma2Model(Gemma2PreTrainedModel):
729
+ """
730
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Gemma2DecoderLayer`]
731
+
732
+ Args:
733
+ config: Gemma2Config
734
+ """
735
+
736
+ def __init__(self, config: Gemma2Config):
737
+ super().__init__(config)
738
+ self.padding_idx = config.pad_token_id
739
+ self.vocab_size = config.vocab_size
740
+
741
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
742
+ self.layers = nn.ModuleList(
743
+ [Gemma2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
744
+ )
745
+ self.norm = Gemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
746
+ self.rotary_emb = Gemma2RotaryEmbedding(config=config)
747
+ self.gradient_checkpointing = False
748
+ self.past_key_values = None
749
+ # Initialize weights and apply final processing
750
+ self.post_init()
751
+
752
+ def get_input_embeddings(self):
753
+ return self.embed_tokens
754
+
755
+ def set_input_embeddings(self, value):
756
+ self.embed_tokens = value
757
+
758
+ @add_start_docstrings_to_model_forward(GEMMA2_INPUTS_DOCSTRING)
759
+ def forward(
760
+ self,
761
+ input_ids: torch.LongTensor = None,
762
+ attention_mask: Optional[torch.Tensor] = None,
763
+ position_ids: Optional[torch.LongTensor] = None,
764
+ past_key_values: Optional[HybridCache] = None,
765
+ inputs_embeds: Optional[torch.FloatTensor] = None,
766
+ use_cache: Optional[bool] = None,
767
+ output_attentions: Optional[bool] = None,
768
+ output_hidden_states: Optional[bool] = None,
769
+ return_dict: Optional[bool] = None,
770
+ cache_position: Optional[torch.LongTensor] = None,
771
+ last_cache_position: Optional[int] = None,
772
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
773
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
774
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
775
+ output_hidden_states = (
776
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
777
+ )
778
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
779
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
780
+
781
+ if (input_ids is None) ^ (inputs_embeds is not None):
782
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
783
+
784
+ if self.gradient_checkpointing and self.training and use_cache:
785
+ logger.warning_once(
786
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
787
+ )
788
+ use_cache = False
789
+
790
+ if inputs_embeds is None:
791
+ inputs_embeds = self.embed_tokens(input_ids)
792
+ # if use_cache and past_key_values is None and not self.training:
793
+ # batch_size, seq_len, _ = inputs_embeds.shape
794
+ # # NOTE: ideally, `HybridCache` should be initialized outside the model with `layer_device_map`
795
+ # past_key_values = HybridCache(
796
+ # self.config,
797
+ # max_batch_size=batch_size,
798
+ # max_cache_len=seq_len,
799
+ # dtype=inputs_embeds.dtype,
800
+ # device=self.device,
801
+ # )
802
+ old_key_cache = past_key_values.key_cache
803
+ old_value_cache = past_key_values.value_cache
804
+ if self.past_key_values is None:
805
+ self.past_key_values = HybridCache(
806
+ self.config,
807
+ max_batch_size=past_key_values.max_batch_size,
808
+ max_cache_len=past_key_values.max_cache_len,
809
+ dtype=inputs_embeds.dtype,
810
+ device=self.device,
811
+ )
812
+ self.past_key_values.key_cache = old_key_cache
813
+ self.past_key_values.value_cache = old_value_cache
814
+ if inputs_embeds.shape[1] > 1:
815
+ self.past_key_values.chunk_cache = {}
816
+ del past_key_values
817
+ del old_key_cache
818
+ del old_value_cache
819
+ gc.collect()
820
+ torch.cuda.empty_cache()
821
+ if cache_position is None:
822
+ past_seen_tokens = self.past_key_values.get_seq_length() if self.past_key_values is not None else 0
823
+ cache_position = torch.arange(
824
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
825
+ )
826
+
827
+ if position_ids is None:
828
+ position_ids = cache_position.unsqueeze(0)
829
+
830
+ # This is needed to correctly slice the mask without data-dependent slicing later on if using dynamo tracing
831
+ # (retrieving the same value from `cache_position` later on would crash dynamo)
832
+ if last_cache_position is None:
833
+ last_cache_position = 0
834
+ if attention_mask is not None:
835
+ # In case a 4d mask is passed directly without using `generate`, we have to rely on cache_position
836
+ # It will break dynamo tracing but there are no way around it (and it should never happen in practice)
837
+ last_cache_position = (
838
+ attention_mask.shape[-1] if attention_mask.dim() == 2 else cache_position[-1].item()
839
+ )
840
+ causal_mask = self._update_causal_mask(
841
+ attention_mask, inputs_embeds, cache_position, self.past_key_values, output_attentions
842
+ )
843
+
844
+ # embed positions
845
+ hidden_states = inputs_embeds
846
+
847
+ # create position embeddings to be shared across the decoder layers
848
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
849
+
850
+ # normalized
851
+ # Gemma2 downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
852
+ # See https://github.com/huggingface/transformers/pull/29402
853
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
854
+ hidden_states = hidden_states * normalizer
855
+
856
+ # decoder layers
857
+ all_hidden_states = () if output_hidden_states else None
858
+ all_self_attns = () if output_attentions else None
859
+
860
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
861
+ if output_hidden_states:
862
+ all_hidden_states += (hidden_states,)
863
+
864
+ if self.gradient_checkpointing and self.training:
865
+ layer_outputs = self._gradient_checkpointing_func(
866
+ decoder_layer.__call__,
867
+ hidden_states,
868
+ position_embeddings,
869
+ causal_mask,
870
+ position_ids,
871
+ self.past_key_values,
872
+ output_attentions,
873
+ use_cache,
874
+ cache_position,
875
+ last_cache_position,
876
+ )
877
+ else:
878
+ layer_outputs = decoder_layer(
879
+ hidden_states,
880
+ position_embeddings=position_embeddings,
881
+ attention_mask=causal_mask,
882
+ position_ids=position_ids,
883
+ past_key_value=self.past_key_values,
884
+ output_attentions=output_attentions,
885
+ use_cache=use_cache,
886
+ cache_position=cache_position,
887
+ last_cache_position=last_cache_position,
888
+ **flash_attn_kwargs,
889
+ )
890
+
891
+ hidden_states = layer_outputs[0]
892
+
893
+ if output_attentions:
894
+ all_self_attns += (layer_outputs[1],)
895
+
896
+ hidden_states = self.norm(hidden_states)
897
+
898
+ if output_hidden_states:
899
+ all_hidden_states += (hidden_states,)
900
+
901
+ output = BaseModelOutputWithPast(
902
+ last_hidden_state=hidden_states,
903
+ past_key_values=self.past_key_values,
904
+ hidden_states=all_hidden_states,
905
+ attentions=all_self_attns,
906
+ )
907
+ return output if return_dict else output.to_tuple()
908
+
909
+ @torch.no_grad()
910
+ def _update_causal_mask(
911
+ self,
912
+ attention_mask: torch.Tensor,
913
+ input_tensor: torch.Tensor,
914
+ cache_position: torch.Tensor,
915
+ past_key_values: HybridCache,
916
+ output_attentions: bool,
917
+ ):
918
+ # Flash Attention currently doesn't support static cache but Gemma2 work only with static cache.
919
+ # So we will pass in attention mask as is in any case, not only when ther's padding. Then we'll use its shape
920
+ # to cut out keys/values trailing 0 used in static cache. This workaround should be compile compatible
921
+ # as it doesn't cause dynamic control issues.
922
+ if self.config._attn_implementation == "flash_attention_2":
923
+ return attention_mask
924
+
925
+ dtype, device = input_tensor.dtype, input_tensor.device
926
+ sequence_length = input_tensor.shape[1]
927
+ if isinstance(past_key_values, (HybridCache, StaticCache)):
928
+ target_length = past_key_values.get_max_cache_shape()
929
+ else:
930
+ target_length = attention_mask.shape[-1] if attention_mask is not None else input_tensor.shape[1]
931
+
932
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
933
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
934
+ attention_mask,
935
+ sequence_length=sequence_length,
936
+ target_length=target_length,
937
+ dtype=dtype,
938
+ device=device,
939
+ cache_position=cache_position,
940
+ batch_size=input_tensor.shape[0],
941
+ )
942
+ return causal_mask
943
+
944
+ @staticmethod
945
+ def _prepare_4d_causal_attention_mask_with_cache_position(
946
+ attention_mask: torch.Tensor,
947
+ sequence_length: int,
948
+ target_length: int,
949
+ dtype: torch.dtype,
950
+ device: torch.device,
951
+ cache_position: torch.Tensor,
952
+ batch_size: int,
953
+ **kwargs,
954
+ ):
955
+ """
956
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
957
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
958
+
959
+ Args:
960
+ attention_mask (`torch.Tensor`):
961
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
962
+ `(batch_size, 1, query_length, key_value_length)`.
963
+ sequence_length (`int`):
964
+ The sequence length being processed.
965
+ target_length (`int`):
966
+ The target length: when generating with static cache, the mask should be as long as the static cache,
967
+ to account for the 0 padding, the part of the cache that is not filled yet.
968
+ dtype (`torch.dtype`):
969
+ The dtype to use for the 4D attention mask.
970
+ device (`torch.device`):
971
+ The device to place the 4D attention mask on.
972
+ cache_position (`torch.Tensor`):
973
+ Indices depicting the position of the input sequence tokens in the sequence.
974
+ batch_size (`torch.Tensor`):
975
+ Batch size.
976
+ """
977
+ if attention_mask is not None and attention_mask.dim() == 4:
978
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
979
+ causal_mask = attention_mask
980
+ else:
981
+ min_dtype = torch.finfo(dtype).min
982
+ causal_mask = torch.full(
983
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
984
+ )
985
+ if sequence_length != 1:
986
+ causal_mask = torch.triu(causal_mask, diagonal=1)
987
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
988
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
989
+ if attention_mask is not None:
990
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
991
+ mask_length = attention_mask.shape[-1]
992
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
993
+ causal_mask.device
994
+ )
995
+ padding_mask = padding_mask == 0
996
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
997
+ padding_mask, min_dtype
998
+ )
999
+
1000
+ return causal_mask
1001
+
1002
+
1003
+ class Gemma2ForCausalLM(Gemma2PreTrainedModel, GenerationMixin):
1004
+ _tied_weights_keys = ["lm_head.weight"]
1005
+ _tp_plan = {"lm_head": "colwise_rep"}
1006
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1007
+
1008
+ def __init__(self, config):
1009
+ super().__init__(config)
1010
+ self.model = Gemma2Model(config)
1011
+ self.vocab_size = config.vocab_size
1012
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1013
+
1014
+ # Initialize weights and apply final processing
1015
+ self.post_init()
1016
+
1017
+ def get_input_embeddings(self):
1018
+ return self.model.embed_tokens
1019
+
1020
+ def set_input_embeddings(self, value):
1021
+ self.model.embed_tokens = value
1022
+
1023
+ def get_output_embeddings(self):
1024
+ return self.lm_head
1025
+
1026
+ def set_output_embeddings(self, new_embeddings):
1027
+ self.lm_head = new_embeddings
1028
+
1029
+ def set_decoder(self, decoder):
1030
+ self.model = decoder
1031
+
1032
+ def get_decoder(self):
1033
+ return self.model
1034
+
1035
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
1036
+ @add_start_docstrings_to_model_forward(GEMMA2_INPUTS_DOCSTRING)
1037
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1038
+ def forward(
1039
+ self,
1040
+ input_ids: torch.LongTensor = None,
1041
+ attention_mask: Optional[torch.Tensor] = None,
1042
+ position_ids: Optional[torch.LongTensor] = None,
1043
+ past_key_values: Optional[HybridCache] = None,
1044
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1045
+ labels: Optional[torch.LongTensor] = None,
1046
+ use_cache: Optional[bool] = None,
1047
+ output_attentions: Optional[bool] = None,
1048
+ output_hidden_states: Optional[bool] = None,
1049
+ return_dict: Optional[bool] = None,
1050
+ cache_position: Optional[torch.LongTensor] = None,
1051
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1052
+ **loss_kwargs,
1053
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1054
+ r"""
1055
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1056
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1057
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1058
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1059
+
1060
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1061
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1062
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1063
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1064
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1065
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1066
+
1067
+ Returns:
1068
+
1069
+ Example:
1070
+
1071
+ ```python
1072
+ >>> from transformers import AutoTokenizer, Gemma2ForCausalLM
1073
+
1074
+ >>> model = Gemma2ForCausalLM.from_pretrained("google/gemma-2-9b")
1075
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
1076
+
1077
+ >>> prompt = "What is your favorite condiment?"
1078
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1079
+
1080
+ >>> # Generate
1081
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1082
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1083
+ "What is your favorite condiment?"
1084
+ ```"""
1085
+
1086
+ if self.training and self.config._attn_implementation != "eager":
1087
+ logger.warning_once(
1088
+ "It is strongly recommended to train Gemma2 models with the `eager` attention implementation "
1089
+ f"instead of `{self.config._attn_implementation}`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`."
1090
+ )
1091
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1092
+ output_hidden_states = (
1093
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1094
+ )
1095
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1096
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1097
+
1098
+ outputs = self.model(
1099
+ input_ids=input_ids,
1100
+ attention_mask=attention_mask,
1101
+ position_ids=position_ids,
1102
+ past_key_values=past_key_values,
1103
+ inputs_embeds=inputs_embeds,
1104
+ use_cache=use_cache,
1105
+ output_attentions=output_attentions,
1106
+ output_hidden_states=output_hidden_states,
1107
+ return_dict=return_dict,
1108
+ cache_position=cache_position,
1109
+ **loss_kwargs,
1110
+ )
1111
+
1112
+ hidden_states = outputs[0]
1113
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1114
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1115
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1116
+ if self.config.final_logit_softcapping is not None:
1117
+ logits = logits / self.config.final_logit_softcapping
1118
+ logits = torch.tanh(logits)
1119
+ logits = logits * self.config.final_logit_softcapping
1120
+
1121
+ loss = None
1122
+ if labels is not None:
1123
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1124
+
1125
+ if not return_dict:
1126
+ output = (logits,) + outputs[1:]
1127
+ return (loss,) + output if loss is not None else output
1128
+
1129
+ return CausalLMOutputWithPast(
1130
+ loss=loss,
1131
+ logits=logits,
1132
+ past_key_values=outputs.past_key_values,
1133
+ hidden_states=outputs.hidden_states,
1134
+ attentions=outputs.attentions,
1135
+ )
1136
+
1137
+ def prepare_inputs_for_generation(
1138
+ self,
1139
+ input_ids,
1140
+ past_key_values=None,
1141
+ attention_mask=None,
1142
+ inputs_embeds=None,
1143
+ cache_position=None,
1144
+ position_ids=None,
1145
+ use_cache=True,
1146
+ logits_to_keep=None,
1147
+ **kwargs,
1148
+ ):
1149
+ # Overwritten: has a special cache type, `HybridCache`
1150
+
1151
+ model_inputs = super().prepare_inputs_for_generation(
1152
+ input_ids,
1153
+ past_key_values=past_key_values,
1154
+ attention_mask=attention_mask,
1155
+ inputs_embeds=inputs_embeds,
1156
+ cache_position=cache_position,
1157
+ position_ids=position_ids,
1158
+ use_cache=use_cache,
1159
+ logits_to_keep=logits_to_keep,
1160
+ **kwargs,
1161
+ )
1162
+
1163
+ # This is needed to correctly slice the mask without data-dependent slicing later on if using dynamo tracing
1164
+ # (retrieving the same value from `cache_position` later on would crash dynamo)
1165
+ model_inputs["last_cache_position"] = attention_mask.shape[-1] if attention_mask is not None else 0
1166
+ if logits_to_keep is None:
1167
+ _ = model_inputs.pop("logits_to_keep", None)
1168
+
1169
+ if (
1170
+ isinstance(past_key_values, HybridCache)
1171
+ and attention_mask.ndim == 2
1172
+ and not self.config._attn_implementation == "flash_attention_2"
1173
+ ):
1174
+ if model_inputs["inputs_embeds"] is not None:
1175
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1176
+ device = model_inputs["inputs_embeds"].device
1177
+ else:
1178
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1179
+ device = model_inputs["input_ids"].device
1180
+
1181
+ attention_mask = self.model._prepare_4d_causal_attention_mask_with_cache_position(
1182
+ attention_mask,
1183
+ sequence_length=sequence_length,
1184
+ target_length=past_key_values.get_max_cache_shape(),
1185
+ dtype=self.lm_head.weight.dtype,
1186
+ device=device,
1187
+ cache_position=cache_position,
1188
+ batch_size=batch_size,
1189
+ )
1190
+ model_inputs["attention_mask"] = attention_mask
1191
+
1192
+ return model_inputs
1193
+
1194
+
1195
+
1196
+ __all__ = [
1197
+ "Gemma2ForCausalLM",
1198
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<start_of_turn>",
4
+ "<end_of_turn>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<bos>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<eos>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "<pad>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "unk_token": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7da53ca29fb16f6b2489482fc0bc6a394162cdab14d12764a1755ebc583fea79
3
+ size 17518525
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2
3
+ size 4241003
tokenizer_config.json ADDED
@@ -0,0 +1,1757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<pad>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<eos>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "<bos>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "3": {
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "4": {
38
+ "content": "<mask>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": false
44
+ },
45
+ "5": {
46
+ "content": "<2mass>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": false
52
+ },
53
+ "6": {
54
+ "content": "[@BOS@]",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": false
60
+ },
61
+ "7": {
62
+ "content": "<unused0>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": false
68
+ },
69
+ "8": {
70
+ "content": "<unused1>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": false
76
+ },
77
+ "9": {
78
+ "content": "<unused2>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": false
84
+ },
85
+ "10": {
86
+ "content": "<unused3>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": false
92
+ },
93
+ "11": {
94
+ "content": "<unused4>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": false
100
+ },
101
+ "12": {
102
+ "content": "<unused5>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": false
108
+ },
109
+ "13": {
110
+ "content": "<unused6>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": false
116
+ },
117
+ "14": {
118
+ "content": "<unused7>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "15": {
126
+ "content": "<unused8>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "16": {
134
+ "content": "<unused9>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "17": {
142
+ "content": "<unused10>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "18": {
150
+ "content": "<unused11>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "19": {
158
+ "content": "<unused12>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "20": {
166
+ "content": "<unused13>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "21": {
174
+ "content": "<unused14>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "22": {
182
+ "content": "<unused15>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "23": {
190
+ "content": "<unused16>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "24": {
198
+ "content": "<unused17>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "25": {
206
+ "content": "<unused18>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "26": {
214
+ "content": "<unused19>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": false
220
+ },
221
+ "27": {
222
+ "content": "<unused20>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": false,
226
+ "single_word": false,
227
+ "special": false
228
+ },
229
+ "28": {
230
+ "content": "<unused21>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": false,
234
+ "single_word": false,
235
+ "special": false
236
+ },
237
+ "29": {
238
+ "content": "<unused22>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": false,
242
+ "single_word": false,
243
+ "special": false
244
+ },
245
+ "30": {
246
+ "content": "<unused23>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": false,
250
+ "single_word": false,
251
+ "special": false
252
+ },
253
+ "31": {
254
+ "content": "<unused24>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": false,
258
+ "single_word": false,
259
+ "special": false
260
+ },
261
+ "32": {
262
+ "content": "<unused25>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": false,
266
+ "single_word": false,
267
+ "special": false
268
+ },
269
+ "33": {
270
+ "content": "<unused26>",
271
+ "lstrip": false,
272
+ "normalized": false,
273
+ "rstrip": false,
274
+ "single_word": false,
275
+ "special": false
276
+ },
277
+ "34": {
278
+ "content": "<unused27>",
279
+ "lstrip": false,
280
+ "normalized": false,
281
+ "rstrip": false,
282
+ "single_word": false,
283
+ "special": false
284
+ },
285
+ "35": {
286
+ "content": "<unused28>",
287
+ "lstrip": false,
288
+ "normalized": false,
289
+ "rstrip": false,
290
+ "single_word": false,
291
+ "special": false
292
+ },
293
+ "36": {
294
+ "content": "<unused29>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": false,
298
+ "single_word": false,
299
+ "special": false
300
+ },
301
+ "37": {
302
+ "content": "<unused30>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": false,
306
+ "single_word": false,
307
+ "special": false
308
+ },
309
+ "38": {
310
+ "content": "<unused31>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": false,
314
+ "single_word": false,
315
+ "special": false
316
+ },
317
+ "39": {
318
+ "content": "<unused32>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": false,
322
+ "single_word": false,
323
+ "special": false
324
+ },
325
+ "40": {
326
+ "content": "<unused33>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": false,
330
+ "single_word": false,
331
+ "special": false
332
+ },
333
+ "41": {
334
+ "content": "<unused34>",
335
+ "lstrip": false,
336
+ "normalized": false,
337
+ "rstrip": false,
338
+ "single_word": false,
339
+ "special": false
340
+ },
341
+ "42": {
342
+ "content": "<unused35>",
343
+ "lstrip": false,
344
+ "normalized": false,
345
+ "rstrip": false,
346
+ "single_word": false,
347
+ "special": false
348
+ },
349
+ "43": {
350
+ "content": "<unused36>",
351
+ "lstrip": false,
352
+ "normalized": false,
353
+ "rstrip": false,
354
+ "single_word": false,
355
+ "special": false
356
+ },
357
+ "44": {
358
+ "content": "<unused37>",
359
+ "lstrip": false,
360
+ "normalized": false,
361
+ "rstrip": false,
362
+ "single_word": false,
363
+ "special": false
364
+ },
365
+ "45": {
366
+ "content": "<unused38>",
367
+ "lstrip": false,
368
+ "normalized": false,
369
+ "rstrip": false,
370
+ "single_word": false,
371
+ "special": false
372
+ },
373
+ "46": {
374
+ "content": "<unused39>",
375
+ "lstrip": false,
376
+ "normalized": false,
377
+ "rstrip": false,
378
+ "single_word": false,
379
+ "special": false
380
+ },
381
+ "47": {
382
+ "content": "<unused40>",
383
+ "lstrip": false,
384
+ "normalized": false,
385
+ "rstrip": false,
386
+ "single_word": false,
387
+ "special": false
388
+ },
389
+ "48": {
390
+ "content": "<unused41>",
391
+ "lstrip": false,
392
+ "normalized": false,
393
+ "rstrip": false,
394
+ "single_word": false,
395
+ "special": false
396
+ },
397
+ "49": {
398
+ "content": "<unused42>",
399
+ "lstrip": false,
400
+ "normalized": false,
401
+ "rstrip": false,
402
+ "single_word": false,
403
+ "special": false
404
+ },
405
+ "50": {
406
+ "content": "<unused43>",
407
+ "lstrip": false,
408
+ "normalized": false,
409
+ "rstrip": false,
410
+ "single_word": false,
411
+ "special": false
412
+ },
413
+ "51": {
414
+ "content": "<unused44>",
415
+ "lstrip": false,
416
+ "normalized": false,
417
+ "rstrip": false,
418
+ "single_word": false,
419
+ "special": false
420
+ },
421
+ "52": {
422
+ "content": "<unused45>",
423
+ "lstrip": false,
424
+ "normalized": false,
425
+ "rstrip": false,
426
+ "single_word": false,
427
+ "special": false
428
+ },
429
+ "53": {
430
+ "content": "<unused46>",
431
+ "lstrip": false,
432
+ "normalized": false,
433
+ "rstrip": false,
434
+ "single_word": false,
435
+ "special": false
436
+ },
437
+ "54": {
438
+ "content": "<unused47>",
439
+ "lstrip": false,
440
+ "normalized": false,
441
+ "rstrip": false,
442
+ "single_word": false,
443
+ "special": false
444
+ },
445
+ "55": {
446
+ "content": "<unused48>",
447
+ "lstrip": false,
448
+ "normalized": false,
449
+ "rstrip": false,
450
+ "single_word": false,
451
+ "special": false
452
+ },
453
+ "56": {
454
+ "content": "<unused49>",
455
+ "lstrip": false,
456
+ "normalized": false,
457
+ "rstrip": false,
458
+ "single_word": false,
459
+ "special": false
460
+ },
461
+ "57": {
462
+ "content": "<unused50>",
463
+ "lstrip": false,
464
+ "normalized": false,
465
+ "rstrip": false,
466
+ "single_word": false,
467
+ "special": false
468
+ },
469
+ "58": {
470
+ "content": "<unused51>",
471
+ "lstrip": false,
472
+ "normalized": false,
473
+ "rstrip": false,
474
+ "single_word": false,
475
+ "special": false
476
+ },
477
+ "59": {
478
+ "content": "<unused52>",
479
+ "lstrip": false,
480
+ "normalized": false,
481
+ "rstrip": false,
482
+ "single_word": false,
483
+ "special": false
484
+ },
485
+ "60": {
486
+ "content": "<unused53>",
487
+ "lstrip": false,
488
+ "normalized": false,
489
+ "rstrip": false,
490
+ "single_word": false,
491
+ "special": false
492
+ },
493
+ "61": {
494
+ "content": "<unused54>",
495
+ "lstrip": false,
496
+ "normalized": false,
497
+ "rstrip": false,
498
+ "single_word": false,
499
+ "special": false
500
+ },
501
+ "62": {
502
+ "content": "<unused55>",
503
+ "lstrip": false,
504
+ "normalized": false,
505
+ "rstrip": false,
506
+ "single_word": false,
507
+ "special": false
508
+ },
509
+ "63": {
510
+ "content": "<unused56>",
511
+ "lstrip": false,
512
+ "normalized": false,
513
+ "rstrip": false,
514
+ "single_word": false,
515
+ "special": false
516
+ },
517
+ "64": {
518
+ "content": "<unused57>",
519
+ "lstrip": false,
520
+ "normalized": false,
521
+ "rstrip": false,
522
+ "single_word": false,
523
+ "special": false
524
+ },
525
+ "65": {
526
+ "content": "<unused58>",
527
+ "lstrip": false,
528
+ "normalized": false,
529
+ "rstrip": false,
530
+ "single_word": false,
531
+ "special": false
532
+ },
533
+ "66": {
534
+ "content": "<unused59>",
535
+ "lstrip": false,
536
+ "normalized": false,
537
+ "rstrip": false,
538
+ "single_word": false,
539
+ "special": false
540
+ },
541
+ "67": {
542
+ "content": "<unused60>",
543
+ "lstrip": false,
544
+ "normalized": false,
545
+ "rstrip": false,
546
+ "single_word": false,
547
+ "special": false
548
+ },
549
+ "68": {
550
+ "content": "<unused61>",
551
+ "lstrip": false,
552
+ "normalized": false,
553
+ "rstrip": false,
554
+ "single_word": false,
555
+ "special": false
556
+ },
557
+ "69": {
558
+ "content": "<unused62>",
559
+ "lstrip": false,
560
+ "normalized": false,
561
+ "rstrip": false,
562
+ "single_word": false,
563
+ "special": false
564
+ },
565
+ "70": {
566
+ "content": "<unused63>",
567
+ "lstrip": false,
568
+ "normalized": false,
569
+ "rstrip": false,
570
+ "single_word": false,
571
+ "special": false
572
+ },
573
+ "71": {
574
+ "content": "<unused64>",
575
+ "lstrip": false,
576
+ "normalized": false,
577
+ "rstrip": false,
578
+ "single_word": false,
579
+ "special": false
580
+ },
581
+ "72": {
582
+ "content": "<unused65>",
583
+ "lstrip": false,
584
+ "normalized": false,
585
+ "rstrip": false,
586
+ "single_word": false,
587
+ "special": false
588
+ },
589
+ "73": {
590
+ "content": "<unused66>",
591
+ "lstrip": false,
592
+ "normalized": false,
593
+ "rstrip": false,
594
+ "single_word": false,
595
+ "special": false
596
+ },
597
+ "74": {
598
+ "content": "<unused67>",
599
+ "lstrip": false,
600
+ "normalized": false,
601
+ "rstrip": false,
602
+ "single_word": false,
603
+ "special": false
604
+ },
605
+ "75": {
606
+ "content": "<unused68>",
607
+ "lstrip": false,
608
+ "normalized": false,
609
+ "rstrip": false,
610
+ "single_word": false,
611
+ "special": false
612
+ },
613
+ "76": {
614
+ "content": "<unused69>",
615
+ "lstrip": false,
616
+ "normalized": false,
617
+ "rstrip": false,
618
+ "single_word": false,
619
+ "special": false
620
+ },
621
+ "77": {
622
+ "content": "<unused70>",
623
+ "lstrip": false,
624
+ "normalized": false,
625
+ "rstrip": false,
626
+ "single_word": false,
627
+ "special": false
628
+ },
629
+ "78": {
630
+ "content": "<unused71>",
631
+ "lstrip": false,
632
+ "normalized": false,
633
+ "rstrip": false,
634
+ "single_word": false,
635
+ "special": false
636
+ },
637
+ "79": {
638
+ "content": "<unused72>",
639
+ "lstrip": false,
640
+ "normalized": false,
641
+ "rstrip": false,
642
+ "single_word": false,
643
+ "special": false
644
+ },
645
+ "80": {
646
+ "content": "<unused73>",
647
+ "lstrip": false,
648
+ "normalized": false,
649
+ "rstrip": false,
650
+ "single_word": false,
651
+ "special": false
652
+ },
653
+ "81": {
654
+ "content": "<unused74>",
655
+ "lstrip": false,
656
+ "normalized": false,
657
+ "rstrip": false,
658
+ "single_word": false,
659
+ "special": false
660
+ },
661
+ "82": {
662
+ "content": "<unused75>",
663
+ "lstrip": false,
664
+ "normalized": false,
665
+ "rstrip": false,
666
+ "single_word": false,
667
+ "special": false
668
+ },
669
+ "83": {
670
+ "content": "<unused76>",
671
+ "lstrip": false,
672
+ "normalized": false,
673
+ "rstrip": false,
674
+ "single_word": false,
675
+ "special": false
676
+ },
677
+ "84": {
678
+ "content": "<unused77>",
679
+ "lstrip": false,
680
+ "normalized": false,
681
+ "rstrip": false,
682
+ "single_word": false,
683
+ "special": false
684
+ },
685
+ "85": {
686
+ "content": "<unused78>",
687
+ "lstrip": false,
688
+ "normalized": false,
689
+ "rstrip": false,
690
+ "single_word": false,
691
+ "special": false
692
+ },
693
+ "86": {
694
+ "content": "<unused79>",
695
+ "lstrip": false,
696
+ "normalized": false,
697
+ "rstrip": false,
698
+ "single_word": false,
699
+ "special": false
700
+ },
701
+ "87": {
702
+ "content": "<unused80>",
703
+ "lstrip": false,
704
+ "normalized": false,
705
+ "rstrip": false,
706
+ "single_word": false,
707
+ "special": false
708
+ },
709
+ "88": {
710
+ "content": "<unused81>",
711
+ "lstrip": false,
712
+ "normalized": false,
713
+ "rstrip": false,
714
+ "single_word": false,
715
+ "special": false
716
+ },
717
+ "89": {
718
+ "content": "<unused82>",
719
+ "lstrip": false,
720
+ "normalized": false,
721
+ "rstrip": false,
722
+ "single_word": false,
723
+ "special": false
724
+ },
725
+ "90": {
726
+ "content": "<unused83>",
727
+ "lstrip": false,
728
+ "normalized": false,
729
+ "rstrip": false,
730
+ "single_word": false,
731
+ "special": false
732
+ },
733
+ "91": {
734
+ "content": "<unused84>",
735
+ "lstrip": false,
736
+ "normalized": false,
737
+ "rstrip": false,
738
+ "single_word": false,
739
+ "special": false
740
+ },
741
+ "92": {
742
+ "content": "<unused85>",
743
+ "lstrip": false,
744
+ "normalized": false,
745
+ "rstrip": false,
746
+ "single_word": false,
747
+ "special": false
748
+ },
749
+ "93": {
750
+ "content": "<unused86>",
751
+ "lstrip": false,
752
+ "normalized": false,
753
+ "rstrip": false,
754
+ "single_word": false,
755
+ "special": false
756
+ },
757
+ "94": {
758
+ "content": "<unused87>",
759
+ "lstrip": false,
760
+ "normalized": false,
761
+ "rstrip": false,
762
+ "single_word": false,
763
+ "special": false
764
+ },
765
+ "95": {
766
+ "content": "<unused88>",
767
+ "lstrip": false,
768
+ "normalized": false,
769
+ "rstrip": false,
770
+ "single_word": false,
771
+ "special": false
772
+ },
773
+ "96": {
774
+ "content": "<unused89>",
775
+ "lstrip": false,
776
+ "normalized": false,
777
+ "rstrip": false,
778
+ "single_word": false,
779
+ "special": false
780
+ },
781
+ "97": {
782
+ "content": "<unused90>",
783
+ "lstrip": false,
784
+ "normalized": false,
785
+ "rstrip": false,
786
+ "single_word": false,
787
+ "special": false
788
+ },
789
+ "98": {
790
+ "content": "<unused91>",
791
+ "lstrip": false,
792
+ "normalized": false,
793
+ "rstrip": false,
794
+ "single_word": false,
795
+ "special": false
796
+ },
797
+ "99": {
798
+ "content": "<unused92>",
799
+ "lstrip": false,
800
+ "normalized": false,
801
+ "rstrip": false,
802
+ "single_word": false,
803
+ "special": false
804
+ },
805
+ "100": {
806
+ "content": "<unused93>",
807
+ "lstrip": false,
808
+ "normalized": false,
809
+ "rstrip": false,
810
+ "single_word": false,
811
+ "special": false
812
+ },
813
+ "101": {
814
+ "content": "<unused94>",
815
+ "lstrip": false,
816
+ "normalized": false,
817
+ "rstrip": false,
818
+ "single_word": false,
819
+ "special": false
820
+ },
821
+ "102": {
822
+ "content": "<unused95>",
823
+ "lstrip": false,
824
+ "normalized": false,
825
+ "rstrip": false,
826
+ "single_word": false,
827
+ "special": false
828
+ },
829
+ "103": {
830
+ "content": "<unused96>",
831
+ "lstrip": false,
832
+ "normalized": false,
833
+ "rstrip": false,
834
+ "single_word": false,
835
+ "special": false
836
+ },
837
+ "104": {
838
+ "content": "<unused97>",
839
+ "lstrip": false,
840
+ "normalized": false,
841
+ "rstrip": false,
842
+ "single_word": false,
843
+ "special": false
844
+ },
845
+ "105": {
846
+ "content": "<unused98>",
847
+ "lstrip": false,
848
+ "normalized": false,
849
+ "rstrip": false,
850
+ "single_word": false,
851
+ "special": false
852
+ },
853
+ "106": {
854
+ "content": "<start_of_turn>",
855
+ "lstrip": false,
856
+ "normalized": false,
857
+ "rstrip": false,
858
+ "single_word": false,
859
+ "special": true
860
+ },
861
+ "107": {
862
+ "content": "<end_of_turn>",
863
+ "lstrip": false,
864
+ "normalized": false,
865
+ "rstrip": false,
866
+ "single_word": false,
867
+ "special": true
868
+ },
869
+ "108": {
870
+ "content": "\n",
871
+ "lstrip": false,
872
+ "normalized": false,
873
+ "rstrip": false,
874
+ "single_word": false,
875
+ "special": false
876
+ },
877
+ "109": {
878
+ "content": "\n\n",
879
+ "lstrip": false,
880
+ "normalized": false,
881
+ "rstrip": false,
882
+ "single_word": false,
883
+ "special": false
884
+ },
885
+ "110": {
886
+ "content": "\n\n\n",
887
+ "lstrip": false,
888
+ "normalized": false,
889
+ "rstrip": false,
890
+ "single_word": false,
891
+ "special": false
892
+ },
893
+ "111": {
894
+ "content": "\n\n\n\n",
895
+ "lstrip": false,
896
+ "normalized": false,
897
+ "rstrip": false,
898
+ "single_word": false,
899
+ "special": false
900
+ },
901
+ "112": {
902
+ "content": "\n\n\n\n\n",
903
+ "lstrip": false,
904
+ "normalized": false,
905
+ "rstrip": false,
906
+ "single_word": false,
907
+ "special": false
908
+ },
909
+ "113": {
910
+ "content": "\n\n\n\n\n\n",
911
+ "lstrip": false,
912
+ "normalized": false,
913
+ "rstrip": false,
914
+ "single_word": false,
915
+ "special": false
916
+ },
917
+ "114": {
918
+ "content": "\n\n\n\n\n\n\n",
919
+ "lstrip": false,
920
+ "normalized": false,
921
+ "rstrip": false,
922
+ "single_word": false,
923
+ "special": false
924
+ },
925
+ "115": {
926
+ "content": "\n\n\n\n\n\n\n\n",
927
+ "lstrip": false,
928
+ "normalized": false,
929
+ "rstrip": false,
930
+ "single_word": false,
931
+ "special": false
932
+ },
933
+ "116": {
934
+ "content": "\n\n\n\n\n\n\n\n\n",
935
+ "lstrip": false,
936
+ "normalized": false,
937
+ "rstrip": false,
938
+ "single_word": false,
939
+ "special": false
940
+ },
941
+ "117": {
942
+ "content": "\n\n\n\n\n\n\n\n\n\n",
943
+ "lstrip": false,
944
+ "normalized": false,
945
+ "rstrip": false,
946
+ "single_word": false,
947
+ "special": false
948
+ },
949
+ "118": {
950
+ "content": "\n\n\n\n\n\n\n\n\n\n\n",
951
+ "lstrip": false,
952
+ "normalized": false,
953
+ "rstrip": false,
954
+ "single_word": false,
955
+ "special": false
956
+ },
957
+ "119": {
958
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n",
959
+ "lstrip": false,
960
+ "normalized": false,
961
+ "rstrip": false,
962
+ "single_word": false,
963
+ "special": false
964
+ },
965
+ "120": {
966
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n",
967
+ "lstrip": false,
968
+ "normalized": false,
969
+ "rstrip": false,
970
+ "single_word": false,
971
+ "special": false
972
+ },
973
+ "121": {
974
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
975
+ "lstrip": false,
976
+ "normalized": false,
977
+ "rstrip": false,
978
+ "single_word": false,
979
+ "special": false
980
+ },
981
+ "122": {
982
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
983
+ "lstrip": false,
984
+ "normalized": false,
985
+ "rstrip": false,
986
+ "single_word": false,
987
+ "special": false
988
+ },
989
+ "123": {
990
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
991
+ "lstrip": false,
992
+ "normalized": false,
993
+ "rstrip": false,
994
+ "single_word": false,
995
+ "special": false
996
+ },
997
+ "124": {
998
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
999
+ "lstrip": false,
1000
+ "normalized": false,
1001
+ "rstrip": false,
1002
+ "single_word": false,
1003
+ "special": false
1004
+ },
1005
+ "125": {
1006
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1007
+ "lstrip": false,
1008
+ "normalized": false,
1009
+ "rstrip": false,
1010
+ "single_word": false,
1011
+ "special": false
1012
+ },
1013
+ "126": {
1014
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1015
+ "lstrip": false,
1016
+ "normalized": false,
1017
+ "rstrip": false,
1018
+ "single_word": false,
1019
+ "special": false
1020
+ },
1021
+ "127": {
1022
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1023
+ "lstrip": false,
1024
+ "normalized": false,
1025
+ "rstrip": false,
1026
+ "single_word": false,
1027
+ "special": false
1028
+ },
1029
+ "128": {
1030
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1031
+ "lstrip": false,
1032
+ "normalized": false,
1033
+ "rstrip": false,
1034
+ "single_word": false,
1035
+ "special": false
1036
+ },
1037
+ "129": {
1038
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1039
+ "lstrip": false,
1040
+ "normalized": false,
1041
+ "rstrip": false,
1042
+ "single_word": false,
1043
+ "special": false
1044
+ },
1045
+ "130": {
1046
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1047
+ "lstrip": false,
1048
+ "normalized": false,
1049
+ "rstrip": false,
1050
+ "single_word": false,
1051
+ "special": false
1052
+ },
1053
+ "131": {
1054
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1055
+ "lstrip": false,
1056
+ "normalized": false,
1057
+ "rstrip": false,
1058
+ "single_word": false,
1059
+ "special": false
1060
+ },
1061
+ "132": {
1062
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1063
+ "lstrip": false,
1064
+ "normalized": false,
1065
+ "rstrip": false,
1066
+ "single_word": false,
1067
+ "special": false
1068
+ },
1069
+ "133": {
1070
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1071
+ "lstrip": false,
1072
+ "normalized": false,
1073
+ "rstrip": false,
1074
+ "single_word": false,
1075
+ "special": false
1076
+ },
1077
+ "134": {
1078
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1079
+ "lstrip": false,
1080
+ "normalized": false,
1081
+ "rstrip": false,
1082
+ "single_word": false,
1083
+ "special": false
1084
+ },
1085
+ "135": {
1086
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1087
+ "lstrip": false,
1088
+ "normalized": false,
1089
+ "rstrip": false,
1090
+ "single_word": false,
1091
+ "special": false
1092
+ },
1093
+ "136": {
1094
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1095
+ "lstrip": false,
1096
+ "normalized": false,
1097
+ "rstrip": false,
1098
+ "single_word": false,
1099
+ "special": false
1100
+ },
1101
+ "137": {
1102
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1103
+ "lstrip": false,
1104
+ "normalized": false,
1105
+ "rstrip": false,
1106
+ "single_word": false,
1107
+ "special": false
1108
+ },
1109
+ "138": {
1110
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1111
+ "lstrip": false,
1112
+ "normalized": false,
1113
+ "rstrip": false,
1114
+ "single_word": false,
1115
+ "special": false
1116
+ },
1117
+ "139": {
1118
+ "content": "▁▁",
1119
+ "lstrip": false,
1120
+ "normalized": false,
1121
+ "rstrip": false,
1122
+ "single_word": false,
1123
+ "special": false
1124
+ },
1125
+ "140": {
1126
+ "content": "▁▁▁",
1127
+ "lstrip": false,
1128
+ "normalized": false,
1129
+ "rstrip": false,
1130
+ "single_word": false,
1131
+ "special": false
1132
+ },
1133
+ "141": {
1134
+ "content": "▁▁▁▁",
1135
+ "lstrip": false,
1136
+ "normalized": false,
1137
+ "rstrip": false,
1138
+ "single_word": false,
1139
+ "special": false
1140
+ },
1141
+ "142": {
1142
+ "content": "▁▁▁▁▁",
1143
+ "lstrip": false,
1144
+ "normalized": false,
1145
+ "rstrip": false,
1146
+ "single_word": false,
1147
+ "special": false
1148
+ },
1149
+ "143": {
1150
+ "content": "▁▁▁▁▁▁",
1151
+ "lstrip": false,
1152
+ "normalized": false,
1153
+ "rstrip": false,
1154
+ "single_word": false,
1155
+ "special": false
1156
+ },
1157
+ "144": {
1158
+ "content": "▁▁▁▁▁▁▁",
1159
+ "lstrip": false,
1160
+ "normalized": false,
1161
+ "rstrip": false,
1162
+ "single_word": false,
1163
+ "special": false
1164
+ },
1165
+ "145": {
1166
+ "content": "▁▁▁▁▁▁▁▁",
1167
+ "lstrip": false,
1168
+ "normalized": false,
1169
+ "rstrip": false,
1170
+ "single_word": false,
1171
+ "special": false
1172
+ },
1173
+ "146": {
1174
+ "content": "▁▁▁▁▁▁▁▁▁",
1175
+ "lstrip": false,
1176
+ "normalized": false,
1177
+ "rstrip": false,
1178
+ "single_word": false,
1179
+ "special": false
1180
+ },
1181
+ "147": {
1182
+ "content": "▁▁▁▁▁▁▁▁▁▁",
1183
+ "lstrip": false,
1184
+ "normalized": false,
1185
+ "rstrip": false,
1186
+ "single_word": false,
1187
+ "special": false
1188
+ },
1189
+ "148": {
1190
+ "content": "▁▁▁▁▁▁▁▁▁▁▁",
1191
+ "lstrip": false,
1192
+ "normalized": false,
1193
+ "rstrip": false,
1194
+ "single_word": false,
1195
+ "special": false
1196
+ },
1197
+ "149": {
1198
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁",
1199
+ "lstrip": false,
1200
+ "normalized": false,
1201
+ "rstrip": false,
1202
+ "single_word": false,
1203
+ "special": false
1204
+ },
1205
+ "150": {
1206
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁",
1207
+ "lstrip": false,
1208
+ "normalized": false,
1209
+ "rstrip": false,
1210
+ "single_word": false,
1211
+ "special": false
1212
+ },
1213
+ "151": {
1214
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1215
+ "lstrip": false,
1216
+ "normalized": false,
1217
+ "rstrip": false,
1218
+ "single_word": false,
1219
+ "special": false
1220
+ },
1221
+ "152": {
1222
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1223
+ "lstrip": false,
1224
+ "normalized": false,
1225
+ "rstrip": false,
1226
+ "single_word": false,
1227
+ "special": false
1228
+ },
1229
+ "153": {
1230
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1231
+ "lstrip": false,
1232
+ "normalized": false,
1233
+ "rstrip": false,
1234
+ "single_word": false,
1235
+ "special": false
1236
+ },
1237
+ "154": {
1238
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1239
+ "lstrip": false,
1240
+ "normalized": false,
1241
+ "rstrip": false,
1242
+ "single_word": false,
1243
+ "special": false
1244
+ },
1245
+ "155": {
1246
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1247
+ "lstrip": false,
1248
+ "normalized": false,
1249
+ "rstrip": false,
1250
+ "single_word": false,
1251
+ "special": false
1252
+ },
1253
+ "156": {
1254
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1255
+ "lstrip": false,
1256
+ "normalized": false,
1257
+ "rstrip": false,
1258
+ "single_word": false,
1259
+ "special": false
1260
+ },
1261
+ "157": {
1262
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1263
+ "lstrip": false,
1264
+ "normalized": false,
1265
+ "rstrip": false,
1266
+ "single_word": false,
1267
+ "special": false
1268
+ },
1269
+ "158": {
1270
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1271
+ "lstrip": false,
1272
+ "normalized": false,
1273
+ "rstrip": false,
1274
+ "single_word": false,
1275
+ "special": false
1276
+ },
1277
+ "159": {
1278
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1279
+ "lstrip": false,
1280
+ "normalized": false,
1281
+ "rstrip": false,
1282
+ "single_word": false,
1283
+ "special": false
1284
+ },
1285
+ "160": {
1286
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1287
+ "lstrip": false,
1288
+ "normalized": false,
1289
+ "rstrip": false,
1290
+ "single_word": false,
1291
+ "special": false
1292
+ },
1293
+ "161": {
1294
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1295
+ "lstrip": false,
1296
+ "normalized": false,
1297
+ "rstrip": false,
1298
+ "single_word": false,
1299
+ "special": false
1300
+ },
1301
+ "162": {
1302
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1303
+ "lstrip": false,
1304
+ "normalized": false,
1305
+ "rstrip": false,
1306
+ "single_word": false,
1307
+ "special": false
1308
+ },
1309
+ "163": {
1310
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1311
+ "lstrip": false,
1312
+ "normalized": false,
1313
+ "rstrip": false,
1314
+ "single_word": false,
1315
+ "special": false
1316
+ },
1317
+ "164": {
1318
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1319
+ "lstrip": false,
1320
+ "normalized": false,
1321
+ "rstrip": false,
1322
+ "single_word": false,
1323
+ "special": false
1324
+ },
1325
+ "165": {
1326
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1327
+ "lstrip": false,
1328
+ "normalized": false,
1329
+ "rstrip": false,
1330
+ "single_word": false,
1331
+ "special": false
1332
+ },
1333
+ "166": {
1334
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1335
+ "lstrip": false,
1336
+ "normalized": false,
1337
+ "rstrip": false,
1338
+ "single_word": false,
1339
+ "special": false
1340
+ },
1341
+ "167": {
1342
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1343
+ "lstrip": false,
1344
+ "normalized": false,
1345
+ "rstrip": false,
1346
+ "single_word": false,
1347
+ "special": false
1348
+ },
1349
+ "168": {
1350
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1351
+ "lstrip": false,
1352
+ "normalized": false,
1353
+ "rstrip": false,
1354
+ "single_word": false,
1355
+ "special": false
1356
+ },
1357
+ "169": {
1358
+ "content": "<table>",
1359
+ "lstrip": false,
1360
+ "normalized": false,
1361
+ "rstrip": false,
1362
+ "single_word": false,
1363
+ "special": false
1364
+ },
1365
+ "170": {
1366
+ "content": "<caption>",
1367
+ "lstrip": false,
1368
+ "normalized": false,
1369
+ "rstrip": false,
1370
+ "single_word": false,
1371
+ "special": false
1372
+ },
1373
+ "171": {
1374
+ "content": "<thead>",
1375
+ "lstrip": false,
1376
+ "normalized": false,
1377
+ "rstrip": false,
1378
+ "single_word": false,
1379
+ "special": false
1380
+ },
1381
+ "172": {
1382
+ "content": "<tbody>",
1383
+ "lstrip": false,
1384
+ "normalized": false,
1385
+ "rstrip": false,
1386
+ "single_word": false,
1387
+ "special": false
1388
+ },
1389
+ "173": {
1390
+ "content": "<tfoot>",
1391
+ "lstrip": false,
1392
+ "normalized": false,
1393
+ "rstrip": false,
1394
+ "single_word": false,
1395
+ "special": false
1396
+ },
1397
+ "174": {
1398
+ "content": "<tr>",
1399
+ "lstrip": false,
1400
+ "normalized": false,
1401
+ "rstrip": false,
1402
+ "single_word": false,
1403
+ "special": false
1404
+ },
1405
+ "175": {
1406
+ "content": "<th>",
1407
+ "lstrip": false,
1408
+ "normalized": false,
1409
+ "rstrip": false,
1410
+ "single_word": false,
1411
+ "special": false
1412
+ },
1413
+ "176": {
1414
+ "content": "<td>",
1415
+ "lstrip": false,
1416
+ "normalized": false,
1417
+ "rstrip": false,
1418
+ "single_word": false,
1419
+ "special": false
1420
+ },
1421
+ "177": {
1422
+ "content": "</table>",
1423
+ "lstrip": false,
1424
+ "normalized": false,
1425
+ "rstrip": false,
1426
+ "single_word": false,
1427
+ "special": false
1428
+ },
1429
+ "178": {
1430
+ "content": "</caption>",
1431
+ "lstrip": false,
1432
+ "normalized": false,
1433
+ "rstrip": false,
1434
+ "single_word": false,
1435
+ "special": false
1436
+ },
1437
+ "179": {
1438
+ "content": "</thead>",
1439
+ "lstrip": false,
1440
+ "normalized": false,
1441
+ "rstrip": false,
1442
+ "single_word": false,
1443
+ "special": false
1444
+ },
1445
+ "180": {
1446
+ "content": "</tbody>",
1447
+ "lstrip": false,
1448
+ "normalized": false,
1449
+ "rstrip": false,
1450
+ "single_word": false,
1451
+ "special": false
1452
+ },
1453
+ "181": {
1454
+ "content": "</tfoot>",
1455
+ "lstrip": false,
1456
+ "normalized": false,
1457
+ "rstrip": false,
1458
+ "single_word": false,
1459
+ "special": false
1460
+ },
1461
+ "182": {
1462
+ "content": "</tr>",
1463
+ "lstrip": false,
1464
+ "normalized": false,
1465
+ "rstrip": false,
1466
+ "single_word": false,
1467
+ "special": false
1468
+ },
1469
+ "183": {
1470
+ "content": "</th>",
1471
+ "lstrip": false,
1472
+ "normalized": false,
1473
+ "rstrip": false,
1474
+ "single_word": false,
1475
+ "special": false
1476
+ },
1477
+ "184": {
1478
+ "content": "</td>",
1479
+ "lstrip": false,
1480
+ "normalized": false,
1481
+ "rstrip": false,
1482
+ "single_word": false,
1483
+ "special": false
1484
+ },
1485
+ "185": {
1486
+ "content": "<h1>",
1487
+ "lstrip": false,
1488
+ "normalized": false,
1489
+ "rstrip": false,
1490
+ "single_word": false,
1491
+ "special": false
1492
+ },
1493
+ "186": {
1494
+ "content": "<h2>",
1495
+ "lstrip": false,
1496
+ "normalized": false,
1497
+ "rstrip": false,
1498
+ "single_word": false,
1499
+ "special": false
1500
+ },
1501
+ "187": {
1502
+ "content": "<h3>",
1503
+ "lstrip": false,
1504
+ "normalized": false,
1505
+ "rstrip": false,
1506
+ "single_word": false,
1507
+ "special": false
1508
+ },
1509
+ "188": {
1510
+ "content": "<h4>",
1511
+ "lstrip": false,
1512
+ "normalized": false,
1513
+ "rstrip": false,
1514
+ "single_word": false,
1515
+ "special": false
1516
+ },
1517
+ "189": {
1518
+ "content": "<h5>",
1519
+ "lstrip": false,
1520
+ "normalized": false,
1521
+ "rstrip": false,
1522
+ "single_word": false,
1523
+ "special": false
1524
+ },
1525
+ "190": {
1526
+ "content": "<h6>",
1527
+ "lstrip": false,
1528
+ "normalized": false,
1529
+ "rstrip": false,
1530
+ "single_word": false,
1531
+ "special": false
1532
+ },
1533
+ "191": {
1534
+ "content": "<blockquote>",
1535
+ "lstrip": false,
1536
+ "normalized": false,
1537
+ "rstrip": false,
1538
+ "single_word": false,
1539
+ "special": false
1540
+ },
1541
+ "192": {
1542
+ "content": "</h1>",
1543
+ "lstrip": false,
1544
+ "normalized": false,
1545
+ "rstrip": false,
1546
+ "single_word": false,
1547
+ "special": false
1548
+ },
1549
+ "193": {
1550
+ "content": "</h2>",
1551
+ "lstrip": false,
1552
+ "normalized": false,
1553
+ "rstrip": false,
1554
+ "single_word": false,
1555
+ "special": false
1556
+ },
1557
+ "194": {
1558
+ "content": "</h3>",
1559
+ "lstrip": false,
1560
+ "normalized": false,
1561
+ "rstrip": false,
1562
+ "single_word": false,
1563
+ "special": false
1564
+ },
1565
+ "195": {
1566
+ "content": "</h4>",
1567
+ "lstrip": false,
1568
+ "normalized": false,
1569
+ "rstrip": false,
1570
+ "single_word": false,
1571
+ "special": false
1572
+ },
1573
+ "196": {
1574
+ "content": "</h5>",
1575
+ "lstrip": false,
1576
+ "normalized": false,
1577
+ "rstrip": false,
1578
+ "single_word": false,
1579
+ "special": false
1580
+ },
1581
+ "197": {
1582
+ "content": "</h6>",
1583
+ "lstrip": false,
1584
+ "normalized": false,
1585
+ "rstrip": false,
1586
+ "single_word": false,
1587
+ "special": false
1588
+ },
1589
+ "198": {
1590
+ "content": "</blockquote>",
1591
+ "lstrip": false,
1592
+ "normalized": false,
1593
+ "rstrip": false,
1594
+ "single_word": false,
1595
+ "special": false
1596
+ },
1597
+ "199": {
1598
+ "content": "<strong>",
1599
+ "lstrip": false,
1600
+ "normalized": false,
1601
+ "rstrip": false,
1602
+ "single_word": false,
1603
+ "special": false
1604
+ },
1605
+ "200": {
1606
+ "content": "<em>",
1607
+ "lstrip": false,
1608
+ "normalized": false,
1609
+ "rstrip": false,
1610
+ "single_word": false,
1611
+ "special": false
1612
+ },
1613
+ "201": {
1614
+ "content": "<b>",
1615
+ "lstrip": false,
1616
+ "normalized": false,
1617
+ "rstrip": false,
1618
+ "single_word": false,
1619
+ "special": false
1620
+ },
1621
+ "202": {
1622
+ "content": "<i>",
1623
+ "lstrip": false,
1624
+ "normalized": false,
1625
+ "rstrip": false,
1626
+ "single_word": false,
1627
+ "special": false
1628
+ },
1629
+ "203": {
1630
+ "content": "<u>",
1631
+ "lstrip": false,
1632
+ "normalized": false,
1633
+ "rstrip": false,
1634
+ "single_word": false,
1635
+ "special": false
1636
+ },
1637
+ "204": {
1638
+ "content": "<s>",
1639
+ "lstrip": false,
1640
+ "normalized": false,
1641
+ "rstrip": false,
1642
+ "single_word": false,
1643
+ "special": false
1644
+ },
1645
+ "205": {
1646
+ "content": "<sub>",
1647
+ "lstrip": false,
1648
+ "normalized": false,
1649
+ "rstrip": false,
1650
+ "single_word": false,
1651
+ "special": false
1652
+ },
1653
+ "206": {
1654
+ "content": "<sup>",
1655
+ "lstrip": false,
1656
+ "normalized": false,
1657
+ "rstrip": false,
1658
+ "single_word": false,
1659
+ "special": false
1660
+ },
1661
+ "207": {
1662
+ "content": "<code>",
1663
+ "lstrip": false,
1664
+ "normalized": false,
1665
+ "rstrip": false,
1666
+ "single_word": false,
1667
+ "special": false
1668
+ },
1669
+ "208": {
1670
+ "content": "</strong>",
1671
+ "lstrip": false,
1672
+ "normalized": false,
1673
+ "rstrip": false,
1674
+ "single_word": false,
1675
+ "special": false
1676
+ },
1677
+ "209": {
1678
+ "content": "</em>",
1679
+ "lstrip": false,
1680
+ "normalized": false,
1681
+ "rstrip": false,
1682
+ "single_word": false,
1683
+ "special": false
1684
+ },
1685
+ "210": {
1686
+ "content": "</b>",
1687
+ "lstrip": false,
1688
+ "normalized": false,
1689
+ "rstrip": false,
1690
+ "single_word": false,
1691
+ "special": false
1692
+ },
1693
+ "211": {
1694
+ "content": "</i>",
1695
+ "lstrip": false,
1696
+ "normalized": false,
1697
+ "rstrip": false,
1698
+ "single_word": false,
1699
+ "special": false
1700
+ },
1701
+ "212": {
1702
+ "content": "</u>",
1703
+ "lstrip": false,
1704
+ "normalized": false,
1705
+ "rstrip": false,
1706
+ "single_word": false,
1707
+ "special": false
1708
+ },
1709
+ "213": {
1710
+ "content": "</s>",
1711
+ "lstrip": false,
1712
+ "normalized": false,
1713
+ "rstrip": false,
1714
+ "single_word": false,
1715
+ "special": false
1716
+ },
1717
+ "214": {
1718
+ "content": "</sub>",
1719
+ "lstrip": false,
1720
+ "normalized": false,
1721
+ "rstrip": false,
1722
+ "single_word": false,
1723
+ "special": false
1724
+ },
1725
+ "215": {
1726
+ "content": "</sup>",
1727
+ "lstrip": false,
1728
+ "normalized": false,
1729
+ "rstrip": false,
1730
+ "single_word": false,
1731
+ "special": false
1732
+ },
1733
+ "216": {
1734
+ "content": "</code>",
1735
+ "lstrip": false,
1736
+ "normalized": false,
1737
+ "rstrip": false,
1738
+ "single_word": false,
1739
+ "special": false
1740
+ }
1741
+ },
1742
+ "additional_special_tokens": [
1743
+ "<start_of_turn>",
1744
+ "<end_of_turn>"
1745
+ ],
1746
+ "bos_token": "<bos>",
1747
+ "chat_template": "{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}",
1748
+ "clean_up_tokenization_spaces": false,
1749
+ "eos_token": "<end_of_turn>",
1750
+ "model_max_length": 1000000000000000019884624838656,
1751
+ "pad_token": "<pad>",
1752
+ "sp_model_kwargs": {},
1753
+ "spaces_between_special_tokens": false,
1754
+ "tokenizer_class": "GemmaTokenizer",
1755
+ "unk_token": "<unk>",
1756
+ "use_default_system_prompt": false
1757
+ }