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,295 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/gpt_neox/modeling_gpt_neox.py
4
+ # Copyright 2023 The vLLM team.
5
+ # Copyright 2022 EleutherAI The HuggingFace Inc. team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """Inference-only GPT-NeoX model compatible with HuggingFace weights."""
19
+ from typing import Iterable, List, Optional, Tuple
20
+
21
+ import torch
22
+ from torch import nn
23
+ from transformers import GPTNeoXConfig
24
+
25
+ from vllm.attention import Attention, AttentionMetadata
26
+ from vllm.distributed import get_tensor_model_parallel_world_size
27
+ from vllm.model_executor.layers.activation import get_act_fn
28
+ from vllm.model_executor.layers.linear import (ColumnParallelLinear,
29
+ QKVParallelLinear,
30
+ RowParallelLinear)
31
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
32
+ from vllm.model_executor.layers.quantization.base_config import (
33
+ QuantizationConfig)
34
+ from vllm.model_executor.layers.rotary_embedding import get_rope
35
+ from vllm.model_executor.layers.sampler import Sampler
36
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
37
+ ParallelLMHead, VocabParallelEmbedding)
38
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
39
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
40
+ from vllm.sequence import SamplerOutput
41
+
42
+
43
+ class GPTNeoXAttention(nn.Module):
44
+
45
+ def __init__(
46
+ self,
47
+ config: GPTNeoXConfig,
48
+ quant_config: Optional[QuantizationConfig] = None,
49
+ ):
50
+ super().__init__()
51
+ self.total_num_heads = config.num_attention_heads
52
+ self.hidden_size = config.hidden_size
53
+ self.head_size = self.hidden_size // self.total_num_heads
54
+ self.bias = getattr(config, "attention_bias", True)
55
+
56
+ tensor_model_parallel_world_size = (
57
+ get_tensor_model_parallel_world_size())
58
+ assert self.total_num_heads % tensor_model_parallel_world_size == 0
59
+ self.num_heads = (self.total_num_heads //
60
+ tensor_model_parallel_world_size)
61
+
62
+ self.query_key_value = QKVParallelLinear(
63
+ config.hidden_size,
64
+ self.head_size,
65
+ self.total_num_heads,
66
+ bias=self.bias,
67
+ quant_config=quant_config,
68
+ )
69
+ self.dense = RowParallelLinear(
70
+ config.hidden_size,
71
+ config.hidden_size,
72
+ bias=self.bias,
73
+ quant_config=quant_config,
74
+ )
75
+ scaling = self.head_size**-0.5
76
+ rotary_dim = int(self.head_size * config.rotary_pct)
77
+ assert rotary_dim % 2 == 0
78
+ rope_theta = getattr(config, "rope_theta", 10000)
79
+ max_position_embeddings = getattr(config, "max_position_embeddings",
80
+ 8192)
81
+ self.rotary_emb = get_rope(
82
+ self.head_size,
83
+ rotary_dim=rotary_dim,
84
+ max_position=max_position_embeddings,
85
+ base=rope_theta,
86
+ )
87
+ self.attn = Attention(self.num_heads, self.head_size, scaling)
88
+
89
+ def forward(
90
+ self,
91
+ position_ids: torch.Tensor,
92
+ hidden_states: torch.Tensor,
93
+ kv_cache: torch.Tensor,
94
+ attn_metadata: AttentionMetadata,
95
+ ) -> torch.Tensor:
96
+ qkv, _ = self.query_key_value(hidden_states)
97
+ q, k, v = qkv.chunk(chunks=3, dim=-1)
98
+ q, k = self.rotary_emb(position_ids, q, k)
99
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
100
+ output, _ = self.dense(attn_output)
101
+ return output
102
+
103
+
104
+ class GPTNeoXMLP(nn.Module):
105
+
106
+ def __init__(
107
+ self,
108
+ config: GPTNeoXConfig,
109
+ quant_config: Optional[QuantizationConfig] = None,
110
+ ):
111
+ super().__init__()
112
+ self.dense_h_to_4h = ColumnParallelLinear(
113
+ config.hidden_size,
114
+ config.intermediate_size,
115
+ quant_config=quant_config,
116
+ )
117
+ self.dense_4h_to_h = RowParallelLinear(
118
+ config.intermediate_size,
119
+ config.hidden_size,
120
+ quant_config=quant_config,
121
+ )
122
+ self.act = get_act_fn(config.hidden_act, quant_config,
123
+ config.intermediate_size)
124
+
125
+ def forward(self, hidden_states):
126
+ hidden_states, _ = self.dense_h_to_4h(hidden_states)
127
+ hidden_states = self.act(hidden_states)
128
+ hidden_states, _ = self.dense_4h_to_h(hidden_states)
129
+ return hidden_states
130
+
131
+
132
+ class GPTNeoXLayer(nn.Module):
133
+
134
+ def __init__(
135
+ self,
136
+ config: GPTNeoXConfig,
137
+ quant_config: Optional[QuantizationConfig] = None,
138
+ ):
139
+ super().__init__()
140
+ self.use_parallel_residual = config.use_parallel_residual
141
+ self.input_layernorm = nn.LayerNorm(config.hidden_size,
142
+ eps=config.layer_norm_eps)
143
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size,
144
+ eps=config.layer_norm_eps)
145
+ self.attention = GPTNeoXAttention(config, quant_config)
146
+ self.mlp = GPTNeoXMLP(config, quant_config)
147
+
148
+ def forward(
149
+ self,
150
+ position_ids: torch.Tensor,
151
+ hidden_states: torch.Tensor,
152
+ kv_cache: torch.Tensor,
153
+ attn_metadata: AttentionMetadata,
154
+ ) -> torch.Tensor:
155
+ attn_input = self.input_layernorm(hidden_states)
156
+ attn_output = self.attention(
157
+ position_ids=position_ids,
158
+ hidden_states=attn_input,
159
+ kv_cache=kv_cache,
160
+ attn_metadata=attn_metadata,
161
+ )
162
+
163
+ if self.use_parallel_residual:
164
+ # pseudocode:
165
+ # x = x + attn(ln1(x)) + mlp(ln2(x))
166
+ mlp_input = self.post_attention_layernorm(hidden_states)
167
+ mlp_output = self.mlp(mlp_input)
168
+ hidden_states = mlp_output + attn_output + hidden_states
169
+ else:
170
+ # pseudocode:
171
+ # x = x + attn(ln1(x))
172
+ # x = x + mlp(ln2(x))
173
+ attn_output = attn_output + hidden_states
174
+ mlp_input = self.post_attention_layernorm(attn_output)
175
+ mlp_output = self.mlp(mlp_input)
176
+ hidden_states = mlp_output + attn_output
177
+ return hidden_states
178
+
179
+
180
+ class GPTNeoXModel(nn.Module):
181
+
182
+ def __init__(
183
+ self,
184
+ config: GPTNeoXConfig,
185
+ quant_config: Optional[QuantizationConfig] = None,
186
+ ):
187
+ super().__init__()
188
+ self.config = config
189
+
190
+ self.embed_in = VocabParallelEmbedding(
191
+ config.vocab_size,
192
+ config.hidden_size,
193
+ )
194
+ self.layers = nn.ModuleList([
195
+ GPTNeoXLayer(config, quant_config)
196
+ for _ in range(config.num_hidden_layers)
197
+ ])
198
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size,
199
+ eps=config.layer_norm_eps)
200
+
201
+ def forward(
202
+ self,
203
+ input_ids: torch.Tensor,
204
+ position_ids: torch.Tensor,
205
+ kv_caches: List[torch.Tensor],
206
+ attn_metadata: AttentionMetadata,
207
+ ) -> torch.Tensor:
208
+ hidden_states = self.embed_in(input_ids)
209
+ for i in range(len(self.layers)):
210
+ layer = self.layers[i]
211
+ hidden_states = layer(
212
+ position_ids,
213
+ hidden_states,
214
+ kv_caches[i],
215
+ attn_metadata,
216
+ )
217
+ hidden_states = self.final_layer_norm(hidden_states)
218
+ return hidden_states
219
+
220
+
221
+ class GPTNeoXForCausalLM(nn.Module):
222
+
223
+ def __init__(
224
+ self,
225
+ config,
226
+ quant_config: Optional[QuantizationConfig] = None,
227
+ ):
228
+ super().__init__()
229
+ self.config = config
230
+ self.quant_config = quant_config
231
+ self.gpt_neox = GPTNeoXModel(config, quant_config)
232
+ self.embed_out = ParallelLMHead(
233
+ config.vocab_size,
234
+ config.hidden_size,
235
+ )
236
+ self.logits_processor = LogitsProcessor(config.vocab_size)
237
+ self.sampler = Sampler()
238
+
239
+ def forward(
240
+ self,
241
+ input_ids: torch.Tensor,
242
+ positions: torch.Tensor,
243
+ kv_caches: List[torch.Tensor],
244
+ attn_metadata: AttentionMetadata,
245
+ ) -> torch.Tensor:
246
+ hidden_states = self.gpt_neox(input_ids, positions, kv_caches,
247
+ attn_metadata)
248
+ return hidden_states
249
+
250
+ def compute_logits(self, hidden_states: torch.Tensor,
251
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
252
+ logits = self.logits_processor(self.embed_out.weight, hidden_states,
253
+ sampling_metadata)
254
+ return logits
255
+
256
+ def sample(
257
+ self,
258
+ logits: torch.Tensor,
259
+ sampling_metadata: SamplingMetadata,
260
+ ) -> Optional[SamplerOutput]:
261
+ next_tokens = self.sampler(logits, sampling_metadata)
262
+ return next_tokens
263
+
264
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
265
+ params_dict = dict(self.named_parameters())
266
+ for name, loaded_weight in weights:
267
+ if ("attention.bias" in name or "attention.masked_bias" in name
268
+ or "rotary_emb.inv_freq" in name):
269
+ continue
270
+ if ("rotary_emb.cos_cached" in name
271
+ or "rotary_emb.sin_cached" in name):
272
+ # Models trained using OpenRLHF may include
273
+ # these tensors in the checkpoint. Skip them.
274
+ continue
275
+ param = params_dict[name]
276
+
277
+ if "query_key_value" in name:
278
+ # NOTE: GPT-NeoX's fused QKV's output_dim has the shape of
279
+ # (num_heads * 3 * head_size), while the
280
+ # required shape is (3 * num_heads * head_size).
281
+ # Thus, we need weight conversion.
282
+ output_dim = getattr(param, "output_dim", None)
283
+ num_heads = self.config.num_attention_heads
284
+ if output_dim is not None:
285
+ loaded_weight_shape = loaded_weight.shape
286
+ loaded_weight = loaded_weight.view(
287
+ loaded_weight_shape[:output_dim] + (num_heads, 3, -1) +
288
+ loaded_weight_shape[output_dim + 1:])
289
+ loaded_weight = loaded_weight.transpose(
290
+ output_dim, output_dim + 1)
291
+ loaded_weight = loaded_weight.reshape(loaded_weight_shape)
292
+
293
+ weight_loader = getattr(param, "weight_loader",
294
+ default_weight_loader)
295
+ weight_loader(param, loaded_weight)
@@ -0,0 +1,323 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
3
+
4
+ import torch
5
+ from torch import nn
6
+ from transformers import PretrainedConfig
7
+
8
+ from vllm.attention import Attention, AttentionMetadata
9
+ from vllm.distributed import get_tensor_model_parallel_world_size
10
+ from vllm.model_executor.layers.activation import SiluAndMul
11
+ from vllm.model_executor.layers.layernorm import RMSNorm
12
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
13
+ QKVParallelLinear,
14
+ RowParallelLinear)
15
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
16
+ from vllm.model_executor.layers.quantization.base_config import (
17
+ QuantizationConfig)
18
+ from vllm.model_executor.layers.rotary_embedding import get_rope
19
+ from vllm.model_executor.layers.sampler import Sampler
20
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
21
+ ParallelLMHead, VocabParallelEmbedding)
22
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
23
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
24
+ from vllm.sequence import SamplerOutput
25
+
26
+
27
+ class InternLM2MLP(nn.Module):
28
+
29
+ def __init__(
30
+ self,
31
+ hidden_size: int,
32
+ intermediate_size: int,
33
+ hidden_act: str,
34
+ quant_config: Optional[QuantizationConfig] = None,
35
+ ) -> None:
36
+ super().__init__()
37
+ self.gate_up_proj = MergedColumnParallelLinear(
38
+ hidden_size, [intermediate_size] * 2,
39
+ bias=False,
40
+ quant_config=quant_config)
41
+ self.w2 = RowParallelLinear(intermediate_size,
42
+ hidden_size,
43
+ bias=False,
44
+ quant_config=quant_config)
45
+ if hidden_act != "silu":
46
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
47
+ "Only silu is supported for now.")
48
+ self.act_fn = SiluAndMul()
49
+
50
+ def forward(self, x):
51
+ gate_up, _ = self.gate_up_proj(x)
52
+ x = self.act_fn(gate_up)
53
+ x, _ = self.w2(x)
54
+ return x
55
+
56
+
57
+ class InternLM2Attention(nn.Module):
58
+
59
+ def __init__(
60
+ self,
61
+ hidden_size: int,
62
+ num_heads: int,
63
+ num_kv_heads: int,
64
+ rope_theta: float = 10000,
65
+ rope_scaling: Optional[Dict[str, Any]] = None,
66
+ max_position_embeddings: int = 8192,
67
+ quant_config: Optional[QuantizationConfig] = None,
68
+ ) -> None:
69
+ super().__init__()
70
+ self.hidden_size = hidden_size
71
+ tp_size = get_tensor_model_parallel_world_size()
72
+ self.total_num_heads = num_heads
73
+ assert self.total_num_heads % tp_size == 0
74
+ self.num_heads = self.total_num_heads // tp_size
75
+ self.total_num_kv_heads = num_kv_heads
76
+ if self.total_num_kv_heads >= tp_size:
77
+ # Number of KV heads is greater than TP size, so we partition
78
+ # the KV heads across multiple tensor parallel GPUs.
79
+ assert self.total_num_kv_heads % tp_size == 0
80
+ else:
81
+ # Number of KV heads is less than TP size, so we replicate
82
+ # the KV heads across multiple tensor parallel GPUs.
83
+ assert tp_size % self.total_num_kv_heads == 0
84
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
85
+ self.head_dim = hidden_size // self.total_num_heads
86
+ self.q_size = self.num_heads * self.head_dim
87
+ self.kv_size = self.num_kv_heads * self.head_dim
88
+ self.scaling = self.head_dim**-0.5
89
+ self.rope_theta = rope_theta
90
+ self.max_position_embeddings = max_position_embeddings
91
+
92
+ self.wqkv = QKVParallelLinear(
93
+ hidden_size,
94
+ self.head_dim,
95
+ self.total_num_heads,
96
+ self.total_num_kv_heads,
97
+ bias=False,
98
+ quant_config=quant_config,
99
+ )
100
+ self.wo = RowParallelLinear(
101
+ self.total_num_heads * self.head_dim,
102
+ hidden_size,
103
+ bias=False,
104
+ quant_config=quant_config,
105
+ )
106
+
107
+ self.rotary_emb = get_rope(
108
+ self.head_dim,
109
+ rotary_dim=self.head_dim,
110
+ max_position=max_position_embeddings,
111
+ base=rope_theta,
112
+ rope_scaling=rope_scaling,
113
+ )
114
+ self.attn = Attention(self.num_heads,
115
+ self.head_dim,
116
+ self.scaling,
117
+ num_kv_heads=self.num_kv_heads)
118
+
119
+ def forward(
120
+ self,
121
+ positions: torch.Tensor,
122
+ hidden_states: torch.Tensor,
123
+ kv_cache: torch.Tensor,
124
+ attn_metadata: AttentionMetadata,
125
+ ) -> torch.Tensor:
126
+ qkv, _ = self.wqkv(hidden_states)
127
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
128
+ q, k = self.rotary_emb(positions, q, k)
129
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
130
+ output, _ = self.wo(attn_output)
131
+ return output
132
+
133
+
134
+ class InternLMDecoderLayer(nn.Module):
135
+
136
+ def __init__(
137
+ self,
138
+ config: PretrainedConfig,
139
+ quant_config: Optional[QuantizationConfig] = None,
140
+ ) -> None:
141
+ super().__init__()
142
+ self.hidden_size = config.hidden_size
143
+ rope_theta = getattr(config, "rope_theta", 10000)
144
+ rope_scaling = getattr(config, "rope_scaling", None)
145
+ max_position_embeddings = getattr(config, "max_position_embeddings",
146
+ 8192)
147
+ self.attention = InternLM2Attention(
148
+ hidden_size=self.hidden_size,
149
+ num_heads=config.num_attention_heads,
150
+ num_kv_heads=config.num_key_value_heads,
151
+ rope_theta=rope_theta,
152
+ rope_scaling=rope_scaling,
153
+ max_position_embeddings=max_position_embeddings,
154
+ quant_config=quant_config,
155
+ )
156
+ self.feed_forward = InternLM2MLP(
157
+ hidden_size=self.hidden_size,
158
+ intermediate_size=config.intermediate_size,
159
+ hidden_act=config.hidden_act,
160
+ quant_config=quant_config,
161
+ )
162
+ self.attention_norm = RMSNorm(config.hidden_size,
163
+ eps=config.rms_norm_eps)
164
+ self.ffn_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
165
+
166
+ def forward(
167
+ self,
168
+ positions: torch.Tensor,
169
+ hidden_states: torch.Tensor,
170
+ kv_cache: torch.Tensor,
171
+ attn_metadata: AttentionMetadata,
172
+ residual: Optional[torch.Tensor],
173
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
174
+ # Self Attention
175
+ if residual is None:
176
+ residual = hidden_states
177
+ hidden_states = self.attention_norm(hidden_states)
178
+ else:
179
+ hidden_states, residual = self.attention_norm(
180
+ hidden_states, residual)
181
+ hidden_states = self.attention(
182
+ positions=positions,
183
+ hidden_states=hidden_states,
184
+ kv_cache=kv_cache,
185
+ attn_metadata=attn_metadata,
186
+ )
187
+
188
+ # Fully Connected
189
+ hidden_states, residual = self.ffn_norm(hidden_states, residual)
190
+ hidden_states = self.feed_forward(hidden_states)
191
+ return hidden_states, residual
192
+
193
+
194
+ class InternLM2Model(nn.Module):
195
+
196
+ def __init__(
197
+ self,
198
+ config: PretrainedConfig,
199
+ quant_config: Optional[QuantizationConfig] = None,
200
+ ) -> None:
201
+ super().__init__()
202
+ self.config = config
203
+ self.padding_idx = config.pad_token_id
204
+ self.vocab_size = config.vocab_size
205
+ self.tok_embeddings = VocabParallelEmbedding(
206
+ config.vocab_size,
207
+ config.hidden_size,
208
+ )
209
+ self.layers = nn.ModuleList([
210
+ InternLMDecoderLayer(config, quant_config)
211
+ for _ in range(config.num_hidden_layers)
212
+ ])
213
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
214
+
215
+ def forward(
216
+ self,
217
+ input_ids: torch.Tensor,
218
+ positions: torch.Tensor,
219
+ kv_caches: List[torch.Tensor],
220
+ attn_metadata: AttentionMetadata,
221
+ ) -> torch.Tensor:
222
+ hidden_states = self.tok_embeddings(input_ids)
223
+ residual = None
224
+ for i in range(len(self.layers)):
225
+ layer = self.layers[i]
226
+ hidden_states, residual = layer(
227
+ positions,
228
+ hidden_states,
229
+ kv_caches[i],
230
+ attn_metadata,
231
+ residual,
232
+ )
233
+ hidden_states, _ = self.norm(hidden_states, residual)
234
+ return hidden_states
235
+
236
+
237
+ class InternLM2ForCausalLM(nn.Module):
238
+
239
+ def __init__(
240
+ self,
241
+ config: PretrainedConfig,
242
+ quant_config: Optional[QuantizationConfig] = None,
243
+ ) -> None:
244
+ super().__init__()
245
+ self.config = config
246
+ self.quant_config = quant_config
247
+ self.model = InternLM2Model(config, quant_config)
248
+ self.output = ParallelLMHead(config.vocab_size, config.hidden_size)
249
+ self.logits_processor = LogitsProcessor(config.vocab_size)
250
+ self.sampler = Sampler()
251
+
252
+ def forward(
253
+ self,
254
+ input_ids: torch.Tensor,
255
+ positions: torch.Tensor,
256
+ kv_caches: List[torch.Tensor],
257
+ attn_metadata: AttentionMetadata,
258
+ ) -> torch.Tensor:
259
+ hidden_states = self.model(input_ids, positions, kv_caches,
260
+ attn_metadata)
261
+ return hidden_states
262
+
263
+ def compute_logits(self, hidden_states: torch.Tensor,
264
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
265
+ logits = self.logits_processor(self.output.weight, hidden_states,
266
+ sampling_metadata)
267
+ return logits
268
+
269
+ def sample(
270
+ self,
271
+ logits: torch.Tensor,
272
+ sampling_metadata: SamplingMetadata,
273
+ ) -> Optional[SamplerOutput]:
274
+ next_tokens = self.sampler(logits, sampling_metadata)
275
+ return next_tokens
276
+
277
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
278
+ stacked_params_mapping = [
279
+ # (param_name, shard_name, shard_id)
280
+ ("gate_up_proj", "w1", 0),
281
+ ("gate_up_proj", "w3", 1),
282
+ ]
283
+ params_dict = dict(self.named_parameters())
284
+ for name, loaded_weight in weights:
285
+ if "rotary_emb.inv_freq" in name:
286
+ continue
287
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
288
+ if weight_name not in name:
289
+ continue
290
+ name = name.replace(weight_name, param_name)
291
+ # Skip loading extra bias for GPTQ models.
292
+ if name.endswith(".bias") and name not in params_dict:
293
+ continue
294
+ param = params_dict[name]
295
+ weight_loader = param.weight_loader
296
+ weight_loader(param, loaded_weight, shard_id)
297
+ break
298
+ else:
299
+ # Skip loading extra bias for GPTQ models.
300
+ if name.endswith(".bias") and name not in params_dict:
301
+ continue
302
+ param = params_dict[name]
303
+ if "wqkv" in name:
304
+ config = self.config
305
+ kv_groups = (config.num_attention_heads //
306
+ config.num_key_value_heads)
307
+ head_dim = config.hidden_size // config.num_attention_heads
308
+ loaded_weight = loaded_weight.view(-1, 2 + kv_groups,
309
+ head_dim,
310
+ loaded_weight.shape[-1])
311
+ wq, wk, wv = torch.split(loaded_weight, [kv_groups, 1, 1],
312
+ dim=1)
313
+ wq = wq.reshape(-1, wq.shape[-1])
314
+ wk = wk.reshape(-1, wk.shape[-1])
315
+ wv = wv.reshape(-1, wv.shape[-1])
316
+ weight_loader = param.weight_loader
317
+ weight_loader(param, wq, 'q')
318
+ weight_loader(param, wk, 'k')
319
+ weight_loader(param, wv, 'v')
320
+ else:
321
+ weight_loader = getattr(param, "weight_loader",
322
+ default_weight_loader)
323
+ weight_loader(param, loaded_weight)