|
| 1 | +import torch |
| 2 | +import torch.functional as F |
| 3 | +import torch.distributed as dist |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from lightllm.models.llama.layer_infer.transformer_layer_infer import LlamaTransformerLayerInfer |
| 7 | +from functools import partial |
| 8 | + |
| 9 | + |
| 10 | +def rotate_half(x): |
| 11 | + x1 = x[..., : x.shape[-1] // 2] |
| 12 | + x2 = x[..., x.shape[-1] // 2 :] |
| 13 | + return torch.cat((-x2, x1), dim=-1) |
| 14 | + |
| 15 | + |
| 16 | +def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1): |
| 17 | + mrope_section = mrope_section * 2 |
| 18 | + cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim) |
| 19 | + sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim) |
| 20 | + |
| 21 | + q_embed = (q * cos) + (rotate_half(q) * sin) |
| 22 | + k_embed = (k * cos) + (rotate_half(k) * sin) |
| 23 | + |
| 24 | + return q_embed, k_embed |
| 25 | + |
| 26 | + |
| 27 | +class Qwen2VLTransformerLayerInfer(LlamaTransformerLayerInfer): |
| 28 | + def __init__(self, layer_num, network_config, mode=[]): |
| 29 | + super().__init__(layer_num, network_config, mode) |
| 30 | + self.mrope_section = network_config["rope_scaling"]["mrope_section"] |
| 31 | + |
| 32 | + def _get_qkv(self, input, cache_kv, infer_state, layer_weight): |
| 33 | + q = layer_weight.q_proj.mm(input) |
| 34 | + cache_kv = layer_weight.kv_proj.mm( |
| 35 | + input, out=cache_kv.view(-1, (self.tp_k_head_num_ + self.tp_v_head_num_) * self.head_dim_) |
| 36 | + ).view(-1, (self.tp_k_head_num_ + self.tp_v_head_num_), self.head_dim_) |
| 37 | + seq_len, _ = q.shape |
| 38 | + q = q.view(1, seq_len, -1, self.head_dim_).transpose(1, 2) |
| 39 | + k = cache_kv[:, : self.tp_k_head_num_, :].view(1, seq_len, -1, self.head_dim_).transpose(1, 2) |
| 40 | + new_q, new_k = apply_multimodal_rotary_pos_emb( |
| 41 | + q, k, infer_state.position_cos, infer_state.position_sin, self.mrope_section |
| 42 | + ) |
| 43 | + new_q = new_q.transpose(1, 2).reshape(1, seq_len, -1) |
| 44 | + cache_kv[:, : self.tp_k_head_num_, :] = new_k.squeeze(0).permute(1, 0, 2) |
| 45 | + |
| 46 | + return new_q, cache_kv |
0 commit comments