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,393 @@
1
+ # coding=utf-8
2
+ # Copyright 2023 The vLLM team.
3
+ # Copyright (c) Google Inc.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Inference-only Gemma model compatible with HuggingFace weights."""
17
+ from functools import lru_cache
18
+ from typing import Iterable, List, Optional, Tuple
19
+
20
+ import torch
21
+ from torch import nn
22
+ from transformers import GemmaConfig
23
+
24
+ from vllm.attention import Attention, AttentionMetadata
25
+ from vllm.config import LoRAConfig
26
+ from vllm.distributed import get_tensor_model_parallel_world_size
27
+ from vllm.logger import init_logger
28
+ from vllm.model_executor.layers.activation import GeluAndMul
29
+ from vllm.model_executor.layers.layernorm import RMSNorm
30
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
31
+ QKVParallelLinear,
32
+ RowParallelLinear)
33
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
34
+ from vllm.model_executor.layers.quantization.base_config import (
35
+ QuantizationConfig)
36
+ from vllm.model_executor.layers.rotary_embedding import get_rope
37
+ from vllm.model_executor.layers.sampler import Sampler
38
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
39
+ VocabParallelEmbedding)
40
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
41
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
42
+ from vllm.sequence import SamplerOutput
43
+
44
+ logger = init_logger(__name__)
45
+
46
+
47
+ @lru_cache(maxsize=None)
48
+ def _get_gemma_act_fn(
49
+ hidden_act: Optional[str],
50
+ hidden_activation: Optional[str],
51
+ ) -> nn.Module:
52
+ if hidden_activation is None:
53
+ if hidden_act is not None:
54
+ logger.warning(
55
+ "Gemma's activation function was incorrectly set to exact GeLU "
56
+ "in the config JSON file when it was initially released. "
57
+ "Changing the activation function to approximate GeLU "
58
+ "(`gelu_pytorch_tanh`). If you want to use the legacy "
59
+ "`%s`, edit the config JSON to set "
60
+ "`hidden_activation=%s` instead of `hidden_act`. "
61
+ "See https://github.com/huggingface/transformers/pull/29402 "
62
+ "for more details.", hidden_act, hidden_act)
63
+ return GeluAndMul(approximate="tanh")
64
+ elif hidden_activation == "gelu_pytorch_tanh":
65
+ return GeluAndMul(approximate="tanh")
66
+ elif hidden_activation == "gelu":
67
+ return GeluAndMul(approximate="none")
68
+ else:
69
+ raise ValueError(f"Activation function {hidden_act} is not "
70
+ "supported for Gemma models.")
71
+
72
+
73
+ class GemmaMLP(nn.Module):
74
+
75
+ def __init__(
76
+ self,
77
+ hidden_size: int,
78
+ intermediate_size: int,
79
+ hidden_act: Optional[str] = None,
80
+ hidden_activation: Optional[str] = None,
81
+ quant_config: Optional[QuantizationConfig] = None,
82
+ ) -> None:
83
+ super().__init__()
84
+ self.gate_up_proj = MergedColumnParallelLinear(
85
+ hidden_size, [intermediate_size] * 2,
86
+ bias=False,
87
+ quant_config=quant_config)
88
+ self.down_proj = RowParallelLinear(intermediate_size,
89
+ hidden_size,
90
+ bias=False,
91
+ quant_config=quant_config)
92
+ self.act_fn = _get_gemma_act_fn(hidden_act, hidden_activation)
93
+
94
+ def forward(self, x):
95
+ gate_up, _ = self.gate_up_proj(x)
96
+ x = self.act_fn(gate_up)
97
+ x, _ = self.down_proj(x)
98
+ return x
99
+
100
+
101
+ class GemmaAttention(nn.Module):
102
+
103
+ def __init__(self,
104
+ hidden_size: int,
105
+ num_heads: int,
106
+ num_kv_heads: int,
107
+ head_dim: int,
108
+ max_position_embeddings: int = 8192,
109
+ rope_theta: float = 10000,
110
+ quant_config: Optional[QuantizationConfig] = None) -> None:
111
+ super().__init__()
112
+ self.hidden_size = hidden_size
113
+ tp_size = get_tensor_model_parallel_world_size()
114
+ self.total_num_heads = num_heads
115
+ assert self.total_num_heads % tp_size == 0
116
+ self.num_heads = self.total_num_heads // tp_size
117
+ self.total_num_kv_heads = num_kv_heads
118
+ if self.total_num_kv_heads >= tp_size:
119
+ # Number of KV heads is greater than TP size, so we partition
120
+ # the KV heads across multiple tensor parallel GPUs.
121
+ assert self.total_num_kv_heads % tp_size == 0
122
+ else:
123
+ # Number of KV heads is less than TP size, so we replicate
124
+ # the KV heads across multiple tensor parallel GPUs.
125
+ assert tp_size % self.total_num_kv_heads == 0
126
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
127
+ self.head_dim = head_dim
128
+ self.q_size = self.num_heads * self.head_dim
129
+ self.kv_size = self.num_kv_heads * self.head_dim
130
+ self.scaling = self.head_dim**-0.5
131
+ self.rope_theta = rope_theta
132
+
133
+ self.qkv_proj = QKVParallelLinear(
134
+ hidden_size,
135
+ self.head_dim,
136
+ self.total_num_heads,
137
+ self.total_num_kv_heads,
138
+ bias=False,
139
+ quant_config=quant_config,
140
+ )
141
+ self.o_proj = RowParallelLinear(
142
+ self.total_num_heads * self.head_dim,
143
+ hidden_size,
144
+ bias=False,
145
+ quant_config=quant_config,
146
+ )
147
+
148
+ self.rotary_emb = get_rope(
149
+ self.head_dim,
150
+ rotary_dim=self.head_dim,
151
+ max_position=max_position_embeddings,
152
+ base=self.rope_theta,
153
+ is_neox_style=True,
154
+ )
155
+ self.attn = Attention(self.num_heads,
156
+ self.head_dim,
157
+ self.scaling,
158
+ num_kv_heads=self.num_kv_heads)
159
+
160
+ def forward(
161
+ self,
162
+ positions: torch.Tensor,
163
+ hidden_states: torch.Tensor,
164
+ kv_cache: torch.Tensor,
165
+ attn_metadata: AttentionMetadata,
166
+ ) -> torch.Tensor:
167
+ qkv, _ = self.qkv_proj(hidden_states)
168
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
169
+ q, k = self.rotary_emb(positions, q, k)
170
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
171
+ output, _ = self.o_proj(attn_output)
172
+ return output
173
+
174
+
175
+ class GemmaDecoderLayer(nn.Module):
176
+
177
+ def __init__(
178
+ self,
179
+ config: GemmaConfig,
180
+ quant_config: Optional[QuantizationConfig] = None,
181
+ ) -> None:
182
+ super().__init__()
183
+ self.hidden_size = config.hidden_size
184
+ self.self_attn = GemmaAttention(
185
+ hidden_size=self.hidden_size,
186
+ num_heads=config.num_attention_heads,
187
+ num_kv_heads=config.num_key_value_heads,
188
+ head_dim=config.head_dim,
189
+ max_position_embeddings=config.max_position_embeddings,
190
+ rope_theta=config.rope_theta,
191
+ quant_config=quant_config,
192
+ )
193
+ self.mlp = GemmaMLP(
194
+ hidden_size=self.hidden_size,
195
+ intermediate_size=config.intermediate_size,
196
+ hidden_act=config.hidden_act,
197
+ hidden_activation=getattr(config, "hidden_activation", None),
198
+ quant_config=quant_config,
199
+ )
200
+ self.input_layernorm = RMSNorm(config.hidden_size,
201
+ eps=config.rms_norm_eps)
202
+ self.post_attention_layernorm = RMSNorm(config.hidden_size,
203
+ eps=config.rms_norm_eps)
204
+
205
+ def forward(
206
+ self,
207
+ positions: torch.Tensor,
208
+ hidden_states: torch.Tensor,
209
+ kv_cache: torch.Tensor,
210
+ attn_metadata: AttentionMetadata,
211
+ residual: Optional[torch.Tensor],
212
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
213
+ # Self Attention
214
+ if residual is None:
215
+ residual = hidden_states
216
+ hidden_states = self.input_layernorm(hidden_states)
217
+ else:
218
+ hidden_states, residual = self.input_layernorm(
219
+ hidden_states, residual)
220
+ hidden_states = self.self_attn(
221
+ positions=positions,
222
+ hidden_states=hidden_states,
223
+ kv_cache=kv_cache,
224
+ attn_metadata=attn_metadata,
225
+ )
226
+
227
+ # Fully Connected
228
+ hidden_states, residual = self.post_attention_layernorm(
229
+ hidden_states, residual)
230
+ hidden_states = self.mlp(hidden_states)
231
+ return hidden_states, residual
232
+
233
+
234
+ class GemmaModel(nn.Module):
235
+
236
+ def __init__(
237
+ self,
238
+ config: GemmaConfig,
239
+ quant_config: Optional[QuantizationConfig] = None,
240
+ ) -> None:
241
+ super().__init__()
242
+ self.config = config
243
+
244
+ self.embed_tokens = VocabParallelEmbedding(
245
+ config.vocab_size,
246
+ config.hidden_size,
247
+ )
248
+ self.layers = nn.ModuleList([
249
+ GemmaDecoderLayer(config, quant_config)
250
+ for _ in range(config.num_hidden_layers)
251
+ ])
252
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
253
+
254
+ # Normalize the embedding by sqrt(hidden_size)
255
+ # The normalizer's data type should be downcasted to the model's
256
+ # data type such as bfloat16, not float32.
257
+ # See https://github.com/huggingface/transformers/pull/29402
258
+ normalizer = self.config.hidden_size**0.5
259
+ self.register_buffer("normalizer", torch.tensor(normalizer))
260
+
261
+ def forward(
262
+ self,
263
+ input_ids: torch.Tensor,
264
+ positions: torch.Tensor,
265
+ kv_caches: List[torch.Tensor],
266
+ attn_metadata: AttentionMetadata,
267
+ ) -> torch.Tensor:
268
+ hidden_states = self.embed_tokens(input_ids)
269
+ hidden_states *= self.normalizer
270
+
271
+ residual = None
272
+ for i in range(len(self.layers)):
273
+ layer = self.layers[i]
274
+ hidden_states, residual = layer(
275
+ positions,
276
+ hidden_states,
277
+ kv_caches[i],
278
+ attn_metadata,
279
+ residual,
280
+ )
281
+ hidden_states, _ = self.norm(hidden_states, residual)
282
+ return hidden_states
283
+
284
+
285
+ class GemmaForCausalLM(nn.Module):
286
+ packed_modules_mapping = {
287
+ "qkv_proj": [
288
+ "q_proj",
289
+ "k_proj",
290
+ "v_proj",
291
+ ],
292
+ "gate_up_proj": [
293
+ "gate_proj",
294
+ "up_proj",
295
+ ],
296
+ }
297
+
298
+ # LoRA specific attributes
299
+ supported_lora_modules = [
300
+ "qkv_proj",
301
+ "o_proj",
302
+ "gate_up_proj",
303
+ "down_proj",
304
+ ]
305
+ # Gemma does not apply LoRA to the embedding layer.
306
+ embedding_modules = {}
307
+ embedding_padding_modules = []
308
+
309
+ def __init__(
310
+ self,
311
+ config: GemmaConfig,
312
+ quant_config: Optional[QuantizationConfig] = None,
313
+ lora_config: Optional[LoRAConfig] = None,
314
+ ) -> None:
315
+ del lora_config # Unused.
316
+ super().__init__()
317
+ self.config = config
318
+ self.quant_config = quant_config
319
+ self.model = GemmaModel(config, quant_config)
320
+ self.logits_processor = LogitsProcessor(config.vocab_size)
321
+ self.sampler = Sampler()
322
+
323
+ @torch.no_grad()
324
+ def forward(
325
+ self,
326
+ input_ids: torch.Tensor,
327
+ positions: torch.Tensor,
328
+ kv_caches: List[torch.Tensor],
329
+ attn_metadata: AttentionMetadata,
330
+ ) -> torch.Tensor:
331
+ hidden_states = self.model(input_ids, positions, kv_caches,
332
+ attn_metadata)
333
+ return hidden_states
334
+
335
+ def compute_logits(self, hidden_states: torch.Tensor,
336
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
337
+ logits = self.logits_processor(self.model.embed_tokens.weight,
338
+ hidden_states, sampling_metadata)
339
+ return logits
340
+
341
+ def sample(
342
+ self,
343
+ logits: torch.Tensor,
344
+ sampling_metadata: SamplingMetadata,
345
+ ) -> Optional[SamplerOutput]:
346
+ next_tokens = self.sampler(logits, sampling_metadata)
347
+ return next_tokens
348
+
349
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
350
+ stacked_params_mapping = [
351
+ # (param_name, shard_name, shard_id)
352
+ ("qkv_proj", "q_proj", "q"),
353
+ ("qkv_proj", "k_proj", "k"),
354
+ ("qkv_proj", "v_proj", "v"),
355
+ ("gate_up_proj", "gate_proj", 0),
356
+ ("gate_up_proj", "up_proj", 1),
357
+ ]
358
+ params_dict = dict(self.named_parameters())
359
+ loaded_params = set()
360
+ for name, loaded_weight in weights:
361
+ for (param_name, shard_name, shard_id) in stacked_params_mapping:
362
+ if shard_name not in name:
363
+ continue
364
+ name = name.replace(shard_name, param_name)
365
+ # Skip loading extra bias for GPTQ models.
366
+ if name.endswith(".bias") and name not in params_dict:
367
+ continue
368
+ param = params_dict[name]
369
+ weight_loader = param.weight_loader
370
+ weight_loader(param, loaded_weight, shard_id)
371
+ break
372
+ else:
373
+ # lm_head is not used in vllm as it is tied with embed_token.
374
+ # To prevent errors, skip loading lm_head.weight.
375
+ if "lm_head.weight" in name:
376
+ continue
377
+ # Skip loading extra bias for GPTQ models.
378
+ if name.endswith(".bias") and name not in params_dict:
379
+ continue
380
+ # GemmaRMSNorm is different from Llama's in that it multiplies
381
+ # (1 + weight) to the output, instead of just weight.
382
+ if "norm.weight" in name:
383
+ loaded_weight += 1.0
384
+ param = params_dict[name]
385
+ weight_loader = getattr(param, "weight_loader",
386
+ default_weight_loader)
387
+ weight_loader(param, loaded_weight)
388
+ loaded_params.add(name)
389
+ unloaded_params = params_dict.keys() - loaded_params
390
+ if unloaded_params:
391
+ raise RuntimeError(
392
+ "Some weights are not initialized from checkpoints: "
393
+ f"{unloaded_params}")
@@ -0,0 +1,266 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/gpt2/modeling_gpt2.py
4
+ # Copyright 2023 The vLLM team.
5
+ # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
6
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """Inference-only GPT-2 model compatible with HuggingFace weights."""
20
+ from typing import Iterable, List, Optional, Tuple
21
+
22
+ import torch
23
+ from torch import nn
24
+ from transformers import GPT2Config
25
+
26
+ from vllm.attention import Attention, AttentionMetadata
27
+ from vllm.distributed import get_tensor_model_parallel_world_size
28
+ from vllm.model_executor.layers.activation import get_act_fn
29
+ from vllm.model_executor.layers.linear import (ColumnParallelLinear,
30
+ QKVParallelLinear,
31
+ RowParallelLinear)
32
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
33
+ from vllm.model_executor.layers.quantization.base_config import (
34
+ QuantizationConfig)
35
+ from vllm.model_executor.layers.sampler import Sampler
36
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
37
+ 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 GPT2Attention(nn.Module):
44
+
45
+ def __init__(
46
+ self,
47
+ config: GPT2Config,
48
+ quant_config: Optional[QuantizationConfig] = None,
49
+ ):
50
+ super().__init__()
51
+ self.hidden_size = config.hidden_size
52
+ total_num_heads = config.num_attention_heads
53
+ tensor_model_parallel_world_size = (
54
+ get_tensor_model_parallel_world_size())
55
+ assert total_num_heads % tensor_model_parallel_world_size == 0
56
+ self.num_heads = total_num_heads // tensor_model_parallel_world_size
57
+ self.head_dim = self.hidden_size // total_num_heads
58
+ self.scale = self.head_dim**-0.5
59
+
60
+ self.c_attn = QKVParallelLinear(
61
+ self.hidden_size,
62
+ self.head_dim,
63
+ total_num_heads,
64
+ bias=True,
65
+ quant_config=quant_config,
66
+ )
67
+ self.c_proj = RowParallelLinear(
68
+ self.hidden_size,
69
+ self.hidden_size,
70
+ bias=True,
71
+ quant_config=quant_config,
72
+ )
73
+ self.attn = Attention(self.num_heads, self.head_dim, scale=self.scale)
74
+
75
+ def forward(
76
+ self,
77
+ hidden_states: torch.Tensor,
78
+ kv_cache: torch.Tensor,
79
+ attn_metadata: AttentionMetadata,
80
+ ) -> torch.Tensor:
81
+ qkv, _ = self.c_attn(hidden_states)
82
+ q, k, v = qkv.chunk(chunks=3, dim=-1)
83
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
84
+ attn_output, _ = self.c_proj(attn_output)
85
+ return attn_output
86
+
87
+
88
+ class GPT2MLP(nn.Module):
89
+
90
+ def __init__(
91
+ self,
92
+ intermediate_size: int,
93
+ config: GPT2Config,
94
+ quant_config: Optional[QuantizationConfig] = None,
95
+ ):
96
+ super().__init__()
97
+ hidden_size = config.hidden_size
98
+ self.c_fc = ColumnParallelLinear(
99
+ hidden_size,
100
+ intermediate_size,
101
+ bias=True,
102
+ quant_config=quant_config,
103
+ )
104
+ self.c_proj = RowParallelLinear(
105
+ intermediate_size,
106
+ hidden_size,
107
+ bias=True,
108
+ quant_config=quant_config,
109
+ )
110
+ self.act = get_act_fn(config.activation_function, quant_config,
111
+ intermediate_size)
112
+
113
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
114
+ hidden_states, _ = self.c_fc(hidden_states)
115
+ hidden_states = self.act(hidden_states)
116
+ hidden_states, _ = self.c_proj(hidden_states)
117
+ return hidden_states
118
+
119
+
120
+ class GPT2Block(nn.Module):
121
+
122
+ def __init__(
123
+ self,
124
+ config: GPT2Config,
125
+ quant_config: Optional[QuantizationConfig] = None,
126
+ ):
127
+ super().__init__()
128
+ hidden_size = config.hidden_size
129
+ inner_dim = (config.n_inner if config.n_inner is not None else 4 *
130
+ hidden_size)
131
+
132
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
133
+ self.attn = GPT2Attention(config, quant_config)
134
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
135
+ self.mlp = GPT2MLP(inner_dim, config, quant_config)
136
+
137
+ def forward(
138
+ self,
139
+ hidden_states: torch.Tensor,
140
+ kv_cache: torch.Tensor,
141
+ attn_metadata: AttentionMetadata,
142
+ ) -> torch.Tensor:
143
+ residual = hidden_states
144
+ hidden_states = self.ln_1(hidden_states)
145
+ attn_output = self.attn(
146
+ hidden_states=hidden_states,
147
+ kv_cache=kv_cache,
148
+ attn_metadata=attn_metadata,
149
+ )
150
+ # residual connection
151
+ hidden_states = attn_output + residual
152
+
153
+ residual = hidden_states
154
+ hidden_states = self.ln_2(hidden_states)
155
+ feed_forward_hidden_states = self.mlp(hidden_states)
156
+ # residual connection
157
+ hidden_states = residual + feed_forward_hidden_states
158
+ return hidden_states
159
+
160
+
161
+ class GPT2Model(nn.Module):
162
+
163
+ def __init__(
164
+ self,
165
+ config: GPT2Config,
166
+ quant_config: Optional[QuantizationConfig] = None,
167
+ ):
168
+ super().__init__()
169
+ self.config = config
170
+ assert not config.add_cross_attention
171
+ assert not config.scale_attn_by_inverse_layer_idx
172
+ assert not config.reorder_and_upcast_attn
173
+ self.embed_dim = config.hidden_size
174
+ self.wte = VocabParallelEmbedding(config.vocab_size, self.embed_dim)
175
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
176
+ self.h = nn.ModuleList([
177
+ GPT2Block(config, quant_config)
178
+ for _ in range(config.num_hidden_layers)
179
+ ])
180
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
181
+
182
+ def forward(
183
+ self,
184
+ input_ids: torch.Tensor,
185
+ position_ids: torch.Tensor,
186
+ kv_caches: List[torch.Tensor],
187
+ attn_metadata: AttentionMetadata,
188
+ ) -> torch.Tensor:
189
+ inputs_embeds = self.wte(input_ids)
190
+ position_embeds = self.wpe(position_ids)
191
+ hidden_states = inputs_embeds + position_embeds
192
+
193
+ for i in range(len(self.h)):
194
+ layer = self.h[i]
195
+ hidden_states = layer(hidden_states, kv_caches[i], attn_metadata)
196
+
197
+ hidden_states = self.ln_f(hidden_states)
198
+ return hidden_states
199
+
200
+
201
+ class GPT2LMHeadModel(nn.Module):
202
+
203
+ def __init__(
204
+ self,
205
+ config: GPT2Config,
206
+ quant_config: Optional[QuantizationConfig] = None,
207
+ ):
208
+ super().__init__()
209
+ self.config = config
210
+ self.quant_config = quant_config
211
+ self.transformer = GPT2Model(config, quant_config)
212
+ self.lm_head_weight = self.transformer.wte.weight
213
+ self.logits_processor = LogitsProcessor(config.vocab_size)
214
+ self.sampler = Sampler()
215
+
216
+ def forward(
217
+ self,
218
+ input_ids: torch.Tensor,
219
+ positions: torch.Tensor,
220
+ kv_caches: List[torch.Tensor],
221
+ attn_metadata: AttentionMetadata,
222
+ ) -> torch.Tensor:
223
+ hidden_states = self.transformer(input_ids, positions, kv_caches,
224
+ attn_metadata)
225
+ return hidden_states
226
+
227
+ def compute_logits(self, hidden_states: torch.Tensor,
228
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
229
+ logits = self.logits_processor(self.lm_head_weight, hidden_states,
230
+ sampling_metadata)
231
+ return logits
232
+
233
+ def sample(
234
+ self,
235
+ logits: torch.Tensor,
236
+ sampling_metadata: SamplingMetadata,
237
+ ) -> Optional[SamplerOutput]:
238
+ next_tokens = self.sampler(logits, sampling_metadata)
239
+ return next_tokens
240
+
241
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
242
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
243
+ for name, loaded_weight in weights:
244
+ if "lm_head.weight" in name:
245
+ # GPT-2 ties the weights of the embedding layer and the final
246
+ # linear layer.
247
+ continue
248
+ if ".attn.bias" in name or ".attn.masked_bias" in name:
249
+ # Skip attention mask.
250
+ # NOTE: "c_attn.bias" should not be skipped.
251
+ continue
252
+ if not name.startswith("transformer."):
253
+ name = "transformer." + name
254
+ param = params_dict[name]
255
+ # The HF's GPT-2 implementation uses Conv1D instead of Linear.
256
+ # Because of this, we need to transpose the weights.
257
+ # Note(zhuohan): the logic below might break quantized models.
258
+ for conv1d_weight_name in ["c_attn", "c_proj", "c_fc"]:
259
+ if conv1d_weight_name not in name:
260
+ continue
261
+ if not name.endswith(".weight"):
262
+ continue
263
+ loaded_weight = loaded_weight.t()
264
+ weight_loader = getattr(param, "weight_loader",
265
+ default_weight_loader)
266
+ weight_loader(param, loaded_weight)