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, 06:45 UTC
[Mistral] Mistral-7B-v0.1 support (#1196)
Co-authored-by: timlacroix <t@mistral.ai>
Chris Bamford committed
Sep 28, 2023 at 19:41 UTC
bb1ba58f064731b179d586ae32fdaaaea439098d
13 files changed
+571
-25
requirements.txt
+1
-1
@@ -7,7 +7,7 @@ sentencepiece # Required for LLaMA tokenizer.
7
numpy
8
torch >= 2.0.0
9
transformers >= 4.33.1 # Required for Code Llama.
10
-xformers >= 0.0.21
10
+xformers >= 0.0.22
11
fastapi
12
uvicorn[standard]
13
pydantic < 2 # Required for OpenAI server.
vllm/config.py
+2
@@ -187,10 +187,12 @@ class CacheConfig:
187
block_size: int,
188
gpu_memory_utilization: float,
189
swap_space: int,
190
+ sliding_window: Optional[int] = None,
191
) -> None:
192
self.block_size = block_size
193
self.gpu_memory_utilization = gpu_memory_utilization
194
self.swap_space_bytes = swap_space * _GB
195
+ self.sliding_window = sliding_window
196
self._verify_args()
197
198
# Will be set after profiling.
vllm/core/block_manager.py
+30
-11
@@ -63,10 +63,18 @@ class BlockSpaceManager:
63
num_gpu_blocks: int,
64
num_cpu_blocks: int,
65
watermark: float = 0.01,
66
+ sliding_window: Optional[int] = None,
67
) -> None:
68
self.block_size = block_size
69
self.num_total_gpu_blocks = num_gpu_blocks
70
self.num_total_cpu_blocks = num_cpu_blocks
71
+
72
+ self.block_sliding_window = None
73
+ if sliding_window is not None:
74
+ assert sliding_window % block_size == 0, (sliding_window,
75
+ block_size)
76
+ self.block_sliding_window = sliding_window // block_size
77
+
78
self.watermark = watermark
79
assert watermark >= 0.0
80
@@ -83,6 +91,9 @@ class BlockSpaceManager:
91
# the same prompt. This may not be true for preempted sequences.
92
seq = seq_group.get_seqs()[0]
93
num_required_blocks = len(seq.logical_token_blocks)
94
+ if self.block_sliding_window is not None:
95
+ num_required_blocks = min(num_required_blocks,
96
+ self.block_sliding_window)
97
num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()
98
# Use watermark to avoid frequent cache eviction.
99
return (num_free_gpu_blocks - num_required_blocks >=
@@ -95,8 +106,12 @@ class BlockSpaceManager:
106
107
# Allocate new physical token blocks that will store the prompt tokens.
108
block_table: BlockTable = []
98
- for _ in range(len(seq.logical_token_blocks)):
99
- block = self.gpu_allocator.allocate()
109
+ for logical_idx in range(len(seq.logical_token_blocks)):
110
+ if (self.block_sliding_window is not None
111
+ and logical_idx >= self.block_sliding_window):
112
+ block = block_table[logical_idx % self.block_sliding_window]
113
+ else:
114
+ block = self.gpu_allocator.allocate()
115
# Set the reference counts of the token blocks.
116
block.ref_count = seq_group.num_seqs()
117
block_table.append(block)
@@ -118,11 +133,17 @@ class BlockSpaceManager:
133
block_table = self.block_tables[seq.seq_id]
134
135
if len(block_table) < len(logical_blocks):
121
- # The sequence has a new logical block.
122
- # Allocate a new physical block.
123
- block = self.gpu_allocator.allocate()
124
- block_table.append(block)
125
- return None
136
+ if (self.block_sliding_window
137
+ and len(block_table) >= self.block_sliding_window):
138
+ # re-use a block
139
+ block_table.append(block_table[len(block_table) %
140
+ self.block_sliding_window])
141
+ else:
142
+ # The sequence has a new logical block.
143
+ # Allocate a new physical block.
144
+ block = self.gpu_allocator.allocate()
145
+ block_table.append(block)
146
+ return None
147
148
# We want to append the token to the last physical block.
149
last_block = block_table[-1]
@@ -154,9 +175,7 @@ class BlockSpaceManager:
175
for seq in seq_group.get_seqs():
176
if seq.is_finished():
177
continue
157
- block_table = self.block_tables[seq.seq_id]
158
- for block in block_table:
159
- blocks.add(block)
178
+ blocks.update(self.block_tables[seq.seq_id])
179
return list(blocks)
180
181
def can_swap_in(self, seq_group: SequenceGroup) -> bool:
@@ -224,7 +243,7 @@ class BlockSpaceManager:
243
return block_number_mapping
244
245
def _free_block_table(self, block_table: BlockTable) -> None:
227
- for block in block_table:
246
+ for block in set(block_table):
247
if block.device == Device.GPU:
248
self.gpu_allocator.free(block)
249
else:
vllm/core/scheduler.py
+1
-1
@@ -73,7 +73,7 @@ class Scheduler:
73
block_size=self.cache_config.block_size,
74
num_gpu_blocks=self.cache_config.num_gpu_blocks,
75
num_cpu_blocks=self.cache_config.num_cpu_blocks,
76
- )
76
+ sliding_window=self.cache_config.sliding_window)
77
78
# TODO(zhuohan): Use deque instead of list for better performance.
79
# Sequence groups in the WAITING state.
vllm/engine/arg_utils.py
+3
-3
@@ -176,9 +176,9 @@ class EngineArgs:
176
self.download_dir, self.load_format,
177
self.dtype, self.seed, self.revision,
178
self.max_model_len, self.quantization)
179
- cache_config = CacheConfig(self.block_size,
180
- self.gpu_memory_utilization,
181
- self.swap_space)
179
+ cache_config = CacheConfig(
180
+ self.block_size, self.gpu_memory_utilization, self.swap_space,
181
+ getattr(model_config.hf_config, 'sliding_window', None))
182
parallel_config = ParallelConfig(self.pipeline_parallel_size,
183
self.tensor_parallel_size,
184
self.worker_use_ray)
vllm/engine/llm_engine.py
+2
@@ -86,6 +86,8 @@ class LLMEngine:
86
87
self.model_config = model_config
88
self.cache_config = cache_config
89
+ assert self.cache_config.sliding_window == getattr(
90
+ self.model_config.hf_config, "sliding_window", None)
91
self.parallel_config = parallel_config
92
self.scheduler_config = scheduler_config
93
self.log_stats = log_stats
vllm/model_executor/input_metadata.py
+20
-1
@@ -1,4 +1,4 @@
1
-from typing import Dict, List, Tuple
1
+from typing import Dict, List, Optional, Tuple
2
3
import torch
4
from xformers.ops import AttentionBias
@@ -29,6 +29,7 @@ class InputMetadata:
29
context_lens: torch.Tensor,
30
max_context_len: int,
31
block_tables: torch.Tensor,
32
+ sliding_window: Optional[int] = None,
33
) -> None:
34
self.seq_groups = seq_groups
35
self.seq_data = seq_data
@@ -38,6 +39,24 @@ class InputMetadata:
39
self.max_context_len = max_context_len
40
self.block_tables = block_tables
41
42
+ self.to_cache = None
43
+ if sliding_window is not None:
44
+ # We need to keep the positions of sliding windows within
45
+ # the key / value tables, this is helpful to know which
46
+ # elements we need to cache and where
47
+ to_cache, start_idx = [], 0
48
+ for prompt_len in self.prompt_lens:
49
+ to_cache.extend(
50
+ range(
51
+ start_idx + max(0, prompt_len - sliding_window),
52
+ start_idx + prompt_len,
53
+ ))
54
+ start_idx += prompt_len
55
+ to_cache.extend(range(start_idx, slot_mapping.shape[0]))
56
+ self.to_cache = torch.tensor(to_cache,
57
+ dtype=torch.int32,
58
+ device=self.slot_mapping.device)
59
+
60
self.num_prompts = len(prompt_lens)
61
self.num_prompt_tokens = sum(prompt_lens)
62
self.num_generation_tokens = context_lens.shape[0]
vllm/model_executor/layers/attention.py
+22
-5
@@ -58,12 +58,14 @@ class PagedAttention(nn.Module):
58
num_heads: int,
59
head_size: int,
60
scale: float,
61
- num_kv_heads: Optional[int] = None) -> None:
61
+ num_kv_heads: Optional[int] = None,
62
+ sliding_window: Optional[int] = None) -> None:
63
super().__init__()
64
self.num_heads = num_heads
65
self.head_size = head_size
66
self.scale = float(scale)
67
self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads
68
+ self.sliding_window = sliding_window
69
70
assert self.num_heads % self.num_kv_heads == 0
71
self.num_queries_per_kv = self.num_heads // self.num_kv_heads
@@ -86,6 +88,8 @@ class PagedAttention(nn.Module):
88
return
89
prompt_lens = input_metadata.prompt_lens
90
attn_bias = BlockDiagonalCausalMask.from_seqlens(prompt_lens)
91
+ if self.sliding_window is not None:
92
+ attn_bias = attn_bias.make_local_attention(self.sliding_window)
93
input_metadata.attn_bias.append(attn_bias)
94
95
def multi_query_kv_attention(
@@ -223,12 +227,20 @@ class PagedAttention(nn.Module):
227
if (num_valid_tokens > 0 and key_cache is not None
228
and value_cache is not None):
229
# The stride is 3 because the key and value are sliced from qkv.
230
+ key_to_cache = key[:num_valid_tokens]
231
+ value_to_cache = value[:num_valid_tokens]
232
+ slot_mapping = input_metadata.slot_mapping
233
+ if input_metadata.to_cache is not None:
234
+ key_to_cache = key_to_cache[input_metadata.to_cache]
235
+ value_to_cache = value_to_cache[input_metadata.to_cache]
236
+ slot_mapping = slot_mapping[input_metadata.to_cache]
237
+
238
cache_ops.reshape_and_cache(
227
- key[:num_valid_tokens],
228
- value[:num_valid_tokens],
239
+ key_to_cache,
240
+ value_to_cache,
241
key_cache,
242
value_cache,
231
- input_metadata.slot_mapping,
243
+ slot_mapping,
244
)
245
246
if input_metadata.num_generation_tokens > 0:
@@ -262,8 +274,13 @@ class PagedAttentionWithRoPE(PagedAttention):
274
num_kv_heads: Optional[int] = None,
275
is_neox_style: bool = True,
276
rope_scaling: Optional[Dict[str, Any]] = None,
277
+ sliding_window: Optional[int] = None,
278
) -> None:
266
- super().__init__(num_heads, head_size, scale, num_kv_heads)
279
+ super().__init__(num_heads,
280
+ head_size,
281
+ scale,
282
+ num_kv_heads,
283
+ sliding_window=sliding_window)
284
if rope_scaling is None:
285
self.rotary_emb = RotaryEmbedding(head_size, rotary_dim,
286
max_position, base,
vllm/model_executor/model_loader.py
+1
@@ -25,6 +25,7 @@ _MODEL_REGISTRY = {
25
"InternLMForCausalLM": InternLMForCausalLM,
26
"LlamaForCausalLM": LlamaForCausalLM,
27
"LLaMAForCausalLM": LlamaForCausalLM, # For decapoda-research/llama-*
28
+ "MistralForCausalLM": MistralForCausalLM,
29
"MPTForCausalLM": MPTForCausalLM,
30
"OPTForCausalLM": OPTForCausalLM,
31
"QWenLMHeadModel": QWenLMHeadModel,
vllm/model_executor/models/__init__.py
+2
@@ -12,6 +12,7 @@ from vllm.model_executor.models.llama import LlamaForCausalLM
12
from vllm.model_executor.models.mpt import MPTForCausalLM
13
from vllm.model_executor.models.opt import OPTForCausalLM
14
from vllm.model_executor.models.qwen import QWenLMHeadModel
15
+from vllm.model_executor.models.mistral import MistralForCausalLM
16
17
__all__ = [
18
"AquilaForCausalLM",
@@ -28,4 +29,5 @@ __all__ = [
29
"MPTForCausalLM",
30
"OPTForCausalLM",
31
"QWenLMHeadModel",
32
+ "MistralForCausalLM",
33
]
vllm/model_executor/models/mistral.py
new
+404
@@ -0,0 +1,404 @@
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 The vLLM team.
5
+# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
6
+#
7
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
8
+# and OPT implementations in this library. It has been modified from its
9
+# original forms to accommodate minor architectural differences compared
10
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
11
+#
12
+# Licensed under the Apache License, Version 2.0 (the "License");
13
+# you may not use this file except in compliance with the License.
14
+# You may obtain a copy of the License at
15
+#
16
+# http://www.apache.org/licenses/LICENSE-2.0
17
+#
18
+# Unless required by applicable law or agreed to in writing, software
19
+# distributed under the License is distributed on an "AS IS" BASIS,
20
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+# See the License for the specific language governing permissions and
22
+# limitations under the License.
23
+"""Inference-only LLaMA model compatible with HuggingFace weights.
24
+
25
+The input of the model is flattened to a 1D tensor of tokens. The model uses
26
+InputMetadata to extract the original 2D shape of the input.
27
+"""
28
+from typing import List, Optional, Tuple
29
+
30
+import torch
31
+from torch import nn
32
+from vllm.transformers_utils.configs.mistral import MistralConfig
33
+
34
+from vllm.model_executor.input_metadata import InputMetadata
35
+from vllm.model_executor.layers.activation import SiluAndMul
36
+from vllm.model_executor.layers.layernorm import RMSNorm
37
+from vllm.model_executor.layers.attention import PagedAttentionWithRoPE
38
+from vllm.model_executor.layers.sampler import Sampler
39
+from vllm.model_executor.layers.quantized_linear import ParallelLinear
40
+from vllm.model_executor.parallel_utils.parallel_state import (
41
+ get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size)
42
+from vllm.model_executor.parallel_utils.tensor_parallel import (
43
+ VocabParallelEmbedding)
44
+from vllm.model_executor.quantization_utils import QuantizationConfig
45
+from vllm.model_executor.weight_utils import (
46
+ convert_pyslice_to_tensor, hf_model_weights_iterator,
47
+ load_tensor_parallel_weights, load_padded_tensor_parallel_vocab)
48
+from vllm.sequence import SamplerOutput
49
+
50
+KVCache = Tuple[torch.Tensor, torch.Tensor]
51
+
52
+
53
+class MistralMLP(nn.Module):
54
+
55
+ def __init__(
56
+ self,
57
+ hidden_size: int,
58
+ intermediate_size: int,
59
+ hidden_act: str,
60
+ quant_config: Optional[QuantizationConfig] = None,
61
+ ) -> None:
62
+ super().__init__()
63
+ self.gate_up_proj = ParallelLinear.column(hidden_size,
64
+ 2 * intermediate_size,
65
+ bias=False,
66
+ gather_output=False,
67
+ perform_initialization=False,
68
+ quant_config=quant_config)
69
+ self.down_proj = ParallelLinear.row(intermediate_size,
70
+ hidden_size,
71
+ bias=False,
72
+ input_is_parallel=True,
73
+ perform_initialization=False,
74
+ quant_config=quant_config)
75
+ if hidden_act != "silu":
76
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
77
+ "Only silu is supported for now.")
78
+ self.act_fn = SiluAndMul()
79
+
80
+ def forward(self, x):
81
+ gate_up, _ = self.gate_up_proj(x)
82
+ x = self.act_fn(gate_up)
83
+ x, _ = self.down_proj(x)
84
+ return x
85
+
86
+
87
+class MistralAttention(nn.Module):
88
+
89
+ def __init__(self,
90
+ hidden_size: int,
91
+ num_heads: int,
92
+ num_kv_heads: int,
93
+ max_position: int = 4096 * 32,
94
+ rope_theta: float = 10000,
95
+ quant_config: Optional[QuantizationConfig] = None,
96
+ sliding_window: Optional[int] = None) -> None:
97
+ super().__init__()
98
+ self.hidden_size = hidden_size
99
+ tp_size = get_tensor_model_parallel_world_size()
100
+ self.total_num_heads = num_heads
101
+ assert self.total_num_heads % tp_size == 0
102
+ self.num_heads = self.total_num_heads // tp_size
103
+ self.total_num_kv_heads = num_kv_heads
104
+ assert self.total_num_kv_heads % tp_size == 0
105
+ self.num_kv_heads = self.total_num_kv_heads // tp_size
106
+ self.head_dim = hidden_size // self.total_num_heads
107
+ self.q_size = self.num_heads * self.head_dim
108
+ self.kv_size = self.num_kv_heads * self.head_dim
109
+ self.scaling = self.head_dim**-0.5
110
+ self.rope_theta = rope_theta
111
+ self.sliding_window = sliding_window
112
+
113
+ self.qkv_proj = ParallelLinear.column(
114
+ hidden_size,
115
+ (self.total_num_heads + 2 * self.total_num_kv_heads) *
116
+ self.head_dim,
117
+ bias=False,
118
+ gather_output=False,
119
+ perform_initialization=False,
120
+ quant_config=quant_config,
121
+ )
122
+ self.o_proj = ParallelLinear.row(
123
+ self.total_num_heads * self.head_dim,
124
+ hidden_size,
125
+ bias=False,
126
+ input_is_parallel=True,
127
+ perform_initialization=False,
128
+ quant_config=quant_config,
129
+ )
130
+ self.attn = PagedAttentionWithRoPE(self.num_heads,
131
+ self.head_dim,
132
+ self.scaling,
133
+ base=self.rope_theta,
134
+ max_position=max_position,
135
+ rotary_dim=self.head_dim,
136
+ num_kv_heads=self.num_kv_heads,
137
+ sliding_window=self.sliding_window)
138
+
139
+ def forward(
140
+ self,
141
+ positions: torch.Tensor,
142
+ hidden_states: torch.Tensor,
143
+ kv_cache: KVCache,
144
+ input_metadata: InputMetadata,
145
+ cache_event: Optional[torch.cuda.Event],
146
+ ) -> torch.Tensor:
147
+ qkv, _ = self.qkv_proj(hidden_states)
148
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
149
+ k_cache, v_cache = kv_cache
150
+ attn_output = self.attn(positions, q, k, v, k_cache, v_cache,
151
+ input_metadata, cache_event)
152
+ output, _ = self.o_proj(attn_output)
153
+ return output
154
+
155
+
156
+class MistralDecoderLayer(nn.Module):
157
+
158
+ def __init__(
159
+ self,
160
+ config: MistralConfig,
161
+ quant_config: Optional[QuantizationConfig] = None,
162
+ ) -> None:
163
+ super().__init__()
164
+ self.hidden_size = config.hidden_size
165
+ # Requires transformers > 4.32.0
166
+ rope_theta = getattr(config, "rope_theta", 10000)
167
+ self.self_attn = MistralAttention(
168
+ hidden_size=self.hidden_size,
169
+ num_heads=config.num_attention_heads,
170
+ max_position=config.max_position_embeddings,
171
+ num_kv_heads=config.num_key_value_heads,
172
+ rope_theta=rope_theta,
173
+ quant_config=quant_config,
174
+ sliding_window=config.sliding_window)
175
+ self.mlp = MistralMLP(
176
+ hidden_size=self.hidden_size,
177
+ intermediate_size=config.intermediate_size,
178
+ hidden_act=config.hidden_act,
179
+ quant_config=quant_config,
180
+ )
181
+ self.input_layernorm = RMSNorm(config.hidden_size,
182
+ eps=config.rms_norm_eps)
183
+ self.post_attention_layernorm = RMSNorm(config.hidden_size,
184
+ eps=config.rms_norm_eps)
185
+
186
+ def forward(
187
+ self,
188
+ positions: torch.Tensor,
189
+ hidden_states: torch.Tensor,
190
+ kv_cache: KVCache,
191
+ input_metadata: InputMetadata,
192
+ cache_event: Optional[torch.cuda.Event],
193
+ ) -> torch.Tensor:
194
+ # Self Attention
195
+ residual = hidden_states
196
+ hidden_states = self.input_layernorm(hidden_states)
197
+ hidden_states = self.self_attn(
198
+ positions=positions,
199
+ hidden_states=hidden_states,
200
+ kv_cache=kv_cache,
201
+ input_metadata=input_metadata,
202
+ cache_event=cache_event,
203
+ )
204
+ hidden_states = residual + hidden_states
205
+
206
+ # Fully Connected
207
+ residual = hidden_states
208
+ hidden_states = self.post_attention_layernorm(hidden_states)
209
+ hidden_states = self.mlp(hidden_states)
210
+ hidden_states = residual + hidden_states
211
+ return hidden_states
212
+
213
+
214
+class MistralModel(nn.Module):
215
+
216
+ def __init__(
217
+ self,
218
+ config: MistralConfig,
219
+ quant_config: Optional[QuantizationConfig] = None,
220
+ ) -> None:
221
+ super().__init__()
222
+ self.config = config
223
+ self.padding_idx = config.pad_token_id
224
+ self.vocab_size = config.vocab_size
225
+
226
+ vocab_size = ((config.vocab_size + 63) // 64) * 64
227
+ self.embed_tokens = VocabParallelEmbedding(
228
+ vocab_size, config.hidden_size, perform_initialization=False)
229
+ self.layers = nn.ModuleList([
230
+ MistralDecoderLayer(config, quant_config)
231
+ for _ in range(config.num_hidden_layers)
232
+ ])
233
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
234
+
235
+ def forward(
236
+ self,
237
+ input_ids: torch.Tensor,
238
+ positions: torch.Tensor,
239
+ kv_caches: List[KVCache],
240
+ input_metadata: InputMetadata,
241
+ cache_events: Optional[List[torch.cuda.Event]],
242
+ ) -> torch.Tensor:
243
+ hidden_states = self.embed_tokens(input_ids)
244
+ for i in range(len(self.layers)):
245
+ if cache_events is None:
246
+ cache_event = None
247
+ else:
248
+ cache_event = cache_events[i]
249
+ layer = self.layers[i]
250
+ hidden_states = layer(
251
+ positions,
252
+ hidden_states,
253
+ kv_caches[i],
254
+ input_metadata,
255
+ cache_event,
256
+ )
257
+ hidden_states = self.norm(hidden_states)
258
+ return hidden_states
259
+
260
+
261
+class MistralForCausalLM(nn.Module):
262
+
263
+ def __init__(
264
+ self,
265
+ config: MistralConfig,
266
+ quant_config: Optional[QuantizationConfig] = None,
267
+ ) -> None:
268
+ super().__init__()
269
+ self.config = config
270
+ self.quant_config = quant_config
271
+ self.model = MistralModel(config, quant_config)
272
+ vocab_size = ((config.vocab_size + 63) // 64) * 64
273
+ # NOTE: The LM head is not quantized.
274
+ self.lm_head = ParallelLinear.column(config.hidden_size,
275
+ vocab_size,
276
+ bias=False,
277
+ gather_output=False,
278
+ perform_initialization=False,
279
+ quant_config=None)
280
+ self.sampler = Sampler(config.vocab_size)
281
+
282
+ def forward(
283
+ self,
284
+ input_ids: torch.Tensor,
285
+ positions: torch.Tensor,
286
+ kv_caches: List[KVCache],
287
+ input_metadata: InputMetadata,
288
+ cache_events: Optional[List[torch.cuda.Event]],
289
+ ) -> SamplerOutput:
290
+ hidden_states = self.model(input_ids, positions, kv_caches,
291
+ input_metadata, cache_events)
292
+ next_tokens = self.sampler(self.lm_head.weight, hidden_states,
293
+ input_metadata)
294
+ return next_tokens
295
+
296
+ _column_parallel_layers = []
297
+ _row_parallel_layers = ["o_proj", "down_proj"]
298
+
299
+ def load_weights(self,
300
+ model_name_or_path: str,
301
+ cache_dir: Optional[str] = None,
302
+ load_format: str = "auto",
303
+ revision: Optional[str] = None):
304
+ if self.quant_config is None:
305
+ weight_suffixes = ["weight"]
306
+ else:
307
+ weight_suffixes = self.quant_config.get_tp_tensor_names()
308
+
309
+ column_parallel_weights: List[str] = []
310
+ for layer in self._column_parallel_layers:
311
+ for suffix in weight_suffixes:
312
+ column_parallel_weights.append(f"{layer}.{suffix}")
313
+ row_parallel_weights: List[str] = []
314
+ for layer in self._row_parallel_layers:
315
+ for suffix in weight_suffixes:
316
+ row_parallel_weights.append(f"{layer}.{suffix}")
317
+
318
+ tp_size = get_tensor_model_parallel_world_size()
319
+ tensor_model_parallel_rank = get_tensor_model_parallel_rank()
320
+ q_proj_shard_size = (self.config.hidden_size // tp_size)
321
+ kv_proj_shard_size = (self.config.hidden_size //
322
+ self.config.num_attention_heads *
323
+ self.config.num_key_value_heads // tp_size)
324
+ attention_weight_specs = [
325
+ # (weight_name, shard_size, offset)
326
+ ("q_proj", q_proj_shard_size, 0),
327
+ ("k_proj", kv_proj_shard_size, q_proj_shard_size),
328
+ ("v_proj", kv_proj_shard_size,
329
+ q_proj_shard_size + kv_proj_shard_size),
330
+ ]
331
+ state_dict = self.state_dict()
332
+
333
+ for name, loaded_weight in hf_model_weights_iterator(
334
+ model_name_or_path, cache_dir, load_format, revision):
335
+ if "rotary_emb.inv_freq" in name:
336
+ continue
337
+
338
+ is_packed = False
339
+ is_transposed = False
340
+ if self.quant_config is not None:
341
+ is_packed = self.quant_config.is_packed(name)
342
+ is_transposed = self.quant_config.is_transposed(name)
343
+ if is_transposed:
344
+ loaded_weight = convert_pyslice_to_tensor(loaded_weight)
345
+ loaded_weight = loaded_weight.T
346
+
347
+ is_attention_weight = False
348
+ for weight_name, shard_size, offset in attention_weight_specs:
349
+ if weight_name not in name:
350
+ continue
351
+ param = state_dict[name.replace(weight_name, "qkv_proj")]
352
+ if is_transposed:
353
+ param = param.T
354
+
355
+ if is_packed:
356
+ shard_size //= self.quant_config.pack_factor
357
+ offset //= self.quant_config.pack_factor
358
+
359
+ loaded_weight = loaded_weight[
360
+ shard_size * tensor_model_parallel_rank:shard_size *
361
+ (tensor_model_parallel_rank + 1)]
362
+ param_slice = param.data[offset:offset + shard_size]
363
+ assert param_slice.shape == loaded_weight.shape
364
+
365
+ param_slice.copy_(loaded_weight)
366
+ is_attention_weight = True
367
+ break
368
+ if is_attention_weight:
369
+ continue
370
+
371
+ is_gate_up_weight = False
372
+ for stride_id, weight_name in enumerate(["gate_proj", "up_proj"]):
373
+ if weight_name not in name:
374
+ continue
375
+ param = state_dict[name.replace(weight_name, "gate_up_proj")]
376
+ if is_transposed:
377
+ param = param.T
378
+
379
+ shard_size = param.shape[0] // 2
380
+ loaded_weight = loaded_weight[
381
+ shard_size * tensor_model_parallel_rank:shard_size *
382
+ (tensor_model_parallel_rank + 1)]
383
+ param_slice = param.data[shard_size * stride_id:shard_size *
384
+ (stride_id + 1)]
385
+ assert param_slice.shape == loaded_weight.shape
386
+ param_slice.copy_(loaded_weight)
387
+ is_gate_up_weight = True
388
+ break
389
+ if is_gate_up_weight:
390
+ continue
391
+
392
+ param = state_dict[name]
393
+ if is_transposed:
394
+ param = param.T
395
+
396
+ if "embed_tokens" in name or "lm_head" in name:
397
+ load_padded_tensor_parallel_vocab(param, loaded_weight,
398
+ tensor_model_parallel_rank)
399
+ continue
400
+
401
+ load_tensor_parallel_weights(param, loaded_weight, name,
402
+ column_parallel_weights,
403
+ row_parallel_weights,
404
+ tensor_model_parallel_rank)
vllm/transformers_utils/configs/mistral.py
new
+66
@@ -0,0 +1,66 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License");
2
+# you may not use this file except in compliance with the License.
3
+# You may obtain a copy of the License at
4
+#
5
+# http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS,
9
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+# See the License for the specific language governing permissions and
11
+# limitations under the License.
12
+"""Mistral-7B-v0.1 configuration"""
13
+from transformers.configuration_utils import PretrainedConfig
14
+
15
+
16
+class MistralConfig(PretrainedConfig):
17
+ model_type = "mistral"
18
+ keys_to_ignore_at_inference = ["past_key_values"]
19
+
20
+ def __init__(
21
+ self,
22
+ vocab_size=32000,
23
+ hidden_size=4096,
24
+ intermediate_size=14336,
25
+ num_hidden_layers=32,
26
+ num_attention_heads=32,
27
+ num_key_value_heads=8,
28
+ hidden_act="silu",
29
+ max_position_embeddings=4096 * 32,
30
+ initializer_range=0.02,
31
+ rms_norm_eps=1e-6,
32
+ use_cache=True,
33
+ pad_token_id=None,
34
+ bos_token_id=1,
35
+ eos_token_id=2,
36
+ tie_word_embeddings=False,
37
+ rope_theta=10000.0,
38
+ sliding_window=4096,
39
+ **kwargs,
40
+ ):
41
+ self.vocab_size = vocab_size
42
+ self.max_position_embeddings = max_position_embeddings
43
+ self.hidden_size = hidden_size
44
+ self.intermediate_size = intermediate_size
45
+ self.num_hidden_layers = num_hidden_layers
46
+ self.num_attention_heads = num_attention_heads
47
+ self.sliding_window = sliding_window
48
+
49
+ # for backward compatibility
50
+ if num_key_value_heads is None:
51
+ num_key_value_heads = num_attention_heads
52
+
53
+ self.num_key_value_heads = num_key_value_heads
54
+ self.hidden_act = hidden_act
55
+ self.initializer_range = initializer_range
56
+ self.rms_norm_eps = rms_norm_eps
57
+ self.use_cache = use_cache
58
+ self.rope_theta = rope_theta
59
+
60
+ super().__init__(
61
+ pad_token_id=pad_token_id,
62
+ bos_token_id=bos_token_id,
63
+ eos_token_id=eos_token_id,
64
+ tie_word_embeddings=tie_word_embeddings,
65
+ **kwargs,
66
+ )
vllm/worker/worker.py
+17
-3
@@ -137,8 +137,10 @@ class Worker:
137
self.cache_config = cache_config
138
self.block_size = cache_config.block_size
139
140
- _check_if_can_support_max_seq_len(self.scheduler_config.max_model_len,
141
- self.block_size)
140
+ max_seq_len = min(self.scheduler_config.max_model_len,
141
+ cache_config.sliding_window or float("inf"))
142
+
143
+ _check_if_can_support_max_seq_len(max_seq_len, self.block_size)
144
145
self.cache_engine = CacheEngine(self.cache_config, self.model_config,
146
self.parallel_config)
@@ -191,6 +193,9 @@ class Worker:
193
slot = block_number * self.block_size + block_offset
194
slot_mapping.append(slot)
195
196
+ sliding_window = getattr(self.model_config.hf_config, "sliding_window",
197
+ float("inf"))
198
+
199
# Add generation tokens.
200
max_context_len = 0
201
max_num_blocks_per_seq = 0
@@ -211,10 +216,11 @@ class Worker:
216
217
context_len = seq_data.get_len()
218
position = context_len - 1
219
+ if sliding_window:
220
+ context_len = min(context_len, sliding_window)
221
input_positions.append(position)
222
223
block_table = seq_group_metadata.block_tables[seq_id]
217
- generation_block_tables.append(block_table)
224
225
max_context_len = max(max_context_len, context_len)
226
max_num_blocks_per_seq = max(max_num_blocks_per_seq,
@@ -226,6 +232,13 @@ class Worker:
232
slot = block_number * self.block_size + block_offset
233
slot_mapping.append(slot)
234
235
+ if sliding_window:
236
+ assert self.cache_config is not None
237
+ sliding_window_blocks = (sliding_window //
238
+ self.cache_config.block_size)
239
+ block_table = block_table[-sliding_window_blocks:]
240
+ generation_block_tables.append(block_table)
241
+
242
# Optimization: Pad the input length to be a multiple of 8.
243
# This is required for utilizing the Tensor Cores in NVIDIA GPUs.
244
input_tokens = _pad_to_alignment(input_tokens, multiple_of=8)
@@ -264,6 +277,7 @@ class Worker:
277
context_lens=context_lens_tensor,
278
max_context_len=max_context_len,
279
block_tables=block_tables_tensor,
280
+ sliding_window=sliding_window,
281
)
282
return tokens_tensor, positions_tensor, input_metadata
283