A high-throughput and memory-efficient inference and serving engine for LLMs
Mirrored from https://github.com/tduncan-lum/Nvidia-Optimization-Stack---VLLM.git
Synced Nov 17, 08:00 UTC
[Model] Add support for GPT-J (#226)
Co-authored-by: woWoosuk Kwon <woosuk.kwon@berkeley.edu>
Andre Slavescu committed
Jul 8, 2023 at 20:55 UTC
c894836108732d0cbb6fce15aeda8de1218a380d
10 files changed
+269
-7
README.md
+1
@@ -44,6 +44,7 @@ vLLM seamlessly supports many Huggingface models, including the following archit
44
- BLOOM (`bigscience/bloom`, `bigscience/bloomz`, etc.)
45
- GPT-2 (`gpt2`, `gpt2-xl`, etc.)
46
- GPT BigCode (`bigcode/starcoder`, `bigcode/gpt_bigcode-santacoder`, etc.)
47
+- GPT-J (`EleutherAI/gpt-j-6b`, `nomic-ai/gpt4all-j`, etc.)
48
- GPT-NeoX (`EleutherAI/gpt-neox-20b`, `databricks/dolly-v2-12b`, `stabilityai/stablelm-tuned-alpha-7b`, etc.)
49
- LLaMA (`lmsys/vicuna-13b-v1.3`, `young-geng/koala`, `openlm-research/open_llama_13b`, etc.)
50
- MPT (`mosaicml/mpt-7b`, `mosaicml/mpt-30b`, etc.)
csrc/attention/attention_kernels.cu
+4
-4
@@ -382,7 +382,7 @@ void single_query_cached_kv_attention_launcher(
382
const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
383
switch (head_size) {
384
// NOTE(woosuk): To reduce the compilation time, we omitted head sizes
385
- // 32, 160, 192, 256.
385
+ // 32, 160, 192.
386
// case 32:
387
// LAUNCH_ATTENTION_KERNEL(T, 32, BLOCK_SIZE, NUM_THREADS);
388
// break;
@@ -407,9 +407,9 @@ void single_query_cached_kv_attention_launcher(
407
// case 192:
408
// LAUNCH_ATTENTION_KERNEL(T, 192, BLOCK_SIZE, NUM_THREADS);
409
// break;
410
- // case 256:
411
- // LAUNCH_ATTENTION_KERNEL(T, 256, BLOCK_SIZE, NUM_THREADS);
412
- // break;
410
+ case 256:
411
+ LAUNCH_ATTENTION_KERNEL(T, 256, BLOCK_SIZE, NUM_THREADS);
412
+ break;
413
default:
414
TORCH_CHECK(false, "Unsupported head size: ", head_size);
415
break;
docs/source/models/supported_models.rst
+3
@@ -23,6 +23,9 @@ Alongside each architecture, we include some popular models that use it.
23
* - :code:`GPTBigCodeForCausalLM`
24
- StarCoder, SantaCoder, WizardCoder
25
- :code:`bigcode/starcoder`, :code:`bigcode/gpt_bigcode-santacoder`, :code:`WizardLM/WizardCoder-15B-V1.0`, etc.
26
+ * - :code:`GPTJForCausalLM`
27
+ - GPT-J
28
+ - :code:`EleutherAI/gpt-j-6b`, :code:`nomic-ai/gpt4all-j`, etc.
29
* - :code:`GPTNeoXForCausalLM`
30
- GPT-NeoX, Pythia, OpenAssistant, Dolly V2, StableLM
31
- :code:`EleutherAI/gpt-neox-20b`, :code:`EleutherAI/pythia-12b`, :code:`OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5`, :code:`databricks/dolly-v2-12b`, :code:`stabilityai/stablelm-tuned-alpha-7b`, etc.
tests/kernels/test_attention.py
+2
-2
@@ -286,7 +286,7 @@ def test_single_query_cached_kv_attention() -> None:
286
torch.cuda.manual_seed(TEST_SEED)
287
for dtype in [torch.half, torch.bfloat16, torch.float]:
288
for block_size in [8, 16, 32]:
289
- for head_size in [64, 80, 96, 128]:
289
+ for head_size in [64, 80, 96, 112, 128, 256]:
290
print(f'Testing single_query_cached_kv_attention with '
291
f'dtype={dtype}, block_size={block_size}, '
292
f'head_size={head_size}')
@@ -304,7 +304,7 @@ def test_multi_query_kv_attention() -> None:
304
torch.random.manual_seed(TEST_SEED)
305
torch.cuda.manual_seed(TEST_SEED)
306
for dtype in [torch.half, torch.bfloat16, torch.float]:
307
- for head_size in [64, 80, 96, 128]:
307
+ for head_size in [64, 80, 96, 112, 128, 256]:
308
print(f'Testing multi_query_kv_attention with dtype={dtype}, '
309
f'head_size={head_size}')
310
run_multi_query_kv_attention(
vllm/model_executor/layers/attention.py
+1
-1
@@ -12,7 +12,7 @@ from vllm import cache_ops
12
from vllm import pos_encoding_ops
13
from vllm.model_executor.input_metadata import InputMetadata
14
15
-_SUPPORTED_HEAD_SIZES = [64, 80, 96, 112, 128]
15
+_SUPPORTED_HEAD_SIZES = [64, 80, 96, 112, 128, 256]
16
17
18
class PagedAttention(nn.Module):
vllm/model_executor/layers/sampler.py
+3
@@ -38,12 +38,15 @@ class Sampler(nn.Module):
38
embedding: torch.Tensor,
39
hidden_states: torch.Tensor,
40
input_metadata: InputMetadata,
41
+ embedding_bias: Optional[torch.Tensor] = None,
42
) -> Dict[int, SequenceOutputs]:
43
# Get the hidden states that we use for sampling.
44
hidden_states = _prune_hidden_states(hidden_states, input_metadata)
45
46
# Get the logits for the next tokens.
47
logits = torch.matmul(hidden_states, embedding.t())
48
+ if embedding_bias is not None:
49
+ logits += embedding_bias
50
logits = gather_from_tensor_model_parallel_region(logits)
51
# Remove paddings in vocab (if any).
52
logits = logits[:, :self.vocab_size]
vllm/model_executor/model_loader.py
+1
@@ -14,6 +14,7 @@ _MODEL_REGISTRY = {
14
"BloomForCausalLM": BloomForCausalLM,
15
"GPT2LMHeadModel": GPT2LMHeadModel,
16
"GPTBigCodeForCausalLM": GPTBigCodeForCausalLM,
17
+ "GPTJForCausalLM": GPTJForCausalLM,
18
"GPTNeoXForCausalLM": GPTNeoXForCausalLM,
19
"LlamaForCausalLM": LlamaForCausalLM,
20
"LLaMAForCausalLM": LlamaForCausalLM, # For decapoda-research/llama-*
vllm/model_executor/models/__init__.py
+2
@@ -1,6 +1,7 @@
1
from vllm.model_executor.models.bloom import BloomForCausalLM
2
from vllm.model_executor.models.gpt2 import GPT2LMHeadModel
3
from vllm.model_executor.models.gpt_bigcode import GPTBigCodeForCausalLM
4
+from vllm.model_executor.models.gpt_j import GPTJForCausalLM
5
from vllm.model_executor.models.gpt_neox import GPTNeoXForCausalLM
6
from vllm.model_executor.models.llama import LlamaForCausalLM
7
from vllm.model_executor.models.mpt import MPTForCausalLM
@@ -10,6 +11,7 @@ __all__ = [
11
"BloomForCausalLM",
12
"GPT2LMHeadModel",
13
"GPTBigCodeForCausalLM",
14
+ "GPTJForCausalLM",
15
"GPTNeoXForCausalLM",
16
"LlamaForCausalLM",
17
"MPTForCausalLM",
vllm/model_executor/models/gpt_j.py
new
+251
@@ -0,0 +1,251 @@
1
+# coding=utf-8
2
+# Adapted from
3
+# https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/gptj/modeling_gptj.py
4
+# Copyright 2023 The vLLM team.
5
+# Copyright 2021 The EleutherAI and HuggingFace Teams. All rights reserved.
6
+#
7
+# Licensed under the Apache License, Version 2.0 (the "License");
8
+# you may not use this file except in compliance with the License.
9
+# You may obtain a copy of the License at
10
+#
11
+# http://www.apache.org/licenses/LICENSE-2.0
12
+#
13
+# Unless required by applicable law or agreed to in writing, software
14
+# distributed under the License is distributed on an "AS IS" BASIS,
15
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+# See the License for the specific language governing permissions and
17
+# limitations under the License.
18
+"""Inference-only GPT-J model compatible with HuggingFace weights.
19
+
20
+The input of the model is flattened to a 1D tensor of tokens. The model uses
21
+InputMetadata to extract the original 2D shape of the input.
22
+"""
23
+from typing import Dict, List, Optional, Tuple
24
+
25
+import torch
26
+from torch import nn
27
+from transformers import GPTJConfig
28
+
29
+from vllm.model_executor.input_metadata import InputMetadata
30
+from vllm.model_executor.layers.activation import get_act_fn
31
+from vllm.model_executor.layers.attention import PagedAttentionWithRoPE
32
+from vllm.model_executor.layers.sampler import Sampler
33
+from vllm.model_executor.weight_utils import (hf_model_weights_iterator,
34
+ load_tensor_parallel_weights)
35
+from vllm.model_executor.parallel_utils.parallel_state import (
36
+ get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size)
37
+from vllm.model_executor.parallel_utils.tensor_parallel import (
38
+ VocabParallelEmbedding, ColumnParallelLinear, RowParallelLinear)
39
+from vllm.sequence import SequenceOutputs
40
+
41
+KVCache = Tuple[torch.Tensor, torch.Tensor]
42
+
43
+
44
+class GPTJAttention(nn.Module):
45
+
46
+ def __init__(self, config: GPTJConfig):
47
+ super().__init__()
48
+ self.total_num_heads = config.num_attention_heads
49
+ self.hidden_size = config.hidden_size
50
+ self.head_size = self.hidden_size // self.total_num_heads
51
+
52
+ self.qkv_proj = ColumnParallelLinear(config.hidden_size,
53
+ 3 * config.hidden_size,
54
+ bias=False,
55
+ gather_output=False,
56
+ perform_initialization=False)
57
+ self.out_proj = RowParallelLinear(config.hidden_size,
58
+ config.hidden_size,
59
+ bias=False,
60
+ input_is_parallel=True,
61
+ perform_initialization=False)
62
+
63
+ tp_world_size = get_tensor_model_parallel_world_size()
64
+ assert self.total_num_heads % tp_world_size == 0
65
+ self.num_heads = self.total_num_heads // tp_world_size
66
+
67
+ scaling = self.head_size**-0.5
68
+ assert config.rotary
69
+ assert config.rotary_dim % 2 == 0
70
+ self.attn = PagedAttentionWithRoPE(self.num_heads, self.head_size,
71
+ scaling, config.rotary_dim)
72
+ self.warmup = False
73
+
74
+ def forward(
75
+ self,
76
+ position_ids: torch.Tensor,
77
+ hidden_states: torch.Tensor,
78
+ kv_cache: KVCache,
79
+ input_metadata: InputMetadata,
80
+ cache_event: Optional[torch.cuda.Event],
81
+ ) -> torch.Tensor:
82
+ qkv, _ = self.qkv_proj(hidden_states)
83
+ q, k, v = qkv.chunk(chunks=3, dim=-1)
84
+ k_cache, v_cache = kv_cache
85
+ attn_output = self.attn(position_ids, q, k, v, k_cache, v_cache,
86
+ input_metadata, cache_event)
87
+ attn_output, _ = self.out_proj(attn_output)
88
+ return attn_output
89
+
90
+
91
+class GPTJMLP(nn.Module):
92
+
93
+ def __init__(self, intermediate_size: int, config: GPTJConfig):
94
+ super().__init__()
95
+ hidden_size = config.n_embd
96
+ self.fc_in = ColumnParallelLinear(hidden_size,
97
+ intermediate_size,
98
+ gather_output=False,
99
+ perform_initialization=False)
100
+ self.fc_out = RowParallelLinear(intermediate_size,
101
+ hidden_size,
102
+ input_is_parallel=True,
103
+ perform_initialization=False)
104
+ self.act = get_act_fn(config.activation_function)
105
+
106
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
107
+ hidden_states, _ = self.fc_in(hidden_states)
108
+ hidden_states = self.act(hidden_states)
109
+ hidden_states, _ = self.fc_out(hidden_states)
110
+ return hidden_states
111
+
112
+
113
+class GPTJBlock(nn.Module):
114
+
115
+ def __init__(self, config: GPTJConfig):
116
+ super().__init__()
117
+ if config.n_inner is None:
118
+ inner_dim = 4 * config.n_embd
119
+ else:
120
+ inner_dim = config.n_inner
121
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
122
+ self.attn = GPTJAttention(config)
123
+ self.mlp = GPTJMLP(inner_dim, config)
124
+
125
+ def forward(
126
+ self,
127
+ position_ids: torch.Tensor,
128
+ hidden_states: torch.Tensor,
129
+ kv_cache: KVCache,
130
+ input_metadata: InputMetadata,
131
+ cache_event: Optional[torch.cuda.Event],
132
+ ) -> torch.Tensor:
133
+ residual = hidden_states
134
+ hidden_states = self.ln_1(hidden_states)
135
+ attn_output = self.attn(
136
+ position_ids=position_ids,
137
+ hidden_states=hidden_states,
138
+ kv_cache=kv_cache,
139
+ input_metadata=input_metadata,
140
+ cache_event=cache_event,
141
+ )
142
+ mlp_output = self.mlp(hidden_states)
143
+ hidden_states = attn_output + mlp_output + residual
144
+ return hidden_states
145
+
146
+
147
+class GPTJModel(nn.Module):
148
+
149
+ def __init__(self, config: GPTJConfig):
150
+ super().__init__()
151
+ self.config = config
152
+ self.embed_dim = config.n_embd
153
+ self.wte = VocabParallelEmbedding(config.vocab_size,
154
+ self.embed_dim,
155
+ perform_initialization=False)
156
+ self.h = nn.ModuleList(
157
+ [GPTJBlock(config) for _ in range(config.n_layer)])
158
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
159
+
160
+ def forward(
161
+ self,
162
+ input_ids: torch.Tensor,
163
+ position_ids: torch.Tensor,
164
+ kv_caches: List[KVCache],
165
+ input_metadata: InputMetadata,
166
+ cache_events: Optional[List[torch.cuda.Event]],
167
+ ) -> torch.Tensor:
168
+ hidden_states = self.wte(input_ids)
169
+ for i in range(len(self.h)):
170
+ if cache_events is None:
171
+ cache_event = None
172
+ else:
173
+ cache_event = cache_events[i]
174
+ layer = self.h[i]
175
+ hidden_states = layer(
176
+ position_ids,
177
+ hidden_states,
178
+ kv_caches[i],
179
+ input_metadata,
180
+ cache_event,
181
+ )
182
+ hidden_states = self.ln_f(hidden_states)
183
+ return hidden_states
184
+
185
+
186
+class GPTJForCausalLM(nn.Module):
187
+
188
+ def __init__(self, config: GPTJConfig):
189
+ super().__init__()
190
+ self.config = config
191
+ assert not config.tie_word_embeddings
192
+ self.transformer = GPTJModel(config)
193
+ self.lm_head = ColumnParallelLinear(config.n_embd,
194
+ config.vocab_size,
195
+ gather_output=False,
196
+ perform_initialization=False)
197
+ self.sampler = Sampler(config.vocab_size)
198
+
199
+ def forward(
200
+ self,
201
+ input_ids: torch.Tensor,
202
+ positions: torch.Tensor,
203
+ kv_caches: List[KVCache],
204
+ input_metadata: InputMetadata,
205
+ cache_events: Optional[List[torch.cuda.Event]],
206
+ ) -> Dict[int, SequenceOutputs]:
207
+ hidden_states = self.transformer(input_ids, positions, kv_caches,
208
+ input_metadata, cache_events)
209
+ next_tokens = self.sampler(self.lm_head.weight, hidden_states,
210
+ input_metadata, self.lm_head.bias)
211
+ return next_tokens
212
+
213
+ _column_parallel_weights = [
214
+ "wte.weight", "fc_in.weight", "fc_in.bias", "lm_head.weight",
215
+ "lm_head.bias"
216
+ ]
217
+ _row_parallel_weights = ["out_proj.weight", "fc_out.weight"]
218
+
219
+ def load_weights(self,
220
+ model_name_or_path: str,
221
+ cache_dir: Optional[str] = None,
222
+ use_np_cache: bool = False):
223
+ tp_rank = get_tensor_model_parallel_rank()
224
+ state_dict = self.state_dict()
225
+ for name, loaded_weight in hf_model_weights_iterator(
226
+ model_name_or_path, cache_dir, use_np_cache):
227
+ if "attn.bias" in name or "attn.masked_bias" in name:
228
+ continue
229
+
230
+ is_attention_weight = False
231
+ for stride_id, att_weight_name in enumerate(
232
+ ["q_proj", "k_proj", "v_proj"]):
233
+ if att_weight_name not in name:
234
+ continue
235
+ param = state_dict[name.replace(att_weight_name, "qkv_proj")]
236
+ shard_size = param.shape[1]
237
+ loaded_weight = loaded_weight[shard_size * tp_rank:shard_size *
238
+ (tp_rank + 1)]
239
+ param_slice = param.data[shard_size * stride_id:shard_size *
240
+ (stride_id + 1)]
241
+ assert param_slice.shape == loaded_weight.shape
242
+ param_slice.copy_(loaded_weight)
243
+ is_attention_weight = True
244
+ break
245
+ if is_attention_weight:
246
+ continue
247
+
248
+ param = state_dict[name]
249
+ load_tensor_parallel_weights(param, loaded_weight, name,
250
+ self._column_parallel_weights,
251
+ self._row_parallel_weights, tp_rank)
vllm/model_executor/models/mpt.py
+1
@@ -1,3 +1,4 @@
1
+# coding=utf-8
2
# Adapted from https://huggingface.co/mosaicml/mpt-7b/tree/main
3
import math
4
from typing import Dict, List, Optional, Tuple