modular_glm.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. # Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
  2. #
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import Optional
  16. import torch
  17. import torch.nn as nn
  18. from ...utils import logging
  19. from ..llama.modeling_llama import (
  20. LlamaAttention,
  21. LlamaForCausalLM,
  22. LlamaForSequenceClassification,
  23. LlamaForTokenClassification,
  24. LlamaRotaryEmbedding,
  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. class GlmRotaryEmbedding(LlamaRotaryEmbedding):
  33. @staticmethod
  34. def compute_default_rope_parameters(
  35. config: GlmConfig | None = None,
  36. device: Optional["torch.device"] = None,
  37. seq_len: int | None = None,
  38. ) -> tuple["torch.Tensor", float]:
  39. """
  40. Computes the inverse frequencies according to the original RoPE implementation
  41. Args:
  42. config ([`~transformers.PreTrainedConfig`]):
  43. The model configuration.
  44. device (`torch.device`):
  45. The device to use for initialization of the inverse frequencies.
  46. seq_len (`int`, *optional*):
  47. The current sequence length. Unused for this type of RoPE.
  48. Returns:
  49. Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
  50. post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
  51. """
  52. base = config.rope_parameters["rope_theta"]
  53. partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
  54. head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  55. dim = int(head_dim * partial_rotary_factor)
  56. attention_factor = 1.0 # Unused in this type of RoPE
  57. # Compute the inverse frequencies
  58. inv_freq = 1.0 / (
  59. base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
  60. )
  61. return inv_freq, attention_factor
  62. def rotate_half(x):
  63. """Rotates half the hidden dims of the input."""
  64. x1 = x[..., 0::2]
  65. x2 = x[..., 1::2]
  66. return torch.stack((-x2, x1), dim=-1).flatten(-2)
  67. def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
  68. """Applies Rotary Position Embedding to the query and key tensors.
  69. Args:
  70. q (`torch.Tensor`): The query tensor.
  71. k (`torch.Tensor`): The key tensor.
  72. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  73. sin (`torch.Tensor`): The sine part of the rotary embedding.
  74. unsqueeze_dim (`int`, *optional*, defaults to 1):
  75. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  76. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  77. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  78. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  79. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  80. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  81. Returns:
  82. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  83. """
  84. cos = cos.unsqueeze(unsqueeze_dim)
  85. sin = sin.unsqueeze(unsqueeze_dim)
  86. # Interleave them instead of usual shape
  87. cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
  88. sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
  89. # Keep half or full tensor for later concatenation
  90. rotary_dim = cos.shape[-1]
  91. q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
  92. k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
  93. # Apply rotary embeddings on the first half or full tensor
  94. q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
  95. k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
  96. # Concatenate back to full shape
  97. q_embed = torch.cat([q_embed, q_pass], dim=-1)
  98. k_embed = torch.cat([k_embed, k_pass], dim=-1)
  99. return q_embed, k_embed
  100. class GlmAttention(LlamaAttention):
  101. def __init__(self, config: GlmConfig, layer_idx: int | None = None):
  102. super().__init__(config, layer_idx)
  103. self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  104. class GlmForCausalLM(LlamaForCausalLM):
  105. pass
  106. class GlmForSequenceClassification(LlamaForSequenceClassification):
  107. pass
  108. class GlmForTokenClassification(LlamaForTokenClassification):
  109. pass
  110. __all__ = [
  111. "GlmPreTrainedModel", # noqa: F822
  112. "GlmModel", # noqa: F822
  113. "GlmForCausalLM",
  114. "GlmForSequenceClassification",
  115. "GlmForTokenClassification",
  116. ]