add remote code + model files
Browse files- __init__.py +1 -0
- __pycache__/__init__.cpython-310.pyc +0 -0
- __pycache__/configuration_forgetting_transformer.cpython-310.pyc +0 -0
- __pycache__/fgate_cache.cpython-310.pyc +0 -0
- __pycache__/glu_linear.cpython-310.pyc +0 -0
- __pycache__/modeling_forgetting_transformer.cpython-310.pyc +0 -0
- __pycache__/token_shift.cpython-310.pyc +0 -0
- configuration_forgetting_transformer.py +89 -0
- fgate_cache.py +203 -0
- glu_linear.py +61 -0
- modeling_forgetting_transformer.py +897 -0
- token_shift.py +314 -0
__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# for HF remote code
|
__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (612 Bytes). View file
|
|
|
__pycache__/configuration_forgetting_transformer.cpython-310.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
__pycache__/fgate_cache.cpython-310.pyc
ADDED
|
Binary file (9.16 kB). View file
|
|
|
__pycache__/glu_linear.cpython-310.pyc
ADDED
|
Binary file (2.35 kB). View file
|
|
|
__pycache__/modeling_forgetting_transformer.cpython-310.pyc
ADDED
|
Binary file (23.7 kB). View file
|
|
|
__pycache__/token_shift.cpython-310.pyc
ADDED
|
Binary file (6.37 kB). View file
|
|
|
configuration_forgetting_transformer.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ForgettingTransformerConfig(PretrainedConfig):
|
| 9 |
+
|
| 10 |
+
model_type = 'forgetting_transformer-project_fox'
|
| 11 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
vocab_size: int = 32000,
|
| 16 |
+
hidden_size: int = 2048,
|
| 17 |
+
hidden_ratio: Optional[float] = 4,
|
| 18 |
+
intermediate_size: Optional[int] = None,
|
| 19 |
+
num_hidden_layers: int = 24,
|
| 20 |
+
num_heads: int = 32,
|
| 21 |
+
num_kv_heads: int = None,
|
| 22 |
+
hidden_act: str = "swish",
|
| 23 |
+
window_size: Optional[int] = None,
|
| 24 |
+
max_position_embeddings: int = 2048,
|
| 25 |
+
initializer_range: float = 0.02,
|
| 26 |
+
elementwise_affine: Optional[bool] = True,
|
| 27 |
+
norm_eps: float = 1e-6,
|
| 28 |
+
use_cache: bool = True,
|
| 29 |
+
pad_token_id: int = None,
|
| 30 |
+
bos_token_id: int = 1,
|
| 31 |
+
eos_token_id: int = 2,
|
| 32 |
+
tie_word_embeddings: bool = False,
|
| 33 |
+
attention_bias: bool = False,
|
| 34 |
+
fuse_norm: bool = True,
|
| 35 |
+
fuse_cross_entropy: bool = True,
|
| 36 |
+
rope_base: float = 500000.0,
|
| 37 |
+
use_rope: bool = False,
|
| 38 |
+
use_output_gate: bool = False,
|
| 39 |
+
ogate_act: str = "sigmoid",
|
| 40 |
+
fgate_type: str = "full",
|
| 41 |
+
fgate_bias_init: bool = False,
|
| 42 |
+
decay_time_min: Optional[float] = None,
|
| 43 |
+
decay_time_max: Optional[float] = None,
|
| 44 |
+
use_output_norm: bool = False,
|
| 45 |
+
qk_norm: bool = False,
|
| 46 |
+
qk_norm_share_param_across_head: bool = False,
|
| 47 |
+
use_k_shift: bool = False,
|
| 48 |
+
use_v_shift: bool = False,
|
| 49 |
+
**kwargs,
|
| 50 |
+
):
|
| 51 |
+
self.vocab_size = vocab_size
|
| 52 |
+
self.hidden_size = hidden_size
|
| 53 |
+
self.hidden_ratio = hidden_ratio
|
| 54 |
+
self.intermediate_size = intermediate_size
|
| 55 |
+
self.num_hidden_layers = num_hidden_layers
|
| 56 |
+
self.num_heads = num_heads
|
| 57 |
+
self.num_kv_heads = num_kv_heads
|
| 58 |
+
self.window_size = window_size
|
| 59 |
+
self.max_position_embeddings = max_position_embeddings
|
| 60 |
+
|
| 61 |
+
self.hidden_act = hidden_act
|
| 62 |
+
self.initializer_range = initializer_range
|
| 63 |
+
self.elementwise_affine = elementwise_affine
|
| 64 |
+
self.norm_eps = norm_eps
|
| 65 |
+
self.use_cache = use_cache
|
| 66 |
+
self.attention_bias = attention_bias
|
| 67 |
+
self.fuse_cross_entropy = fuse_cross_entropy
|
| 68 |
+
self.fuse_norm = fuse_norm
|
| 69 |
+
self.rope_base = rope_base
|
| 70 |
+
self.use_rope = use_rope
|
| 71 |
+
self.use_output_gate = use_output_gate
|
| 72 |
+
self.ogate_act = ogate_act
|
| 73 |
+
self.fgate_type = fgate_type
|
| 74 |
+
self.fgate_bias_init = fgate_bias_init
|
| 75 |
+
self.decay_time_min = decay_time_min
|
| 76 |
+
self.decay_time_max = decay_time_max
|
| 77 |
+
self.use_output_norm = use_output_norm
|
| 78 |
+
self.qk_norm = qk_norm
|
| 79 |
+
self.qk_norm_share_param_across_head = qk_norm_share_param_across_head
|
| 80 |
+
self.use_k_shift = use_k_shift
|
| 81 |
+
self.use_v_shift = use_v_shift
|
| 82 |
+
|
| 83 |
+
super().__init__(
|
| 84 |
+
pad_token_id=pad_token_id,
|
| 85 |
+
bos_token_id=bos_token_id,
|
| 86 |
+
eos_token_id=eos_token_id,
|
| 87 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 88 |
+
**kwargs,
|
| 89 |
+
)
|
fgate_cache.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Tuple, Optional, Any, Dict
|
| 2 |
+
import torch
|
| 3 |
+
from transformers.cache_utils import Cache
|
| 4 |
+
|
| 5 |
+
class FgateDynamicCache(Cache):
|
| 6 |
+
"""
|
| 7 |
+
A cache that grows dynamically as more tokens are generated. This is the default for generative models.
|
| 8 |
+
|
| 9 |
+
It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is
|
| 10 |
+
`[batch_size, num_heads, seq_len, head_dim]`.
|
| 11 |
+
|
| 12 |
+
Example:
|
| 13 |
+
|
| 14 |
+
```python
|
| 15 |
+
>>> from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache
|
| 16 |
+
|
| 17 |
+
>>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
|
| 18 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
|
| 19 |
+
|
| 20 |
+
>>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
|
| 21 |
+
|
| 22 |
+
>>> # Prepare a cache class and pass it to model's forward
|
| 23 |
+
>>> past_key_values = DynamicCache()
|
| 24 |
+
>>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
|
| 25 |
+
>>> outputs.past_key_values # access cache filled with key/values from generation
|
| 26 |
+
DynamicCache()
|
| 27 |
+
```
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self) -> None:
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.key_cache: List[torch.Tensor] = []
|
| 33 |
+
self.value_cache: List[torch.Tensor] = []
|
| 34 |
+
self.log_fgate_cache: List[torch.Tensor] = []
|
| 35 |
+
|
| 36 |
+
self.key_shift_cache: List[torch.Tensor] = []
|
| 37 |
+
self.value_shift_cache: List[torch.Tensor] = []
|
| 38 |
+
|
| 39 |
+
self._seen_tokens = 0 # Used in `generate` to keep tally of how many tokens the cache has seen
|
| 40 |
+
|
| 41 |
+
def update_shift_cache(
|
| 42 |
+
self,
|
| 43 |
+
key_shift_state: torch.Tensor,
|
| 44 |
+
value_shift_state: torch.Tensor,
|
| 45 |
+
layer_idx,
|
| 46 |
+
):
|
| 47 |
+
assert layer_idx == len(self.key_shift_cache) == len(self.value_shift_cache)
|
| 48 |
+
self.key_shift_cache.append(key_shift_state)
|
| 49 |
+
self.value_shift_cache.append(value_shift_state)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def __getitem__(self, layer_idx: int) -> List[Tuple[torch.Tensor]]:
|
| 53 |
+
"""
|
| 54 |
+
Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
|
| 55 |
+
sequence length.
|
| 56 |
+
"""
|
| 57 |
+
if layer_idx < len(self):
|
| 58 |
+
return (self.key_cache[layer_idx], self.value_cache[layer_idx], self.log_fgate_cache[layer_idx])
|
| 59 |
+
else:
|
| 60 |
+
raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
|
| 61 |
+
|
| 62 |
+
def __iter__(self):
|
| 63 |
+
"""
|
| 64 |
+
Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
|
| 65 |
+
keys and values
|
| 66 |
+
"""
|
| 67 |
+
for layer_idx in range(len(self)):
|
| 68 |
+
yield (self.key_cache[layer_idx], self.value_cache[layer_idx], self.log_fgate_cache[layer_idx])
|
| 69 |
+
|
| 70 |
+
def __len__(self):
|
| 71 |
+
"""
|
| 72 |
+
Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
|
| 73 |
+
to the number of layers in the model.
|
| 74 |
+
"""
|
| 75 |
+
return len(self.key_cache)
|
| 76 |
+
|
| 77 |
+
def update(
|
| 78 |
+
self,
|
| 79 |
+
key_states: torch.Tensor,
|
| 80 |
+
value_states: torch.Tensor,
|
| 81 |
+
log_fgate_states: torch.Tensor,
|
| 82 |
+
layer_idx: int,
|
| 83 |
+
cache_kwargs: Optional[Dict[str, Any]] = None,
|
| 84 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 85 |
+
"""
|
| 86 |
+
Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
|
| 87 |
+
|
| 88 |
+
Parameters:
|
| 89 |
+
key_states (`torch.Tensor`):
|
| 90 |
+
The new key states to cache.
|
| 91 |
+
value_states (`torch.Tensor`):
|
| 92 |
+
The new value states to cache.
|
| 93 |
+
layer_idx (`int`):
|
| 94 |
+
The index of the layer to cache the states for.
|
| 95 |
+
cache_kwargs (`Dict[str, Any]`, `optional`):
|
| 96 |
+
Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
|
| 97 |
+
|
| 98 |
+
Return:
|
| 99 |
+
A tuple containing the updated key and value states.
|
| 100 |
+
"""
|
| 101 |
+
assert log_fgate_states.ndim == 3, f"log_fgate must be (B, H, T), but get {log_fgate_states.size()}"
|
| 102 |
+
# Update the number of seen tokens
|
| 103 |
+
if layer_idx == 0:
|
| 104 |
+
self._seen_tokens += key_states.shape[-2]
|
| 105 |
+
|
| 106 |
+
# Update the cache
|
| 107 |
+
if len(self.key_cache) <= layer_idx:
|
| 108 |
+
self.key_cache.append(key_states)
|
| 109 |
+
self.value_cache.append(value_states)
|
| 110 |
+
self.log_fgate_cache.append(log_fgate_states)
|
| 111 |
+
else:
|
| 112 |
+
self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
|
| 113 |
+
self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
|
| 114 |
+
self.log_fgate_cache[layer_idx] = torch.cat([self.log_fgate_cache[layer_idx], log_fgate_states], dim=-1)
|
| 115 |
+
|
| 116 |
+
return self.key_cache[layer_idx], self.value_cache[layer_idx], self.log_fgate_cache[layer_idx]
|
| 117 |
+
|
| 118 |
+
def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
|
| 119 |
+
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
|
| 120 |
+
# TODO: deprecate this function in favor of `cache_position`
|
| 121 |
+
if len(self.key_cache) <= layer_idx:
|
| 122 |
+
return 0
|
| 123 |
+
return self.key_cache[layer_idx].shape[-2]
|
| 124 |
+
|
| 125 |
+
def get_max_length(self) -> Optional[int]:
|
| 126 |
+
"""Returns the maximum sequence length of the cached states. DynamicCache does not have a maximum length."""
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
|
| 130 |
+
"""Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
|
| 131 |
+
backward compatibility."""
|
| 132 |
+
legacy_cache = ()
|
| 133 |
+
for layer_idx in range(len(self)):
|
| 134 |
+
legacy_cache += ((self.key_cache[layer_idx], self.value_cache[layer_idx], self.log_fgate_cache[layer_idx]),)
|
| 135 |
+
return legacy_cache
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, num_layers: Optional[int] = None) -> "DynamicCache":
|
| 139 |
+
"""Converts a cache in the legacy cache format into an equivalent `DynamicCache`. Used for
|
| 140 |
+
backward compatibility."""
|
| 141 |
+
raise NotImplementedError
|
| 142 |
+
assert num_layers is not None
|
| 143 |
+
cache = cls(num_layers)
|
| 144 |
+
if past_key_values is not None:
|
| 145 |
+
for layer_idx in range(len(past_key_values)):
|
| 146 |
+
key_states, value_states, log_fgate_states = past_key_values[layer_idx]
|
| 147 |
+
cache.update(key_states, value_states, log_fgate_states, layer_idx)
|
| 148 |
+
return cache
|
| 149 |
+
|
| 150 |
+
def crop(self, max_length: int):
|
| 151 |
+
"""Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
|
| 152 |
+
negative to remove `max_length` tokens. This is used in assisted decoding and contrastive search."""
|
| 153 |
+
# In case it is negative
|
| 154 |
+
if max_length < 0:
|
| 155 |
+
max_length = self.get_seq_length() - abs(max_length)
|
| 156 |
+
|
| 157 |
+
if self.get_seq_length() <= max_length:
|
| 158 |
+
return
|
| 159 |
+
|
| 160 |
+
self._seen_tokens = max_length
|
| 161 |
+
for idx in range(len(self.key_cache)):
|
| 162 |
+
self.key_cache[idx] = self.key_cache[idx][..., :max_length, :]
|
| 163 |
+
self.value_cache[idx] = self.value_cache[idx][..., :max_length, :]
|
| 164 |
+
self.log_fgate_cache[idx] = self.log_fgate_cache[idx][..., :max_length]
|
| 165 |
+
|
| 166 |
+
def batch_split(self, full_batch_size: int, split_size: int) -> List["DynamicCache"]:
|
| 167 |
+
"""Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
|
| 168 |
+
`_split_model_inputs()` in `generation.utils`"""
|
| 169 |
+
out = []
|
| 170 |
+
for i in range(0, full_batch_size, split_size):
|
| 171 |
+
current_split = DynamicCache()
|
| 172 |
+
current_split._seen_tokens = self._seen_tokens
|
| 173 |
+
current_split.key_cache = [tensor[i : i + split_size] for tensor in self.key_cache]
|
| 174 |
+
current_split.value_cache = [tensor[i : i + split_size] for tensor in self.value_cache]
|
| 175 |
+
current_split.log_fgate_cache = [tensor[i : i + split_size] for tensor in self.log_fgate_cache]
|
| 176 |
+
out.append(current_split)
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
@classmethod
|
| 180 |
+
def from_batch_splits(cls, splits: List["DynamicCache"]) -> "DynamicCache":
|
| 181 |
+
"""This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
|
| 182 |
+
`generation.utils`"""
|
| 183 |
+
cache = cls()
|
| 184 |
+
for idx in range(len(splits[0])):
|
| 185 |
+
layer_keys = torch.cat([current.key_cache[idx] for current in splits], dim=0)
|
| 186 |
+
layer_values = torch.cat([current.value_cache[idx] for current in splits], dim=0)
|
| 187 |
+
layer_log_fgates = torch.cat([current.log_fgate_cache[idx] for current in splits], dim=0)
|
| 188 |
+
cache.update(layer_keys, layer_values, layer_log_fgates, idx)
|
| 189 |
+
return cache
|
| 190 |
+
|
| 191 |
+
def batch_repeat_interleave(self, repeats: int):
|
| 192 |
+
"""Repeat the cache `repeats` times in the batch dimension. Used in contrastive search."""
|
| 193 |
+
for layer_idx in range(len(self)):
|
| 194 |
+
self.key_cache[layer_idx] = self.key_cache[layer_idx].repeat_interleave(repeats, dim=0)
|
| 195 |
+
self.value_cache[layer_idx] = self.value_cache[layer_idx].repeat_interleave(repeats, dim=0)
|
| 196 |
+
self.log_fgate_cache[layer_idx] = self.log_fgate_cache[layer_idx].repeat_interleave(repeats, dim=0)
|
| 197 |
+
|
| 198 |
+
def batch_select_indices(self, indices: torch.Tensor):
|
| 199 |
+
"""Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
|
| 200 |
+
for layer_idx in range(len(self)):
|
| 201 |
+
self.key_cache[layer_idx] = self.key_cache[layer_idx][indices, ...]
|
| 202 |
+
self.value_cache[layer_idx] = self.value_cache[layer_idx][indices, ...]
|
| 203 |
+
self.log_fgate_cache[layer_idx] = self.log_fgate_cache[layer_idx][indices, ...]
|
glu_linear.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
glu_fwd_codestring = """
|
| 6 |
+
template <typename T> T glu_fwd(T x, T y) {
|
| 7 |
+
return float(y) / (1.0f + ::exp(-float(x)));
|
| 8 |
+
}
|
| 9 |
+
"""
|
| 10 |
+
glu_bwd_codestring = """
|
| 11 |
+
template <typename T> T glu_bwd(T x, T y, T g, T& dx, T& dy) {
|
| 12 |
+
float x_sigmoid = 1.0f / (1.0f + ::exp(-float(x)));
|
| 13 |
+
dx = x_sigmoid * (1.0f - x_sigmoid) * float(g) * float(y);
|
| 14 |
+
dy = x_sigmoid * float(g);
|
| 15 |
+
}
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
glu_bwd_with_output_codestring = """
|
| 19 |
+
template <typename T> T glu_bwd_with_output(T x, T y, T g, T& dx, T& dy, T& z) {
|
| 20 |
+
float x_sigmoid = 1.0f / (1.0f + ::exp(-float(x)));
|
| 21 |
+
dx = x_sigmoid * (1.0f - x_sigmoid) * float(g) * float(y);
|
| 22 |
+
dy = x_sigmoid * float(g);
|
| 23 |
+
z = x_sigmoid * float(y);
|
| 24 |
+
}
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
glu_fwd = torch.cuda.jiterator._create_jit_fn(glu_fwd_codestring)
|
| 28 |
+
glu_bwd = torch.cuda.jiterator._create_multi_output_jit_fn(glu_bwd_codestring, num_outputs=2)
|
| 29 |
+
glu_bwd_with_output = torch.cuda.jiterator._create_multi_output_jit_fn(glu_bwd_with_output_codestring, num_outputs=3)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class GLULinearFunction(torch.autograd.Function):
|
| 33 |
+
r"""
|
| 34 |
+
Gated Linear Unit (GLU) function followed by a linear transformation.
|
| 35 |
+
|
| 36 |
+
.. math::
|
| 37 |
+
\text{GLULinear}(x, y, W, b) = (sh(x) * y) W + b
|
| 38 |
+
|
| 39 |
+
This simple wrap discards the intermediate results of GLU(x, y) to save memory.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def forward(ctx, x, y, weight, bias):
|
| 44 |
+
z = glu_fwd(x, y)
|
| 45 |
+
out = F.linear(z.to(weight.dtype), weight, bias)
|
| 46 |
+
# We don't store z, will be recomputed in the backward pass to save memory
|
| 47 |
+
ctx.save_for_backward(x, y, weight)
|
| 48 |
+
ctx.linear_bias_is_none = bias is None
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def backward(ctx, dout, *args):
|
| 53 |
+
x, y, weight = ctx.saved_tensors
|
| 54 |
+
dout = dout.reshape(-1, dout.shape[-1])
|
| 55 |
+
dz = F.linear(dout, weight.t()).view_as(x)
|
| 56 |
+
dx, dy, z = glu_bwd_with_output(x, y, dz)
|
| 57 |
+
dlinear_weight = torch.einsum("bo,bi->oi", dout, z.reshape(-1, z.shape[-1]))
|
| 58 |
+
dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
|
| 59 |
+
return dx, dy, dlinear_weight, dlinear_bias
|
| 60 |
+
|
| 61 |
+
glu_linear = GLULinearFunction.apply
|
modeling_forgetting_transformer.py
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.utils.checkpoint
|
| 12 |
+
from transformers.activations import ACT2FN
|
| 13 |
+
from transformers.cache_utils import Cache
|
| 14 |
+
from transformers.modeling_outputs import (BaseModelOutputWithPast,
|
| 15 |
+
CausalLMOutputWithPast)
|
| 16 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 17 |
+
from transformers.utils import logging
|
| 18 |
+
|
| 19 |
+
# from fla.layers.attn import Attention
|
| 20 |
+
from fla.modules import FusedCrossEntropyLoss, RMSNorm
|
| 21 |
+
from fla.modules.layernorm import group_norm_fn
|
| 22 |
+
from fla.modules.activations import swiglu_linear
|
| 23 |
+
|
| 24 |
+
from fla.modules import RotaryEmbedding
|
| 25 |
+
from einops import rearrange
|
| 26 |
+
|
| 27 |
+
from .configuration_forgetting_transformer import ForgettingTransformerConfig
|
| 28 |
+
from forgetting_transformer.ops.forgetting_attention import forgetting_attention
|
| 29 |
+
from .fgate_cache import FgateDynamicCache
|
| 30 |
+
from .glu_linear import glu_linear
|
| 31 |
+
from .token_shift import token_shift
|
| 32 |
+
|
| 33 |
+
from functools import partial
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ShiftLinear(nn.Module):
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
input_dim: int,
|
| 43 |
+
output_dim: int,
|
| 44 |
+
num_heads: int,
|
| 45 |
+
bias: bool,
|
| 46 |
+
shift_bias: bool = False
|
| 47 |
+
):
|
| 48 |
+
super().__init__()
|
| 49 |
+
|
| 50 |
+
self.input_dim = input_dim
|
| 51 |
+
self.output_dim = output_dim
|
| 52 |
+
self.num_heads = num_heads
|
| 53 |
+
assert self.output_dim % self.num_heads == 0
|
| 54 |
+
|
| 55 |
+
self.linear = nn.Linear(input_dim, output_dim, bias=bias)
|
| 56 |
+
self.shift_proj = nn.Linear(input_dim, num_heads, bias=shift_bias)
|
| 57 |
+
|
| 58 |
+
def __repr__(self) -> str:
|
| 59 |
+
s = f"{self.__class__.__name__}({self.input_dim}, {self.output_dim})"
|
| 60 |
+
return s
|
| 61 |
+
|
| 62 |
+
def forward(self, x: torch.Tensor, shift_state: Optional[torch.Tensor]) -> torch.Tensor:
|
| 63 |
+
assert x.ndim == 3, "Input must be (B, T, D)"
|
| 64 |
+
B, T, D = x.size()
|
| 65 |
+
out = self.linear(x)
|
| 66 |
+
# (B, T, H, 1)
|
| 67 |
+
alpha = torch.sigmoid(self.shift_proj(x).float()).float()
|
| 68 |
+
# left, right, top, bottom (B, T=H, D=W)
|
| 69 |
+
# out_prev = nn.functional.pad(out, (0, 0, 1, -1))
|
| 70 |
+
# out_prev = torch.roll(out, shifts=1, dims=1)
|
| 71 |
+
|
| 72 |
+
out_per_head = rearrange(out, 'b t (h d) -> b t h d', h=self.num_heads)
|
| 73 |
+
if T > 1:
|
| 74 |
+
# TODO: note in this case cache is not used
|
| 75 |
+
result_per_head = token_shift(out_per_head, alpha, 1.0 - alpha)
|
| 76 |
+
else:
|
| 77 |
+
shift_state_per_head = rearrange(shift_state, 'b (h d) -> b 1 h d', h=self.num_heads)
|
| 78 |
+
result_per_head = (alpha[..., None] * shift_state_per_head + (1 - alpha[..., None]) * out_per_head)
|
| 79 |
+
|
| 80 |
+
result_per_head = result_per_head.to(out.dtype)
|
| 81 |
+
|
| 82 |
+
if shift_state is not None:
|
| 83 |
+
shift_state.copy_(out[:, -1, :])
|
| 84 |
+
|
| 85 |
+
result = rearrange(result_per_head, 'b t h d -> b t (h d)', h=self.num_heads)
|
| 86 |
+
return result
|
| 87 |
+
|
| 88 |
+
class GroupRMSNorm(nn.Module):
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
num_groups: int,
|
| 92 |
+
hidden_size: int,
|
| 93 |
+
elementwise_affine: bool = True,
|
| 94 |
+
bias: bool = False,
|
| 95 |
+
eps: float = 1e-5
|
| 96 |
+
) -> GroupRMSNorm:
|
| 97 |
+
super().__init__()
|
| 98 |
+
|
| 99 |
+
if hidden_size % num_groups != 0:
|
| 100 |
+
raise ValueError('num_channels must be divisible by num_groups')
|
| 101 |
+
|
| 102 |
+
self.num_groups = num_groups
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.elementwise_affine = elementwise_affine
|
| 105 |
+
self.eps = eps
|
| 106 |
+
|
| 107 |
+
self.register_parameter("weight", None)
|
| 108 |
+
self.register_parameter("bias", None)
|
| 109 |
+
if elementwise_affine:
|
| 110 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 111 |
+
if bias:
|
| 112 |
+
self.bias = nn.Parameter(torch.zeros(hidden_size))
|
| 113 |
+
|
| 114 |
+
def __repr__(self) -> str:
|
| 115 |
+
s = f"{self.__class__.__name__}({self.num_groups}, {self.hidden_size}"
|
| 116 |
+
if not self.elementwise_affine:
|
| 117 |
+
s += f", elementwise_affine={self.elementwise_affine}"
|
| 118 |
+
s += f", eps={self.eps}"
|
| 119 |
+
s += ")"
|
| 120 |
+
return s
|
| 121 |
+
|
| 122 |
+
def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False):
|
| 123 |
+
return group_norm_fn(
|
| 124 |
+
x,
|
| 125 |
+
self.weight,
|
| 126 |
+
self.bias,
|
| 127 |
+
residual=residual,
|
| 128 |
+
eps=self.eps,
|
| 129 |
+
prenorm=prenorm,
|
| 130 |
+
residual_in_fp32=residual_in_fp32,
|
| 131 |
+
is_rms_norm=True,
|
| 132 |
+
num_groups=self.num_groups
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
class ForgettingAttentionLayer(nn.Module):
|
| 136 |
+
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
hidden_size: int = 2048,
|
| 140 |
+
num_heads: int = 32,
|
| 141 |
+
num_kv_heads: Optional[int] = None,
|
| 142 |
+
window_size: Optional[int] = None,
|
| 143 |
+
max_position_embeddings: Optional[int] = None,
|
| 144 |
+
use_rope: bool = False,
|
| 145 |
+
rope_base: float = 500000.0,
|
| 146 |
+
use_output_gate: bool = False,
|
| 147 |
+
ogate_act: str = "sigmoid",
|
| 148 |
+
fgate_type: str = "full",
|
| 149 |
+
fgate_bias_init: bool = False,
|
| 150 |
+
decay_time_min: Optional[float] = None,
|
| 151 |
+
decay_time_max: Optional[float] = None,
|
| 152 |
+
use_output_norm: bool = False,
|
| 153 |
+
norm_eps: float = 1e-6,
|
| 154 |
+
qk_norm: bool = False,
|
| 155 |
+
qk_norm_share_param_across_head: bool = False,
|
| 156 |
+
use_k_shift: bool = False,
|
| 157 |
+
use_v_shift: bool = False,
|
| 158 |
+
initializer_range: float = 0.02,
|
| 159 |
+
layer_idx: int = None
|
| 160 |
+
):
|
| 161 |
+
"""
|
| 162 |
+
Forgetting Attention layer.
|
| 163 |
+
|
| 164 |
+
Arguments:
|
| 165 |
+
- hidden_size: Input dimension and qkv dimension
|
| 166 |
+
- num_heads: Number of heads
|
| 167 |
+
- num_kv_heads: Not used. Should be None
|
| 168 |
+
- window_size: Not used. Should be None
|
| 169 |
+
- max_position_embeddings: Not used. Should be None
|
| 170 |
+
- use_rope: Whether to use RoPE. Default is False
|
| 171 |
+
- rope_base: the theta hyperparameter in RoPE. This has no effect if
|
| 172 |
+
use_rope=False
|
| 173 |
+
- use_output_gate: Whether to use output gates. Note that using output gates
|
| 174 |
+
introduces extra parameters and you may want to reduce parameters from
|
| 175 |
+
other components (e.g., MLPs)
|
| 176 |
+
- ogate_act: Activation for the output gate. Either "sigmoid" or "silu"
|
| 177 |
+
- fgate_type: Forget gate type. The following are supported:
|
| 178 |
+
- "full": The default data-dependent forget gate
|
| 179 |
+
- "bias_only": The data-independent forget gate
|
| 180 |
+
- "fixed": Forget gates with fixed values
|
| 181 |
+
- "none": Not using forget gates. Equivalent to forget gates with all
|
| 182 |
+
ones.
|
| 183 |
+
- fgate_bias_init: Whether to use special initalization for the bias terms in
|
| 184 |
+
the forget gate. This should only be used with fgate types in
|
| 185 |
+
["bias_only", "fixed"].
|
| 186 |
+
- decay_time_min: T_min for the forget gate bias initialization. See paper
|
| 187 |
+
for details.
|
| 188 |
+
- decay_time_max: T_max for the forget gate bias initalization. See paper
|
| 189 |
+
for details.
|
| 190 |
+
- use_output_norm: Whether to use output normalization.
|
| 191 |
+
- norm_eps: Epsilon for the RMSNorms
|
| 192 |
+
- qk_norm: Whether to use qk_norm
|
| 193 |
+
- qk_norm_share_param_across_head: In QK-norm, whether to share the RMSNorm
|
| 194 |
+
scaling parameters across heads. This is just for backward compatibility.
|
| 195 |
+
- use_k_shift: Whether to use data-dependent key shift
|
| 196 |
+
- use_v_shift: Whether to use data-dependent value shift
|
| 197 |
+
- initializer_range: standard deviation for initialization
|
| 198 |
+
- layer_idx: The block index of this layer. Needed for KV-cache
|
| 199 |
+
"""
|
| 200 |
+
super().__init__()
|
| 201 |
+
|
| 202 |
+
self.num_heads = num_heads
|
| 203 |
+
if num_kv_heads is None:
|
| 204 |
+
self.num_kv_heads = self.num_heads
|
| 205 |
+
else:
|
| 206 |
+
raise NotImplementedError("GQA has not been tested.")
|
| 207 |
+
self.num_kv_heads = num_kv_heads
|
| 208 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 209 |
+
self.hidden_size = hidden_size
|
| 210 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 211 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 212 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 213 |
+
self.window_size = window_size
|
| 214 |
+
self.max_position_embeddings = max_position_embeddings
|
| 215 |
+
self.layer_idx = layer_idx
|
| 216 |
+
|
| 217 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 218 |
+
if use_k_shift:
|
| 219 |
+
self.k_proj = ShiftLinear(self.hidden_size, self.kv_dim, self.num_heads, bias=False)
|
| 220 |
+
else:
|
| 221 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 222 |
+
|
| 223 |
+
if use_v_shift:
|
| 224 |
+
self.v_proj = ShiftLinear(self.hidden_size, self.kv_dim, self.num_heads, bias=False)
|
| 225 |
+
else:
|
| 226 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 227 |
+
|
| 228 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 229 |
+
self.use_k_shift = use_k_shift
|
| 230 |
+
self.use_v_shift = use_v_shift
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
device = next(self.parameters()).device
|
| 234 |
+
# Forget gate
|
| 235 |
+
assert fgate_type in ["full", "bias_only", "fixed", "none"]
|
| 236 |
+
self.fgate_type = fgate_type
|
| 237 |
+
self.fgate_bias_init = fgate_bias_init
|
| 238 |
+
if fgate_type == "full":
|
| 239 |
+
assert not fgate_bias_init
|
| 240 |
+
self.fgate_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True)
|
| 241 |
+
elif fgate_type == "bias_only":
|
| 242 |
+
self.fgate_bias = nn.Parameter(torch.zeros(size=(self.num_heads,), device=device))
|
| 243 |
+
self.fgate_bias._no_weight_decay = True
|
| 244 |
+
elif fgate_type == "fixed":
|
| 245 |
+
assert fgate_bias_init, "You must set fgate_bias_init = True with fixed fgate"
|
| 246 |
+
fgate_bias = torch.zeros(size=(self.num_heads,), device=device)
|
| 247 |
+
self.register_buffer("fgate_bias", fgate_bias)
|
| 248 |
+
elif fgate_type == "none":
|
| 249 |
+
pass
|
| 250 |
+
else:
|
| 251 |
+
raise ValueError(f"Unknown fgate type {fgate_type}")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# Forget gate intialization for data-independent and fixed forget gates
|
| 256 |
+
if fgate_bias_init:
|
| 257 |
+
assert decay_time_min is not None and decay_time_max is not None
|
| 258 |
+
assert decay_time_min > 0 and decay_time_max > 0
|
| 259 |
+
with torch.no_grad():
|
| 260 |
+
log_decay_time = torch.linspace(math.log(decay_time_min), math.log(decay_time_max), steps=self.num_heads)
|
| 261 |
+
decay_time = torch.exp(log_decay_time)
|
| 262 |
+
# Such that t = -1 / log(sigmoid(b))
|
| 263 |
+
bias_init = -torch.log(torch.expm1(1 / decay_time))
|
| 264 |
+
self.fgate_bias.copy_(bias_init)
|
| 265 |
+
else:
|
| 266 |
+
assert decay_time_min is None and decay_time_max is None
|
| 267 |
+
|
| 268 |
+
if use_output_gate:
|
| 269 |
+
self.ogate_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 270 |
+
self.ogate_act = ogate_act
|
| 271 |
+
assert ogate_act in ["silu", "sigmoid"]
|
| 272 |
+
else:
|
| 273 |
+
self.ogate_proj = None
|
| 274 |
+
|
| 275 |
+
if use_output_norm:
|
| 276 |
+
self.output_norm = GroupRMSNorm(num_groups=self.num_heads, hidden_size=self.hidden_size, eps=norm_eps)
|
| 277 |
+
else:
|
| 278 |
+
self.output_norm = None
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
if use_rope:
|
| 282 |
+
self.rotary = RotaryEmbedding(self.head_dim, base=rope_base)
|
| 283 |
+
else:
|
| 284 |
+
self.rotary = None
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
self.qk_norm = qk_norm
|
| 288 |
+
self.qk_norm_share_param_across_head = qk_norm_share_param_across_head
|
| 289 |
+
if qk_norm:
|
| 290 |
+
if self.qk_norm_share_param_across_head:
|
| 291 |
+
# This is an incorrect implemention kept just for backward compatibility
|
| 292 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 293 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 294 |
+
else:
|
| 295 |
+
self.q_norm = GroupRMSNorm(num_groups=self.num_heads, hidden_size=self.hidden_size)
|
| 296 |
+
self.k_norm = GroupRMSNorm(num_groups=self.num_heads, hidden_size=self.hidden_size)
|
| 297 |
+
|
| 298 |
+
self.initializer_range = initializer_range
|
| 299 |
+
self.apply(self._initialize_weights)
|
| 300 |
+
|
| 301 |
+
def _initialize_weights(self, module: nn.Module):
|
| 302 |
+
# This will actually be overwritten by outer init.
|
| 303 |
+
if isinstance(module, nn.Linear):
|
| 304 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.initializer_range)
|
| 305 |
+
if module.bias is not None:
|
| 306 |
+
nn.init.zeros_(module.bias)
|
| 307 |
+
|
| 308 |
+
def forward(
|
| 309 |
+
self,
|
| 310 |
+
hidden_states: torch.Tensor,
|
| 311 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 312 |
+
past_key_values: Optional[Cache] = None,
|
| 313 |
+
output_attentions: bool = False,
|
| 314 |
+
use_cache: bool = False,
|
| 315 |
+
**kwargs,
|
| 316 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 317 |
+
"""
|
| 318 |
+
We assume that during decoding attention mask is always 1. Otherwise it won't work.
|
| 319 |
+
"""
|
| 320 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 321 |
+
if use_cache:
|
| 322 |
+
key_shift_state = past_key_values.key_shift_cache[self.layer_idx]
|
| 323 |
+
value_shift_state = past_key_values.value_shift_cache[self.layer_idx]
|
| 324 |
+
else:
|
| 325 |
+
key_shift_state = value_shift_state = None
|
| 326 |
+
|
| 327 |
+
# Shift states are updated in place
|
| 328 |
+
q = self.q_proj(hidden_states)
|
| 329 |
+
if self.use_k_shift:
|
| 330 |
+
k = self.k_proj(hidden_states, key_shift_state)
|
| 331 |
+
else:
|
| 332 |
+
k = self.k_proj(hidden_states)
|
| 333 |
+
if self.use_v_shift:
|
| 334 |
+
v = self.v_proj(hidden_states, value_shift_state)
|
| 335 |
+
else:
|
| 336 |
+
v = self.v_proj(hidden_states)
|
| 337 |
+
|
| 338 |
+
if self.qk_norm and (not self.qk_norm_share_param_across_head):
|
| 339 |
+
q = self.q_norm(q).to(q.dtype)
|
| 340 |
+
k = self.k_norm(k).to(k.dtype)
|
| 341 |
+
|
| 342 |
+
q = rearrange(q, '... (h d) -> ... h d', h=self.num_heads)
|
| 343 |
+
k = rearrange(k, '... (h d) -> ... h d', h=self.num_kv_heads)
|
| 344 |
+
v = rearrange(v, 'b t (h d) -> b h t d', h=self.num_kv_heads)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
if self.qk_norm and (self.qk_norm_share_param_across_head):
|
| 348 |
+
q = self.q_norm(q).to(q.dtype)
|
| 349 |
+
k = self.k_norm(k).to(k.dtype)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
seqlen_offset, max_seqlen = 0, q.shape[1]
|
| 353 |
+
if past_key_values is not None:
|
| 354 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 355 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 356 |
+
|
| 357 |
+
if attention_mask is not None:
|
| 358 |
+
# to deliminate the offsets of padding tokens
|
| 359 |
+
seqlen_offset = (seqlen_offset + attention_mask.sum(-1) - attention_mask.shape[-1])
|
| 360 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 361 |
+
|
| 362 |
+
if self.max_position_embeddings is not None:
|
| 363 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 364 |
+
if self.rotary is not None:
|
| 365 |
+
q, k = self.rotary(q, k, seqlen_offset, max_seqlen)
|
| 366 |
+
|
| 367 |
+
if self.fgate_type == "full":
|
| 368 |
+
fgate_logit = self.fgate_proj(hidden_states)
|
| 369 |
+
fgate_logit = rearrange(fgate_logit, "b t h -> b h t")
|
| 370 |
+
log_fgate = torch.nn.functional.logsigmoid(fgate_logit.float())
|
| 371 |
+
elif self.fgate_type == "none":
|
| 372 |
+
log_fgate = torch.zeros((batch_size, self.num_heads, q_len), dtype=torch.float32, device=hidden_states.device)
|
| 373 |
+
else:
|
| 374 |
+
assert self.fgate_type in ["fixed", "bias_only"]
|
| 375 |
+
fgate_logit = torch.broadcast_to(self.fgate_bias, (batch_size, q_len, self.num_heads))
|
| 376 |
+
fgate_logit = rearrange(fgate_logit, "b t h -> b h t")
|
| 377 |
+
log_fgate = torch.nn.functional.logsigmoid(fgate_logit.float())
|
| 378 |
+
|
| 379 |
+
k = rearrange(k, 'b t h d -> b h t d')
|
| 380 |
+
if past_key_values is not None:
|
| 381 |
+
k, v, log_fgate = past_key_values.update(k, v, log_fgate, self.layer_idx)
|
| 382 |
+
# k, v = rearrange(k, 'b h t d -> b t h d'), rearrange(v, 'b h t d -> b t h d')
|
| 383 |
+
q = rearrange(q, 'b t h d -> b h t d')
|
| 384 |
+
|
| 385 |
+
if self.num_kv_groups > 1:
|
| 386 |
+
assert False
|
| 387 |
+
k = rearrange(k.unsqueeze(-2).repeat(1, 1, 1, self.num_kv_groups, 1), 'b t h g d -> b t (h g) d')
|
| 388 |
+
v = rearrange(v.unsqueeze(-2).repeat(1, 1, 1, self.num_kv_groups, 1), 'b t h g d -> b t (h g) d')
|
| 389 |
+
|
| 390 |
+
# Contains at least one padding token in the sequence
|
| 391 |
+
if attention_mask is not None:
|
| 392 |
+
B, _, T = log_fgate.size()
|
| 393 |
+
assert attention_mask.size() == (B, T), ((B, T), attention_mask.size())
|
| 394 |
+
seq_start = T - attention_mask.sum(dim=-1)
|
| 395 |
+
o = forgetting_attention(
|
| 396 |
+
q, k, v,
|
| 397 |
+
log_fgate,
|
| 398 |
+
head_first=True,
|
| 399 |
+
seq_start=seq_start,
|
| 400 |
+
sm_scale=1 / math.sqrt(self.head_dim),
|
| 401 |
+
)
|
| 402 |
+
o = rearrange(o, "b h t d -> b t h d")
|
| 403 |
+
else:
|
| 404 |
+
o = forgetting_attention(
|
| 405 |
+
q, k, v,
|
| 406 |
+
log_fgate,
|
| 407 |
+
head_first=True,
|
| 408 |
+
sm_scale=1 / math.sqrt(self.head_dim),
|
| 409 |
+
)
|
| 410 |
+
o = rearrange(o, "b h t d -> b t h d")
|
| 411 |
+
|
| 412 |
+
o = o.reshape(batch_size, q_len, self.hidden_size)
|
| 413 |
+
|
| 414 |
+
if self.output_norm is not None:
|
| 415 |
+
o = self.output_norm(o)
|
| 416 |
+
|
| 417 |
+
if self.ogate_proj is not None:
|
| 418 |
+
# ogate = self.ogate act(self.ogate_proj(hidden_states))
|
| 419 |
+
# o = o * ogate
|
| 420 |
+
# ogate = act_gate(self.ogate_proj(hidden_states), o)
|
| 421 |
+
ogate_logit = self.ogate_proj(hidden_states)
|
| 422 |
+
dtype = ogate_logit.dtype
|
| 423 |
+
if self.ogate_act == "silu":
|
| 424 |
+
o = swiglu_linear(ogate_logit, o, self.o_proj.weight.to(dtype), self.o_proj.bias.to(dtype) if self.o_proj.bias is not None else self.o_proj.bias)
|
| 425 |
+
elif self.ogate_act == "sigmoid":
|
| 426 |
+
o = glu_linear(ogate_logit, o, self.o_proj.weight.to(dtype), self.o_proj.bias.to(dtype) if self.o_proj.bias is not None else self.o_proj.bias)
|
| 427 |
+
else:
|
| 428 |
+
raise ValueError(f"Unknown ogate act {self.ogate_act}")
|
| 429 |
+
else:
|
| 430 |
+
o = self.o_proj(o)
|
| 431 |
+
|
| 432 |
+
if not output_attentions:
|
| 433 |
+
attentions = None
|
| 434 |
+
else:
|
| 435 |
+
SAVE_HEADS = [0, 1, 2, 3]
|
| 436 |
+
# (B, H, T, T)
|
| 437 |
+
score = q[:, SAVE_HEADS] @ k[:, SAVE_HEADS].mT
|
| 438 |
+
log_lambda = torch.cumsum(log_fgate, dim=-1)
|
| 439 |
+
decay_bias = (log_lambda[:, SAVE_HEADS, :, None] - log_lambda[:, SAVE_HEADS, None, :]).to(torch.bfloat16)
|
| 440 |
+
# normalized_score = torch.softmax(score, dim=-1)
|
| 441 |
+
attentions = (score, decay_bias)
|
| 442 |
+
|
| 443 |
+
return o, attentions, past_key_values
|
| 444 |
+
|
| 445 |
+
def init_shift_state(self, batch_size: int):
|
| 446 |
+
param = next(self.parameters())
|
| 447 |
+
state = dict()
|
| 448 |
+
try:
|
| 449 |
+
dtype = torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled("cuda") else torch.float32
|
| 450 |
+
except TypeError:
|
| 451 |
+
# Support legacy torch version
|
| 452 |
+
dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else torch.float32
|
| 453 |
+
if self.use_k_shift:
|
| 454 |
+
state['key_shift'] = param.new_zeros(batch_size, self.kv_dim, dtype=dtype)
|
| 455 |
+
else:
|
| 456 |
+
state['key_shift'] = None
|
| 457 |
+
if self.use_v_shift:
|
| 458 |
+
state['value_shift'] = param.new_zeros(batch_size, self.kv_dim, dtype=dtype)
|
| 459 |
+
else:
|
| 460 |
+
state['value_shift'] = None
|
| 461 |
+
return state
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
class ForgettingTransformerMLP(nn.Module):
|
| 465 |
+
|
| 466 |
+
def __init__(
|
| 467 |
+
self,
|
| 468 |
+
hidden_size: int,
|
| 469 |
+
hidden_ratio: Optional[float] = None,
|
| 470 |
+
intermediate_size: Optional[int] = None,
|
| 471 |
+
hidden_act: str = 'swish'
|
| 472 |
+
) -> ForgettingTransformerMLP:
|
| 473 |
+
super().__init__()
|
| 474 |
+
|
| 475 |
+
self.hidden_size = hidden_size
|
| 476 |
+
# the final number of params is `hidden_ratio * hidden_size^2`
|
| 477 |
+
# `intermediate_size` is chosen to be a multiple of 256 closest to `2/3 * hidden_size * hidden_ratio`
|
| 478 |
+
if hidden_ratio is None:
|
| 479 |
+
hidden_ratio = 4
|
| 480 |
+
if intermediate_size is None:
|
| 481 |
+
intermediate_size = int(hidden_size * hidden_ratio * 2 / 3)
|
| 482 |
+
intermediate_size = 256 * ((intermediate_size + 256 - 1) // 256)
|
| 483 |
+
self.hidden_ratio = hidden_ratio
|
| 484 |
+
self.intermediate_size = intermediate_size
|
| 485 |
+
|
| 486 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=False)
|
| 487 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 488 |
+
self.act_fn = ACT2FN[hidden_act]
|
| 489 |
+
self.hidden_act = hidden_act
|
| 490 |
+
assert hidden_act in ["swish", "sigmoid"]
|
| 491 |
+
|
| 492 |
+
def forward(self, x):
|
| 493 |
+
y = self.gate_proj(x)
|
| 494 |
+
gate, y = y.chunk(2, -1)
|
| 495 |
+
# TODO: maybe wrap swiglu_linear in custom_fwd/custom_bwd
|
| 496 |
+
if self.hidden_act == "swish":
|
| 497 |
+
return swiglu_linear(
|
| 498 |
+
gate, y,
|
| 499 |
+
self.down_proj.weight.to(y.dtype),
|
| 500 |
+
self.down_proj.bias.to(y.dtype) if self.down_proj.bias is not None else self.down_proj.bias
|
| 501 |
+
)
|
| 502 |
+
elif self.hidden_act == "sigmoid":
|
| 503 |
+
return glu_linear(
|
| 504 |
+
gate, y,
|
| 505 |
+
self.down_proj.weight.to(y.dtype),
|
| 506 |
+
self.down_proj.bias.to(y.dtype) if self.down_proj.bias is not None else self.down_proj.bias
|
| 507 |
+
)
|
| 508 |
+
else:
|
| 509 |
+
raise ValueError()
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
class ForgettingTransformerBlock(nn.Module):
|
| 513 |
+
def __init__(self, config: ForgettingTransformerConfig, layer_idx: int):
|
| 514 |
+
super().__init__()
|
| 515 |
+
self.hidden_size = config.hidden_size
|
| 516 |
+
|
| 517 |
+
self.attn_norm = RMSNorm(hidden_size=config.hidden_size, eps=config.norm_eps)
|
| 518 |
+
self.attn = ForgettingAttentionLayer(
|
| 519 |
+
hidden_size=config.hidden_size,
|
| 520 |
+
num_heads=config.num_heads,
|
| 521 |
+
num_kv_heads=config.num_kv_heads,
|
| 522 |
+
window_size=config.window_size,
|
| 523 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 524 |
+
rope_base=config.rope_base,
|
| 525 |
+
use_rope=config.use_rope,
|
| 526 |
+
use_output_gate=config.use_output_gate,
|
| 527 |
+
ogate_act=config.ogate_act,
|
| 528 |
+
fgate_type=config.fgate_type,
|
| 529 |
+
fgate_bias_init=config.fgate_bias_init,
|
| 530 |
+
decay_time_min=config.decay_time_min,
|
| 531 |
+
decay_time_max=config.decay_time_max,
|
| 532 |
+
use_output_norm = config.use_output_norm,
|
| 533 |
+
norm_eps=config.norm_eps,
|
| 534 |
+
qk_norm=config.qk_norm,
|
| 535 |
+
qk_norm_share_param_across_head=config.qk_norm_share_param_across_head,
|
| 536 |
+
use_k_shift=config.use_k_shift,
|
| 537 |
+
use_v_shift=config.use_v_shift,
|
| 538 |
+
initializer_range=config.initializer_range,
|
| 539 |
+
layer_idx=layer_idx
|
| 540 |
+
)
|
| 541 |
+
self.mlp_norm = RMSNorm(hidden_size=config.hidden_size, eps=config.norm_eps)
|
| 542 |
+
self.mlp = ForgettingTransformerMLP(
|
| 543 |
+
hidden_size=config.hidden_size,
|
| 544 |
+
hidden_ratio=config.hidden_ratio,
|
| 545 |
+
intermediate_size=config.intermediate_size,
|
| 546 |
+
hidden_act=config.hidden_act
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
def forward_attn(
|
| 550 |
+
self,
|
| 551 |
+
hidden_states: torch.Tensor,
|
| 552 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 553 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
| 554 |
+
output_attentions: Optional[bool] = False,
|
| 555 |
+
use_cache: Optional[bool] = False,
|
| 556 |
+
**kwargs,
|
| 557 |
+
):
|
| 558 |
+
# residual handled outside of this
|
| 559 |
+
# residual = hidden_states
|
| 560 |
+
hidden_states = self.attn_norm(hidden_states)
|
| 561 |
+
hidden_states, attentions, past_key_values = self.attn(
|
| 562 |
+
hidden_states=hidden_states,
|
| 563 |
+
attention_mask=attention_mask,
|
| 564 |
+
past_key_values=past_key_values,
|
| 565 |
+
use_cache=use_cache,
|
| 566 |
+
output_attentions=output_attentions
|
| 567 |
+
)
|
| 568 |
+
return hidden_states, attentions, past_key_values
|
| 569 |
+
|
| 570 |
+
def forward_mlp(
|
| 571 |
+
self,
|
| 572 |
+
hidden_states: torch.Tensor,
|
| 573 |
+
residual: torch.Tensor,
|
| 574 |
+
):
|
| 575 |
+
hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
|
| 576 |
+
hidden_states = self.mlp(hidden_states)
|
| 577 |
+
hidden_states = residual + hidden_states
|
| 578 |
+
|
| 579 |
+
return hidden_states
|
| 580 |
+
|
| 581 |
+
def forward(
|
| 582 |
+
self,
|
| 583 |
+
hidden_states: torch.Tensor,
|
| 584 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 585 |
+
past_key_values: Optional[Tuple[torch.Tensor]] = None,
|
| 586 |
+
output_attentions: Optional[bool] = False,
|
| 587 |
+
use_cache: Optional[bool] = False,
|
| 588 |
+
gradient_checkpointing: bool = False
|
| 589 |
+
# **kwargs,
|
| 590 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 591 |
+
|
| 592 |
+
residual = hidden_states
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
if gradient_checkpointing:
|
| 596 |
+
forward_attn = partial(torch.utils.checkpoint.checkpoint, self.forward_attn, use_reentrant=False)
|
| 597 |
+
forward_mlp = partial(torch.utils.checkpoint.checkpoint, self.forward_mlp, use_reentrant=False)
|
| 598 |
+
else:
|
| 599 |
+
forward_attn = self.forward_attn
|
| 600 |
+
forward_mlp = self.forward_mlp
|
| 601 |
+
|
| 602 |
+
hidden_states, attentions, past_key_values = forward_attn(
|
| 603 |
+
hidden_states=hidden_states,
|
| 604 |
+
attention_mask=attention_mask,
|
| 605 |
+
past_key_values=past_key_values,
|
| 606 |
+
use_cache=use_cache,
|
| 607 |
+
output_attentions=output_attentions
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
hidden_states = forward_mlp(
|
| 611 |
+
hidden_states,
|
| 612 |
+
residual,
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
outputs = (hidden_states,)
|
| 616 |
+
|
| 617 |
+
if output_attentions:
|
| 618 |
+
outputs += (attentions,)
|
| 619 |
+
|
| 620 |
+
if use_cache:
|
| 621 |
+
outputs += (past_key_values,)
|
| 622 |
+
|
| 623 |
+
return outputs
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
class ForgettingTransformerPreTrainedModel(PreTrainedModel):
|
| 628 |
+
|
| 629 |
+
config_class = ForgettingTransformerConfig
|
| 630 |
+
supports_gradient_checkpointing = True
|
| 631 |
+
_no_split_modules = ['ForgettingTransformerBlock']
|
| 632 |
+
|
| 633 |
+
def __init__(self, *inputs, **kwargs):
|
| 634 |
+
super().__init__(*inputs, **kwargs)
|
| 635 |
+
|
| 636 |
+
def _init_weights(
|
| 637 |
+
self,
|
| 638 |
+
module: nn.Module,
|
| 639 |
+
):
|
| 640 |
+
# if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 641 |
+
if isinstance(module, (nn.Linear)):
|
| 642 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 643 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 644 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 645 |
+
if module.bias is not None:
|
| 646 |
+
nn.init.zeros_(module.bias)
|
| 647 |
+
elif isinstance(module, nn.Embedding):
|
| 648 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 649 |
+
if module.padding_idx is not None:
|
| 650 |
+
module.weight.data[module.padding_idx].zero_()
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class ForgettingTransformerModel(ForgettingTransformerPreTrainedModel):
|
| 654 |
+
|
| 655 |
+
def __init__(self, config: ForgettingTransformerConfig):
|
| 656 |
+
super().__init__(config)
|
| 657 |
+
self.padding_idx = config.pad_token_id
|
| 658 |
+
self.vocab_size = config.vocab_size
|
| 659 |
+
|
| 660 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 661 |
+
self.layers = nn.ModuleList([ForgettingTransformerBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 662 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
|
| 663 |
+
|
| 664 |
+
self.gradient_checkpointing = False
|
| 665 |
+
|
| 666 |
+
self.post_init()
|
| 667 |
+
|
| 668 |
+
def get_input_embeddings(self):
|
| 669 |
+
return self.embeddings
|
| 670 |
+
|
| 671 |
+
def set_input_embeddings(self, value):
|
| 672 |
+
self.embeddings = value
|
| 673 |
+
|
| 674 |
+
def forward(
|
| 675 |
+
self,
|
| 676 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 677 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 678 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 679 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 680 |
+
use_cache: Optional[bool] = None,
|
| 681 |
+
output_attentions: Optional[bool] = None,
|
| 682 |
+
output_hidden_states: Optional[bool] = None,
|
| 683 |
+
return_dict: Optional[bool] = None
|
| 684 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 685 |
+
# if output_attentions:
|
| 686 |
+
# warnings.warn(
|
| 687 |
+
# "`ForgettingTransformerModel` does not support output attention weights now, so `output_attentions` is set to `False`."
|
| 688 |
+
# )
|
| 689 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 690 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 691 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 692 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 693 |
+
|
| 694 |
+
# retrieve input_ids and inputs_embeds
|
| 695 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 696 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 697 |
+
elif input_ids is None and inputs_embeds is None:
|
| 698 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 699 |
+
|
| 700 |
+
if use_cache:
|
| 701 |
+
# use_legacy_cache = not isinstance(past_key_values, Cache)
|
| 702 |
+
# if use_legacy_cache:
|
| 703 |
+
# past_key_values = FgateDynamicCache.from_legacy_cache(past_key_values)
|
| 704 |
+
if past_key_values is None:
|
| 705 |
+
past_key_values = FgateDynamicCache()
|
| 706 |
+
for layer_idx, layer in enumerate(self.layers):
|
| 707 |
+
shift_state = layer.attn.init_shift_state(
|
| 708 |
+
batch_size=input_ids.size(0),
|
| 709 |
+
)
|
| 710 |
+
past_key_values.update_shift_cache(
|
| 711 |
+
key_shift_state=shift_state["key_shift"],
|
| 712 |
+
value_shift_state=shift_state["value_shift"],
|
| 713 |
+
layer_idx=layer_idx
|
| 714 |
+
)
|
| 715 |
+
else:
|
| 716 |
+
assert isinstance(past_key_values, FgateDynamicCache)
|
| 717 |
+
|
| 718 |
+
if inputs_embeds is None:
|
| 719 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 720 |
+
|
| 721 |
+
# embed positions
|
| 722 |
+
hidden_states = inputs_embeds
|
| 723 |
+
|
| 724 |
+
if self.gradient_checkpointing and self.training:
|
| 725 |
+
if use_cache:
|
| 726 |
+
logger.warning_once(
|
| 727 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 728 |
+
)
|
| 729 |
+
use_cache = False
|
| 730 |
+
|
| 731 |
+
all_hidden_states = () if output_hidden_states else None
|
| 732 |
+
all_attns = {} if output_attentions else None
|
| 733 |
+
next_decoder_cache = None
|
| 734 |
+
|
| 735 |
+
for layer_id, layer in enumerate(self.layers):
|
| 736 |
+
if output_hidden_states:
|
| 737 |
+
all_hidden_states += (hidden_states,)
|
| 738 |
+
|
| 739 |
+
layer_outputs = layer(
|
| 740 |
+
hidden_states,
|
| 741 |
+
attention_mask=attention_mask,
|
| 742 |
+
past_key_values=past_key_values,
|
| 743 |
+
output_attentions=output_attentions,
|
| 744 |
+
use_cache=use_cache,
|
| 745 |
+
gradient_checkpointing=self.gradient_checkpointing and self.training
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
hidden_states = layer_outputs[0]
|
| 749 |
+
|
| 750 |
+
if use_cache:
|
| 751 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 752 |
+
|
| 753 |
+
if output_attentions:
|
| 754 |
+
OUTPUT_ATTN_LAYERS = [0, 7, 15, 23]
|
| 755 |
+
if layer_id in OUTPUT_ATTN_LAYERS:
|
| 756 |
+
# all_attns += (layer_outputs[1],)
|
| 757 |
+
all_attns[layer_id] = layer_outputs[1]
|
| 758 |
+
|
| 759 |
+
hidden_states = self.norm(hidden_states)
|
| 760 |
+
|
| 761 |
+
# add hidden states from the last decoder layer
|
| 762 |
+
if output_hidden_states:
|
| 763 |
+
all_hidden_states += (hidden_states,)
|
| 764 |
+
|
| 765 |
+
next_cache = None
|
| 766 |
+
if use_cache:
|
| 767 |
+
# next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
| 768 |
+
next_cache = next_decoder_cache
|
| 769 |
+
if not return_dict:
|
| 770 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attns] if v is not None)
|
| 771 |
+
|
| 772 |
+
return BaseModelOutputWithPast(
|
| 773 |
+
last_hidden_state=hidden_states,
|
| 774 |
+
past_key_values=next_cache,
|
| 775 |
+
hidden_states=all_hidden_states,
|
| 776 |
+
attentions=all_attns
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
class ForgettingTransformerForCausalLM(ForgettingTransformerPreTrainedModel):
|
| 781 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 782 |
+
|
| 783 |
+
def __init__(self, config):
|
| 784 |
+
super().__init__(config)
|
| 785 |
+
self.model = ForgettingTransformerModel(config)
|
| 786 |
+
self.vocab_size = config.vocab_size
|
| 787 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 788 |
+
|
| 789 |
+
# Initialize weights and apply final processing
|
| 790 |
+
self.post_init()
|
| 791 |
+
|
| 792 |
+
def get_input_embeddings(self):
|
| 793 |
+
return self.model.embeddings
|
| 794 |
+
|
| 795 |
+
def set_input_embeddings(self, value):
|
| 796 |
+
self.model.embeddings = value
|
| 797 |
+
|
| 798 |
+
def get_output_embeddings(self):
|
| 799 |
+
return self.lm_head
|
| 800 |
+
|
| 801 |
+
def set_output_embeddings(self, new_embeddings):
|
| 802 |
+
self.lm_head = new_embeddings
|
| 803 |
+
|
| 804 |
+
def set_decoder(self, decoder):
|
| 805 |
+
self.model = decoder
|
| 806 |
+
|
| 807 |
+
def get_decoder(self):
|
| 808 |
+
return self.model
|
| 809 |
+
|
| 810 |
+
def prepare_inputs_for_generation(
|
| 811 |
+
self,
|
| 812 |
+
input_ids: torch.LongTensor = None,
|
| 813 |
+
past_key_values: Optional[torch.Tensor] = None,
|
| 814 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 815 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 816 |
+
**kwargs
|
| 817 |
+
):
|
| 818 |
+
# only last token for `inputs_ids` if the `past_key_values` is passed along.
|
| 819 |
+
if past_key_values is not None:
|
| 820 |
+
input_ids = input_ids[:, -1:]
|
| 821 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 822 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 823 |
+
model_inputs = {'inputs_embeds': inputs_embeds}
|
| 824 |
+
else:
|
| 825 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
| 826 |
+
# recompiles graphs as the stride of the inputs is a guard.
|
| 827 |
+
# Ref: https://github.com/huggingface/transformers/pull/29114
|
| 828 |
+
# TODO: use `next_tokens` directly instead.
|
| 829 |
+
model_inputs = {'input_ids': input_ids.contiguous()}
|
| 830 |
+
|
| 831 |
+
model_inputs.update({
|
| 832 |
+
'past_key_values': past_key_values,
|
| 833 |
+
'use_cache': kwargs.get('use_cache'),
|
| 834 |
+
'attention_mask': attention_mask,
|
| 835 |
+
})
|
| 836 |
+
return model_inputs
|
| 837 |
+
|
| 838 |
+
def forward(
|
| 839 |
+
self,
|
| 840 |
+
input_ids: torch.LongTensor = None,
|
| 841 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 842 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 843 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 844 |
+
labels: Optional[torch.LongTensor] = None,
|
| 845 |
+
use_cache: Optional[bool] = None,
|
| 846 |
+
output_attentions: Optional[bool] = None,
|
| 847 |
+
output_hidden_states: Optional[bool] = None,
|
| 848 |
+
return_dict: Optional[bool] = None,
|
| 849 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 850 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 851 |
+
output_hidden_states = (
|
| 852 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 853 |
+
)
|
| 854 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 855 |
+
|
| 856 |
+
outputs = self.model(
|
| 857 |
+
input_ids=input_ids,
|
| 858 |
+
attention_mask=attention_mask,
|
| 859 |
+
past_key_values=past_key_values,
|
| 860 |
+
inputs_embeds=inputs_embeds,
|
| 861 |
+
use_cache=use_cache,
|
| 862 |
+
output_attentions=output_attentions,
|
| 863 |
+
output_hidden_states=output_hidden_states,
|
| 864 |
+
return_dict=return_dict
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
+
hidden_states = outputs[0]
|
| 868 |
+
|
| 869 |
+
loss = None
|
| 870 |
+
if labels is not None:
|
| 871 |
+
if self.config.fuse_cross_entropy:
|
| 872 |
+
loss_fct = FusedCrossEntropyLoss(inplace_backward=True, reduction='none')
|
| 873 |
+
else:
|
| 874 |
+
loss_fct = nn.CrossEntropyLoss(reduction='none')
|
| 875 |
+
logits = self.lm_head(hidden_states)
|
| 876 |
+
# Enable model parallelism
|
| 877 |
+
labels = labels.to(logits.device)
|
| 878 |
+
# labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], loss_fct.ignore_index)), 1)
|
| 879 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 880 |
+
loss = loss.view(*labels.size())
|
| 881 |
+
del logits
|
| 882 |
+
logits = None
|
| 883 |
+
else:
|
| 884 |
+
logits = self.lm_head(hidden_states)
|
| 885 |
+
|
| 886 |
+
if not return_dict:
|
| 887 |
+
raise NotImplementedError
|
| 888 |
+
output = (logits,) + outputs[1:]
|
| 889 |
+
return (loss,) + output if loss is not None else output
|
| 890 |
+
|
| 891 |
+
return CausalLMOutputWithPast(
|
| 892 |
+
loss=loss,
|
| 893 |
+
logits=logits,
|
| 894 |
+
past_key_values=outputs.past_key_values,
|
| 895 |
+
hidden_states=outputs.hidden_states,
|
| 896 |
+
attentions=outputs.attentions,
|
| 897 |
+
)
|
token_shift.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
import triton
|
| 4 |
+
import triton.language as tl
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
def maybe_contiguous(x):
|
| 8 |
+
# only when the inner most dimension is contiguous can LDGSTS be used
|
| 9 |
+
# so inner-dimension contiguity is enforced.
|
| 10 |
+
return x.contiguous() if x.stride(-1) != 1 else x
|
| 11 |
+
|
| 12 |
+
@triton.jit
|
| 13 |
+
def shift_fwd_kernel(
|
| 14 |
+
X_PTR,
|
| 15 |
+
PREV_WEIGHT_PTR,
|
| 16 |
+
CURR_WEIGHT_PTR,
|
| 17 |
+
OUT_PTR,
|
| 18 |
+
|
| 19 |
+
stride_x_b, stride_x_t, stride_x_h, stride_x_d,
|
| 20 |
+
stride_weight_b, stride_weight_t, stride_weight_h,
|
| 21 |
+
T: tl.constexpr, D: tl.constexpr,
|
| 22 |
+
BLOCK_T: tl.constexpr,
|
| 23 |
+
):
|
| 24 |
+
"""
|
| 25 |
+
everything is (B, T, D)
|
| 26 |
+
"""
|
| 27 |
+
b_offset = tl.program_id(axis=0).to(tl.int64)
|
| 28 |
+
t_offset = tl.program_id(axis=1).to(tl.int64) * BLOCK_T
|
| 29 |
+
h_offset = tl.program_id(axis=2).to(tl.int64)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
x_ptr_offset = b_offset * stride_x_b + t_offset * stride_x_t + h_offset * stride_x_h
|
| 33 |
+
X_PTR += x_ptr_offset
|
| 34 |
+
OUT_PTR += x_ptr_offset
|
| 35 |
+
|
| 36 |
+
weight_ptr_offset = b_offset * stride_weight_b + t_offset * stride_weight_t + h_offset * stride_weight_h
|
| 37 |
+
CURR_WEIGHT_PTR += weight_ptr_offset
|
| 38 |
+
PREV_WEIGHT_PTR += weight_ptr_offset
|
| 39 |
+
|
| 40 |
+
x_ptr = X_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_x_t + tl.arange(0, D)[None, :] * stride_x_d
|
| 41 |
+
t_offset_block = t_offset + tl.arange(0, BLOCK_T)[:, None]
|
| 42 |
+
x_mask = t_offset_block < T
|
| 43 |
+
|
| 44 |
+
# Yeah this is correct
|
| 45 |
+
x_prev_ptr = x_ptr - stride_x_t
|
| 46 |
+
t_prev_offset_block = t_offset_block - 1
|
| 47 |
+
x_prev_mask = ((t_prev_offset_block) < T) & (t_prev_offset_block >= 0)
|
| 48 |
+
|
| 49 |
+
curr_weight_ptr = CURR_WEIGHT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_weight_t
|
| 50 |
+
prev_weight_ptr = PREV_WEIGHT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_weight_t
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
x = tl.load(x_ptr, mask=x_mask, other=0.0)
|
| 54 |
+
x_prev = tl.load(x_prev_ptr, mask=x_prev_mask, other=0.0)
|
| 55 |
+
curr_weight = tl.load(curr_weight_ptr, mask=x_mask, other=0.0)
|
| 56 |
+
prev_weight = tl.load(prev_weight_ptr, mask=x_mask, other=0.0)
|
| 57 |
+
|
| 58 |
+
result = x * curr_weight.to(tl.float32) + x_prev * prev_weight.to(tl.float32)
|
| 59 |
+
result = result.to(x.dtype)
|
| 60 |
+
|
| 61 |
+
out_ptr = OUT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_x_t + tl.arange(0, D)[None, :] * stride_x_d
|
| 62 |
+
tl.store(out_ptr, result, mask=x_mask)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@triton.jit
|
| 66 |
+
def shift_bwd_kernel(
|
| 67 |
+
X_PTR,
|
| 68 |
+
PREV_WEIGHT_PTR,
|
| 69 |
+
CURR_WEIGHT_PTR,
|
| 70 |
+
|
| 71 |
+
DOUT_PTR,
|
| 72 |
+
DX_PTR,
|
| 73 |
+
DPREV_WEIGHT_PTR,
|
| 74 |
+
DCURR_WEIGHT_PTR,
|
| 75 |
+
|
| 76 |
+
stride_x_b, stride_x_t, stride_x_h, stride_x_d,
|
| 77 |
+
stride_weight_b, stride_weight_t, stride_weight_h,
|
| 78 |
+
T: tl.constexpr, D: tl.constexpr,
|
| 79 |
+
BLOCK_T: tl.constexpr,
|
| 80 |
+
):
|
| 81 |
+
"""
|
| 82 |
+
everything is (B, T, D)
|
| 83 |
+
"""
|
| 84 |
+
b_offset = tl.program_id(axis=0).to(tl.int64)
|
| 85 |
+
t_offset = tl.program_id(axis=1).to(tl.int64) * BLOCK_T
|
| 86 |
+
h_offset = tl.program_id(axis=2).to(tl.int64)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
x_ptr_offset = b_offset * stride_x_b + t_offset * stride_x_t + h_offset * stride_x_h
|
| 90 |
+
X_PTR += x_ptr_offset
|
| 91 |
+
DX_PTR += x_ptr_offset
|
| 92 |
+
DOUT_PTR += x_ptr_offset
|
| 93 |
+
|
| 94 |
+
weight_ptr_offset = b_offset * stride_weight_b + t_offset * stride_weight_t + h_offset * stride_weight_h
|
| 95 |
+
CURR_WEIGHT_PTR += weight_ptr_offset
|
| 96 |
+
PREV_WEIGHT_PTR += weight_ptr_offset
|
| 97 |
+
DCURR_WEIGHT_PTR += weight_ptr_offset
|
| 98 |
+
DPREV_WEIGHT_PTR += weight_ptr_offset
|
| 99 |
+
|
| 100 |
+
x_ptr = X_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_x_t + tl.arange(0, D)[None, :] * stride_x_d
|
| 101 |
+
t_offset_block = t_offset + tl.arange(0, BLOCK_T)[:, None]
|
| 102 |
+
x_mask = t_offset_block < T
|
| 103 |
+
|
| 104 |
+
dout_ptr = DOUT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_x_t + tl.arange(0, D)[None, :] * stride_x_d
|
| 105 |
+
|
| 106 |
+
# Yeah this is correct
|
| 107 |
+
dout_next_ptr = dout_ptr + stride_x_t
|
| 108 |
+
t_next_offset_block = t_offset_block + 1
|
| 109 |
+
x_next_mask = (t_next_offset_block) < T
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# Yeah this is correct
|
| 113 |
+
x_prev_ptr = x_ptr - stride_x_t
|
| 114 |
+
t_prev_offset_block = t_offset_block - 1
|
| 115 |
+
x_prev_mask = ((t_prev_offset_block) < T) & (t_prev_offset_block >= 0)
|
| 116 |
+
|
| 117 |
+
curr_weight_ptr = CURR_WEIGHT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_weight_t
|
| 118 |
+
prev_weight_ptr = PREV_WEIGHT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_weight_t
|
| 119 |
+
next_prev_weight_ptr = prev_weight_ptr + stride_weight_t
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
x = tl.load(x_ptr, mask=x_mask, other=0.0)
|
| 123 |
+
x_prev = tl.load(x_prev_ptr, mask=x_prev_mask, other=0.0)
|
| 124 |
+
dout = tl.load(dout_ptr, mask=x_mask, other=0.0)
|
| 125 |
+
dout_next= tl.load(dout_next_ptr, mask=x_next_mask, other=0.0)
|
| 126 |
+
|
| 127 |
+
curr_weight = tl.load(curr_weight_ptr, mask=x_mask, other=0.0)
|
| 128 |
+
next_prev_weight = tl.load(next_prev_weight_ptr, mask=x_next_mask, other=0.0)
|
| 129 |
+
|
| 130 |
+
dx = dout * curr_weight.to(tl.float32) + dout_next * next_prev_weight.to(tl.float32)
|
| 131 |
+
dx = dx.to(x.dtype)
|
| 132 |
+
|
| 133 |
+
dcurr_weight = tl.sum(dout.to(tl.float32) * x, axis=1, keep_dims=True)
|
| 134 |
+
dprev_weight = tl.sum(dout.to(tl.float32) * x_prev, axis=1, keep_dims=True)
|
| 135 |
+
|
| 136 |
+
dx_ptr = DX_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_x_t + tl.arange(0, D)[None, :] * stride_x_d
|
| 137 |
+
tl.store(dx_ptr, dx, mask=x_mask)
|
| 138 |
+
dcurr_weight_ptr = DCURR_WEIGHT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_weight_t
|
| 139 |
+
tl.store(dcurr_weight_ptr, dcurr_weight, mask=x_mask)
|
| 140 |
+
dprev_weight_ptr = DPREV_WEIGHT_PTR + tl.arange(0, BLOCK_T)[:, None] * stride_weight_t
|
| 141 |
+
tl.store(dprev_weight_ptr, dprev_weight, mask=x_mask)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class TokenShift(torch.autograd.Function):
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def forward(ctx, x: torch.Tensor, prev_weight: torch.Tensor, curr_weight: torch.Tensor):
|
| 149 |
+
|
| 150 |
+
B, T, H, D = x.size()
|
| 151 |
+
assert D in {16, 32, 64, 128}
|
| 152 |
+
assert prev_weight.size() == curr_weight.size() == (B, T, H)
|
| 153 |
+
assert prev_weight.stride() == curr_weight.stride()
|
| 154 |
+
x = maybe_contiguous(x)
|
| 155 |
+
out = torch.empty_like(x)
|
| 156 |
+
|
| 157 |
+
BLOCK_T = triton.next_power_of_2(min(64, T))
|
| 158 |
+
|
| 159 |
+
grid = lambda meta: (B, triton.cdiv(T, meta["BLOCK_T"]), H)
|
| 160 |
+
# NOTE:
|
| 161 |
+
# - Each torch.tensor object is implicitly converted into a pointer to its first element.
|
| 162 |
+
# - `triton.jit`'ed functions can be indexed with a launch grid to obtain a callable GPU kernel.
|
| 163 |
+
# - Don't forget to pass meta-parameters as keywords arguments.
|
| 164 |
+
shift_fwd_kernel[grid](
|
| 165 |
+
x,
|
| 166 |
+
prev_weight,
|
| 167 |
+
curr_weight,
|
| 168 |
+
out,
|
| 169 |
+
*x.stride(),
|
| 170 |
+
*curr_weight.stride(),
|
| 171 |
+
T=T, D=D,
|
| 172 |
+
BLOCK_T=BLOCK_T,
|
| 173 |
+
)
|
| 174 |
+
ctx.save_for_backward(x, prev_weight, curr_weight)
|
| 175 |
+
# We return a handle to z but, since `torch.cuda.synchronize()` hasn't been called, the kernel is still
|
| 176 |
+
# running asynchronously at this point.
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def backward(ctx, dout: torch.Tensor):
|
| 181 |
+
|
| 182 |
+
x, prev_weight, curr_weight = ctx.saved_tensors
|
| 183 |
+
B, T, H, D = x.size()
|
| 184 |
+
assert D in {16, 32, 64, 128}
|
| 185 |
+
assert prev_weight.size() == curr_weight.size() == (B, T, H)
|
| 186 |
+
assert prev_weight.stride() == curr_weight.stride()
|
| 187 |
+
x = maybe_contiguous(x)
|
| 188 |
+
assert dout.stride() == x.stride()
|
| 189 |
+
dx = torch.empty_like(x)
|
| 190 |
+
dcurr_weight = torch.empty_like(curr_weight)
|
| 191 |
+
dprev_weight = torch.empty_like(prev_weight)
|
| 192 |
+
|
| 193 |
+
BLOCK_T = triton.next_power_of_2(min(64, T))
|
| 194 |
+
|
| 195 |
+
grid = lambda meta: (B, triton.cdiv(T, meta["BLOCK_T"]), H)
|
| 196 |
+
# NOTE:
|
| 197 |
+
# - Each torch.tensor object is implicitly converted into a pointer to its first element.
|
| 198 |
+
# - `triton.jit`'ed functions can be indexed with a launch grid to obtain a callable GPU kernel.
|
| 199 |
+
# - Don't forget to pass meta-parameters as keywords arguments.
|
| 200 |
+
shift_bwd_kernel[grid](
|
| 201 |
+
x,
|
| 202 |
+
prev_weight,
|
| 203 |
+
curr_weight,
|
| 204 |
+
dout,
|
| 205 |
+
dx,
|
| 206 |
+
dprev_weight,
|
| 207 |
+
dcurr_weight,
|
| 208 |
+
*x.stride(),
|
| 209 |
+
*curr_weight.stride(),
|
| 210 |
+
T=T,
|
| 211 |
+
D=D,
|
| 212 |
+
BLOCK_T=BLOCK_T,
|
| 213 |
+
)
|
| 214 |
+
# We return a handle to z but, since `torch.cuda.synchronize()` hasn't been called, the kernel is still
|
| 215 |
+
# running asynchronously at this point.
|
| 216 |
+
return dx, dprev_weight, dcurr_weight
|
| 217 |
+
|
| 218 |
+
def token_shift(x, prev_weight, curr_weight):
|
| 219 |
+
return TokenShift.apply(x, prev_weight, curr_weight)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@pytest.mark.parametrize("B, T, H, D", [(4, 2048, 12, 128)])
|
| 224 |
+
def test_op(B, T, H, D, dtype=torch.float32):
|
| 225 |
+
torch.manual_seed(24)
|
| 226 |
+
B = 4
|
| 227 |
+
T = 2088
|
| 228 |
+
H = 12
|
| 229 |
+
D = 128
|
| 230 |
+
# x = torch.rand(size, device='cuda')
|
| 231 |
+
x = torch.randn(B, T, H, D, device="cuda", dtype=dtype, requires_grad=True)
|
| 232 |
+
dout = torch.randn(B, T, H, D, device="cuda", dtype=dtype)
|
| 233 |
+
curr_weight = torch.rand(B, T, H, device="cuda", requires_grad=True)
|
| 234 |
+
|
| 235 |
+
prev_weight = 1.0 - curr_weight
|
| 236 |
+
x_prev = torch.roll(x, shifts=1, dims=1)
|
| 237 |
+
x_prev[:, 0, :, :] = 0.0
|
| 238 |
+
ref_out = (x_prev * prev_weight[..., None] + x * curr_weight[..., None]).to(dtype)
|
| 239 |
+
|
| 240 |
+
ref_out.backward(dout)
|
| 241 |
+
ref_dx, x.grad = x.grad.clone(), None
|
| 242 |
+
ref_dcurr_weight, curr_weight.grad = curr_weight.grad.clone(), None
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
prev_weight = 1.0 - curr_weight
|
| 246 |
+
# out_torch = x if x.sum() > 0.0 else y
|
| 247 |
+
|
| 248 |
+
tri_out = token_shift(x, prev_weight, curr_weight)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
tri_out.backward(dout)
|
| 252 |
+
tri_dx, x.grad = x.grad.clone(), None
|
| 253 |
+
tri_dcurr_weight, curr_weight.grad = curr_weight.grad.clone(), None
|
| 254 |
+
|
| 255 |
+
# out_torch = x if x.sum() > 0.0 else y
|
| 256 |
+
|
| 257 |
+
# import pdb; pdb.set_trace()
|
| 258 |
+
|
| 259 |
+
assert torch.allclose(ref_out, tri_out, atol=1e-2, rtol=0), (ref_out - tri_out).abs().max()
|
| 260 |
+
assert torch.allclose(ref_dx, tri_dx, atol=1e-2, rtol=0), (ref_dx - tri_dx).abs().max()
|
| 261 |
+
assert torch.allclose(ref_dcurr_weight, tri_dcurr_weight, atol=1e-2, rtol=0), (ref_dcurr_weight - tri_dcurr_weight).abs().max()
|
| 262 |
+
|
| 263 |
+
if __name__ == "__main__":
|
| 264 |
+
torch.manual_seed(0)
|
| 265 |
+
B = 4
|
| 266 |
+
T = 2088
|
| 267 |
+
H = 12
|
| 268 |
+
D = 128
|
| 269 |
+
# x = torch.rand(size, device='cuda')
|
| 270 |
+
x = torch.randn(B, T, H, D, device="cuda")
|
| 271 |
+
dout = torch.randn(B, T, H, D, device="cuda")
|
| 272 |
+
curr_weight = torch.rand(B, T, H, device="cuda")
|
| 273 |
+
prev_weight = 1.0 - curr_weight
|
| 274 |
+
# out_torch = x if x.sum() > 0.0 else y
|
| 275 |
+
result = shift_fwd(x, prev_weight, curr_weight)
|
| 276 |
+
print(result[0, :, 0, 0])
|
| 277 |
+
import ipdb; ipdb.set_trace()
|
| 278 |
+
# # for mode in ["fwd", "bwd"]:
|
| 279 |
+
# configs.append(
|
| 280 |
+
# triton.testing.Benchmark(
|
| 281 |
+
# x_names=["SIZE"],
|
| 282 |
+
# # x_vals=[2**i for i in range(10, 15)],
|
| 283 |
+
# x_vals=[98432],
|
| 284 |
+
# line_arg="provider",
|
| 285 |
+
# # line_vals=["triton-fp16", "flag"] + (["flash"] if HAS_FLASH else []),
|
| 286 |
+
# # line_names=["Triton [FP16]", "Flag"] + (["Flash-2"] if HAS_FLASH else []),
|
| 287 |
+
# line_vals=["debug"],
|
| 288 |
+
# line_names=["Debug"],
|
| 289 |
+
# styles=[("red", "-")],
|
| 290 |
+
# ylabel="ms",
|
| 291 |
+
# plot_name="hi",
|
| 292 |
+
# args={},
|
| 293 |
+
# )
|
| 294 |
+
# )
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# @triton.testing.perf_report(configs)
|
| 298 |
+
# def bench_flash_attention(SIZE, provider, device="cuda"):
|
| 299 |
+
# warmup = 25
|
| 300 |
+
# rep = 100
|
| 301 |
+
# torch.manual_seed(0)
|
| 302 |
+
# size = 98432
|
| 303 |
+
# # x = torch.rand(size, device='cuda')
|
| 304 |
+
# x = torch.ones(size, device="cuda")
|
| 305 |
+
# y = torch.rand(size, device="cuda")
|
| 306 |
+
# # out_torch = x if x.sum() > 0.0 else y
|
| 307 |
+
# fn = lambda: add(x, y)
|
| 308 |
+
# ms = triton.testing.do_bench(fn, warmup=warmup, rep=rep)
|
| 309 |
+
# return ms
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# if __name__ == "__main__":
|
| 313 |
+
# # only works on post-Ampere GPUs right now
|
| 314 |
+
# bench_flash_attention.run(save_path=".", print_data=True)
|