code: def chatglm2_attention_forward_8eb45c(
      self,
      hidden_states,
      attention_mask,
      rotary_pos_emb,
      kv_cache=None,
      use_cache=True,
  ):
      # hidden_states: [sq, b, h]
  
      # =================================================
      # Pre-allocate memory for key-values for inference.
      # =================================================
      # =====================
      # Query, Key, and Value
      # =====================
  
      # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
      device = hidden_states.device
      mixed_x_layer = self.query_key_value(hidden_states)
  
      if self.multi_query_attention:
          (query_layer, key_layer, value_layer) = mixed_x_layer.split(
              [
                  self.num_attention_heads_per_partition
                  * self.hidden_size_per_attention_head,
                  self.num_multi_query_groups_per_partition
                  * self.hidden_size_per_attention_head,
                  self.num_multi_query_groups_per_partition
                  * self.hidden_size_per_attention_head,
              ],
              dim=-1,
          )
          query_layer = query_layer.view(
              query_layer.size()[:-1]
              + (
                  self.num_attention_heads_per_partition,
                  self.hidden_size_per_attention_head,
              )
          )
          key_layer = key_layer.view(
              key_layer.size()[:-1]
              + (
                  self.num_multi_query_groups_per_partition,
                  self.hidden_size_per_attention_head,
              )
          )
          value_layer = value_layer.view(
              value_layer.size()[:-1]
              + (
                  self.num_multi_query_groups_per_partition,
                  self.hidden_size_per_attention_head,
              )
          )
      else:
          new_tensor_shape = mixed_x_layer.size()[:-1] + (
              self.num_attention_heads_per_partition,
              3 * self.hidden_size_per_attention_head,
          )
          mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
  
          # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
          (
              query_layer,
              key_layer,
              value_layer,
          ) = split_tensor_along_last_dim(mixed_x_layer, 3)
  
      cur_length, batch_size = (
          query_layer.shape[0],
          query_layer.shape[1],
      )
  
      # apply relative positional encoding (rotary embedding)
      if rotary_pos_emb is not None:
          if (
              len(rotary_pos_emb) == 2
          ):  # use_fuse_rope, see chatglm2_model_forward
              cos, sin = rotary_pos_emb
              rot_dim = cos.shape[-1]
              query_layer = query_layer.transpose(0, 1)
              key_layer = key_layer.transpose(0, 1)
              query_layer_cur = query_layer[..., :rot_dim]
              key_layer_cur = key_layer[..., :rot_dim]
              # ipex's apply_rotary_embedding can change the origin storage, so query_layer will get
              # the result directly.
              torch.ops.torch_ipex.apply_rotary_embedding(
                  query_layer_cur, sin, cos, query_layer_cur
              )
              torch.ops.torch_ipex.apply_rotary_embedding(
                  key_layer_cur, sin, cos, key_layer_cur
              )
              query_layer = query_layer.transpose(0, 1)
              key_layer = key_layer.transpose(0, 1)
          else:
              query_layer = apply_rotary_pos_emb_chatglm(
                  query_layer, rotary_pos_emb
              )
              key_layer = apply_rotary_pos_emb_chatglm(
                  key_layer, rotary_pos_emb
              )
  
      if self.multi_query_attention:
          if (
              device.type == "xpu" and batch_size > 1
          ):  # use beam_search for generation.
              # If batch_size > 1 on gpu, permute key/value_layer to [bs, np, sl, hn]
              # to reduce memory usage. Otherwise，expend key/value_layer to [bs, nh, sl, hn].
              key_layer = key_layer.permute(
                  1, 2, 0, 3
              )  # [bs, np, sl, hn]
              value_layer = value_layer.permute(
                  1, 2, 0, 3
              )  # [bs, np, sl, hn]
          else:
              key_length = key_layer.size(0)
              query_group_size = (
                  self.num_attention_heads_per_partition
                  // self.num_multi_query_groups_per_partition
              )
              key_layer = key_layer.permute(1, 2, 0, 3).unsqueeze(
                  -3
              )  # [bs, nh/k, sl, hn]
              key_layer = key_layer.expand(
                  -1, -1, query_group_size, -1, -1
              )
              key_layer = key_layer.contiguous().view(
                  (
                      batch_size,
                      self.num_attention_heads_per_partition,
                      key_length,
                      self.hidden_size_per_attention_head,
                  )
              )
              value_layer = value_layer.permute(1, 2, 0, 3).unsqueeze(
                  -3
              )  # [bs, nh/k, sl, hn]
              value_layer = value_layer.expand(
                  -1, -1, query_group_size, -1, -1
              )
              value_layer = value_layer.contiguous().view(
                  (
                      batch_size,
                      self.num_attention_heads_per_partition,
                      key_length,
                      self.hidden_size_per_attention_head,
                  )
              )
  
      # adjust key and value for inference
      if kv_cache is not None:
          cache_k, cache_v = kv_cache
          cache_k = cache_k.permute(1, 2, 0, 3)
          cache_v = cache_v.permute(1, 2, 0, 3)
          past_length = cache_k.size(2)
  
          if cache_k.stride()[1] <= cache_k.size(2) * cache_k.size(3):
              max_cache_length = (
                  past_length + cur_length + KV_CACHE_ALLOC_BLOCK_LENGTH
              )
              if (
                  device.type == "xpu" and batch_size > 1
              ):  # use beam_search for generation.
                  # If batch_size > 1 on gpu, use init_kv_cache to avoid empty cache for ensuring
                  # generation correctness.
                  # Set the num_heads in init_kv_cache to np, ensuring that the tensors of
                  # new_cache_k/v and key/value_layer have the same size.
                  new_cache_k, new_cache_v = init_kv_cache(
                      batch_size,
                      self.num_multi_query_groups_per_partition,
                      self.hidden_size_per_attention_head,
                      past_length,
                      max_cache_length,
                      dtype=query_layer.dtype,
                      device=device,
                  )
              else:
                  new_cache_k, new_cache_v = extend_kv_cache(
                      batch_size,
                      self.num_attention_heads_per_partition,
                      self.hidden_size_per_attention_head,
                      past_length,
                      max_cache_length,
                      dtype=query_layer.dtype,
                      device=device,
                  )
              new_cache_k[:] = cache_k
              new_cache_v[:] = cache_v
              cache_k = new_cache_k
              cache_v = new_cache_v
  
          key_layer, value_layer = append_kv_cache(
              cache_k, cache_v, key_layer, value_layer
          )
  
      elif use_cache:
          max_cache_length = (
              max(KV_CACHE_ALLOC_MIN_LENGTH, cur_length)
              + KV_CACHE_ALLOC_BLOCK_LENGTH
          )
  
          if (
              device.type == "xpu" and batch_size > 1
          ):  # use beam_search for generation.
              # Ensure the tensors of key/value_cache and key/value_layer have the same size.
              nums_per_partition = (
                  self.num_multi_query_groups_per_partition
              )
          else:
              nums_per_partition = (
                  self.num_attention_heads_per_partition
              )
  
          key_cache, value_cache = init_kv_cache(
              batch_size,
              nums_per_partition,
              self.hidden_size_per_attention_head,
              cur_length,
              max_cache_length,
              dtype=query_layer.dtype,
              device=device,
          )
          key_cache[:] = key_layer
          value_cache[:] = value_layer
          key_layer = key_cache
          value_layer = value_cache
  
      # If batch_size > 1, return tensors with shape [bs, np, sl, hn] as past_key_values. This could
      # reduce memory usage as tensors are not expended to [bs, nh, sl, hn].
      # Otherwise, return views of [bs, nh, sl, hn].
      cache_key_layer = key_layer
      cache_value_layer = value_layer
  
      if use_cache:
          kv_cache = (key_layer, value_layer)
      else:
          kv_cache = None
  
      # ==================================
      # core attention computation
      # ==================================
      if (
          device.type == "xpu" and batch_size > 1
      ):  # use beam_search for generation.
          # If batch_size > 1, expend key/value_layer to [ns, nh, sl, bn] for
          # core attention computation.
          # The expanded tensors will not be returned as past_key_values.
          if self.multi_query_attention:
              query_group_size = (
                  self.num_attention_heads_per_partition
                  // self.num_multi_query_groups_per_partition
              )
              key_layer = key_layer.unsqueeze(-3)
              key_layer = key_layer.expand(
                  -1, -1, query_group_size, -1, -1
              )
              save_length = key_layer.size(3)
              # [bs, np, sl, hn] --> [bs, nh, sl, hn]
              key_layer = key_layer.contiguous().view(
                  (
                      batch_size,
                      self.num_attention_heads_per_partition,
                      save_length,
                      self.hidden_size_per_attention_head,
                  )
              )
              value_layer = value_layer.unsqueeze(-3)
              value_layer = value_layer.expand(
                  -1, -1, query_group_size, -1, -1
              )
              # [bs, np, sl, hn] --> [bs, nh, sl, hn]
              value_layer = value_layer.contiguous().view(
                  (
                      batch_size,
                      self.num_attention_heads_per_partition,
                      save_length,
                      self.hidden_size_per_attention_head,
                  )
              )
  
      context_layer = self.core_attention(
          query_layer, key_layer, value_layer, attention_mask
      )
  
      # =================
      # Output. [sq, b, h]
      # =================
  
      output = self.dense(context_layer)
  
      return output, (
          cache_key_layer.permute(2, 0, 1, 3),
          cache_value_layer.permute(2, 0, 1, 3),
      )
  
file_path: BigDL/python/llm/src/bigdl/llm/transformers/models/chatglm2.py
imports: import math
  import torch
  from typing import Optional, Tuple, List
  import torch.nn.functional
  from transformers.modeling_outputs import BaseModelOutputWithPast
  from bigdl.llm.transformers.models.utils import init_kv_cache, extend_kv_cache, append_kv_cache
  from bigdl.llm.transformers.models.utils import use_flash_attention
  from bigdl.llm.transformers.models.llama import get_ipex_version
label_desc: Use image node_id 5 for calling a global function with example usage: chatglm2_attention_forward_8eb45c(hidden_states, attention_mask, rotary_pos_emb, kv_cache, use_cache) and returns: output,  cache_key_layer,  cache_value_layer