decilm.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
  4. # Copyright 2023 The PygmalionAI team.
  5. # Copyright 2023 DeciAI Research Team. All rights reserved.
  6. # Copyright 2023 The vLLM team.
  7. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  8. #
  9. # This code is based on MistralAI GPT-NeoX library and the GPT-NeoX
  10. # and OPT implementations in this library. It has been modified from its
  11. # original forms to accommodate minor architectural differences compared
  12. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. """Inference-only DeciLM model compatible with HuggingFace weights."""
  26. from typing import Optional
  27. import torch
  28. from transformers import PretrainedConfig
  29. from aphrodite.common.config import LoRAConfig
  30. from aphrodite.modeling.layers.linear import LinearMethodBase
  31. from aphrodite.modeling.models.llama import LlamaForCausalLM
  32. from aphrodite.modeling.hf_downloader import (default_weight_loader,
  33. hf_model_weights_iterator)
  34. class DeciLMForCausalLM(LlamaForCausalLM):
  35. """
  36. Implementation for https://huggingface.co/Deci/DeciLM-7b-instruct.
  37. Based on the llama executor.
  38. The main difference is that DeciLM uses Variable Grouped Query Attention.
  39. The constant number of GQA heads in the decoder is overridden with a value
  40. per layer.
  41. Usually, in the HuggingFace implementation, instead of
  42. "config.num_key_value_heads", we use
  43. "config.num_key_value_heads_per_layer[i]" which varies.
  44. Currently, PagedAttention does not work well with variable GQA, so we
  45. normalize the weights upon loading, and use uniform GQA with the max value
  46. instead.
  47. """
  48. def __init__(
  49. self,
  50. config: Optional[PretrainedConfig] = None,
  51. linear_method: Optional[LinearMethodBase] = None,
  52. lora_config: Optional[LoRAConfig] = None,
  53. ) -> None:
  54. config.num_key_value_heads = max(config.num_key_value_heads_per_layer)
  55. delattr(config, "num_key_value_heads_per_layer")
  56. super().__init__(config=config,
  57. linear_method=linear_method,
  58. lora_config=lora_config)
  59. def load_weights(self,
  60. model_name_or_path: str,
  61. cache_dir: Optional[str] = None,
  62. load_format: str = "auto",
  63. revision: Optional[str] = None):
  64. stacked_params_mapping = [
  65. # (param_name, shard_name, shard_id)
  66. ("qkv_proj", "q_proj", "q"),
  67. ("qkv_proj", "k_proj", "k"),
  68. ("qkv_proj", "v_proj", "v"),
  69. ("gate_up_proj", "gate_proj", 0),
  70. ("gate_up_proj", "up_proj", 1),
  71. ]
  72. params_dict = dict(self.named_parameters())
  73. for name, loaded_weight in hf_model_weights_iterator(
  74. model_name_or_path, cache_dir, load_format, revision,
  75. self.config):
  76. if "rotary_emb.inv_freq" in name:
  77. continue
  78. if "k_proj" in name or "v_proj" in name:
  79. loaded_weight = self._degroup_weight(loaded_weight)
  80. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  81. if weight_name not in name:
  82. continue
  83. name = name.replace(weight_name, param_name)
  84. # Skip loading extra bias for GPTQ models.
  85. if name.endswith(".bias") and name not in params_dict:
  86. continue
  87. param = params_dict[name]
  88. weight_loader = param.weight_loader
  89. weight_loader(param, loaded_weight, shard_id)
  90. break
  91. else:
  92. # Skip loading extra bias for GPTQ models.
  93. if name.endswith(".bias") and name not in params_dict:
  94. continue
  95. param = params_dict[name]
  96. weight_loader = getattr(param, "weight_loader",
  97. default_weight_loader)
  98. weight_loader(param, loaded_weight)
  99. def _degroup_weight(self, loaded_weight: torch.Tensor) -> torch.Tensor:
  100. hidden_size = self.config.hidden_size
  101. head_size = self.config.hidden_size // self.config.num_attention_heads
  102. target_num_kv_heads = self.config.num_key_value_heads
  103. num_kv_heads = loaded_weight.shape[0] // head_size
  104. n_repeats = target_num_kv_heads / num_kv_heads
  105. assert n_repeats == int(n_repeats)
  106. n_repeats = int(n_repeats)
  107. loaded_weight = loaded_weight.view(num_kv_heads, head_size,
  108. hidden_size)
  109. loaded_weight = torch.repeat_interleave(loaded_weight,
  110. repeats=n_repeats,
  111. dim=0)
  112. loaded_weight = loaded_weight.reshape(target_num_kv_heads * head_size,
  113. hidden_size)
  114. return loaded_weight