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,319 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://huggingface.co/OrionStarAI/Orion-14B-Base/blob/main/modeling_orion.py
4
+ # Copyright (c) OrionStar Inc.
5
+ # LICENSE: https://huggingface.co/OrionStarAI/Orion-14B-Base/blob/main/LICENSE
6
+ """Inference-only Orion-14B 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.linear import (MergedColumnParallelLinear,
17
+ QKVParallelLinear,
18
+ RowParallelLinear)
19
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
20
+ from vllm.model_executor.layers.quantization.base_config import (
21
+ QuantizationConfig)
22
+ from vllm.model_executor.layers.rotary_embedding import get_rope
23
+ from vllm.model_executor.layers.sampler import Sampler
24
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
25
+ ParallelLMHead, VocabParallelEmbedding)
26
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
27
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
28
+ from vllm.sequence import SamplerOutput
29
+
30
+
31
+ class OrionMLP(nn.Module):
32
+
33
+ def __init__(
34
+ self,
35
+ hidden_size: int,
36
+ intermediate_size: int,
37
+ hidden_act: str,
38
+ quant_config: Optional[QuantizationConfig] = None,
39
+ ) -> None:
40
+ super().__init__()
41
+ self.gate_up_proj = MergedColumnParallelLinear(
42
+ hidden_size, [intermediate_size] * 2,
43
+ bias=False,
44
+ quant_config=quant_config)
45
+ self.down_proj = RowParallelLinear(intermediate_size,
46
+ hidden_size,
47
+ bias=False,
48
+ quant_config=quant_config)
49
+ if hidden_act != "silu":
50
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
51
+ "Only silu is supported for now.")
52
+ self.act_fn = SiluAndMul()
53
+
54
+ def forward(self, x):
55
+ gate_up, _ = self.gate_up_proj(x)
56
+ x = self.act_fn(gate_up)
57
+ x, _ = self.down_proj(x)
58
+ return x
59
+
60
+
61
+ class OrionAttention(nn.Module):
62
+
63
+ def __init__(
64
+ self,
65
+ hidden_size: int,
66
+ num_heads: int,
67
+ num_kv_heads: int,
68
+ rope_theta: float = 10000,
69
+ rope_scaling: Optional[Dict[str, Any]] = None,
70
+ max_position_embeddings: int = 8192,
71
+ quant_config: Optional[QuantizationConfig] = None,
72
+ ) -> None:
73
+ super().__init__()
74
+ self.hidden_size = hidden_size
75
+ tp_size = get_tensor_model_parallel_world_size()
76
+ self.total_num_heads = num_heads
77
+ assert self.total_num_heads % tp_size == 0
78
+ self.num_heads = self.total_num_heads // tp_size
79
+ self.total_num_kv_heads = num_kv_heads
80
+ if self.total_num_kv_heads >= tp_size:
81
+ # Number of KV heads is greater than TP size, so we partition
82
+ # the KV heads across multiple tensor parallel GPUs.
83
+ assert self.total_num_kv_heads % tp_size == 0
84
+ else:
85
+ # Number of KV heads is less than TP size, so we replicate
86
+ # the KV heads across multiple tensor parallel GPUs.
87
+ assert tp_size % self.total_num_kv_heads == 0
88
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
89
+ self.head_dim = hidden_size // self.total_num_heads
90
+ self.q_size = self.num_heads * self.head_dim
91
+ self.kv_size = self.num_kv_heads * self.head_dim
92
+ self.scaling = self.head_dim**-0.5
93
+ self.rope_theta = rope_theta
94
+ self.max_position_embeddings = max_position_embeddings
95
+
96
+ self.qkv_proj = QKVParallelLinear(
97
+ hidden_size,
98
+ self.head_dim,
99
+ self.total_num_heads,
100
+ self.total_num_kv_heads,
101
+ bias=False,
102
+ quant_config=quant_config,
103
+ )
104
+ self.o_proj = RowParallelLinear(
105
+ self.total_num_heads * self.head_dim,
106
+ hidden_size,
107
+ bias=False,
108
+ quant_config=quant_config,
109
+ )
110
+
111
+ self.rotary_emb = get_rope(
112
+ self.head_dim,
113
+ rotary_dim=self.head_dim,
114
+ max_position=max_position_embeddings,
115
+ base=rope_theta,
116
+ rope_scaling=rope_scaling,
117
+ )
118
+ self.attn = Attention(self.num_heads,
119
+ self.head_dim,
120
+ self.scaling,
121
+ num_kv_heads=self.num_kv_heads)
122
+
123
+ def forward(
124
+ self,
125
+ positions: torch.Tensor,
126
+ hidden_states: torch.Tensor,
127
+ kv_cache: torch.Tensor,
128
+ attn_metadata: AttentionMetadata,
129
+ ) -> torch.Tensor:
130
+ qkv, _ = self.qkv_proj(hidden_states)
131
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
132
+ q, k = self.rotary_emb(positions, q, k)
133
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
134
+ output, _ = self.o_proj(attn_output)
135
+ return output
136
+
137
+
138
+ class OrionDecoderLayer(nn.Module):
139
+
140
+ def __init__(
141
+ self,
142
+ config: PretrainedConfig,
143
+ quant_config: Optional[QuantizationConfig] = None,
144
+ ) -> None:
145
+ super().__init__()
146
+ self.hidden_size = config.hidden_size
147
+ rope_theta = getattr(config, "rope_theta", 10000)
148
+ rope_scaling = getattr(config, "rope_scaling", None)
149
+ max_position_embeddings = getattr(config, "max_position_embeddings",
150
+ 8192)
151
+ self.self_attn = OrionAttention(
152
+ hidden_size=self.hidden_size,
153
+ num_heads=config.num_attention_heads,
154
+ num_kv_heads=config.num_key_value_heads,
155
+ rope_theta=rope_theta,
156
+ rope_scaling=rope_scaling,
157
+ max_position_embeddings=max_position_embeddings,
158
+ quant_config=quant_config,
159
+ )
160
+ self.mlp = OrionMLP(
161
+ hidden_size=self.hidden_size,
162
+ intermediate_size=config.intermediate_size,
163
+ hidden_act=config.hidden_act,
164
+ quant_config=quant_config,
165
+ )
166
+
167
+ self.input_layernorm = nn.LayerNorm(config.hidden_size,
168
+ eps=config.rms_norm_eps)
169
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size,
170
+ eps=config.rms_norm_eps)
171
+
172
+ def forward(
173
+ self,
174
+ positions: torch.Tensor,
175
+ hidden_states: torch.Tensor,
176
+ kv_cache: torch.Tensor,
177
+ attn_metadata: AttentionMetadata,
178
+ residual: Optional[torch.Tensor],
179
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
180
+ # Self Attention
181
+ residual = hidden_states
182
+ hidden_states = self.input_layernorm(hidden_states)
183
+ hidden_states = self.self_attn(
184
+ positions=positions,
185
+ hidden_states=hidden_states,
186
+ kv_cache=kv_cache,
187
+ attn_metadata=attn_metadata,
188
+ )
189
+
190
+ hidden_states = residual + hidden_states
191
+
192
+ # Fully Connected
193
+ residual = hidden_states
194
+ hidden_states = self.post_attention_layernorm(hidden_states)
195
+ hidden_states = self.mlp(hidden_states)
196
+ hidden_states = residual + hidden_states
197
+ return hidden_states, None
198
+
199
+
200
+ class OrionModel(nn.Module):
201
+
202
+ def __init__(
203
+ self,
204
+ config: PretrainedConfig,
205
+ quant_config: Optional[QuantizationConfig] = None,
206
+ ) -> None:
207
+ super().__init__()
208
+ self.config = config
209
+ self.padding_idx = config.pad_token_id
210
+ self.vocab_size = config.vocab_size
211
+ self.embed_tokens = VocabParallelEmbedding(
212
+ config.vocab_size,
213
+ config.hidden_size,
214
+ )
215
+ self.layers = nn.ModuleList([
216
+ OrionDecoderLayer(config, quant_config)
217
+ for _ in range(config.num_hidden_layers)
218
+ ])
219
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
220
+
221
+ def forward(
222
+ self,
223
+ input_ids: torch.Tensor,
224
+ positions: torch.Tensor,
225
+ kv_caches: List[torch.Tensor],
226
+ attn_metadata: AttentionMetadata,
227
+ ) -> torch.Tensor:
228
+ hidden_states = self.embed_tokens(input_ids)
229
+ residual = None
230
+ for i in range(len(self.layers)):
231
+ layer = self.layers[i]
232
+ hidden_states, residual = layer(
233
+ positions,
234
+ hidden_states,
235
+ kv_caches[i],
236
+ attn_metadata,
237
+ residual,
238
+ )
239
+ hidden_states = self.norm(hidden_states)
240
+ return hidden_states
241
+
242
+
243
+ class OrionForCausalLM(nn.Module):
244
+
245
+ def __init__(
246
+ self,
247
+ config: PretrainedConfig,
248
+ quant_config: Optional[QuantizationConfig] = None,
249
+ ) -> None:
250
+ super().__init__()
251
+ self.config = config
252
+ self.quant_config = quant_config
253
+ self.model = OrionModel(config, quant_config)
254
+ self.lm_head = ParallelLMHead(config.vocab_size, config.hidden_size)
255
+ self.logits_processor = LogitsProcessor(config.vocab_size)
256
+ self.sampler = Sampler()
257
+
258
+ def forward(
259
+ self,
260
+ input_ids: torch.Tensor,
261
+ positions: torch.Tensor,
262
+ kv_caches: List[torch.Tensor],
263
+ attn_metadata: AttentionMetadata,
264
+ ) -> torch.Tensor:
265
+ hidden_states = self.model(input_ids, positions, kv_caches,
266
+ attn_metadata)
267
+ return hidden_states
268
+
269
+ def compute_logits(self, hidden_states: torch.Tensor,
270
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
271
+ logits = self.logits_processor(self.lm_head.weight, hidden_states,
272
+ sampling_metadata)
273
+ return logits
274
+
275
+ def sample(
276
+ self,
277
+ logits: torch.Tensor,
278
+ sampling_metadata: SamplingMetadata,
279
+ ) -> Optional[SamplerOutput]:
280
+ next_tokens = self.sampler(logits, sampling_metadata)
281
+ return next_tokens
282
+
283
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
284
+ stacked_params_mapping = [
285
+ # (param_name, shard_name, shard_id)
286
+ ("qkv_proj", "q_proj", "q"),
287
+ ("qkv_proj", "k_proj", "k"),
288
+ ("qkv_proj", "v_proj", "v"),
289
+ ("gate_up_proj", "gate_proj", 0),
290
+ ("gate_up_proj", "up_proj", 1),
291
+ ]
292
+ params_dict = dict(self.named_parameters())
293
+ for name, loaded_weight in weights:
294
+ if "rotary_emb.inv_freq" in name:
295
+ continue
296
+ if ("rotary_emb.cos_cached" in name
297
+ or "rotary_emb.sin_cached" in name):
298
+ # Models trained using ColossalAI may include these tensors in
299
+ # the checkpoint. Skip them.
300
+ continue
301
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
302
+ if weight_name not in name:
303
+ continue
304
+ name = name.replace(weight_name, param_name)
305
+ # Skip loading extra bias for GPTQ models.
306
+ if name.endswith(".bias") and name not in params_dict:
307
+ continue
308
+ param = params_dict[name]
309
+ weight_loader = param.weight_loader
310
+ weight_loader(param, loaded_weight, shard_id)
311
+ break
312
+ else:
313
+ # Skip loading extra bias for GPTQ models.
314
+ if name.endswith(".bias") and name not in params_dict:
315
+ continue
316
+ param = params_dict[name]
317
+ weight_loader = getattr(param, "weight_loader",
318
+ default_weight_loader)
319
+ weight_loader(param, loaded_weight)
@@ -0,0 +1,300 @@
1
+ # coding=utf-8
2
+ # Adapted from
3
+ # https://huggingface.co/microsoft/phi-1_5/blob/main/modeling_phi.py
4
+ # Copyright 2023 The vLLM team.
5
+ # Copyright (c) Microsoft Corporation.
6
+ # Licensed under the MIT license.
7
+ #
8
+ # BSD 3-Clause License
9
+ #
10
+ # Copyright (c) 2022, Tri Dao, trid@cs.stanford.edu.
11
+ # All rights reserved.
12
+ #
13
+ # Redistribution and use in source and binary forms, with or without
14
+ # modification, are permitted provided that the following conditions are met:
15
+ #
16
+ # * Redistributions of source code must retain the above copyright notice, this
17
+ # list of conditions and the following disclaimer.
18
+ #
19
+ # * Redistributions in binary form must reproduce the above copyright notice,
20
+ # this list of conditions and the following disclaimer in the documentation
21
+ # and/or other materials provided with the distribution.
22
+ #
23
+ # * Neither the name of the copyright holder nor the names of its
24
+ # contributors may be used to endorse or promote products derived from
25
+ # this software without specific prior written permission.
26
+ #
27
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
30
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
31
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
33
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
35
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
+ """Inference-only Phi-1.5 model compatible with HuggingFace weights."""
38
+ from typing import Iterable, List, Optional, Tuple
39
+
40
+ import torch
41
+ from torch import nn
42
+ from transformers import PretrainedConfig
43
+
44
+ from vllm.attention import Attention, AttentionMetadata
45
+ from vllm.distributed import get_tensor_model_parallel_world_size
46
+ from vllm.model_executor.layers.activation import get_act_fn
47
+ from vllm.model_executor.layers.linear import (ColumnParallelLinear,
48
+ QKVParallelLinear,
49
+ RowParallelLinear)
50
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
51
+ from vllm.model_executor.layers.quantization.base_config import (
52
+ QuantizationConfig)
53
+ from vllm.model_executor.layers.rotary_embedding import get_rope
54
+ from vllm.model_executor.layers.sampler import Sampler
55
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
56
+ ParallelLMHead, VocabParallelEmbedding)
57
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
58
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
59
+ from vllm.sequence import SamplerOutput
60
+
61
+
62
+ class PhiAttention(nn.Module):
63
+
64
+ def __init__(self,
65
+ config: PretrainedConfig,
66
+ quant_config: Optional[QuantizationConfig] = None):
67
+ super().__init__()
68
+ self.total_num_heads = config.num_attention_heads
69
+ self.hidden_size = config.hidden_size
70
+ self.head_size = self.hidden_size // self.total_num_heads
71
+
72
+ tensor_model_parallel_world_size = (
73
+ get_tensor_model_parallel_world_size())
74
+ assert self.total_num_heads % tensor_model_parallel_world_size == 0
75
+ self.num_heads = (self.total_num_heads //
76
+ tensor_model_parallel_world_size)
77
+
78
+ # pylint: disable=C0103
79
+ self.qkv_proj = QKVParallelLinear(
80
+ self.hidden_size,
81
+ self.head_size,
82
+ self.total_num_heads,
83
+ bias=True,
84
+ quant_config=quant_config,
85
+ )
86
+ self.dense = RowParallelLinear(
87
+ self.hidden_size,
88
+ self.hidden_size,
89
+ quant_config=quant_config,
90
+ )
91
+
92
+ scaling = self.head_size**-0.5
93
+ rotary_dim = int(config.partial_rotary_factor *
94
+ (config.hidden_size // config.num_attention_heads))
95
+ assert rotary_dim % 2 == 0
96
+
97
+ # pylint: disable=C0301
98
+ # Refer to:
99
+ # https://huggingface.co/microsoft/phi-1_5/blob/d212a789620c380ff32ca1d1ee9943a777360987/modeling_phi.py#L518
100
+ rope_theta = 10000
101
+ max_position_embeddings = getattr(config, "n_positions", 2048)
102
+ self.rotary_emb = get_rope(
103
+ self.head_size,
104
+ rotary_dim=rotary_dim,
105
+ max_position=max_position_embeddings,
106
+ base=rope_theta,
107
+ )
108
+ self.attn = Attention(self.num_heads, self.head_size, scaling)
109
+
110
+ def forward(
111
+ self,
112
+ position_ids: torch.Tensor,
113
+ hidden_states: torch.Tensor,
114
+ kv_cache: torch.Tensor,
115
+ attn_metadata: AttentionMetadata,
116
+ ) -> torch.Tensor:
117
+ qkv, _ = self.qkv_proj(hidden_states)
118
+ q, k, v = qkv.chunk(chunks=3, dim=-1)
119
+ q, k = self.rotary_emb(position_ids, q, k)
120
+ attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
121
+ output, _ = self.dense(attn_output)
122
+ return output
123
+
124
+
125
+ class PhiMLP(nn.Module):
126
+
127
+ def __init__(self,
128
+ config: PretrainedConfig,
129
+ quant_config: Optional[QuantizationConfig] = None):
130
+ super().__init__()
131
+
132
+ n_inner = getattr(config, "n_inner", None)
133
+ n_inner = n_inner if n_inner is not None else 4 * config.hidden_size
134
+
135
+ self.fc1 = ColumnParallelLinear(
136
+ config.hidden_size,
137
+ n_inner,
138
+ quant_config=quant_config,
139
+ )
140
+ self.fc2 = RowParallelLinear(
141
+ n_inner,
142
+ config.hidden_size,
143
+ quant_config=quant_config,
144
+ )
145
+ self.act = get_act_fn(config.hidden_act, quant_config, n_inner)
146
+
147
+ def forward(self, hidden_states):
148
+ hidden_states, _ = self.fc1(hidden_states)
149
+ hidden_states = self.act(hidden_states)
150
+ hidden_states, _ = self.fc2(hidden_states)
151
+ return hidden_states
152
+
153
+
154
+ class PhiLayer(nn.Module):
155
+
156
+ def __init__(self,
157
+ config: PretrainedConfig,
158
+ quant_config: Optional[QuantizationConfig] = None):
159
+ super().__init__()
160
+ self.input_layernorm = nn.LayerNorm(config.hidden_size,
161
+ eps=config.layer_norm_eps)
162
+ self.self_attn = PhiAttention(config, quant_config)
163
+ self.mlp = PhiMLP(config, quant_config)
164
+
165
+ def forward(
166
+ self,
167
+ position_ids: torch.Tensor,
168
+ hidden_states: torch.Tensor,
169
+ kv_cache: torch.Tensor,
170
+ attn_metadata: AttentionMetadata,
171
+ ) -> torch.Tensor:
172
+ residual = hidden_states
173
+ hidden_states = self.input_layernorm(hidden_states)
174
+ attn_outputs = self.self_attn(
175
+ position_ids=position_ids,
176
+ hidden_states=hidden_states,
177
+ kv_cache=kv_cache,
178
+ attn_metadata=attn_metadata,
179
+ )
180
+ feed_forward_hidden_states = self.mlp(hidden_states)
181
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
182
+ return hidden_states
183
+
184
+
185
+ class PhiModel(nn.Module):
186
+
187
+ def __init__(self,
188
+ config: PretrainedConfig,
189
+ quant_config: Optional[QuantizationConfig] = None):
190
+ super().__init__()
191
+ self.config = config
192
+ self.quant_config = quant_config
193
+ self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
194
+ config.hidden_size)
195
+ self.layers = nn.ModuleList([
196
+ PhiLayer(config, quant_config)
197
+ for _ in range(config.num_hidden_layers)
198
+ ])
199
+ self.final_layernorm = nn.LayerNorm(config.hidden_size,
200
+ eps=config.layer_norm_eps)
201
+
202
+ def forward(
203
+ self,
204
+ input_ids: torch.Tensor,
205
+ positions: torch.Tensor,
206
+ kv_caches: List[torch.Tensor],
207
+ attn_metadata: AttentionMetadata,
208
+ ) -> torch.Tensor:
209
+ hidden_states = self.embed_tokens(input_ids)
210
+ for i in range(self.config.num_hidden_layers):
211
+ layer = self.layers[i]
212
+ hidden_states = layer(
213
+ positions,
214
+ hidden_states,
215
+ kv_caches[i],
216
+ attn_metadata,
217
+ )
218
+
219
+ hidden_states = self.final_layernorm(hidden_states)
220
+
221
+ return hidden_states
222
+
223
+
224
+ class PhiForCausalLM(nn.Module):
225
+
226
+ def __init__(self,
227
+ config: PretrainedConfig,
228
+ quant_config: Optional[QuantizationConfig] = None):
229
+ super().__init__()
230
+ self.config = config
231
+ self.quant_config = quant_config
232
+
233
+ self.model = PhiModel(config, quant_config)
234
+
235
+ self.lm_head = ParallelLMHead(config.vocab_size,
236
+ config.hidden_size,
237
+ bias=True)
238
+ self.logits_processor = LogitsProcessor(config.vocab_size)
239
+ self.sampler = Sampler()
240
+
241
+ def forward(
242
+ self,
243
+ input_ids: torch.Tensor,
244
+ positions: torch.Tensor,
245
+ kv_caches: List[torch.Tensor],
246
+ attn_metadata: AttentionMetadata,
247
+ ) -> torch.Tensor:
248
+ hidden_states = self.model(input_ids, positions, kv_caches,
249
+ attn_metadata)
250
+
251
+ return hidden_states
252
+
253
+ def compute_logits(self, hidden_states: torch.Tensor,
254
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
255
+ logits = self.logits_processor(self.lm_head.weight, hidden_states,
256
+ sampling_metadata, self.lm_head.bias)
257
+ return logits
258
+
259
+ def sample(
260
+ self,
261
+ logits: torch.Tensor,
262
+ sampling_metadata: SamplingMetadata,
263
+ ) -> Optional[SamplerOutput]:
264
+ next_tokens = self.sampler(logits, sampling_metadata)
265
+ return next_tokens
266
+
267
+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
268
+ stacked_params_mapping = [
269
+ # (param_name, shard_name, shard_id)
270
+ ("qkv_proj", "q_proj", "q"),
271
+ ("qkv_proj", "k_proj", "k"),
272
+ ("qkv_proj", "v_proj", "v")
273
+ ]
274
+ params_dict = dict(self.named_parameters())
275
+
276
+ for name, loaded_weight in weights:
277
+ if "rotary_emb.inv_freq" in name:
278
+ continue
279
+
280
+ for (param_name, weight_name, shard_id) in stacked_params_mapping:
281
+ if weight_name not in name:
282
+ continue
283
+ name = name.replace(weight_name, param_name)
284
+ # Skip loading extra bias for GPTQ models.
285
+ if name.endswith(".bias") and name not in params_dict:
286
+ continue
287
+ param = params_dict[name]
288
+ weight_loader = param.weight_loader
289
+ weight_loader(param, loaded_weight, shard_id)
290
+ break
291
+ else:
292
+ # Skip loading extra bias for GPTQ models.
293
+ if name.endswith(".bias") and name not in params_dict:
294
+ continue
295
+ # pylint: disable=E1136
296
+
297
+ param = params_dict[name]
298
+ weight_loader = getattr(param, "weight_loader",
299
+ default_weight_loader)
300
+ weight_loader(param, loaded_weight)