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,284 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://huggingface.co/Qwen/Qwen-7B/blob/main/modeling_qwen.py
4
+ # Copyright (c) Alibaba Cloud.
5
+ # LICENSE: https://huggingface.co/Qwen/Qwen-7B/blob/main/LICENSE
6
+ """Inference-only QWen model compatible with HuggingFace weights."""
7
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
8
+
9
+ import torch
10
+ from torch import nn
11
+ from transformers import PretrainedConfig
12
+
13
+ from vllm.attention import Attention, AttentionMetadata
14
+ from vllm.distributed import get_tensor_model_parallel_world_size
15
+ from vllm.model_executor.layers.activation import SiluAndMul
16
+ from vllm.model_executor.layers.layernorm import RMSNorm
17
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
18
+ QKVParallelLinear,
19
+ RowParallelLinear)
20
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
21
+ from vllm.model_executor.layers.quantization.base_config import (
22
+ QuantizationConfig)
23
+ from vllm.model_executor.layers.rotary_embedding import get_rope
24
+ from vllm.model_executor.layers.sampler import Sampler
25
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
26
+ ParallelLMHead, VocabParallelEmbedding)
27
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
28
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
29
+ from vllm.sequence import SamplerOutput
30
+
31
+
32
+ class QWenMLP(nn.Module):
33
+
34
+ def __init__(
35
+ self,
36
+ hidden_size: int,
37
+ intermediate_size: int,
38
+ hidden_act: str = "silu",
39
+ quant_config: Optional[QuantizationConfig] = None,
40
+ ):
41
+ super().__init__()
42
+ self.gate_up_proj = MergedColumnParallelLinear(
43
+ hidden_size, [intermediate_size] * 2,
44
+ bias=False,
45
+ quant_config=quant_config)
46
+ self.c_proj = RowParallelLinear(intermediate_size,
47
+ hidden_size,
48
+ bias=False,
49
+ quant_config=quant_config)
50
+ if hidden_act != "silu":
51
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
52
+ "Only silu is supported for now.")
53
+ self.act_fn = SiluAndMul()
54
+
55
+ def forward(self, x):
56
+ gate_up, _ = self.gate_up_proj(x)
57
+ x = self.act_fn(gate_up)
58
+ x, _ = self.c_proj(x)
59
+ return x
60
+
61
+
62
+ class QWenAttention(nn.Module):
63
+
64
+ def __init__(
65
+ self,
66
+ hidden_size: int,
67
+ num_heads: int,
68
+ max_position_embeddings: int,
69
+ rope_theta: float = 10000,
70
+ rope_scaling: Optional[Dict[str, Any]] = None,
71
+ quant_config: Optional[QuantizationConfig] = None,
72
+ ):
73
+ super().__init__()
74
+ self.hidden_size = hidden_size
75
+ tensor_model_parallel_world_size = get_tensor_model_parallel_world_size(
76
+ )
77
+ self.total_num_heads = num_heads
78
+ assert self.total_num_heads % tensor_model_parallel_world_size == 0
79
+ self.num_heads = (self.total_num_heads //
80
+ tensor_model_parallel_world_size)
81
+ self.head_dim = hidden_size // self.total_num_heads
82
+ self.c_attn = QKVParallelLinear(
83
+ hidden_size,
84
+ self.head_dim,
85
+ self.total_num_heads,
86
+ bias=True,
87
+ quant_config=quant_config,
88
+ )
89
+ self.c_proj = RowParallelLinear(
90
+ self.total_num_heads * self.head_dim,
91
+ hidden_size,
92
+ bias=False,
93
+ quant_config=quant_config,
94
+ )
95
+ self.scaling = self.head_dim**-0.5
96
+
97
+ self.rotary_emb = get_rope(
98
+ self.head_dim,
99
+ rotary_dim=self.head_dim,
100
+ max_position=max_position_embeddings,
101
+ base=rope_theta,
102
+ rope_scaling=rope_scaling,
103
+ )
104
+ self.attn = Attention(self.num_heads, self.head_dim, self.scaling)
105
+
106
+ def forward(
107
+ self,
108
+ positions: torch.Tensor,
109
+ hidden_states: torch.Tensor,
110
+ kv_cache: torch.Tensor,
111
+ attn_metadata: AttentionMetadata,
112
+ ) -> torch.Tensor:
113
+ qkv, _ = self.c_attn(hidden_states)
114
+ q, k, v = qkv.chunk(chunks=3, dim=-1)
115
+ q, k = self.rotary_emb(positions, q, k)
116
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
117
+ output, _ = self.c_proj(attn_output)
118
+ return output
119
+
120
+
121
+ class QWenBlock(nn.Module):
122
+
123
+ def __init__(
124
+ self,
125
+ config: PretrainedConfig,
126
+ quant_config: Optional[QuantizationConfig] = None,
127
+ ):
128
+ super().__init__()
129
+ self.ln_1 = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
130
+
131
+ rope_theta = getattr(config, "rope_theta", 10000)
132
+ rope_scaling = getattr(config, "rope_scaling", None)
133
+ self.attn = QWenAttention(config.hidden_size,
134
+ config.num_attention_heads,
135
+ config.max_position_embeddings,
136
+ rope_theta=rope_theta,
137
+ rope_scaling=rope_scaling,
138
+ quant_config=quant_config)
139
+
140
+ self.ln_2 = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
141
+
142
+ self.mlp = QWenMLP(config.hidden_size,
143
+ config.intermediate_size // 2,
144
+ quant_config=quant_config)
145
+
146
+ def forward(
147
+ self,
148
+ positions: torch.Tensor,
149
+ hidden_states: torch.Tensor,
150
+ kv_cache: torch.Tensor,
151
+ attn_metadata: AttentionMetadata,
152
+ residual: Optional[torch.Tensor],
153
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
154
+ # Self Attention
155
+ if residual is None:
156
+ residual = hidden_states
157
+ hidden_states = self.ln_1(hidden_states)
158
+ else:
159
+ hidden_states, residual = self.ln_1(hidden_states, residual)
160
+ hidden_states = self.attn(
161
+ positions=positions,
162
+ hidden_states=hidden_states,
163
+ kv_cache=kv_cache,
164
+ attn_metadata=attn_metadata,
165
+ )
166
+
167
+ # Fully Connected
168
+ hidden_states, residual = self.ln_2(hidden_states, residual)
169
+ hidden_states = self.mlp(hidden_states)
170
+ return hidden_states, residual
171
+
172
+
173
+ class QWenModel(nn.Module):
174
+
175
+ def __init__(
176
+ self,
177
+ config: PretrainedConfig,
178
+ quant_config: Optional[QuantizationConfig] = None,
179
+ ):
180
+ super().__init__()
181
+ self.config = config
182
+ self.vocab_size = config.vocab_size
183
+
184
+ self.wte = VocabParallelEmbedding(
185
+ config.vocab_size,
186
+ config.hidden_size,
187
+ )
188
+ self.h = nn.ModuleList([
189
+ QWenBlock(config, quant_config)
190
+ for _ in range(config.num_hidden_layers)
191
+ ])
192
+ self.ln_f = RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
193
+
194
+ def forward(
195
+ self,
196
+ input_ids: torch.Tensor,
197
+ positions: torch.Tensor,
198
+ kv_caches: List[torch.Tensor],
199
+ attn_metadata: AttentionMetadata,
200
+ ) -> torch.Tensor:
201
+ hidden_states = self.wte(input_ids)
202
+ residual = None
203
+ for i in range(len(self.h)):
204
+ layer = self.h[i]
205
+ hidden_states, residual = layer(
206
+ positions,
207
+ hidden_states,
208
+ kv_caches[i],
209
+ attn_metadata,
210
+ residual,
211
+ )
212
+ hidden_states, _ = self.ln_f(hidden_states, residual)
213
+ return hidden_states
214
+
215
+
216
+ class QWenLMHeadModel(nn.Module):
217
+
218
+ def __init__(
219
+ self,
220
+ config: PretrainedConfig,
221
+ quant_config: Optional[QuantizationConfig] = None,
222
+ ):
223
+ super().__init__()
224
+ self.config = config
225
+ self.quant_config = quant_config
226
+ self.transformer = QWenModel(config, quant_config)
227
+ self.lm_head = ParallelLMHead(config.vocab_size, config.hidden_size)
228
+ self.logits_processor = LogitsProcessor(config.vocab_size)
229
+ self.sampler = Sampler()
230
+
231
+ def forward(
232
+ self,
233
+ input_ids: torch.Tensor,
234
+ positions: torch.Tensor,
235
+ kv_caches: List[torch.Tensor],
236
+ attn_metadata: AttentionMetadata,
237
+ ) -> torch.Tensor:
238
+ hidden_states = self.transformer(input_ids, positions, kv_caches,
239
+ attn_metadata)
240
+ return hidden_states
241
+
242
+ def compute_logits(self, hidden_states: torch.Tensor,
243
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
244
+ logits = self.logits_processor(self.lm_head.weight, hidden_states,
245
+ sampling_metadata)
246
+ return logits
247
+
248
+ def sample(
249
+ self,
250
+ logits: torch.Tensor,
251
+ sampling_metadata: SamplingMetadata,
252
+ ) -> Optional[SamplerOutput]:
253
+ next_tokens = self.sampler(logits, sampling_metadata)
254
+ return next_tokens
255
+
256
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
257
+ stacked_params_mapping = [
258
+ # (param_name, shard_name, shard_id)
259
+ ("gate_up_proj", "w2", 0),
260
+ ("gate_up_proj", "w1", 1),
261
+ ]
262
+ params_dict = dict(self.named_parameters())
263
+ for name, loaded_weight in weights:
264
+ if "rotary_emb.inv_freq" in name:
265
+ continue
266
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
267
+ if weight_name not in name:
268
+ continue
269
+ name = name.replace(weight_name, param_name)
270
+ # Skip loading extra bias for GPTQ models.
271
+ if name.endswith(".bias") and name not in params_dict:
272
+ continue
273
+ param = params_dict[name]
274
+ weight_loader = param.weight_loader
275
+ weight_loader(param, loaded_weight, shard_id)
276
+ break
277
+ else:
278
+ # Skip loading extra bias for GPTQ models.
279
+ if name.endswith(".bias") and name not in params_dict:
280
+ continue
281
+ param = params_dict[name]
282
+ weight_loader = getattr(param, "weight_loader",
283
+ default_weight_loader)
284
+ weight_loader(param, loaded_weight)
@@ -0,0 +1,367 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/qwen2/modeling_qwen2.py
4
+ # Copyright 2024 The Qwen team.
5
+ # Copyright 2023 The vLLM team.
6
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
7
+ #
8
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
9
+ # and OPT implementations in this library. It has been modified from its
10
+ # original forms to accommodate minor architectural differences compared
11
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
12
+ #
13
+ # Licensed under the Apache License, Version 2.0 (the "License");
14
+ # you may not use this file except in compliance with the License.
15
+ # You may obtain a copy of the License at
16
+ #
17
+ # http://www.apache.org/licenses/LICENSE-2.0
18
+ #
19
+ # Unless required by applicable law or agreed to in writing, software
20
+ # distributed under the License is distributed on an "AS IS" BASIS,
21
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
+ # See the License for the specific language governing permissions and
23
+ # limitations under the License.
24
+ """Inference-only Qwen2 model compatible with HuggingFace weights."""
25
+ from typing import Iterable, List, Optional, Tuple
26
+
27
+ import torch
28
+ from torch import nn
29
+ from transformers import Qwen2Config
30
+
31
+ from vllm.attention import Attention, AttentionMetadata
32
+ from vllm.config import LoRAConfig
33
+ from vllm.distributed import get_tensor_model_parallel_world_size
34
+ from vllm.model_executor.layers.activation import SiluAndMul
35
+ from vllm.model_executor.layers.layernorm import RMSNorm
36
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
37
+ QKVParallelLinear,
38
+ RowParallelLinear)
39
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
40
+ from vllm.model_executor.layers.quantization.base_config import (
41
+ QuantizationConfig)
42
+ from vllm.model_executor.layers.rotary_embedding import get_rope
43
+ from vllm.model_executor.layers.sampler import Sampler
44
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
45
+ ParallelLMHead, VocabParallelEmbedding)
46
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
47
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
48
+ from vllm.sequence import SamplerOutput
49
+
50
+
51
+ class Qwen2MLP(nn.Module):
52
+
53
+ def __init__(
54
+ self,
55
+ hidden_size: int,
56
+ intermediate_size: int,
57
+ hidden_act: str,
58
+ quant_config: Optional[QuantizationConfig] = None,
59
+ ) -> None:
60
+ super().__init__()
61
+ self.gate_up_proj = MergedColumnParallelLinear(
62
+ hidden_size, [intermediate_size] * 2,
63
+ bias=False,
64
+ quant_config=quant_config)
65
+ self.down_proj = RowParallelLinear(intermediate_size,
66
+ hidden_size,
67
+ bias=False,
68
+ quant_config=quant_config)
69
+ if hidden_act != "silu":
70
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
71
+ "Only silu is supported for now.")
72
+ self.act_fn = SiluAndMul()
73
+
74
+ def forward(self, x):
75
+ gate_up, _ = self.gate_up_proj(x)
76
+ x = self.act_fn(gate_up)
77
+ x, _ = self.down_proj(x)
78
+ return x
79
+
80
+
81
+ class Qwen2Attention(nn.Module):
82
+
83
+ def __init__(self,
84
+ hidden_size: int,
85
+ num_heads: int,
86
+ num_kv_heads: int,
87
+ max_position: int = 4096 * 32,
88
+ rope_theta: float = 10000,
89
+ use_sliding_window: bool = False,
90
+ quant_config: Optional[QuantizationConfig] = None,
91
+ sliding_window: Optional[int] = None) -> None:
92
+ super().__init__()
93
+ self.hidden_size = hidden_size
94
+ tp_size = get_tensor_model_parallel_world_size()
95
+ self.total_num_heads = num_heads
96
+ assert self.total_num_heads % tp_size == 0
97
+ self.num_heads = self.total_num_heads // tp_size
98
+ self.total_num_kv_heads = num_kv_heads
99
+ if self.total_num_kv_heads >= tp_size:
100
+ # Number of KV heads is greater than TP size, so we partition
101
+ # the KV heads across multiple tensor parallel GPUs.
102
+ assert self.total_num_kv_heads % tp_size == 0
103
+ else:
104
+ # Number of KV heads is less than TP size, so we replicate
105
+ # the KV heads across multiple tensor parallel GPUs.
106
+ assert tp_size % self.total_num_kv_heads == 0
107
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
108
+ self.head_dim = hidden_size // self.total_num_heads
109
+ self.q_size = self.num_heads * self.head_dim
110
+ self.kv_size = self.num_kv_heads * self.head_dim
111
+ self.scaling = self.head_dim**-0.5
112
+ self.rope_theta = rope_theta
113
+ self.sliding_window = sliding_window if use_sliding_window else None
114
+
115
+ self.qkv_proj = QKVParallelLinear(
116
+ hidden_size,
117
+ self.head_dim,
118
+ self.total_num_heads,
119
+ self.total_num_kv_heads,
120
+ bias=True,
121
+ quant_config=quant_config,
122
+ )
123
+ self.o_proj = RowParallelLinear(
124
+ self.total_num_heads * self.head_dim,
125
+ hidden_size,
126
+ bias=False,
127
+ quant_config=quant_config,
128
+ )
129
+
130
+ self.rotary_emb = get_rope(
131
+ self.head_dim,
132
+ rotary_dim=self.head_dim,
133
+ max_position=max_position,
134
+ base=self.rope_theta,
135
+ )
136
+ self.attn = Attention(self.num_heads,
137
+ self.head_dim,
138
+ self.scaling,
139
+ num_kv_heads=self.num_kv_heads,
140
+ sliding_window=self.sliding_window)
141
+
142
+ def forward(
143
+ self,
144
+ positions: torch.Tensor,
145
+ hidden_states: torch.Tensor,
146
+ kv_cache: torch.Tensor,
147
+ attn_metadata: AttentionMetadata,
148
+ ) -> torch.Tensor:
149
+ qkv, _ = self.qkv_proj(hidden_states)
150
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
151
+ q, k = self.rotary_emb(positions, q, k)
152
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
153
+ output, _ = self.o_proj(attn_output)
154
+ return output
155
+
156
+
157
+ class Qwen2DecoderLayer(nn.Module):
158
+
159
+ def __init__(
160
+ self,
161
+ config: Qwen2Config,
162
+ layer_idx: int,
163
+ quant_config: Optional[QuantizationConfig] = None,
164
+ ) -> None:
165
+ super().__init__()
166
+ self.hidden_size = config.hidden_size
167
+ # Requires transformers > 4.32.0
168
+ rope_theta = getattr(config, "rope_theta", 1000000)
169
+ use_sliding_window = (config.use_sliding_window
170
+ and layer_idx < config.max_window_layers)
171
+ self.self_attn = Qwen2Attention(
172
+ hidden_size=self.hidden_size,
173
+ num_heads=config.num_attention_heads,
174
+ max_position=config.max_position_embeddings,
175
+ num_kv_heads=config.num_key_value_heads,
176
+ rope_theta=rope_theta,
177
+ use_sliding_window=use_sliding_window,
178
+ quant_config=quant_config,
179
+ sliding_window=config.sliding_window)
180
+ self.mlp = Qwen2MLP(
181
+ hidden_size=self.hidden_size,
182
+ intermediate_size=config.intermediate_size,
183
+ hidden_act=config.hidden_act,
184
+ quant_config=quant_config,
185
+ )
186
+ self.input_layernorm = RMSNorm(config.hidden_size,
187
+ eps=config.rms_norm_eps)
188
+ self.post_attention_layernorm = RMSNorm(config.hidden_size,
189
+ eps=config.rms_norm_eps)
190
+
191
+ def forward(
192
+ self,
193
+ positions: torch.Tensor,
194
+ hidden_states: torch.Tensor,
195
+ kv_cache: torch.Tensor,
196
+ attn_metadata: AttentionMetadata,
197
+ residual: Optional[torch.Tensor],
198
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
199
+ # Self Attention
200
+ if residual is None:
201
+ residual = hidden_states
202
+ hidden_states = self.input_layernorm(hidden_states)
203
+ else:
204
+ hidden_states, residual = self.input_layernorm(
205
+ hidden_states, residual)
206
+ hidden_states = self.self_attn(
207
+ positions=positions,
208
+ hidden_states=hidden_states,
209
+ kv_cache=kv_cache,
210
+ attn_metadata=attn_metadata,
211
+ )
212
+
213
+ # Fully Connected
214
+ hidden_states, residual = self.post_attention_layernorm(
215
+ hidden_states, residual)
216
+ hidden_states = self.mlp(hidden_states)
217
+ return hidden_states, residual
218
+
219
+
220
+ class Qwen2Model(nn.Module):
221
+
222
+ def __init__(
223
+ self,
224
+ config: Qwen2Config,
225
+ quant_config: Optional[QuantizationConfig] = None,
226
+ ) -> None:
227
+ super().__init__()
228
+ self.config = config
229
+ self.padding_idx = config.pad_token_id
230
+ self.vocab_size = config.vocab_size
231
+
232
+ self.embed_tokens = VocabParallelEmbedding(
233
+ config.vocab_size,
234
+ config.hidden_size,
235
+ )
236
+ self.layers = nn.ModuleList([
237
+ Qwen2DecoderLayer(config, layer_idx, quant_config)
238
+ for layer_idx in range(config.num_hidden_layers)
239
+ ])
240
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
241
+
242
+ def forward(
243
+ self,
244
+ input_ids: torch.Tensor,
245
+ positions: torch.Tensor,
246
+ kv_caches: List[torch.Tensor],
247
+ attn_metadata: AttentionMetadata,
248
+ ) -> torch.Tensor:
249
+ hidden_states = self.embed_tokens(input_ids)
250
+ residual = None
251
+ for i in range(len(self.layers)):
252
+ layer = self.layers[i]
253
+ hidden_states, residual = layer(
254
+ positions,
255
+ hidden_states,
256
+ kv_caches[i],
257
+ attn_metadata,
258
+ residual,
259
+ )
260
+ hidden_states, _ = self.norm(hidden_states, residual)
261
+ return hidden_states
262
+
263
+
264
+ class Qwen2ForCausalLM(nn.Module):
265
+ packed_modules_mapping = {
266
+ "qkv_proj": [
267
+ "q_proj",
268
+ "k_proj",
269
+ "v_proj",
270
+ ],
271
+ "gate_up_proj": [
272
+ "gate_proj",
273
+ "up_proj",
274
+ ],
275
+ }
276
+
277
+ # LoRA specific attributes
278
+ supported_lora_modules = [
279
+ "qkv_proj",
280
+ "o_proj",
281
+ "gate_up_proj",
282
+ "down_proj",
283
+ ]
284
+ embedding_modules = {}
285
+ embedding_padding_modules = []
286
+
287
+ def __init__(
288
+ self,
289
+ config: Qwen2Config,
290
+ quant_config: Optional[QuantizationConfig] = None,
291
+ lora_config: Optional[LoRAConfig] = None,
292
+ ) -> None:
293
+ del lora_config
294
+ super().__init__()
295
+ self.config = config
296
+ self.quant_config = quant_config
297
+ self.model = Qwen2Model(config, quant_config)
298
+
299
+ if config.tie_word_embeddings:
300
+ self.lm_head_weight = self.model.embed_tokens.weight
301
+ else:
302
+ self.lm_head = ParallelLMHead(config.vocab_size,
303
+ config.hidden_size)
304
+ self.lm_head_weight = self.lm_head.weight
305
+
306
+ self.logits_processor = LogitsProcessor(config.vocab_size)
307
+ self.sampler = Sampler()
308
+
309
+ def forward(
310
+ self,
311
+ input_ids: torch.Tensor,
312
+ positions: torch.Tensor,
313
+ kv_caches: List[torch.Tensor],
314
+ attn_metadata: AttentionMetadata,
315
+ ) -> torch.Tensor:
316
+ hidden_states = self.model(input_ids, positions, kv_caches,
317
+ attn_metadata)
318
+ return hidden_states
319
+
320
+ def compute_logits(self, hidden_states: torch.Tensor,
321
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
322
+ logits = self.logits_processor(self.lm_head_weight, hidden_states,
323
+ sampling_metadata)
324
+ return logits
325
+
326
+ def sample(
327
+ self,
328
+ logits: torch.Tensor,
329
+ sampling_metadata: SamplingMetadata,
330
+ ) -> Optional[SamplerOutput]:
331
+ next_tokens = self.sampler(logits, sampling_metadata)
332
+ return next_tokens
333
+
334
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
335
+ stacked_params_mapping = [
336
+ # (param_name, shard_name, shard_id)
337
+ ("qkv_proj", "q_proj", "q"),
338
+ ("qkv_proj", "k_proj", "k"),
339
+ ("qkv_proj", "v_proj", "v"),
340
+ ("gate_up_proj", "gate_proj", 0),
341
+ ("gate_up_proj", "up_proj", 1),
342
+ ]
343
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
344
+ for name, loaded_weight in weights:
345
+ if "rotary_emb.inv_freq" in name:
346
+ continue
347
+ if self.config.tie_word_embeddings and "lm_head.weight" in name:
348
+ continue
349
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
350
+ if weight_name not in name:
351
+ continue
352
+ name = name.replace(weight_name, param_name)
353
+ # Skip loading extra bias for GPTQ models.
354
+ if name.endswith(".bias") and name not in params_dict:
355
+ continue
356
+ param = params_dict[name]
357
+ weight_loader = param.weight_loader
358
+ weight_loader(param, loaded_weight, shard_id)
359
+ break
360
+ else:
361
+ # Skip loading extra bias for GPTQ models.
362
+ if name.endswith(".bias") and name not in params_dict:
363
+ continue
364
+ param = params_dict[name]
365
+ weight_loader = getattr(param, "weight_loader",
366
+ default_weight_loader)
367
+ weight_loader(param, loaded_weight)