Gausson commited on
Commit
8140d19
·
verified ·
1 Parent(s): 75bb3c9

Upload README.md

Browse files
Files changed (1) hide show
  1. README.md +324 -0
README.md ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## 1. Abstract
2
+ `SepCache` is a simple yet effective, native sparse attention `Cache` class proposed in the [`SepLLM paper - ICML 2025`](https://icml.cc/virtual/2025/poster/45536) , which most closely aligns with the semantic distribution of natural language. In the training phase, `SepLLM` condenses the segment information into the KV of the separator that divides the segment. In the inference phase, the corresponding `SepCache` only needs to store the KVs of initial tokens, separator tokens, and recent tokens for generation.
3
+
4
+ Notably, `SepCache` also delivers strong performance across many tasks in training-free scenarios. Moreover, `SepLLM` (or simply `SepCache`) is the **most suitable baseline method for sparse attention mechanisms and KV compression/management**, as it is the natively sparse attention mechanism that best aligns with the natural semantic distribution of language.
5
+
6
+ See more details and advanced usage in https://github.com/HKUDS/SepLLM
7
+
8
+ ![image](https://hackmd.io/_uploads/r1POJoR4yg.png)
9
+
10
+ ## 2. Usage
11
+
12
+ ### 2.1 Sample Base Model
13
+
14
+ We recommend using models from the **Llama 3 series**. Our example model is based on `meta-llama/Meta-Llama-3-8B-Instruct`, for which we have already prepared a targeted `monkey patch`.
15
+
16
+ For other models, using `SepCache` requires minor modifications to the corresponding `modeling_xxx.py` file or writing a **custom monkey patch**. These changes are **very simple** -- you only need to pass arguments like `input_ids` to the `update` function of `SepCache` when calling it.
17
+
18
+ We will provide a detailed guide later on how to modify your `modeling_xxx.py` file or `monkey patch` file to adapt `SepCache` to any model.
19
+
20
+ ### 2.2 Quick Start
21
+
22
+ #### 2.2.1 Environment Setup
23
+ You need to install `transformers>=4.53`, and we recommend using `lm_eval>=0.4.9` for running evaluations. We suggest managing your Python environment with `conda` for better dependency control.
24
+
25
+ ```bash
26
+ conda create -n sepcache python=3.10
27
+ conda activate sepcache
28
+ pip install transformers==4.53
29
+ pip install lm_eval==0.4.9
30
+ ```
31
+ #### 2.2.2 A Simple Example
32
+ You can use `SepCache` by specifying `custom_generate="transformers-community/sep_cache"` or `custom_generate="Gausson/sep_cache"` when calling the `generate` function. In our demo, we have already prepared sample monkey patching for the `Llama 3 series` models and provided some common parameters for initializing `SepCache`.
33
+
34
+ ```python
35
+ # requires `transformers>=4.53.0`
36
+ from transformers import AutoModelForCausalLM, AutoTokenizer
37
+
38
+ # Preparing model, tokenizer, and model inputs
39
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
40
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto")
41
+
42
+
43
+ messages = [{"role": "user", "content": "Tell me a story about a cat."}]
44
+ text = tokenizer.apply_chat_template(
45
+ messages,
46
+ tokenize=False,
47
+ add_generation_prompt=True,
48
+ enable_thinking=False
49
+ )
50
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
51
+
52
+
53
+ # Using SepCache for generation
54
+ gen_out = model.generate(
55
+ # usual `generate` arguments
56
+ **model_inputs,
57
+ do_sample=False,
58
+ max_new_tokens=100,
59
+ return_dict_in_generate=True,
60
+ monkey_patch_verbose = True, # To see which functions are actually being monkey patched for `SepCache`.
61
+
62
+ # Using SepCache
63
+ custom_generate="transformers-community/sep_cache", ## Alternatively, you can use `Gausson/sep_cache`
64
+ trust_remote_code=True,
65
+
66
+ # SepCache arguments
67
+ init_cache_size = 4,
68
+ sep_cache_size = 128,
69
+ local_size = 256,
70
+ cache_size = 512,
71
+ USE_MAX_SEP_CACHE = True,
72
+ model_type = 'llama'
73
+ )
74
+
75
+ print(tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True))
76
+ assert "sepcache" in str(type(gen_out.past_key_values)).lower()
77
+ ```
78
+
79
+ It is worth noting that you must specify the `separator_token_ids: List[int]` and `PADDING_ID: int` parameters for initializing `SepCache`. In the example above, we did not do this because, for convenience, in the demo above, we specified `model_type = "llama"`, in which case `separator_token_ids` and `PADDING_ID` will be automatically filled.
80
+
81
+ However, when you use a tokenizer for a non-Llama 3 series model, you need to specify the specific values of `separator_token_ids` and `PADDING_ID` based on the tokenizer you are using. For example, the following example is based on the values obtained from a Llama 3 series tokenizer.
82
+ ```python
83
+ # Using SepCache for generation
84
+ gen_out = model.generate(
85
+ # usual `generate` arguments
86
+ **model_inputs,
87
+ do_sample=False,
88
+ max_new_tokens=100,
89
+ return_dict_in_generate=True,
90
+ monkey_patch_verbose = True, # To see which functions are actually being monkey patched for `SepCache`.
91
+
92
+ # Using SepCache
93
+ custom_generate="transformers-community/sep_cache", ## Alternatively, you can use `Gausson/sep_cache`
94
+ trust_remote_code=True,
95
+
96
+ # SepCache arguments
97
+ init_cache_size = 4,
98
+ sep_cache_size = 128,
99
+ local_size = 256,
100
+ cache_size = 512,
101
+ USE_MAX_SEP_CACHE = True,
102
+ separator_token_ids = [128000, 13, 11, 30, 0, 26, 25, 198, 220, 662, 1174, 949, 758, 2652, 551, 720, 256,262],
103
+ PADDING_ID = 128009
104
+ )
105
+ ```
106
+
107
+
108
+ #### 2.2.3 Frequently-Used Parameters
109
+
110
+ Below, we provide explanations and examples for the most commonly used parameters when initializing `SepCache`. These parameters can be passed through the `generate` function.
111
+
112
+ ```
113
+ `SepCache` stores the Key and Value states as lists of tensors, two lists for each layer. The expected shape for each tensor is
114
+ `[batch_size, num_heads, seq_len, head_dim]`.
115
+
116
+ Frequently-Used Parameters:
117
+
118
+ `init_cache_size: Union[int, List]`:
119
+ The maximum number of KVs to be stored for initial tokens.
120
+ In the paper, the hyperparameter `a` is an abbreviated alias for `init_cache_size`.
121
+
122
+ `sep_cache_size: Union[int, List]`:
123
+ The maximum number of KVs to be stored for separator tokens.
124
+ In the paper, the hyperparameter `s` is an abbreviated alias for `sep_cache_size`.
125
+
126
+ `local_size: Union[int, List]`:
127
+ The maximum number of KVs to be stored for local tokens (i.e., sliding window).
128
+ In the paper, the hyperparameter `w` is an abbreviated alias for `local_size`.
129
+
130
+ `cache_size: Union[int, List]`:
131
+ The maximum number of KVs to be stored for all the tokens, i.e., the size for the whole KV cache.
132
+ In the paper, the hyperparameter `c` is an abbreviated alias for `cache_size`.
133
+
134
+ Concerning these four parameters above:
135
+ When a list is passed (its length must be `layer_num`), it represents different values for each layer.
136
+ When an integer is passed, it means the setting is the same for all layers.
137
+
138
+
139
+ `USE_MAX_SEP_CACHE: bool`:
140
+ If True, it means we only keep at most `sep_cache_size` seperators' KVs.
141
+ If the number exceeds this limit, older separators' KVs will be discarded, keeping only the most recent `sep_cache_size` KVs.
142
+ In the paper, the hyperparameter `s` is an abbreviated alias for `sep_cache_size`.
143
+
144
+ `separator_token_ids: List[int]`:
145
+ The token ids of the separator tokens for the current model's tokenizer.
146
+ We have some examples, such as the Llama-3 series models, where setting `model_type='llama'` allows you
147
+ to skip setting `separator_token_ids` and `PADDING_ID` (SepCache will auto-fill them).
148
+
149
+ `PADDING_ID: int`:
150
+ The token id of the padding token. You can just set `PADDING_ID` to the id of "<|endoftext|>" token of the tokenizer for the pretrained model.
151
+ ```
152
+ Important Note:
153
+ - When `cache_size` and `local_size` are set to infinity (i.e., sufficiently large positive integers), and `USE_MAX_SEP_CACHE` is `False`, `SepCache` degenerates into a regular Cache.
154
+ - You must always ensure that `init_cache_size` + `sep_cache_size` + `local_size` + `left_padding_offset` < `cache_size`. Here, `left_padding_offset` denotes the number of padding tokens in the record with the largest left paddings within a runtime batch. `left_padding_offset` can only be determined at runtime.
155
+ - To guarantee the above inequality always holds during runtime, when setting, you can intentionally create a sufficient margin between both sides of the following inequality:
156
+ `init_cache_size` + `sep_cache_size` + `local_size` < `cache_size`, i.e., `a`+`s`+`w`<`c` in the [SepLLM paper - ICML 2025](https://arxiv.org/abs/2412.12094) to leave room for `left_padding_offset`.
157
+
158
+ **More Important Note: In practice, no need to do positional encoding (PE) shifting like [StreamingLLM](https://github.com/mit-han-lab/streaming-llm/) if the actual length does not exceed the pretrained max PE length (which applies to most downstream tasks.) . So, for most basic usages, just set `APPLY_PE_SHIFT=False` (`False` is also the default setting) and `APPLY_PES_INSIDE=False` for initialization.**
159
+
160
+
161
+ #### 2.2.4 Update Function
162
+ After initialization, another key point to note is that when using the `update` function of `SepCache` to update the **keys/values** and the **past token IDs** (which is necessary in SepCache), the current `input_ids` must also be provided.
163
+ ```python
164
+ key_states, value_states = past_key_values.update(
165
+ key_states = key_states,
166
+ value_states = value_states,
167
+ input_ids = input_ids, ## required
168
+ layer_idx = layer_idx,
169
+ PREFILLING_FLAG = q_len > 1, ## `q_len` is the sequence length of the current `query_states`
170
+ )
171
+ ```
172
+
173
+
174
+ #### 2.2.5 Monkey Patch Demo
175
+ To adapt the `update` function of `SepCache` mentioned in [`2.2.4 Update Function`](#224-update-function), i.e., passing the current `input_ids` as a parameter to the `update` function. It is worth noting that during the prefilling stage, the shape of the input_ids tensor is `[batch_size, seq_len]`, while during the decoding stage of auto-regressive models, the shape of the `input_ids` tensor should be `[batch_size, 1]`.
176
+
177
+
178
+ In our `custom_generate/generate.py` file, we provide the `monkey_patching` function, which works by replacing the `forward` function in all the related instances of the `XXXAttention` class (for example, in the Llama 3 series model, it would be `LlamaAttention`) with our customized forward function (specified by the `model_atten_forward` parameter of the `monkey_patching` function).
179
+ ```python
180
+ def monkey_patching(model_obj,
181
+ model_atten_forward , ## The `forward` function used to patch.
182
+ possible_inner_model_names: List[str] = ["model", "transformer", "gpt_neox"] , # In `XXXForCausalLM` class, the possible name of internal attribute for model. e.g., "model", "transformer", "gpt_neox", etc.
183
+ possible_layers_names: List[str] = ["layers", "h" ], # In `XXXModel` class, the possible name of internal attribute for decoder layers, e.g., "layers", "h", etc.
184
+ atten_attr_name_pattern_list: List[str] = ["attention", "self_attn"], # In `XXXDecoderLayer` class, the possible name of internal attribute for self-attention, e.g., "attention", "self_attn", etc.
185
+ atten_attr_name_pattern_exclude: List[str] = ["norm", "layer"], # In `XXXDecoderLayer` class, the impossible name patterns (i.e., the patterns to be excluded) of internal attribute for self-attention module class, e.g., "norm" , etc. Sometimes, there will be some attributes like "post_attention_norm" and we do not want modify the `forward` function of it - we want to modify the `forward` function of `XXXAttention`. So, we need to exclude attribute name patterns like "norm" to accurately find the correct "forward" function to replace.
186
+ verbose = True):
187
+
188
+ """
189
+ This `monkey_patching` function is to
190
+ - find the `forward` function of the `XXXAttention` class.
191
+ - replace all the related `forward` functions of the instances of `XXXAttention` class with `model_atten_forward`.
192
+ """
193
+
194
+ ## To avoid the argument check failure, i.e., let "sepllm_kwargs" pass the check.
195
+ transformers.generation.GenerationMixin._validate_model_kwargs = _validate_model_kwargs
196
+
197
+ ## Get inner model obj
198
+ inner_model_type = PreTrainedModel
199
+ inner_model = find_inner_attribute(model_obj, possible_inner_model_names, inner_model_type)
200
+
201
+ ## Get the decoder layers (`nn.ModuleList`) obj
202
+ layers_type = nn.ModuleList
203
+ model_layers = find_inner_attribute(inner_model, possible_layers_names, layers_type)
204
+
205
+ ## Replace all the related `forward` functions of XXXAttention class's instances.
206
+ for i, decoder_layer in enumerate(model_layers):
207
+ self_attn_module = find_attribute_name(decoder_layer, atten_attr_name_pattern_list, atten_attr_name_pattern_exclude, nn.Module)
208
+ result = monkey_patch_by_class_path(self_attn_module, model_atten_forward)
209
+ if verbose:
210
+ decoder_class_name = get_importable_class_path(decoder_layer)
211
+ print(f"For Layer {i}'s `{decoder_class_name}`: {result}")
212
+
213
+ return model_layers
214
+ ```
215
+
216
+ The `monkey_patching` function primarily does three things:
217
+ - Precisely locate the `forward` function of all instances of the `XXXAttention` class.
218
+ - Replace the `forward` function with the `model_atten_forward` function you provide.
219
+ - Return the corresponding properties of the decoder layers found during the process, typically of type `nn.ModuleList`. This return value (`model_layers`) is only used to determine the number of layers in the current model later on (obtained by `len(model_layers)`).
220
+
221
+ In addition, the `monkey_patching` function replaces `transformers.generation.GenerationMixin._validate_model_kwargs` with our `_validate_model_kwargs` to bypass some parameter checks, as we will provide an additional `sepllm_kwargs` parameter to wrap the `input_ids` for eventual transmission to the `SepCache` `update` function.
222
+
223
+
224
+ **Please ensure that the `monkey_patching` function accurately locates and replaces the `forward` function of the `XXXAttention` class. The current `monkey_patching` is designed for the `Llama 3 series` models. For other models, you need to appropriately modify `monkey_patching` to ensure its correctness of targeting and replacement !** You can monitor the monkey patching process by setting `verbose=True` in the `monkey_patching` function (or, `monkey_patch_verbose = True` for the `generate` function.)
225
+
226
+
227
+ ```python
228
+ def truncate_input_ids_4_autoregression(input_ids, key_states):
229
+ if input_ids.shape[-1] != key_states.shape[-2]:
230
+ assert input_ids.shape[-1] >= key_states.shape[-2]
231
+ truncated_input_ids = input_ids[..., -key_states.shape[-2]: ]
232
+ return truncated_input_ids
233
+ else:
234
+ return input_ids
235
+ ```
236
+ The `truncate_input_ids_4_autoregression` function in the `custom_generate/generate.py` file is used to shape the `input_ids` tensor to `[batch_size, 1]` during decoding.
237
+
238
+ #### 2.2.5 Downstream Task Evaluation
239
+ We recommend using `lm_eval==0.4.9` for downstream task evaluation. You can pass model-related parameters via `--model_args` and generation-related parameters (including those required for initializing `SepCache`) via `--gen_kwargs`. Notably, you typically need to pass a `list` to `separator_token_ids` using a string format like `"id1;id2;id3"` (as shown in the example below).
240
+ ```bash
241
+ lm_eval --model hf \
242
+ --model_args pretrained=meta-llama/Meta-Llama-3-8B-Instruct,attn_implementation=flash_attention_2 \
243
+ --tasks gsm8k_cot \
244
+ --gen_kwargs custom_generate=transformers-community/sep_cache,trust_remote_code=True,monkey_patch_verbose=True,separator_token_ids="128000;13;11;30;0;26;25;198;220;662;1174;949;758;2652;551;720;256;262",PADDING_ID=128009\
245
+ --device cuda:0\
246
+ --batch_size 80 2>&1 | tee log.txt
247
+ ```
248
+ Note: `SepCache` is typically used in combination with `Flash Attention` to maximize generation efficiency.
249
+
250
+ #### 2.2.5 The Detailed Signature of `generate` Function
251
+ Here is the detailed signature of our customized `generate` function for `SepCache` in `custom_generate/generate.py` file:
252
+
253
+ ```python
254
+ def generate(model,
255
+ ## For SepCache
256
+ init_cache_size: Union[int, List] = 4,
257
+ sep_cache_size: Union[int, List] = 128,
258
+ local_size: Union[int, List]=256,
259
+ cache_size: Union[int, List]=512,
260
+ SEP_ACCUMULATION: bool = True,
261
+ USE_MAX_SEP_CACHE: bool = False,
262
+ SEP_PADDING_IN_BATCH: bool = False,
263
+ separator_token_ids: List[int] = None, ## required for initialization if `model_type` is not provided.
264
+ PADDING_ID: int = None, ## required for initialization if `model_type` is not provided.
265
+
266
+ ## For inheritance & initialization states
267
+ past_tok_ids: List[torch.Tensor] = None, ## It saves all the token ids corresponding to the saved KVs for all layers in SepCache.
268
+ key_cache: List[torch.Tensor] = None,
269
+ value_cache: List[torch.Tensor] = None,
270
+
271
+ ## For debugging
272
+ PRINT_KV_RATIO_INSIDE: bool = False,
273
+ print_KV_inside_per_steps: int = 1000,
274
+ _seen_tokens: int = 0,
275
+ _kept_kv_ratio: List[Tuple[int]] = None,
276
+
277
+ ### For positional encoding shifting
278
+ APPLY_PE_SHIFT: bool = False,
279
+ APPLY_PES_INSIDE: bool = False,
280
+ _shifted_position_ids: List[torch.Tensor] = None,
281
+ _rope_unsqueeze_dim: int = 1, ## The unsqueeze_dim when applying RoPE.
282
+ _rope_seq_dim: int=1, ## The seq_len dimension for the `cos` or `sin` tensors.
283
+ pe_scaling_factor:float = 1.0,
284
+ pe_dim:int=128, ## The number of dims for positional encoding. Typically, just set the `head_dim` to this.
285
+ max_position_embeddings: int = 8192,
286
+ base: int=10000, ## The base for RoPE.
287
+
288
+ ## For basic transformer architecture
289
+ k_seq_dim: int=2, ## The dimension for seq_len in key tensors
290
+ v_seq_dim: int=2, ## The dimension for seq_len in value tensors
291
+ layer_num: int = None, ## required for initialization
292
+
293
+ model_type: str = 'llama', ## The model type for running the example. choose from ['llama', 'pythia','falcon'].
294
+ device = None,
295
+
296
+ ## For verbosity of monkey patching
297
+ monkey_patch_verbose: bool = False,
298
+
299
+ **kwargs
300
+ ):
301
+ ...
302
+ ```
303
+
304
+ ### 3. Adaptation for Other Models
305
+
306
+ Adapting `SepCache` to various models is simple - two approaches:
307
+
308
+
309
+ #### 3.1 Method 1 - Monkey Patching
310
+ - Modify the `monkey_patching` function to correctly locate and target the `forward` function of your model's `XXXAttention` class (e.g., `LlamaAttention` for Llame 3).
311
+ - Write your custom `model_atten_forward` function and use `monkey_patching` to replace the `forward` function of all `XXXAttention` class instances. The key modification is passing `input_ids` to `SepCache`'s `update` function.
312
+
313
+ #### 3.2 Method 2 - Direct Code Modification (Recommended for Simplicity)
314
+ Simply edit your `modeling_xxx.py` file to implement:
315
+
316
+ - Initialize `past_key_values` as a `SepCache` instance at the appropriate location (e.g., in `XXXForCausalLM` or `XXXModel` class' `forward` function).
317
+ - Modify the `forward` function of the `XXXAttention` class to pass `input_ids` to `SepCache`'s `update` function.
318
+
319
+ #### 3.3 Important Note
320
+ The shape of `input_ids` is `[batch_size, seq_len]` during prefilling, and `[batch_size, 1]` during generation.
321
+
322
+ ## Other Advanced Usage
323
+
324
+ Please refer to https://github.com/HKUDS/SepLLM, in which there are detailed explanations and examples.