modular_glm.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # coding=utf-8
  2. # Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
  3. #
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from typing import Optional
  17. import torch
  18. import torch.nn as nn
  19. from ...utils import logging
  20. from ..llama.modeling_llama import (
  21. LlamaAttention,
  22. LlamaForCausalLM,
  23. LlamaForSequenceClassification,
  24. LlamaForTokenClassification,
  25. )
  26. from ..phi3.modeling_phi3 import Phi3MLP
  27. from .configuration_glm import GlmConfig
  28. logger = logging.get_logger(__name__)
  29. _CHECKPOINT_FOR_DOC = "THUDM/glm-4-9b"
  30. class GlmMLP(Phi3MLP):
  31. pass
  32. def rotate_half(x):
  33. """Rotates half the hidden dims of the input."""
  34. x1 = x[..., 0::2]
  35. x2 = x[..., 1::2]
  36. return torch.stack((-x2, x1), dim=-1).flatten(-2)
  37. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  38. """Applies Rotary Position Embedding to the query and key tensors.
  39. Args:
  40. q (`torch.Tensor`): The query tensor.
  41. k (`torch.Tensor`): The key tensor.
  42. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  43. sin (`torch.Tensor`): The sine part of the rotary embedding.
  44. position_ids (`torch.Tensor`, *optional*):
  45. Deprecated and unused.
  46. unsqueeze_dim (`int`, *optional*, defaults to 1):
  47. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  48. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  49. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  50. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  51. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  52. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  53. Returns:
  54. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  55. """
  56. cos = cos.unsqueeze(unsqueeze_dim)
  57. sin = sin.unsqueeze(unsqueeze_dim)
  58. # Interleave them instead of usual shape
  59. cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
  60. sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
  61. # Keep half or full tensor for later concatenation
  62. rotary_dim = cos.shape[-1]
  63. q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
  64. k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
  65. # Apply rotary embeddings on the first half or full tensor
  66. q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
  67. k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
  68. # Concatenate back to full shape
  69. q_embed = torch.cat([q_embed, q_pass], dim=-1)
  70. k_embed = torch.cat([k_embed, k_pass], dim=-1)
  71. return q_embed, k_embed
  72. class GlmAttention(LlamaAttention):
  73. def __init__(self, config: GlmConfig, layer_idx: Optional[int] = None):
  74. super().__init__(config, layer_idx)
  75. self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  76. class GlmForCausalLM(LlamaForCausalLM):
  77. pass
  78. class GlmForSequenceClassification(LlamaForSequenceClassification):
  79. pass
  80. class GlmForTokenClassification(LlamaForTokenClassification):
  81. pass
  82. __all__ = [
  83. "GlmPreTrainedModel", # noqa: F822
  84. "GlmModel", # noqa: F822
  85. "GlmForCausalLM",
  86. "GlmForSequenceClassification",
  87. "GlmForTokenClassification",
  88. ]