vllm-npu 0.4.2__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (219) hide show
  1. vllm/__init__.py +23 -0
  2. vllm/_custom_ops.py +251 -0
  3. vllm/attention/__init__.py +13 -0
  4. vllm/attention/backends/__init__.py +0 -0
  5. vllm/attention/backends/abstract.py +127 -0
  6. vllm/attention/backends/flash_attn.py +271 -0
  7. vllm/attention/backends/flashinfer.py +220 -0
  8. vllm/attention/backends/rocm_flash_attn.py +374 -0
  9. vllm/attention/backends/torch_sdpa.py +250 -0
  10. vllm/attention/backends/xformers.py +393 -0
  11. vllm/attention/layer.py +56 -0
  12. vllm/attention/ops/__init__.py +0 -0
  13. vllm/attention/ops/paged_attn.py +216 -0
  14. vllm/attention/ops/prefix_prefill.py +792 -0
  15. vllm/attention/ops/triton_flash_attention.py +810 -0
  16. vllm/attention/selector.py +91 -0
  17. vllm/block.py +84 -0
  18. vllm/config.py +1225 -0
  19. vllm/core/__init__.py +0 -0
  20. vllm/core/block/__init__.py +0 -0
  21. vllm/core/block/block_table.py +295 -0
  22. vllm/core/block/common.py +199 -0
  23. vllm/core/block/cpu_gpu_block_allocator.py +228 -0
  24. vllm/core/block/interfaces.py +205 -0
  25. vllm/core/block/naive_block.py +318 -0
  26. vllm/core/block/prefix_caching_block.py +606 -0
  27. vllm/core/block_manager_v1.py +625 -0
  28. vllm/core/block_manager_v2.py +258 -0
  29. vllm/core/evictor_v1.py +105 -0
  30. vllm/core/evictor_v2.py +127 -0
  31. vllm/core/interfaces.py +113 -0
  32. vllm/core/policy.py +45 -0
  33. vllm/core/scheduler.py +1163 -0
  34. vllm/distributed/__init__.py +3 -0
  35. vllm/distributed/communication_op.py +237 -0
  36. vllm/distributed/device_communicators/__init__.py +0 -0
  37. vllm/distributed/device_communicators/custom_all_reduce.py +274 -0
  38. vllm/distributed/device_communicators/pynccl.py +287 -0
  39. vllm/distributed/device_communicators/pynccl_utils.py +66 -0
  40. vllm/distributed/parallel_state.py +339 -0
  41. vllm/distributed/utils.py +136 -0
  42. vllm/engine/__init__.py +0 -0
  43. vllm/engine/arg_utils.py +649 -0
  44. vllm/engine/async_llm_engine.py +737 -0
  45. vllm/engine/llm_engine.py +784 -0
  46. vllm/engine/metrics.py +368 -0
  47. vllm/engine/output_processor/__init__.py +0 -0
  48. vllm/engine/output_processor/interfaces.py +76 -0
  49. vllm/engine/output_processor/multi_step.py +142 -0
  50. vllm/engine/output_processor/single_step.py +284 -0
  51. vllm/engine/output_processor/stop_checker.py +101 -0
  52. vllm/engine/output_processor/util.py +19 -0
  53. vllm/entrypoints/__init__.py +0 -0
  54. vllm/entrypoints/api_server.py +119 -0
  55. vllm/entrypoints/llm.py +259 -0
  56. vllm/entrypoints/openai/__init__.py +0 -0
  57. vllm/entrypoints/openai/api_server.py +186 -0
  58. vllm/entrypoints/openai/cli_args.py +115 -0
  59. vllm/entrypoints/openai/protocol.py +460 -0
  60. vllm/entrypoints/openai/serving_chat.py +392 -0
  61. vllm/entrypoints/openai/serving_completion.py +347 -0
  62. vllm/entrypoints/openai/serving_engine.py +234 -0
  63. vllm/envs.py +217 -0
  64. vllm/executor/__init__.py +0 -0
  65. vllm/executor/cpu_executor.py +152 -0
  66. vllm/executor/distributed_gpu_executor.py +115 -0
  67. vllm/executor/executor_base.py +115 -0
  68. vllm/executor/gpu_executor.py +150 -0
  69. vllm/executor/multiproc_worker_utils.py +263 -0
  70. vllm/executor/neuron_executor.py +91 -0
  71. vllm/executor/ray_gpu_executor.py +327 -0
  72. vllm/executor/ray_utils.py +119 -0
  73. vllm/logger.py +153 -0
  74. vllm/logging/__init__.py +5 -0
  75. vllm/logging/formatter.py +15 -0
  76. vllm/lora/__init__.py +0 -0
  77. vllm/lora/fully_sharded_layers.py +262 -0
  78. vllm/lora/layers.py +1181 -0
  79. vllm/lora/lora.py +167 -0
  80. vllm/lora/models.py +645 -0
  81. vllm/lora/punica.py +213 -0
  82. vllm/lora/request.py +32 -0
  83. vllm/lora/utils.py +98 -0
  84. vllm/lora/worker_manager.py +251 -0
  85. vllm/model_executor/__init__.py +7 -0
  86. vllm/model_executor/guided_decoding/__init__.py +25 -0
  87. vllm/model_executor/guided_decoding/lm_format_enforcer_decoding.py +70 -0
  88. vllm/model_executor/guided_decoding/outlines_decoding.py +130 -0
  89. vllm/model_executor/guided_decoding/outlines_logits_processors.py +184 -0
  90. vllm/model_executor/layers/__init__.py +0 -0
  91. vllm/model_executor/layers/activation.py +173 -0
  92. vllm/model_executor/layers/fused_moe/__init__.py +7 -0
  93. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  94. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  95. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  96. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  97. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  98. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  99. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  100. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  101. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  102. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  103. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  104. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  105. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=float8.json +140 -0
  106. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  107. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  108. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  109. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  110. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=float8.json +146 -0
  111. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  112. vllm/model_executor/layers/fused_moe/fused_moe.py +479 -0
  113. vllm/model_executor/layers/layernorm.py +71 -0
  114. vllm/model_executor/layers/linear.py +709 -0
  115. vllm/model_executor/layers/logits_processor.py +115 -0
  116. vllm/model_executor/layers/ops/__init__.py +0 -0
  117. vllm/model_executor/layers/ops/rand.py +157 -0
  118. vllm/model_executor/layers/ops/sample.py +406 -0
  119. vllm/model_executor/layers/quantization/__init__.py +35 -0
  120. vllm/model_executor/layers/quantization/aqlm.py +376 -0
  121. vllm/model_executor/layers/quantization/awq.py +175 -0
  122. vllm/model_executor/layers/quantization/base_config.py +97 -0
  123. vllm/model_executor/layers/quantization/fp8.py +265 -0
  124. vllm/model_executor/layers/quantization/gptq.py +224 -0
  125. vllm/model_executor/layers/quantization/gptq_marlin.py +438 -0
  126. vllm/model_executor/layers/quantization/marlin.py +227 -0
  127. vllm/model_executor/layers/quantization/schema.py +84 -0
  128. vllm/model_executor/layers/quantization/squeezellm.py +137 -0
  129. vllm/model_executor/layers/rejection_sampler.py +405 -0
  130. vllm/model_executor/layers/rotary_embedding.py +525 -0
  131. vllm/model_executor/layers/sampler.py +1051 -0
  132. vllm/model_executor/layers/vocab_parallel_embedding.py +155 -0
  133. vllm/model_executor/model_loader/__init__.py +30 -0
  134. vllm/model_executor/model_loader/loader.py +362 -0
  135. vllm/model_executor/model_loader/neuron.py +136 -0
  136. vllm/model_executor/model_loader/tensorizer.py +368 -0
  137. vllm/model_executor/model_loader/utils.py +41 -0
  138. vllm/model_executor/model_loader/weight_utils.py +372 -0
  139. vllm/model_executor/models/__init__.py +119 -0
  140. vllm/model_executor/models/baichuan.py +410 -0
  141. vllm/model_executor/models/bloom.py +327 -0
  142. vllm/model_executor/models/chatglm.py +386 -0
  143. vllm/model_executor/models/commandr.py +373 -0
  144. vllm/model_executor/models/dbrx.py +413 -0
  145. vllm/model_executor/models/decilm.py +122 -0
  146. vllm/model_executor/models/deepseek.py +438 -0
  147. vllm/model_executor/models/falcon.py +444 -0
  148. vllm/model_executor/models/gemma.py +393 -0
  149. vllm/model_executor/models/gpt2.py +266 -0
  150. vllm/model_executor/models/gpt_bigcode.py +274 -0
  151. vllm/model_executor/models/gpt_j.py +281 -0
  152. vllm/model_executor/models/gpt_neox.py +295 -0
  153. vllm/model_executor/models/internlm2.py +323 -0
  154. vllm/model_executor/models/jais.py +333 -0
  155. vllm/model_executor/models/llama.py +442 -0
  156. vllm/model_executor/models/llava.py +239 -0
  157. vllm/model_executor/models/minicpm.py +531 -0
  158. vllm/model_executor/models/mixtral.py +583 -0
  159. vllm/model_executor/models/mixtral_quant.py +404 -0
  160. vllm/model_executor/models/mpt.py +295 -0
  161. vllm/model_executor/models/olmo.py +356 -0
  162. vllm/model_executor/models/opt.py +349 -0
  163. vllm/model_executor/models/orion.py +319 -0
  164. vllm/model_executor/models/phi.py +300 -0
  165. vllm/model_executor/models/qwen.py +284 -0
  166. vllm/model_executor/models/qwen2.py +367 -0
  167. vllm/model_executor/models/qwen2_moe.py +447 -0
  168. vllm/model_executor/models/stablelm.py +301 -0
  169. vllm/model_executor/models/starcoder2.py +302 -0
  170. vllm/model_executor/models/xverse.py +366 -0
  171. vllm/model_executor/sampling_metadata.py +588 -0
  172. vllm/model_executor/utils.py +35 -0
  173. vllm/outputs.py +150 -0
  174. vllm/py.typed +2 -0
  175. vllm/sampling_params.py +340 -0
  176. vllm/sequence.py +766 -0
  177. vllm/spec_decode/__init__.py +0 -0
  178. vllm/spec_decode/batch_expansion.py +397 -0
  179. vllm/spec_decode/interfaces.py +73 -0
  180. vllm/spec_decode/metrics.py +191 -0
  181. vllm/spec_decode/multi_step_worker.py +203 -0
  182. vllm/spec_decode/ngram_worker.py +176 -0
  183. vllm/spec_decode/spec_decode_worker.py +472 -0
  184. vllm/spec_decode/top1_proposer.py +200 -0
  185. vllm/spec_decode/util.py +228 -0
  186. vllm/test_utils.py +41 -0
  187. vllm/transformers_utils/__init__.py +0 -0
  188. vllm/transformers_utils/config.py +58 -0
  189. vllm/transformers_utils/configs/__init__.py +16 -0
  190. vllm/transformers_utils/configs/chatglm.py +68 -0
  191. vllm/transformers_utils/configs/dbrx.py +278 -0
  192. vllm/transformers_utils/configs/falcon.py +87 -0
  193. vllm/transformers_utils/configs/jais.py +236 -0
  194. vllm/transformers_utils/configs/mpt.py +178 -0
  195. vllm/transformers_utils/detokenizer.py +313 -0
  196. vllm/transformers_utils/tokenizer.py +149 -0
  197. vllm/transformers_utils/tokenizer_group/__init__.py +33 -0
  198. vllm/transformers_utils/tokenizer_group/base_tokenizer_group.py +55 -0
  199. vllm/transformers_utils/tokenizer_group/ray_tokenizer_group.py +169 -0
  200. vllm/transformers_utils/tokenizer_group/tokenizer_group.py +78 -0
  201. vllm/transformers_utils/tokenizers/__init__.py +5 -0
  202. vllm/transformers_utils/tokenizers/baichuan.py +255 -0
  203. vllm/usage/__init__.py +0 -0
  204. vllm/usage/usage_lib.py +209 -0
  205. vllm/utils.py +677 -0
  206. vllm/worker/__init__.py +0 -0
  207. vllm/worker/cache_engine.py +105 -0
  208. vllm/worker/cpu_model_runner.py +346 -0
  209. vllm/worker/cpu_worker.py +321 -0
  210. vllm/worker/model_runner.py +1168 -0
  211. vllm/worker/neuron_model_runner.py +196 -0
  212. vllm/worker/neuron_worker.py +98 -0
  213. vllm/worker/worker.py +345 -0
  214. vllm/worker/worker_base.py +146 -0
  215. vllm_npu-0.4.2.dist-info/LICENSE +201 -0
  216. vllm_npu-0.4.2.dist-info/METADATA +173 -0
  217. vllm_npu-0.4.2.dist-info/RECORD +219 -0
  218. vllm_npu-0.4.2.dist-info/WHEEL +5 -0
  219. vllm_npu-0.4.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,531 @@
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 vLLM team.
5
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
6
+ #
7
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
8
+ # and OPT implementations in this library. It has been modified from its
9
+ # original forms to accommodate minor architectural differences compared
10
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+ """Inference-only MiniCPM model compatible with HuggingFace weights."""
24
+ import math
25
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
26
+
27
+ import torch
28
+ from torch import nn
29
+
30
+ from vllm.attention import Attention, AttentionMetadata
31
+ from vllm.config import LoRAConfig
32
+ from vllm.distributed import (get_tensor_model_parallel_rank,
33
+ get_tensor_model_parallel_world_size,
34
+ tensor_model_parallel_all_reduce)
35
+ from vllm.model_executor.layers.activation import SiluAndMul
36
+ from vllm.model_executor.layers.fused_moe import fused_moe
37
+ from vllm.model_executor.layers.layernorm import RMSNorm
38
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
39
+ QKVParallelLinear,
40
+ ReplicatedLinear,
41
+ RowParallelLinear)
42
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
43
+ from vllm.model_executor.layers.quantization.base_config import (
44
+ QuantizationConfig)
45
+ from vllm.model_executor.layers.rotary_embedding import get_rope
46
+ from vllm.model_executor.layers.sampler import Sampler
47
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
48
+ DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
49
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
50
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
51
+ from vllm.model_executor.utils import set_weight_attrs
52
+ from vllm.sequence import SamplerOutput
53
+
54
+
55
+ class MiniCPMMoE(nn.Module):
56
+ """A tensor-parallel MoE implementation that shards each expert
57
+ across all ranks.
58
+
59
+ Each expert's weights are sharded across all ranks and a fused MoE
60
+ kernel is used for the forward pass, and finally we reduce the outputs
61
+ across ranks.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ num_experts: int,
67
+ top_k: int,
68
+ hidden_size: int,
69
+ intermediate_size: int,
70
+ params_dtype: Optional[torch.dtype] = None,
71
+ tp_size: Optional[int] = None,
72
+ ):
73
+ super().__init__()
74
+ self.tp_size = tp_size or get_tensor_model_parallel_world_size()
75
+ self.num_total_experts = num_experts
76
+ self.top_k = top_k
77
+ self.hidden_size = hidden_size
78
+ self.intermediate_size = intermediate_size // self.tp_size
79
+
80
+ if params_dtype is None:
81
+ params_dtype = torch.get_default_dtype()
82
+ self.params_dtype = params_dtype
83
+
84
+ self.gate = ReplicatedLinear(self.hidden_size,
85
+ self.num_total_experts,
86
+ bias=False,
87
+ params_dtype=self.params_dtype,
88
+ quant_config=None)
89
+
90
+ self.ws = nn.Parameter(
91
+ torch.empty(self.num_total_experts,
92
+ 2 * self.intermediate_size,
93
+ self.hidden_size,
94
+ device="cuda",
95
+ dtype=self.params_dtype))
96
+ self.w2s = nn.Parameter(
97
+ torch.empty(self.num_total_experts,
98
+ self.hidden_size,
99
+ self.intermediate_size,
100
+ device="cuda",
101
+ dtype=self.params_dtype))
102
+
103
+ set_weight_attrs(self.ws, {
104
+ "weight_loader": self.weight_loader,
105
+ })
106
+ set_weight_attrs(self.w2s, {
107
+ "weight_loader": self.weight_loader,
108
+ })
109
+
110
+ def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor,
111
+ weight_name: str, expert_id: int):
112
+ tp_rank = get_tensor_model_parallel_rank()
113
+ param_data = param.data
114
+ shard_size = self.intermediate_size
115
+ shard = slice(tp_rank * shard_size, (tp_rank + 1) * shard_size)
116
+ if weight_name.endswith("w1.weight"):
117
+ param_data[expert_id, 0:shard_size, :] = loaded_weight[shard, :]
118
+ if weight_name.endswith("w3.weight"):
119
+ param_data[expert_id,
120
+ shard_size:2 * shard_size, :] = loaded_weight[shard, :]
121
+ if weight_name.endswith("w2.weight"):
122
+ param_data[expert_id, :, :] = loaded_weight[:, shard]
123
+
124
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
125
+ num_tokens, hidden_size = hidden_states.shape
126
+ hidden_states = hidden_states.view(-1, self.hidden_size)
127
+ # router_logits: (num_tokens, n_experts)
128
+ router_logits, _ = self.gate(hidden_states)
129
+ final_hidden_states = fused_moe(hidden_states,
130
+ self.ws,
131
+ self.w2s,
132
+ router_logits,
133
+ self.top_k,
134
+ renormalize=True,
135
+ inplace=True)
136
+
137
+ if self.tp_size > 1:
138
+ final_hidden_states = tensor_model_parallel_all_reduce(
139
+ final_hidden_states)
140
+
141
+ return final_hidden_states.view(num_tokens, hidden_size)
142
+
143
+
144
+ class MiniCPMMLP(nn.Module):
145
+
146
+ def __init__(
147
+ self,
148
+ hidden_size: int,
149
+ intermediate_size: int,
150
+ hidden_act: str,
151
+ quant_config: Optional[QuantizationConfig] = None,
152
+ ) -> None:
153
+ super().__init__()
154
+ self.gate_up_proj = MergedColumnParallelLinear(
155
+ hidden_size, [intermediate_size] * 2,
156
+ bias=False,
157
+ quant_config=quant_config)
158
+ self.down_proj = RowParallelLinear(intermediate_size,
159
+ hidden_size,
160
+ bias=False,
161
+ quant_config=quant_config)
162
+ if hidden_act != "silu":
163
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
164
+ "Only silu is supported for now.")
165
+ self.act_fn = SiluAndMul()
166
+
167
+ def forward(self, x):
168
+ gate_up, _ = self.gate_up_proj(x)
169
+ x = self.act_fn(gate_up)
170
+ x, _ = self.down_proj(x)
171
+ return x
172
+
173
+
174
+ class MiniCPMAttention(nn.Module):
175
+
176
+ def __init__(
177
+ self,
178
+ hidden_size: int,
179
+ num_heads: int,
180
+ num_kv_heads: int,
181
+ rope_theta: float = 10000,
182
+ rope_scaling: Optional[Dict[str, Any]] = None,
183
+ max_position_embeddings: int = 8192,
184
+ quant_config: Optional[QuantizationConfig] = None,
185
+ ) -> None:
186
+ super().__init__()
187
+ self.hidden_size = hidden_size
188
+ tp_size = get_tensor_model_parallel_world_size()
189
+ self.total_num_heads = num_heads
190
+ assert self.total_num_heads % tp_size == 0
191
+ self.num_heads = self.total_num_heads // tp_size
192
+ self.total_num_kv_heads = num_kv_heads
193
+ if self.total_num_kv_heads >= tp_size:
194
+ # Number of KV heads is greater than TP size, so we partition
195
+ # the KV heads across multiple tensor parallel GPUs.
196
+ assert self.total_num_kv_heads % tp_size == 0
197
+ else:
198
+ # Number of KV heads is less than TP size, so we replicate
199
+ # the KV heads across multiple tensor parallel GPUs.
200
+ assert tp_size % self.total_num_kv_heads == 0
201
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
202
+ self.head_dim = hidden_size // self.total_num_heads
203
+ self.q_size = self.num_heads * self.head_dim
204
+ self.kv_size = self.num_kv_heads * self.head_dim
205
+ self.scaling = self.head_dim**-0.5
206
+ self.rope_theta = rope_theta
207
+ self.max_position_embeddings = max_position_embeddings
208
+
209
+ self.qkv_proj = QKVParallelLinear(
210
+ hidden_size,
211
+ self.head_dim,
212
+ self.total_num_heads,
213
+ self.total_num_kv_heads,
214
+ bias=False,
215
+ quant_config=quant_config,
216
+ )
217
+ self.o_proj = RowParallelLinear(
218
+ self.total_num_heads * self.head_dim,
219
+ hidden_size,
220
+ bias=False,
221
+ quant_config=quant_config,
222
+ )
223
+
224
+ self.rotary_emb = get_rope(
225
+ self.head_dim,
226
+ rotary_dim=self.head_dim,
227
+ max_position=max_position_embeddings,
228
+ base=rope_theta,
229
+ rope_scaling=rope_scaling,
230
+ )
231
+ # set rope as fp32 instead of bf16
232
+ self.rotary_emb.cos_sin_cache = self.rotary_emb._compute_cos_sin_cache(
233
+ )
234
+ self.attn = Attention(self.num_heads,
235
+ self.head_dim,
236
+ self.scaling,
237
+ num_kv_heads=self.num_kv_heads)
238
+
239
+ def forward(
240
+ self,
241
+ positions: torch.Tensor,
242
+ hidden_states: torch.Tensor,
243
+ kv_cache: torch.Tensor,
244
+ attn_metadata: AttentionMetadata,
245
+ ) -> torch.Tensor:
246
+ qkv, _ = self.qkv_proj(hidden_states)
247
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
248
+ orig_dtype = q.dtype
249
+ q, k = q.float(), k.float()
250
+ q, k = self.rotary_emb(positions, q, k)
251
+ q, k = q.to(orig_dtype), k.to(orig_dtype)
252
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
253
+ output, _ = self.o_proj(attn_output)
254
+ return output
255
+
256
+
257
+ class MiniCPMDecoderLayer(nn.Module):
258
+
259
+ def __init__(
260
+ self,
261
+ config,
262
+ quant_config: Optional[QuantizationConfig] = None,
263
+ ) -> None:
264
+ super().__init__()
265
+ self.config = config
266
+ self.hidden_size = config.hidden_size
267
+ rope_theta = getattr(config, "rope_theta", 10000)
268
+ rope_scaling = getattr(config, "rope_scaling", None)
269
+ max_position_embeddings = getattr(config, "max_position_embeddings",
270
+ 8192)
271
+ self.self_attn = MiniCPMAttention(
272
+ hidden_size=self.hidden_size,
273
+ num_heads=config.num_attention_heads,
274
+ num_kv_heads=config.num_key_value_heads,
275
+ rope_theta=rope_theta,
276
+ rope_scaling=rope_scaling,
277
+ max_position_embeddings=max_position_embeddings,
278
+ quant_config=quant_config,
279
+ )
280
+ self.num_experts = getattr(self.config, "num_experts", 0)
281
+ if self.num_experts == 0:
282
+ self.mlp = MiniCPMMLP(
283
+ hidden_size=self.hidden_size,
284
+ intermediate_size=config.intermediate_size,
285
+ hidden_act=config.hidden_act,
286
+ quant_config=quant_config,
287
+ )
288
+ else:
289
+ self.mlp = MiniCPMMoE(num_experts=config.num_experts,
290
+ top_k=config.num_experts_per_tok,
291
+ hidden_size=config.hidden_size,
292
+ intermediate_size=config.intermediate_size)
293
+ self.input_layernorm = RMSNorm(config.hidden_size,
294
+ eps=config.rms_norm_eps)
295
+ self.post_attention_layernorm = RMSNorm(config.hidden_size,
296
+ eps=config.rms_norm_eps)
297
+
298
+ def forward(
299
+ self,
300
+ positions: torch.Tensor,
301
+ hidden_states: torch.Tensor,
302
+ kv_cache: torch.Tensor,
303
+ attn_metadata: AttentionMetadata,
304
+ residual: Optional[torch.Tensor],
305
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
306
+ # Self Attention
307
+ residual = hidden_states
308
+ hidden_states = self.input_layernorm(hidden_states)
309
+ hidden_states = self.self_attn(
310
+ positions=positions,
311
+ hidden_states=hidden_states,
312
+ kv_cache=kv_cache,
313
+ attn_metadata=attn_metadata,
314
+ )
315
+ hidden_states = residual + hidden_states * \
316
+ (self.config.scale_depth / math.sqrt(self.config.num_hidden_layers))
317
+
318
+ # Fully Connected
319
+ residual = hidden_states
320
+ hidden_states = self.post_attention_layernorm(hidden_states)
321
+ hidden_states = self.mlp(hidden_states)
322
+ hidden_states = residual + hidden_states * \
323
+ (self.config.scale_depth / math.sqrt(self.config.num_hidden_layers))
324
+
325
+ return hidden_states, None
326
+
327
+
328
+ class MiniCPMModel(nn.Module):
329
+
330
+ def __init__(
331
+ self,
332
+ config,
333
+ quant_config: Optional[QuantizationConfig] = None,
334
+ lora_config: Optional[LoRAConfig] = None,
335
+ ) -> None:
336
+ super().__init__()
337
+ self.config = config
338
+ self.padding_idx = config.pad_token_id
339
+ lora_vocab = (lora_config.lora_extra_vocab_size *
340
+ (lora_config.max_loras or 1)) if lora_config else 0
341
+ self.vocab_size = config.vocab_size + lora_vocab
342
+ self.org_vocab_size = config.vocab_size
343
+ self.embed_tokens = VocabParallelEmbedding(
344
+ self.vocab_size,
345
+ config.hidden_size,
346
+ org_num_embeddings=config.vocab_size,
347
+ )
348
+ self.layers = nn.ModuleList([
349
+ MiniCPMDecoderLayer(config, quant_config)
350
+ for _ in range(config.num_hidden_layers)
351
+ ])
352
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
353
+
354
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
355
+ embedding = self.embed_tokens(input_ids)
356
+ return embedding * self.config.scale_emb
357
+
358
+ def forward(
359
+ self,
360
+ input_ids: torch.Tensor,
361
+ positions: torch.Tensor,
362
+ kv_caches: List[torch.Tensor],
363
+ attn_metadata: AttentionMetadata,
364
+ inputs_embeds: Optional[torch.Tensor] = None,
365
+ ) -> torch.Tensor:
366
+ if inputs_embeds is not None:
367
+ hidden_states = inputs_embeds
368
+ else:
369
+ hidden_states = self.get_input_embeddings(input_ids)
370
+ residual = None
371
+
372
+ for i in range(len(self.layers)):
373
+ layer = self.layers[i]
374
+ hidden_states, residual = layer(
375
+ positions,
376
+ hidden_states,
377
+ kv_caches[i],
378
+ attn_metadata,
379
+ residual,
380
+ )
381
+ hidden_states = self.norm(hidden_states)
382
+ return hidden_states
383
+
384
+
385
+ class MiniCPMForCausalLM(nn.Module):
386
+ packed_modules_mapping = {
387
+ "qkv_proj": [
388
+ "q_proj",
389
+ "k_proj",
390
+ "v_proj",
391
+ ],
392
+ "gate_up_proj": [
393
+ "gate_proj",
394
+ "up_proj",
395
+ ],
396
+ }
397
+
398
+ # LoRA specific attributes
399
+ supported_lora_modules = [
400
+ "qkv_proj",
401
+ "o_proj",
402
+ "gate_up_proj",
403
+ "down_proj",
404
+ "embed_tokens",
405
+ "lm_head",
406
+ ]
407
+ embedding_modules = {
408
+ "embed_tokens": "input_embeddings",
409
+ "lm_head": "output_embeddings",
410
+ }
411
+ embedding_padding_modules = ["lm_head"]
412
+
413
+ def __init__(
414
+ self,
415
+ config,
416
+ quant_config: Optional[QuantizationConfig] = None,
417
+ lora_config: Optional[LoRAConfig] = None,
418
+ ) -> None:
419
+ super().__init__()
420
+ self.config = config
421
+ self.num_experts = getattr(self.config, "num_experts", 0)
422
+ self.quant_config = quant_config
423
+ self.model = MiniCPMModel(config,
424
+ quant_config,
425
+ lora_config=lora_config)
426
+ unpadded_vocab_size = config.vocab_size
427
+ if lora_config:
428
+ unpadded_vocab_size += lora_config.lora_extra_vocab_size
429
+ if not self.config.tie_word_embeddings:
430
+ self.lm_head = ParallelLMHead(
431
+ unpadded_vocab_size,
432
+ config.hidden_size,
433
+ org_num_embeddings=config.vocab_size,
434
+ padding_size=DEFAULT_VOCAB_PADDING_SIZE
435
+ # We need bigger padding if using lora for kernel
436
+ # compatibility
437
+ if not lora_config else lora_config.lora_vocab_padding_size,
438
+ )
439
+ self.scale_width = self.config.hidden_size / self.config.dim_model_base
440
+
441
+ self.logits_processor = LogitsProcessor(unpadded_vocab_size,
442
+ config.vocab_size)
443
+ self.sampler = Sampler()
444
+
445
+ def forward(
446
+ self,
447
+ input_ids: torch.Tensor,
448
+ positions: torch.Tensor,
449
+ kv_caches: List[torch.Tensor],
450
+ attn_metadata: AttentionMetadata,
451
+ ) -> torch.Tensor:
452
+ hidden_states = self.model(input_ids, positions, kv_caches,
453
+ attn_metadata)
454
+ return hidden_states
455
+
456
+ def compute_logits(self, hidden_states: torch.Tensor,
457
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
458
+ hidden_states = hidden_states / self.scale_width
459
+ if self.config.tie_word_embeddings:
460
+ lm_head_weight = self.model.embed_tokens.weight
461
+ else:
462
+ lm_head_weight = self.lm_head.weight
463
+ logits = self.logits_processor(lm_head_weight, hidden_states,
464
+ sampling_metadata)
465
+ return logits
466
+
467
+ def sample(
468
+ self,
469
+ logits: torch.Tensor,
470
+ sampling_metadata: SamplingMetadata,
471
+ ) -> Optional[SamplerOutput]:
472
+ next_tokens = self.sampler(logits, sampling_metadata)
473
+ return next_tokens
474
+
475
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
476
+ stacked_params_mapping = [
477
+ # (param_name, shard_name, shard_id)
478
+ ("qkv_proj", "q_proj", "q"),
479
+ ("qkv_proj", "k_proj", "k"),
480
+ ("qkv_proj", "v_proj", "v"),
481
+ ("gate_up_proj", "gate_proj", 0),
482
+ ("gate_up_proj", "up_proj", 1),
483
+ ]
484
+ expert_params_mapping = [
485
+ # (param_name, weight_name, expert_id)
486
+ ("ws" if weight_name in ["w1", "w3"] else "w2s",
487
+ f"experts.{expert_id}.{weight_name}.weight", expert_id)
488
+ for expert_id in range(self.num_experts)
489
+ for weight_name in ["w1", "w2", "w3"]
490
+ ]
491
+ params_dict = dict(self.named_parameters())
492
+ for name, loaded_weight in weights:
493
+ if "rotary_emb.inv_freq" in name:
494
+ continue
495
+ if ("rotary_emb.cos_cached" in name
496
+ or "rotary_emb.sin_cached" in name):
497
+ # Models trained using ColossalAI may include these tensors in
498
+ # the checkpoint. Skip them.
499
+ continue
500
+
501
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
502
+ if weight_name not in name:
503
+ continue
504
+ name = name.replace(weight_name, param_name)
505
+ # Skip loading extra bias for GPTQ models.
506
+ if name.endswith(".bias") and name not in params_dict:
507
+ continue
508
+ param = params_dict[name]
509
+ weight_loader = param.weight_loader
510
+ weight_loader(param, loaded_weight, shard_id)
511
+ break
512
+ else:
513
+ for param_name, weight_name, expert_id in expert_params_mapping:
514
+ if weight_name not in name:
515
+ continue
516
+ name = name.replace(weight_name, param_name)
517
+ param = params_dict[name]
518
+ weight_loader = param.weight_loader
519
+ weight_loader(param,
520
+ loaded_weight,
521
+ weight_name,
522
+ expert_id=expert_id)
523
+ break
524
+ else:
525
+ # Skip loading extra bias for GPTQ models.
526
+ if name.endswith(".bias") and name not in params_dict:
527
+ continue
528
+ param = params_dict[name]
529
+ weight_loader = getattr(param, "weight_loader",
530
+ default_weight_loader)
531
+ weight_loader(param, loaded_weight)