Views
No views yet
SQuatCache class. It requires passing an additional query_states input to .update(). To support this, you can monkey patch the LlamaAttention.forward method—see the example usage below.meta-llama/Llama-3.1-8B-Instructtransformer LLM/VLM trained for causal language modeling.backend (str, optional): quantization backend, default is quantonbits (int, optional): number of bits for quantization, default is 2quant_group_size (int, optional): quantization group size, default is 64residual_length (int, optional): residual length, default is 32squat_lambda (float, optional): squat lambda, default is 0.001subspace_dim (int, optional): subspace dimension, default is 10shared_svd (bool, optional): if use shared svd, default is True1import torch
2from typing import Callable, Optional, Tuple
3from transformers.cache_utils import Cache
4from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, eager_attention_forward
5from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
6from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
7from transformers.processing_utils import Unpack
8import transformers
9
10from transformers import AutoTokenizer, AutoModelForCausalLM
11
12def llama_attn_forward(
13 self,
14 hidden_states: torch.Tensor,
15 position_embeddings: Tuple[torch.Tensor, torch.Tensor],
16 attention_mask: Optional[torch.Tensor],
17 past_key_value: Optional[Cache] = None,
18 cache_position: Optional[torch.LongTensor] = None,
19 **kwargs: Unpack[FlashAttentionKwargs],
20) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
21
22 input_shape = hidden_states.shape[:-1]
23 hidden_shape = (*input_shape, -1, self.head_dim)
24
25 query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
26 key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
27 value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
28
29 cos, sin = position_embeddings
30 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
31
32 if past_key_value is not None:
33 # sin and cos are specific to RoPE models; cache_position needed for the static cache
34 cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position, "query_states": query_states, "attention_mask": attention_mask}
35 key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
36
37 attention_interface: Callable = eager_attention_forward
38
39 if self.config._attn_implementation != "eager":
40 if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
41 logger.warning_once(
42 "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
43 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
44 )
45 else:
46 attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
47
48 attn_output, attn_weights = attention_interface(
49 self,
50 query_states,
51 key_states,
52 value_states,
53 attention_mask,
54 dropout=0.0 if not self.training else self.attention_dropout,
55 scaling=self.scaling,
56 **kwargs,
57 )
58
59 attn_output = attn_output.reshape(*input_shape, -1).contiguous()
60 attn_output = self.o_proj(attn_output)
61 return attn_output, attn_weights
62
63def replace_llama():
64 transformers.models.llama.modeling_llama.LlamaAttention.forward = llama_attn_forward
65
66replace_llama()
67
68tokenizer = AutoTokenizer.from_pretrained('meta-llama/Llama-3.1-8B-Instruct')
69model = AutoModelForCausalLM.from_pretrained('meta-llama/Llama-3.1-8B-Instruct', device_map="auto")
70
71inputs = tokenizer(["I like rock music because"], return_tensors="pt").to(model.device)
72
73gen_out = model.generate(**inputs, custom_generate="ligongh/squat", trust_remote_code=True)
74print(tokenizer.batch_decode(gen_out))