utils_llama.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import math
  2. from typing import Optional, Tuple
  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. __all__ = ["H2OLlamaForCausalLM"]
  20. def _make_causal_mask(
  21. bsz: int, tgt_len: int, past_key_values_length: int, dtype: torch.dtype, device: torch.device):
  22. """
  23. Make causal mask used for bi-directional self-attention.
  24. """
  25. mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
  26. mask_cond = torch.arange(mask.size(-1), device=device)
  27. mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
  28. mask = mask.to(dtype)
  29. if past_key_values_length > 0:
  30. mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
  31. return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
  32. def apply_rotary_pos_emb_single(x, cos, sin, position_ids):
  33. # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
  34. cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
  35. sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
  36. cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
  37. sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
  38. x_embed = (x * cos) + (rotate_half(x) * sin)
  39. return x_embed
  40. class H2OKVCache_LayerWise:
  41. def __init__(
  42. self,
  43. hh_size=4,
  44. recent_size=512,
  45. k_seq_dim=2,
  46. v_seq_dim=2,
  47. ):
  48. self.hh_size = hh_size
  49. self.recent_size = recent_size
  50. self.cache_size = hh_size + recent_size
  51. self.k_seq_dim = k_seq_dim
  52. self.v_seq_dim = v_seq_dim
  53. self.hh_score = None
  54. def __call__(self, past_key_values, attn_score_cache):
  55. self._update_hh_score(attn_score_cache)
  56. if past_key_values is None:
  57. return None
  58. seq_len = past_key_values[0].size(self.k_seq_dim)
  59. if seq_len <= self.cache_size:
  60. return past_key_values
  61. # hh-selection
  62. bsz, num_heads, _, head_dim = past_key_values[0].shape
  63. select_hh_scores = self.hh_score[:, :seq_len - self.recent_size]
  64. _, keep_topk = torch.topk(select_hh_scores, self.hh_size, dim=-1)
  65. keep_topk = keep_topk.sort().values
  66. # keep_recent = torch.arange(seq_len - self.recent_size, seq_len).expand(keep_topk.shape[0], 1).to(keep_topk.device)
  67. keep_recent = torch.arange(seq_len - self.recent_size, seq_len, device=keep_topk.device).repeat(keep_topk.shape[0], 1)
  68. keep_idx = torch.cat([keep_topk, keep_recent], dim=-1)
  69. mask = torch.zeros(self.hh_score.shape, dtype=torch.bool).to(past_key_values[0].device)
  70. mask = mask.scatter(-1, keep_idx, 1)
  71. k_hh_recent = past_key_values[0].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  72. v_hh_recent = past_key_values[1].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  73. self.hh_score= self.hh_score[mask].view(num_heads, self.cache_size)
  74. return (k_hh_recent, v_hh_recent)
  75. def evict_for_space(self, past_key_values, num_coming):
  76. if past_key_values is None:
  77. return None
  78. seq_len = past_key_values[0][0].size(self.k_seq_dim)
  79. if seq_len + num_coming <= self.cache_size:
  80. return past_key_values
  81. # hh-selection
  82. bsz, num_heads, _, head_dim = past_key_values[0].shape
  83. select_hh_scores = self.hh_score[:, :seq_len - self.recent_size + num_coming]
  84. _, keep_topk = torch.topk(select_hh_scores, self.hh_size, dim=-1)
  85. keep_topk = keep_topk.sort().values
  86. # keep_recent = torch.arange(seq_len - self.recent_size, seq_len).expand(keep_topk.shape[0], 1).to(keep_topk.device)
  87. keep_recent = torch.arange(seq_len - self.recent_size + num_coming, seq_len, device=keep_topk.device).repeat(keep_topk.shape[0], 1)
  88. keep_idx = torch.cat([keep_topk, keep_recent], dim=-1)
  89. mask = torch.zeros(self.hh_score.shape, dtype=torch.bool).to(past_key_values[0].device)
  90. mask = mask.scatter(-1, keep_idx, 1)
  91. k_hh_recent = past_key_values[0].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  92. v_hh_recent = past_key_values[1].squeeze()[mask].view(bsz, num_heads, -1, head_dim)
  93. self.hh_score= self.hh_score[mask].view(num_heads, self.cache_size)
  94. return (k_hh_recent, v_hh_recent)
  95. def _update_hh_score(self, attn_score_cache):
  96. num_new_tokens = attn_score_cache.shape[2]
  97. if self.hh_score is None:
  98. self.hh_score = attn_score_cache.sum(0).sum(1)
  99. else:
  100. attn_score_cache = attn_score_cache.sum(0).sum(1)
  101. attn_score_cache[:, :-num_new_tokens] += self.hh_score
  102. self.hh_score = attn_score_cache
  103. def _clean_scores(self):
  104. self.hh_score = None
  105. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  106. """
  107. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  108. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  109. """
  110. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  111. if n_rep == 1:
  112. return hidden_states
  113. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  114. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  115. class H2OLlamaAttention(nn.Module):
  116. """Multi-headed attention from 'Attention Is All You Need' paper"""
  117. def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
  118. super().__init__()
  119. self.config = config
  120. self.layer_idx = layer_idx
  121. if layer_idx is None:
  122. logger.warning_once(
  123. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  124. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  125. "when creating this class."
  126. )
  127. self.attention_dropout = config.attention_dropout
  128. self.hidden_size = config.hidden_size
  129. self.num_heads = config.num_attention_heads
  130. self.head_dim = self.hidden_size // self.num_heads
  131. self.num_key_value_heads = config.num_key_value_heads
  132. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  133. self.max_position_embeddings = config.max_position_embeddings
  134. self.rope_theta = config.rope_theta
  135. self.is_causal = True
  136. if (self.head_dim * self.num_heads) != self.hidden_size:
  137. raise ValueError(
  138. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  139. f" and `num_heads`: {self.num_heads})."
  140. )
  141. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
  142. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  143. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  144. self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
  145. self._init_rope()
  146. def _init_rope(self):
  147. if self.config.rope_scaling is None:
  148. self.rotary_emb = LlamaRotaryEmbedding(
  149. self.head_dim,
  150. max_position_embeddings=self.max_position_embeddings,
  151. base=self.rope_theta,
  152. )
  153. else:
  154. scaling_type = self.config.rope_scaling["type"]
  155. scaling_factor = self.config.rope_scaling["factor"]
  156. if scaling_type == "linear":
  157. self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
  158. self.head_dim,
  159. max_position_embeddings=self.max_position_embeddings,
  160. scaling_factor=scaling_factor,
  161. base=self.rope_theta,
  162. )
  163. elif scaling_type == "dynamic":
  164. self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
  165. self.head_dim,
  166. max_position_embeddings=self.max_position_embeddings,
  167. scaling_factor=scaling_factor,
  168. base=self.rope_theta,
  169. )
  170. else:
  171. raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
  172. def forward(
  173. self,
  174. hidden_states: torch.Tensor,
  175. attention_mask: Optional[torch.Tensor] = None,
  176. position_ids: Optional[torch.LongTensor] = None,
  177. past_key_value: Optional[Cache] = None,
  178. output_attentions: bool = False,
  179. use_cache: bool = False,
  180. cache_position: Optional[torch.LongTensor] = None,
  181. **kwargs,
  182. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  183. bsz, q_len, _ = hidden_states.size()
  184. if self.config.pretraining_tp > 1:
  185. key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
  186. query_slices = self.q_proj.weight.split(
  187. (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
  188. )
  189. key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
  190. value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
  191. query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
  192. query_states = torch.cat(query_states, dim=-1)
  193. key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
  194. key_states = torch.cat(key_states, dim=-1)
  195. value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
  196. value_states = torch.cat(value_states, dim=-1)
  197. else:
  198. query_states = self.q_proj(hidden_states)
  199. key_states = self.k_proj(hidden_states)
  200. value_states = self.v_proj(hidden_states)
  201. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  202. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  203. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  204. past_key_value = getattr(self, "past_key_value", past_key_value)
  205. cos, sin = self.rotary_emb(value_states, position_ids)
  206. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  207. if past_key_value is not None:
  208. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  209. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  210. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  211. key_states = repeat_kv(key_states, self.num_key_value_groups)
  212. value_states = repeat_kv(value_states, self.num_key_value_groups)
  213. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
  214. if attention_mask is not None: # no matter the length, we just slice it
  215. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  216. attn_weights = attn_weights + causal_mask
  217. # upcast attention to fp32
  218. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  219. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  220. attn_output = torch.matmul(attn_weights, value_states)
  221. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  222. raise ValueError(
  223. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  224. f" {attn_output.size()}"
  225. )
  226. attn_output = attn_output.transpose(1, 2).contiguous()
  227. attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  228. if self.config.pretraining_tp > 1:
  229. attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
  230. o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
  231. attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
  232. else:
  233. attn_output = self.o_proj(attn_output)
  234. if not output_attentions:
  235. attn_weights = None
  236. return attn_output, attn_weights, past_key_value
  237. # class H2OLlamaAttention(nn.Module):
  238. # """Multi-headed attention from 'Attention Is All You Need' paper"""
  239. # def __init__(self, config: LlamaConfig):
  240. # super().__init__()
  241. # self.config = config
  242. # self.hidden_size = config.hidden_size
  243. # self.num_heads = config.num_attention_heads
  244. # self.head_dim = self.hidden_size // self.num_heads
  245. # self.num_key_value_heads = config.num_key_value_heads
  246. # self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  247. # self.max_position_embeddings = config.max_position_embeddings
  248. # self.rope_theta = config.rope_theta
  249. # if (self.head_dim * self.num_heads) != self.hidden_size:
  250. # raise ValueError(
  251. # f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  252. # f" and `num_heads`: {self.num_heads})."
  253. # )
  254. # self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
  255. # self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  256. # self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  257. # self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  258. # self._init_rope()
  259. # self.kv_cache = H2OKVCache_LayerWise(
  260. # hh_size=config.hh_size,
  261. # recent_size=config.recent_size,
  262. # k_seq_dim=2,
  263. # v_seq_dim=2,
  264. # )
  265. # def _init_rope(self):
  266. # if self.config.rope_scaling is None:
  267. # self.rotary_emb = LlamaRotaryEmbedding(
  268. # self.head_dim,
  269. # max_position_embeddings=self.max_position_embeddings,
  270. # base=self.rope_theta,
  271. # )
  272. # else:
  273. # scaling_type = self.config.rope_scaling["type"]
  274. # scaling_factor = self.config.rope_scaling["factor"]
  275. # if scaling_type == "linear":
  276. # self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
  277. # self.head_dim,
  278. # max_position_embeddings=self.max_position_embeddings,
  279. # scaling_factor=scaling_factor,
  280. # base=self.rope_theta,
  281. # )
  282. # elif scaling_type == "dynamic":
  283. # self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
  284. # self.head_dim,
  285. # max_position_embeddings=self.max_position_embeddings,
  286. # scaling_factor=scaling_factor,
  287. # base=self.rope_theta,
  288. # )
  289. # else:
  290. # raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
  291. # def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
  292. # return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  293. # def _clean_cache(self):
  294. # self.kv_cache._clean_scores()
  295. # def forward(
  296. # self,
  297. # hidden_states: torch.Tensor,
  298. # attention_mask: Optional[torch.Tensor] = None,
  299. # position_ids: Optional[torch.LongTensor] = None,
  300. # past_key_value: Optional[Tuple[torch.Tensor]] = None,
  301. # output_attentions: bool = False,
  302. # use_cache: bool = False,
  303. # cache_position: Optional[torch.LongTensor] = None,
  304. # ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  305. # bsz, q_len, _ = hidden_states.size()
  306. # if self.config.pretraining_tp > 1:
  307. # key_value_slicing = (
  308. # self.num_key_value_heads * self.head_dim
  309. # ) // self.config.pretraining_tp
  310. # query_slices = self.q_proj.weight.split(
  311. # (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
  312. # )
  313. # key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
  314. # value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
  315. # query_states = [
  316. # F.linear(hidden_states, query_slices[i])
  317. # for i in range(self.config.pretraining_tp)
  318. # ]
  319. # query_states = torch.cat(query_states, dim=-1)
  320. # key_states = [
  321. # F.linear(hidden_states, key_slices[i])
  322. # for i in range(self.config.pretraining_tp)
  323. # ]
  324. # key_states = torch.cat(key_states, dim=-1)
  325. # value_states = [
  326. # F.linear(hidden_states, value_slices[i])
  327. # for i in range(self.config.pretraining_tp)
  328. # ]
  329. # value_states = torch.cat(value_states, dim=-1)
  330. # else:
  331. # query_states = self.q_proj(hidden_states)
  332. # key_states = self.k_proj(hidden_states)
  333. # value_states = self.v_proj(hidden_states)
  334. # query_states = query_states.view(
  335. # bsz, q_len, self.num_heads, self.head_dim
  336. # ).transpose(1, 2)
  337. # key_states = key_states.view(
  338. # bsz, q_len, self.num_key_value_heads, self.head_dim
  339. # ).transpose(1, 2)
  340. # value_states = value_states.view(
  341. # bsz, q_len, self.num_key_value_heads, self.head_dim
  342. # ).transpose(1, 2)
  343. # # remake causal mask
  344. # attention_mask = _make_causal_mask(
  345. # bsz=bsz,
  346. # tgt_len=q_len,
  347. # past_key_values_length=past_key_value[0].shape[-2] if past_key_value is not None else 0,
  348. # dtype=query_states.dtype,
  349. # device=query_states.device,
  350. # )
  351. # kv_seq_len = key_states.shape[-2]
  352. # if past_key_value is not None:
  353. # kv_seq_len += past_key_value[0].shape[-2]
  354. # if not position_ids.nelement() > 1:
  355. # position_ids[0][0] = kv_seq_len - 1
  356. # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
  357. # ### Shift Pos: query pos is min(cache_size, idx)
  358. # # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
  359. # query_states = apply_rotary_pos_emb_single(query_states, cos, sin, position_ids)
  360. # ###
  361. # if past_key_value is not None:
  362. # # reuse k, v, self_attention
  363. # key_states = torch.cat([past_key_value[0], key_states], dim=2)
  364. # value_states = torch.cat([past_key_value[1], value_states], dim=2)
  365. # past_key_value = (key_states, value_states) if use_cache else None
  366. # ### Shift Pos: key pos is the pos in cache (Rolling KV Cache and using relative pos emb)
  367. # key_position_ids = torch.arange(kv_seq_len, device=position_ids.device).unsqueeze(0)
  368. # key_states = apply_rotary_pos_emb_single(key_states, cos, sin, key_position_ids)
  369. # ###
  370. # # repeat k/v heads if n_kv_heads < n_heads
  371. # key_states = repeat_kv(key_states, self.num_key_value_groups)
  372. # value_states = repeat_kv(value_states, self.num_key_value_groups)
  373. # attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(
  374. # self.head_dim
  375. # )
  376. # if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
  377. # raise ValueError(
  378. # f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
  379. # f" {attn_weights.size()}"
  380. # )
  381. # if attention_mask is not None:
  382. # if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
  383. # raise ValueError(
  384. # f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
  385. # )
  386. # attn_weights = attn_weights + attention_mask
  387. # # upcast attention to fp32
  388. # attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
  389. # query_states.dtype
  390. # )
  391. # past_key_value = self.kv_cache(past_key_value, attn_weights.detach().clone())
  392. # attn_output = torch.matmul(attn_weights, value_states)
  393. # if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  394. # raise ValueError(
  395. # f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  396. # f" {attn_output.size()}"
  397. # )
  398. # attn_output = attn_output.transpose(1, 2).contiguous()
  399. # attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
  400. # if self.config.pretraining_tp > 1:
  401. # attn_output = attn_output.split(
  402. # self.hidden_size // self.config.pretraining_tp, dim=2
  403. # )
  404. # o_proj_slices = self.o_proj.weight.split(
  405. # self.hidden_size // self.config.pretraining_tp, dim=1
  406. # )
  407. # attn_output = sum(
  408. # [
  409. # F.linear(attn_output[i], o_proj_slices[i])
  410. # for i in range(self.config.pretraining_tp)
  411. # ]
  412. # )
  413. # else:
  414. # attn_output = self.o_proj(attn_output)
  415. # if not output_attentions:
  416. # attn_weights = None
  417. # return attn_output, attn_weights, past_key_value
  418. class H2OLlamaForCausalLM(LlamaForCausalLM):
  419. def __init__(self, config):
  420. super().__init__(config)
  421. num_layers = len(self.model.layers)
  422. for layer_idx in range(num_layers):
  423. self.model.layers[layer_idx].self_attn = H2OLlamaAttention(config)