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,413 @@
1
+ # coding=utf-8
2
+ from typing import Iterable, List, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from vllm.attention import Attention, AttentionMetadata
8
+ from vllm.distributed import (get_tensor_model_parallel_rank,
9
+ get_tensor_model_parallel_world_size,
10
+ tensor_model_parallel_all_reduce)
11
+ from vllm.model_executor.layers.fused_moe import fused_moe
12
+ from vllm.model_executor.layers.linear import (QKVParallelLinear,
13
+ ReplicatedLinear,
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
+ DEFAULT_VOCAB_PADDING_SIZE, 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.model_executor.utils import set_weight_attrs
25
+ from vllm.sequence import SamplerOutput
26
+ from vllm.transformers_utils.configs.dbrx import DbrxConfig
27
+
28
+
29
+ class DbrxRouter(nn.Module):
30
+ """A Router implementation for DBRX that returns logits for each expert
31
+ per token.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ config: DbrxConfig,
37
+ params_dtype: Optional[torch.dtype] = None,
38
+ ):
39
+ super().__init__()
40
+ self.tp_size = get_tensor_model_parallel_world_size()
41
+ self.num_total_experts = config.ffn_config.moe_num_experts
42
+ self.d_model = config.d_model
43
+ self.layer = ReplicatedLinear(
44
+ self.d_model,
45
+ self.num_total_experts,
46
+ bias=False,
47
+ params_dtype=params_dtype,
48
+ quant_config=None,
49
+ )
50
+
51
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
52
+ router_logits, _ = self.layer(hidden_states)
53
+ return router_logits
54
+
55
+
56
+ class DbrxExperts(nn.Module):
57
+ """A tensor-parallel MoE implementation for DBRX.
58
+
59
+ Each expert's weights are sharded across all ranks and a fused MoE
60
+ kernel is used for the forward pass, and finally we reduce the outputs
61
+ across ranks.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ config: DbrxConfig,
67
+ quant_config: Optional[QuantizationConfig] = None,
68
+ params_dtype: Optional[torch.dtype] = None,
69
+ ):
70
+ super().__init__()
71
+ self.tp_size = get_tensor_model_parallel_world_size()
72
+ self.num_total_experts = config.ffn_config.moe_num_experts
73
+ self.top_k = config.ffn_config.moe_top_k
74
+ self.d_model = config.d_model
75
+ self.intermediate_size = (config.ffn_config.ffn_hidden_size //
76
+ self.tp_size)
77
+
78
+ if params_dtype is None:
79
+ params_dtype = torch.get_default_dtype()
80
+ self.params_dtype = params_dtype
81
+
82
+ self.router = DbrxRouter(config, self.params_dtype)
83
+ self.ws = nn.Parameter(
84
+ torch.empty(
85
+ self.num_total_experts,
86
+ 2 * self.intermediate_size,
87
+ self.d_model,
88
+ device="cuda",
89
+ dtype=self.params_dtype,
90
+ ))
91
+ self.w2s = nn.Parameter(
92
+ torch.empty(
93
+ self.num_total_experts,
94
+ self.d_model,
95
+ self.intermediate_size,
96
+ device="cuda",
97
+ dtype=self.params_dtype,
98
+ ))
99
+
100
+ set_weight_attrs(
101
+ self.ws,
102
+ {
103
+ "weight_loader": self.weight_loader,
104
+ },
105
+ )
106
+ set_weight_attrs(
107
+ self.w2s,
108
+ {
109
+ "weight_loader": self.weight_loader,
110
+ },
111
+ )
112
+
113
+ def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor,
114
+ weight_name: str):
115
+ tp_rank = get_tensor_model_parallel_rank()
116
+ param_data = param.data
117
+ shard_size = self.intermediate_size
118
+ shard = slice(tp_rank * shard_size, (tp_rank + 1) * shard_size)
119
+ # DBRX uses GLU for each experts.
120
+ # GLU has 3 linear layers: w1, v1 and w2.
121
+ if weight_name.endswith("w1"):
122
+ loaded_weight = torch.reshape(
123
+ loaded_weight,
124
+ [-1, self.intermediate_size * self.tp_size, self.d_model],
125
+ )
126
+ param_data[:, 0:shard_size, :] = loaded_weight[:, shard, :]
127
+ if weight_name.endswith("v1"):
128
+ loaded_weight = torch.reshape(
129
+ loaded_weight,
130
+ [-1, self.intermediate_size * self.tp_size, self.d_model],
131
+ )
132
+ param_data[:,
133
+ shard_size:2 * shard_size, :] = loaded_weight[:,
134
+ shard, :]
135
+ if weight_name.endswith("w2"):
136
+ loaded_weight = torch.reshape(
137
+ loaded_weight,
138
+ [-1, self.intermediate_size * self.tp_size, self.d_model],
139
+ ).transpose(1, 2)
140
+ param_data[:] = loaded_weight[:, :, shard]
141
+
142
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
143
+ num_tokens, hidden_size = hidden_states.shape
144
+ hidden_states = hidden_states.view(-1, self.d_model)
145
+ # router_logits: (num_tokens, n_experts)
146
+ router_logits = self.router(hidden_states)
147
+ final_hidden_states = fused_moe(
148
+ hidden_states,
149
+ self.ws,
150
+ self.w2s,
151
+ router_logits,
152
+ self.top_k,
153
+ renormalize=True,
154
+ inplace=True,
155
+ )
156
+
157
+ if self.tp_size > 1:
158
+ final_hidden_states = tensor_model_parallel_all_reduce(
159
+ final_hidden_states)
160
+
161
+ return final_hidden_states.view(num_tokens, hidden_size)
162
+
163
+
164
+ class DbrxAttention(nn.Module):
165
+
166
+ def __init__(
167
+ self,
168
+ config: DbrxConfig,
169
+ quant_config: Optional[QuantizationConfig] = None,
170
+ ):
171
+ super().__init__()
172
+ self.d_model = config.d_model
173
+ self.total_num_heads = config.n_heads
174
+ self.head_dim = self.d_model // self.total_num_heads
175
+ self.total_num_kv_heads = config.attn_config.kv_n_heads
176
+ self.clip_qkv = config.attn_config.clip_qkv
177
+ self.rope_theta = config.attn_config.rope_theta
178
+ self.max_position = config.max_seq_len
179
+
180
+ # pylint: disable=invalid-name
181
+ self.Wqkv = QKVParallelLinear(
182
+ self.d_model,
183
+ self.head_dim,
184
+ self.total_num_heads,
185
+ self.total_num_kv_heads,
186
+ bias=False,
187
+ quant_config=quant_config,
188
+ )
189
+ self.out_proj = RowParallelLinear(
190
+ self.d_model,
191
+ self.d_model,
192
+ bias=False,
193
+ quant_config=quant_config,
194
+ )
195
+ self.rotary_emb = get_rope(
196
+ self.head_dim,
197
+ rotary_dim=self.head_dim,
198
+ max_position=self.max_position,
199
+ base=int(self.rope_theta),
200
+ is_neox_style=True,
201
+ )
202
+
203
+ tp_world_size = get_tensor_model_parallel_world_size()
204
+ self.tp_size = tp_world_size
205
+ assert self.total_num_heads % tp_world_size == 0
206
+ self.num_heads = self.total_num_heads // tp_world_size
207
+ if self.total_num_kv_heads >= tp_world_size:
208
+ # Number of KV heads is greater than TP size, so we partition
209
+ # the KV heads across multiple tensor parallel GPUs.
210
+ assert self.total_num_kv_heads % tp_world_size == 0
211
+ else:
212
+ # Number of KV heads is less than TP size, so we replicate
213
+ # the KV heads across multiple tensor parallel GPUs.
214
+ assert tp_world_size % self.total_num_kv_heads == 0
215
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_world_size)
216
+ self.q_size = self.num_heads * self.head_dim
217
+ self.kv_size = self.num_kv_heads * self.head_dim
218
+ self.scaling = self.head_dim**-0.5
219
+ self.attn = Attention(
220
+ self.num_heads,
221
+ self.head_dim,
222
+ self.scaling,
223
+ num_kv_heads=self.num_kv_heads,
224
+ )
225
+
226
+ def forward(
227
+ self,
228
+ position_ids: torch.Tensor,
229
+ hidden_states: torch.Tensor,
230
+ kv_cache: torch.Tensor,
231
+ attn_metadata: AttentionMetadata,
232
+ ) -> torch.Tensor:
233
+ qkv, _ = self.Wqkv(hidden_states)
234
+ if self.clip_qkv is not None:
235
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
236
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
237
+ q, k = self.rotary_emb(position_ids, q, k)
238
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
239
+ hidden_states, _ = self.out_proj(attn_output)
240
+ return hidden_states
241
+
242
+
243
+ class DbrxFusedNormAttention(nn.Module):
244
+
245
+ def __init__(
246
+ self,
247
+ config: DbrxConfig,
248
+ quant_config: Optional[QuantizationConfig] = None,
249
+ ):
250
+ super().__init__()
251
+ self.d_model = config.d_model
252
+ self.attn = DbrxAttention(config, quant_config)
253
+ self.norm_1 = nn.LayerNorm(self.d_model)
254
+ self.norm_2 = nn.LayerNorm(self.d_model)
255
+
256
+ def forward(
257
+ self,
258
+ position_ids: torch.Tensor,
259
+ hidden_states: torch.Tensor,
260
+ kv_cache: torch.Tensor,
261
+ attn_metadata: AttentionMetadata,
262
+ ) -> torch.Tensor:
263
+ residual = hidden_states
264
+ hidden_states = self.norm_1(hidden_states)
265
+ x = self.attn(
266
+ position_ids=position_ids,
267
+ hidden_states=hidden_states,
268
+ kv_cache=kv_cache,
269
+ attn_metadata=attn_metadata,
270
+ )
271
+ hidden_states = residual + x
272
+ residual = hidden_states
273
+ hidden_states = self.norm_2(hidden_states)
274
+ return hidden_states, residual
275
+
276
+
277
+ class DbrxBlock(nn.Module):
278
+
279
+ def __init__(
280
+ self,
281
+ config: DbrxConfig,
282
+ quant_config: Optional[QuantizationConfig] = None,
283
+ ):
284
+ super().__init__()
285
+ self.norm_attn_norm = DbrxFusedNormAttention(config, quant_config)
286
+ self.ffn = DbrxExperts(config, quant_config)
287
+
288
+ def forward(
289
+ self,
290
+ position_ids: torch.Tensor,
291
+ hidden_states: torch.Tensor,
292
+ kv_cache: torch.Tensor,
293
+ attn_metadata: AttentionMetadata,
294
+ ) -> torch.Tensor:
295
+ hidden_states, residual = self.norm_attn_norm(
296
+ position_ids=position_ids,
297
+ hidden_states=hidden_states,
298
+ kv_cache=kv_cache,
299
+ attn_metadata=attn_metadata,
300
+ )
301
+ hidden_states = self.ffn(hidden_states)
302
+ hidden_states = hidden_states + residual
303
+ return hidden_states
304
+
305
+
306
+ class DbrxModel(nn.Module):
307
+
308
+ def __init__(
309
+ self,
310
+ config: DbrxConfig,
311
+ quant_config: Optional[QuantizationConfig] = None,
312
+ ):
313
+ super().__init__()
314
+ self.wte = VocabParallelEmbedding(
315
+ config.vocab_size,
316
+ config.d_model,
317
+ )
318
+ self.blocks = nn.ModuleList(
319
+ [DbrxBlock(config, quant_config) for _ in range(config.n_layers)])
320
+ self.norm_f = nn.LayerNorm(config.d_model, eps=1e-5)
321
+ for module in self.modules():
322
+ if hasattr(module, "bias") and isinstance(module.bias,
323
+ nn.Parameter):
324
+ # Remove the bias term in Linear and LayerNorm.
325
+ module.register_parameter("bias", None)
326
+
327
+ def forward(
328
+ self,
329
+ input_ids: torch.Tensor,
330
+ position_ids: torch.Tensor,
331
+ kv_caches: List[torch.Tensor],
332
+ attn_metadata: AttentionMetadata,
333
+ ) -> torch.Tensor:
334
+ hidden_states = self.wte(input_ids)
335
+ for i in range(len(self.blocks)):
336
+ block = self.blocks[i]
337
+ hidden_states = block(
338
+ position_ids,
339
+ hidden_states,
340
+ kv_caches[i],
341
+ attn_metadata,
342
+ )
343
+ hidden_states = self.norm_f(hidden_states)
344
+ return hidden_states
345
+
346
+
347
+ class DbrxForCausalLM(nn.Module):
348
+
349
+ def __init__(
350
+ self,
351
+ config: DbrxConfig,
352
+ quant_config: Optional[QuantizationConfig] = None,
353
+ ):
354
+ super().__init__()
355
+ self.config = config
356
+ self.quant_config = quant_config
357
+ self.unpadded_vocab_size = config.vocab_size
358
+ self.transformer = DbrxModel(config, quant_config)
359
+ self.lm_head = ParallelLMHead(
360
+ config.vocab_size,
361
+ config.d_model,
362
+ org_num_embeddings=config.vocab_size,
363
+ padding_size=DEFAULT_VOCAB_PADDING_SIZE,
364
+ )
365
+ self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
366
+ config.vocab_size)
367
+ self.sampler = Sampler()
368
+
369
+ def forward(
370
+ self,
371
+ input_ids: torch.Tensor,
372
+ positions: torch.Tensor,
373
+ kv_caches: List[torch.Tensor],
374
+ attn_metadata: AttentionMetadata,
375
+ ) -> torch.Tensor:
376
+ hidden_states = self.transformer(input_ids, positions, kv_caches,
377
+ attn_metadata)
378
+ return hidden_states
379
+
380
+ def compute_logits(self, hidden_states: torch.Tensor,
381
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
382
+ logits = self.logits_processor(self.lm_head.weight, hidden_states,
383
+ sampling_metadata)
384
+ return logits
385
+
386
+ def sample(
387
+ self,
388
+ logits: Optional[torch.Tensor],
389
+ sampling_metadata: SamplingMetadata,
390
+ ) -> Optional[SamplerOutput]:
391
+ next_tokens = self.sampler(logits, sampling_metadata)
392
+ return next_tokens
393
+
394
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
395
+ expert_params_mapping = [(
396
+ "ws" if weight_name in ["w1", "v1"] else "w2s",
397
+ f"experts.mlp.{weight_name}",
398
+ ) for weight_name in ["w1", "v1", "w2"]]
399
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
400
+ for name, loaded_weight in weights:
401
+ for param_name, weight_name in expert_params_mapping:
402
+ if weight_name not in name:
403
+ continue
404
+ name = name.replace(weight_name, param_name)
405
+ param = params_dict[name]
406
+ weight_loader = param.weight_loader
407
+ weight_loader(param, loaded_weight, weight_name)
408
+ break
409
+ else:
410
+ param = params_dict[name]
411
+ weight_loader = getattr(param, "weight_loader",
412
+ default_weight_loader)
413
+ weight_loader(param, loaded_weight)
@@ -0,0 +1,122 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
4
+ # Copyright 2023 DeciAI Research Team. All rights reserved.
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 MistralAI 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 DeciLM model compatible with HuggingFace weights."""
25
+
26
+ from typing import Iterable, Optional, Tuple
27
+
28
+ import torch
29
+ from transformers import PretrainedConfig
30
+
31
+ from vllm.config import LoRAConfig
32
+ from vllm.model_executor.layers.quantization.base_config import (
33
+ QuantizationConfig)
34
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
35
+ from vllm.model_executor.models.llama import LlamaForCausalLM
36
+
37
+
38
+ class DeciLMForCausalLM(LlamaForCausalLM):
39
+ """
40
+ Implementation for https://huggingface.co/Deci/DeciLM-7b-instruct.
41
+ Based on the llama executor.
42
+
43
+ The main difference is that DeciLM uses Variable Grouped Query Attention.
44
+ The constant number of GQA heads in the decoder is overridden with a value
45
+ per layer.
46
+
47
+ Usually, in the HuggingFace implementation, instead of
48
+ "config.num_key_value_heads", we use
49
+ "config.num_key_value_heads_per_layer[i]" which varies.
50
+
51
+ Currently, PagedAttention does not work well with variable GQA, so we
52
+ normalize the weights upon loading, and use uniform GQA with the max value
53
+ instead.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ config: Optional[PretrainedConfig] = None,
59
+ quant_config: Optional[QuantizationConfig] = None,
60
+ lora_config: Optional[LoRAConfig] = None,
61
+ ) -> None:
62
+ config.num_key_value_heads = max(config.num_key_value_heads_per_layer)
63
+ delattr(config, "num_key_value_heads_per_layer")
64
+ super().__init__(config=config,
65
+ quant_config=quant_config,
66
+ lora_config=lora_config)
67
+
68
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
69
+ stacked_params_mapping = [
70
+ # (param_name, shard_name, shard_id)
71
+ ("qkv_proj", "q_proj", "q"),
72
+ ("qkv_proj", "k_proj", "k"),
73
+ ("qkv_proj", "v_proj", "v"),
74
+ ("gate_up_proj", "gate_proj", 0),
75
+ ("gate_up_proj", "up_proj", 1),
76
+ ]
77
+ params_dict = dict(self.named_parameters())
78
+ for name, loaded_weight in weights:
79
+ if "rotary_emb.inv_freq" in name:
80
+ continue
81
+
82
+ if "k_proj" in name or "v_proj" in name:
83
+ loaded_weight = self._degroup_weight(loaded_weight)
84
+
85
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
86
+ if weight_name not in name:
87
+ continue
88
+ name = name.replace(weight_name, param_name)
89
+ # Skip loading extra bias for GPTQ models.
90
+ if name.endswith(".bias") and name not in params_dict:
91
+ continue
92
+ param = params_dict[name]
93
+ weight_loader = param.weight_loader
94
+ weight_loader(param, loaded_weight, shard_id)
95
+ break
96
+ else:
97
+ # Skip loading extra bias for GPTQ models.
98
+ if name.endswith(".bias") and name not in params_dict:
99
+ continue
100
+ param = params_dict[name]
101
+ weight_loader = getattr(param, "weight_loader",
102
+ default_weight_loader)
103
+ weight_loader(param, loaded_weight)
104
+
105
+ def _degroup_weight(self, loaded_weight: torch.Tensor) -> torch.Tensor:
106
+ hidden_size = self.config.hidden_size
107
+ head_size = self.config.hidden_size // self.config.num_attention_heads
108
+ target_num_kv_heads = self.config.num_key_value_heads
109
+ num_kv_heads = loaded_weight.shape[0] // head_size
110
+ n_repeats = target_num_kv_heads / num_kv_heads
111
+ assert n_repeats == int(n_repeats)
112
+
113
+ n_repeats = int(n_repeats)
114
+ loaded_weight = loaded_weight.view(num_kv_heads, head_size,
115
+ hidden_size)
116
+ loaded_weight = torch.repeat_interleave(loaded_weight,
117
+ repeats=n_repeats,
118
+ dim=0)
119
+ loaded_weight = loaded_weight.reshape(target_num_kv_heads * head_size,
120
+ hidden_size)
121
+
122
+ return loaded_weight