utils_llama.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. import math
  2. from typing import Any, Dict, List, Optional, Tuple, Union
  3. import pdb
  4. import types
  5. import torch
  6. from torch import nn
  7. import torch.utils.checkpoint
  8. import torch.nn.functional as F
  9. from transformers.models.llama.configuration_llama import LlamaConfig
  10. from transformers.models.llama.modeling_llama import (
  11. LlamaAttention,
  12. rotate_half,
  13. apply_rotary_pos_emb,
  14. repeat_kv,
  15. LlamaRotaryEmbedding,
  16. apply_rotary_pos_emb,
  17. LlamaForCausalLM,
  18. )
  19. from cache_utils import Cache, HHCache, StaticCache
  20. from transformers.utils import logging
  21. from transformers.modeling_outputs import BaseModelOutputWithPast
  22. logger = logging.get_logger(__name__)
  23. __all__ = ["H2OLlamaForCausalLM"]
  24. def _make_causal_mask(
  25. bsz: int, tgt_len: int, past_key_values_length: int, dtype: torch.dtype, device: torch.device):
  26. """
  27. Make causal mask used for bi-directional self-attention.
  28. """
  29. mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
  30. mask_cond = torch.arange(mask.size(-1), device=device)
  31. mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
  32. mask = mask.to(dtype)
  33. if past_key_values_length > 0:
  34. mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
  35. return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
  36. def apply_rotary_pos_emb_single(x, cos, sin, position_ids):
  37. # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
  38. cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
  39. sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
  40. cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
  41. sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
  42. x_embed = (x * cos) + (rotate_half(x) * sin)
  43. return x_embed
  44. class H2OKVCache_LayerWise:
  45. def __init__(
  46. self,
  47. hh_size=4,
  48. recent_size=512,
  49. k_seq_dim=2,
  50. v_seq_dim=2,
  51. ):
  52. self.hh_size = hh_size
  53. self.recent_size = recent_size
  54. self.cache_size = hh_size + recent_size
  55. self.k_seq_dim = k_seq_dim
  56. self.v_seq_dim = v_seq_dim
  57. self.hh_score = None
  58. def __call__(self, past_key_values, attn_score_cache):
  59. self._update_hh_score(attn_score_cache)
  60. if past_key_values is None:
  61. return None
  62. seq_len = past_key_values[0].size(self.k_seq_dim)
  63. if seq_len <= self.cache_size:
  64. return past_key_values
  65. # hh-selection
  66. bsz, num_heads, _, head_dim = past_key_values[0].shape
  67. select_hh_scores = self.hh_score[:, :seq_len - self.recent_size]
  68. _, keep_topk = torch.topk(select_hh_scores, self.hh_size, dim=-1)
  69. keep_topk = keep_topk.sort().values
  70. # keep_recent = torch.arange(seq_len - self.recent_size, seq_len).expand(keep_topk.shape[0], 1).to(keep_topk.device)
  71. keep_recent = torch.arange(seq_len - self.recent_size, seq_len, device=keep_topk.device).repeat(keep_topk.shape[0], 1)
  72. keep_idx = torch.cat([keep_topk, keep_recent], dim=-1)
  73. mask = torch.zeros(self.hh_score.shape, dtype=torch.bool).to(past_key_values[0].device)
  74. mask = mask.scatter(-1, keep_idx, 1)
  75. k_hh_recent = past_key_values[0].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  76. v_hh_recent = past_key_values[1].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  77. self.hh_score= self.hh_score[mask].view(num_heads, self.cache_size)
  78. return (k_hh_recent, v_hh_recent)
  79. def evict_for_space(self, past_key_values, num_coming):
  80. if past_key_values is None:
  81. return None
  82. seq_len = past_key_values[0][0].size(self.k_seq_dim)
  83. if seq_len + num_coming <= self.cache_size:
  84. return past_key_values
  85. # hh-selection
  86. bsz, num_heads, _, head_dim = past_key_values[0].shape
  87. select_hh_scores = self.hh_score[:, :seq_len - self.recent_size + num_coming]
  88. _, keep_topk = torch.topk(select_hh_scores, self.hh_size, dim=-1)
  89. keep_topk = keep_topk.sort().values
  90. # keep_recent = torch.arange(seq_len - self.recent_size, seq_len).expand(keep_topk.shape[0], 1).to(keep_topk.device)
  91. keep_recent = torch.arange(seq_len - self.recent_size + num_coming, seq_len, device=keep_topk.device).repeat(keep_topk.shape[0], 1)
  92. keep_idx = torch.cat([keep_topk, keep_recent], dim=-1)
  93. mask = torch.zeros(self.hh_score.shape, dtype=torch.bool).to(past_key_values[0].device)
  94. mask = mask.scatter(-1, keep_idx, 1)
  95. k_hh_recent = past_key_values[0].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  96. v_hh_recent = past_key_values[1].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  97. self.hh_score= self.hh_score[mask].view(num_heads, self.cache_size)
  98. return (k_hh_recent, v_hh_recent)
  99. def _update_hh_score(self, attn_score_cache):
  100. num_new_tokens = attn_score_cache.shape[2]
  101. if self.hh_score is None:
  102. self.hh_score = attn_score_cache.sum(0).sum(1)
  103. else:
  104. attn_score_cache = attn_score_cache.sum(0).sum(1)
  105. attn_score_cache[:, :-num_new_tokens] += self.hh_score
  106. self.hh_score = attn_score_cache
  107. def _clean_scores(self):
  108. self.hh_score = None
  109. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  110. """
  111. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  112. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  113. """
  114. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  115. if n_rep == 1:
  116. return hidden_states
  117. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  118. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  119. class H2OLlamaAttention(nn.Module):
  120. """Multi-headed attention from 'Attention Is All You Need' paper"""
  121. def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
  122. super().__init__()
  123. self.config = config
  124. self.layer_idx = layer_idx
  125. if layer_idx is None:
  126. logger.warning_once(
  127. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  128. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  129. "when creating this class."
  130. )
  131. self.attention_dropout = config.attention_dropout
  132. self.hidden_size = config.hidden_size
  133. self.num_heads = config.num_attention_heads
  134. self.head_dim = self.hidden_size // self.num_heads
  135. self.num_key_value_heads = config.num_key_value_heads
  136. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  137. self.max_position_embeddings = config.max_position_embeddings
  138. self.rope_theta = config.rope_theta
  139. self.is_causal = True
  140. if (self.head_dim * self.num_heads) != self.hidden_size:
  141. raise ValueError(
  142. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  143. f" and `num_heads`: {self.num_heads})."
  144. )
  145. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
  146. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  147. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  148. self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
  149. self._init_rope()
  150. def _init_rope(self):
  151. if self.config.rope_scaling is None:
  152. self.rotary_emb = LlamaRotaryEmbedding(
  153. self.head_dim,
  154. max_position_embeddings=self.max_position_embeddings,
  155. base=self.rope_theta,
  156. )
  157. else:
  158. scaling_type = self.config.rope_scaling["type"]
  159. scaling_factor = self.config.rope_scaling["factor"]
  160. if scaling_type == "linear":
  161. self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
  162. self.head_dim,
  163. max_position_embeddings=self.max_position_embeddings,
  164. scaling_factor=scaling_factor,
  165. base=self.rope_theta,
  166. )
  167. elif scaling_type == "dynamic":
  168. self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
  169. self.head_dim,
  170. max_position_embeddings=self.max_position_embeddings,
  171. scaling_factor=scaling_factor,
  172. base=self.rope_theta,
  173. )
  174. else:
  175. raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
  176. def forward(
  177. self,
  178. hidden_states: torch.Tensor,
  179. attention_mask: Optional[torch.Tensor] = None,
  180. position_ids: Optional[torch.LongTensor] = None,
  181. past_key_value: Optional[Cache] = None,
  182. output_attentions: bool = False,
  183. use_cache: bool = False,
  184. cache_position: Optional[torch.LongTensor] = None,
  185. **kwargs,
  186. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  187. bsz, q_len, _ = hidden_states.size()
  188. if self.config.pretraining_tp > 1:
  189. key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
  190. query_slices = self.q_proj.weight.split(
  191. (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
  192. )
  193. key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
  194. value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
  195. query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
  196. query_states = torch.cat(query_states, dim=-1)
  197. key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
  198. key_states = torch.cat(key_states, dim=-1)
  199. value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
  200. value_states = torch.cat(value_states, dim=-1)
  201. else:
  202. query_states = self.q_proj(hidden_states)
  203. key_states = self.k_proj(hidden_states)
  204. value_states = self.v_proj(hidden_states)
  205. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  206. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  207. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  208. past_key_value = getattr(self, "past_key_value", past_key_value)
  209. cos, sin = self.rotary_emb(value_states, position_ids)
  210. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  211. if past_key_value is not None:
  212. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  213. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  214. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  215. key_states = repeat_kv(key_states, self.num_key_value_groups)
  216. value_states = repeat_kv(value_states, self.num_key_value_groups)
  217. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  218. if attention_mask is not None: # no matter the length, we just slice it
  219. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  220. attn_weights = attn_weights + causal_mask
  221. # upcast attention to fp32
  222. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  223. # Update KV Cache based on Heavy-Hitter Oracle
  224. if past_key_value is not None:
  225. past_key_value.update_slimming(attn_weights, self.num_key_value_groups, self.layer_idx, cache_kwargs)
  226. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  227. attn_output = torch.matmul(attn_weights, value_states)
  228. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  229. raise ValueError(
  230. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  231. f" {attn_output.size()}"
  232. )
  233. attn_output = attn_output.transpose(1, 2).contiguous()
  234. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  235. if self.config.pretraining_tp > 1:
  236. attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
  237. o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
  238. attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
  239. else:
  240. attn_output = self.o_proj(attn_output)
  241. if not output_attentions:
  242. attn_weights = None
  243. print(past_key_value.key_cache[self.layer_idx].shape, past_key_value.accumulated_attention_scores[self.layer_idx].shape)
  244. return attn_output, attn_weights, past_key_value
  245. def enable_h2ocache_forward(
  246. self,
  247. input_ids: torch.LongTensor = None,
  248. attention_mask: Optional[torch.Tensor] = None,
  249. position_ids: Optional[torch.LongTensor] = None,
  250. past_key_values: Optional[List[torch.FloatTensor]] = None,
  251. inputs_embeds: Optional[torch.FloatTensor] = None,
  252. use_cache: Optional[bool] = None,
  253. output_attentions: Optional[bool] = None,
  254. output_hidden_states: Optional[bool] = None,
  255. return_dict: Optional[bool] = None,
  256. cache_position: Optional[torch.LongTensor] = None,
  257. ) -> Union[Tuple, BaseModelOutputWithPast]:
  258. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  259. output_hidden_states = (
  260. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  261. )
  262. use_cache = use_cache if use_cache is not None else self.config.use_cache
  263. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  264. if (input_ids is None) ^ (inputs_embeds is not None):
  265. raise ValueError(
  266. "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
  267. )
  268. if self.gradient_checkpointing and self.training and use_cache:
  269. logger.warning_once(
  270. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  271. )
  272. use_cache = False
  273. if inputs_embeds is None:
  274. inputs_embeds = self.embed_tokens(input_ids)
  275. past_seen_tokens = 0
  276. if use_cache: # kept for BC (cache positions)
  277. if not isinstance(past_key_values, StaticCache):
  278. past_key_values = HHCache.from_legacy_cache(self.num_window_length, self.num_heavy_hitter_tokens, past_key_values)
  279. past_seen_tokens = past_key_values.get_seq_length()
  280. if cache_position is None:
  281. if isinstance(past_key_values, StaticCache):
  282. raise ValueError("cache_position is a required argument when using StaticCache.")
  283. cache_position = torch.arange(
  284. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  285. )
  286. if position_ids is None:
  287. position_ids = cache_position.unsqueeze(0)
  288. causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
  289. # embed positions
  290. hidden_states = inputs_embeds
  291. # decoder layers
  292. all_hidden_states = () if output_hidden_states else None
  293. all_self_attns = () if output_attentions else None
  294. next_decoder_cache = None
  295. for decoder_layer in self.layers:
  296. if output_hidden_states:
  297. all_hidden_states += (hidden_states,)
  298. if self.gradient_checkpointing and self.training:
  299. layer_outputs = self._gradient_checkpointing_func(
  300. decoder_layer.__call__,
  301. hidden_states,
  302. causal_mask,
  303. position_ids,
  304. past_key_values,
  305. output_attentions,
  306. use_cache,
  307. cache_position,
  308. )
  309. else:
  310. layer_outputs = decoder_layer(
  311. hidden_states,
  312. attention_mask=causal_mask,
  313. position_ids=position_ids,
  314. past_key_value=past_key_values,
  315. output_attentions=output_attentions,
  316. use_cache=use_cache,
  317. cache_position=cache_position,
  318. )
  319. hidden_states = layer_outputs[0]
  320. if use_cache:
  321. next_decoder_cache = layer_outputs[2 if output_attentions else 1]
  322. if output_attentions:
  323. all_self_attns += (layer_outputs[1],)
  324. hidden_states = self.norm(hidden_states)
  325. import pdb; pdb.set_trace()
  326. # add hidden states from the last decoder layer
  327. if output_hidden_states:
  328. all_hidden_states += (hidden_states,)
  329. next_cache = None
  330. if use_cache:
  331. next_cache = (
  332. next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
  333. )
  334. if not return_dict:
  335. return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
  336. return BaseModelOutputWithPast(
  337. last_hidden_state=hidden_states,
  338. past_key_values=next_cache,
  339. hidden_states=all_hidden_states,
  340. attentions=all_self_attns,
  341. )
  342. # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
  343. # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
  344. # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
  345. # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
  346. def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
  347. if self.config._attn_implementation == "flash_attention_2":
  348. if attention_mask is not None and 0.0 in attention_mask:
  349. return attention_mask
  350. return None
  351. dtype, device = input_tensor.dtype, input_tensor.device
  352. min_dtype = torch.finfo(dtype).min
  353. sequence_length = input_tensor.shape[1]
  354. if hasattr(self.layers[0].self_attn, "past_key_value"): # static cache
  355. target_length = self.config.max_position_embeddings
  356. else: # dynamic cache
  357. target_length = (
  358. attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else cache_position[-1] + 1
  359. )
  360. causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
  361. if sequence_length != 1:
  362. causal_mask = torch.triu(causal_mask, diagonal=1)
  363. causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
  364. causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
  365. if attention_mask is not None:
  366. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  367. if attention_mask.dim() == 2:
  368. mask_length = attention_mask.shape[-1]
  369. padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
  370. causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
  371. elif attention_mask.dim() == 4:
  372. # backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
  373. # cache. In that case, the 4D attention mask attends to the newest tokens only.
  374. if attention_mask.shape[-2] < cache_position[0] + sequence_length:
  375. offset = cache_position[0]
  376. else:
  377. offset = 0
  378. mask_shape = attention_mask.shape
  379. mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
  380. causal_mask[
  381. : mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
  382. ] = mask_slice
  383. if (
  384. self.config._attn_implementation == "sdpa"
  385. and attention_mask is not None
  386. and attention_mask.device.type == "cuda"
  387. ):
  388. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  389. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  390. # Details: https://github.com/pytorch/pytorch/issues/110213
  391. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  392. return causal_mask
  393. # class H2OLlamaAttention(nn.Module):
  394. # """Multi-headed attention from 'Attention Is All You Need' paper"""
  395. # def __init__(self, config: LlamaConfig):
  396. # super().__init__()
  397. # self.config = config
  398. # self.hidden_size = config.hidden_size
  399. # self.num_heads = config.num_attention_heads
  400. # self.head_dim = self.hidden_size // self.num_heads
  401. # self.num_key_value_heads = config.num_key_value_heads
  402. # self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  403. # self.max_position_embeddings = config.max_position_embeddings
  404. # self.rope_theta = config.rope_theta
  405. # if (self.head_dim * self.num_heads) != self.hidden_size:
  406. # raise ValueError(
  407. # f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  408. # f" and `num_heads`: {self.num_heads})."
  409. # )
  410. # self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  411. # self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  412. # self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  413. # self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  414. # self._init_rope()
  415. # self.kv_cache = H2OKVCache_LayerWise(
  416. # hh_size=config.hh_size,
  417. # recent_size=config.recent_size,
  418. # k_seq_dim=2,
  419. # v_seq_dim=2,
  420. # )
  421. # def _init_rope(self):
  422. # if self.config.rope_scaling is None:
  423. # self.rotary_emb = LlamaRotaryEmbedding(
  424. # self.head_dim,
  425. # max_position_embeddings=self.max_position_embeddings,
  426. # base=self.rope_theta,
  427. # )
  428. # else:
  429. # scaling_type = self.config.rope_scaling["type"]
  430. # scaling_factor = self.config.rope_scaling["factor"]
  431. # if scaling_type == "linear":
  432. # self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
  433. # self.head_dim,
  434. # max_position_embeddings=self.max_position_embeddings,
  435. # scaling_factor=scaling_factor,
  436. # base=self.rope_theta,
  437. # )
  438. # elif scaling_type == "dynamic":
  439. # self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
  440. # self.head_dim,
  441. # max_position_embeddings=self.max_position_embeddings,
  442. # scaling_factor=scaling_factor,
  443. # base=self.rope_theta,
  444. # )
  445. # else:
  446. # raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
  447. # def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
  448. # return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  449. # def _clean_cache(self):
  450. # self.kv_cache._clean_scores()
  451. # def forward(
  452. # self,
  453. # hidden_states: torch.Tensor,
  454. # attention_mask: Optional[torch.Tensor] = None,
  455. # position_ids: Optional[torch.LongTensor] = None,
  456. # past_key_value: Optional[Tuple[torch.Tensor]] = None,
  457. # output_attentions: bool = False,
  458. # use_cache: bool = False,
  459. # cache_position: Optional[torch.LongTensor] = None,
  460. # ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  461. # bsz, q_len, _ = hidden_states.size()
  462. # if self.config.pretraining_tp > 1:
  463. # key_value_slicing = (
  464. # self.num_key_value_heads * self.head_dim
  465. # ) // self.config.pretraining_tp
  466. # query_slices = self.q_proj.weight.split(
  467. # (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
  468. # )
  469. # key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
  470. # value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
  471. # query_states = [
  472. # F.linear(hidden_states, query_slices[i])
  473. # for i in range(self.config.pretraining_tp)
  474. # ]
  475. # query_states = torch.cat(query_states, dim=-1)
  476. # key_states = [
  477. # F.linear(hidden_states, key_slices[i])
  478. # for i in range(self.config.pretraining_tp)
  479. # ]
  480. # key_states = torch.cat(key_states, dim=-1)
  481. # value_states = [
  482. # F.linear(hidden_states, value_slices[i])
  483. # for i in range(self.config.pretraining_tp)
  484. # ]
  485. # value_states = torch.cat(value_states, dim=-1)
  486. # else:
  487. # query_states = self.q_proj(hidden_states)
  488. # key_states = self.k_proj(hidden_states)
  489. # value_states = self.v_proj(hidden_states)
  490. # query_states = query_states.view(
  491. # bsz, q_len, self.num_heads, self.head_dim
  492. # ).transpose(1, 2)
  493. # key_states = key_states.view(
  494. # bsz, q_len, self.num_key_value_heads, self.head_dim
  495. # ).transpose(1, 2)
  496. # value_states = value_states.view(
  497. # bsz, q_len, self.num_key_value_heads, self.head_dim
  498. # ).transpose(1, 2)
  499. # # remake causal mask
  500. # attention_mask = _make_causal_mask(
  501. # bsz=bsz,
  502. # tgt_len=q_len,
  503. # past_key_values_length=past_key_value[0].shape[-2] if past_key_value is not None else 0,
  504. # dtype=query_states.dtype,
  505. # device=query_states.device,
  506. # )
  507. # kv_seq_len = key_states.shape[-2]
  508. # if past_key_value is not None:
  509. # kv_seq_len += past_key_value[0].shape[-2]
  510. # if not position_ids.nelement() > 1:
  511. # position_ids[0][0] = kv_seq_len - 1
  512. # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
  513. # ### Shift Pos: query pos is min(cache_size, idx)
  514. # # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
  515. # query_states = apply_rotary_pos_emb_single(query_states, cos, sin, position_ids)
  516. # ###
  517. # if past_key_value is not None:
  518. # # reuse k, v, self_attention
  519. # key_states = torch.cat([past_key_value[0], key_states], dim=2)
  520. # value_states = torch.cat([past_key_value[1], value_states], dim=2)
  521. # past_key_value = (key_states, value_states) if use_cache else None
  522. # ### Shift Pos: key pos is the pos in cache (Rolling KV Cache and using relative pos emb)
  523. # key_position_ids = torch.arange(kv_seq_len, device=position_ids.device).unsqueeze(0)
  524. # key_states = apply_rotary_pos_emb_single(key_states, cos, sin, key_position_ids)
  525. # ###
  526. # # repeat k/v heads if n_kv_heads < n_heads
  527. # key_states = repeat_kv(key_states, self.num_key_value_groups)
  528. # value_states = repeat_kv(value_states, self.num_key_value_groups)
  529. # attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(
  530. # self.head_dim
  531. # )
  532. # if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
  533. # raise ValueError(
  534. # f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
  535. # f" {attn_weights.size()}"
  536. # )
  537. # if attention_mask is not None:
  538. # if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
  539. # raise ValueError(
  540. # f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
  541. # )
  542. # attn_weights = attn_weights + attention_mask
  543. # # upcast attention to fp32
  544. # attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
  545. # query_states.dtype
  546. # )
  547. # past_key_value = self.kv_cache(past_key_value, attn_weights.detach().clone())
  548. # attn_output = torch.matmul(attn_weights, value_states)
  549. # if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  550. # raise ValueError(
  551. # f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  552. # f" {attn_output.size()}"
  553. # )
  554. # attn_output = attn_output.transpose(1, 2).contiguous()
  555. # attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  556. # if self.config.pretraining_tp > 1:
  557. # attn_output = attn_output.split(
  558. # self.hidden_size // self.config.pretraining_tp, dim=2
  559. # )
  560. # o_proj_slices = self.o_proj.weight.split(
  561. # self.hidden_size // self.config.pretraining_tp, dim=1
  562. # )
  563. # attn_output = sum(
  564. # [
  565. # F.linear(attn_output[i], o_proj_slices[i])
  566. # for i in range(self.config.pretraining_tp)
  567. # ]
  568. # )
  569. # else:
  570. # attn_output = self.o_proj(attn_output)
  571. # if not output_attentions:
  572. # attn_weights = None
  573. # return attn_output, attn_weights, past_key_value
  574. class H2OLlamaForCausalLM(LlamaForCausalLM):
  575. def __init__(self, config):
  576. super().__init__(config)
  577. num_layers = len(self.model.layers)
  578. for layer_idx in range(num_layers):
  579. self.model.layers[layer_idx].self_attn = H2OLlamaAttention(config, layer_idx)
  580. self.model.forward = types.MethodType(enable_h2ocache_forward, self.model)
  581. self.model.num_heavy_hitter_tokens = config.num_heavy_hitter_tokens
  582. self.model.num_window_length = config.num_window_length