main
py 461 lines 15.6 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 # Adapted from
4 # https://github.com/zai-org/ChatGLM2-6B
5 """Inference-only ChatGLM model compatible with THUDM weights."""
6
7 import json
8 from collections.abc import Iterable
9 from itertools import islice
10
11 import torch
12 from torch import nn
13 from torch.nn import LayerNorm
14
15 from vllm.compilation.decorators import support_torch_compile
16 from vllm.config import CacheConfig, VllmConfig
17 from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
18 from vllm.model_executor.layers.activation import SiluAndMul
19 from vllm.model_executor.layers.attention import Attention
20 from vllm.model_executor.layers.layernorm import RMSNorm
21 from vllm.model_executor.layers.linear import (
22 MergedColumnParallelLinear,
23 QKVParallelLinear,
24 RowParallelLinear,
25 )
26 from vllm.model_executor.layers.logits_processor import LogitsProcessor
27 from vllm.model_executor.layers.quantization import QuantizationConfig
28 from vllm.model_executor.layers.rotary_embedding import get_rope
29 from vllm.model_executor.layers.vocab_parallel_embedding import (
30 ParallelLMHead,
31 VocabParallelEmbedding,
32 )
33 from vllm.sequence import IntermediateTensors
34 from vllm.transformers_utils.configs.chatglm import ChatGLMConfig
35
36 from .interfaces import SupportsLoRA, SupportsPP, SupportsQuant
37 from .utils import (
38 AutoWeightsLoader,
39 WeightsMapper,
40 make_empty_intermediate_tensors_factory,
41 make_layers,
42 maybe_prefix,
43 )
44
45
46 class GLMAttention(nn.Module):
47 def __init__(
48 self,
49 config: ChatGLMConfig,
50 cache_config: CacheConfig | None = None,
51 quant_config: QuantizationConfig | None = None,
52 prefix: str = "",
53 ):
54 super().__init__()
55 self.hidden_size = config.hidden_size
56 tp_size = get_tensor_model_parallel_world_size()
57 self.total_num_heads = config.num_attention_heads
58 assert self.total_num_heads % tp_size == 0
59 self.num_heads = self.total_num_heads // tp_size
60 self.multi_query_attention = config.multi_query_attention
61 self.total_num_kv_heads = (
62 config.multi_query_group_num
63 if config.multi_query_attention
64 else config.num_attention_heads
65 )
66 if self.total_num_kv_heads >= tp_size:
67 # Number of KV heads is greater than TP size, so we partition
68 # the KV heads across multiple tensor parallel GPUs.
69 assert self.total_num_kv_heads % tp_size == 0
70 else:
71 # Number of KV heads is less than TP size, so we replicate
72 # the KV heads across multiple tensor parallel GPUs.
73 assert tp_size % self.total_num_kv_heads == 0
74 self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
75 self.head_dim = config.hidden_size // self.total_num_heads
76 self.q_size = self.num_heads * self.head_dim
77 self.kv_size = self.num_kv_heads * self.head_dim
78 self.scaling = self.head_dim**-0.5
79
80 self.query_key_value = QKVParallelLinear(
81 self.hidden_size,
82 self.head_dim,
83 self.total_num_heads,
84 self.total_num_kv_heads,
85 bias=config.add_bias_linear or config.add_qkv_bias,
86 quant_config=quant_config,
87 prefix=f"{prefix}.query_key_value",
88 )
89 self.dense = RowParallelLinear(
90 self.total_num_heads * self.head_dim,
91 config.hidden_size,
92 bias=config.add_bias_linear,
93 quant_config=quant_config,
94 prefix=f"{prefix}.dense",
95 )
96
97 # https://huggingface.co/zai-org/chatglm3-6b-32k/blob/e210410255278dd9d74463cf396ba559c0ef801c/modeling_chatglm.py#L141
98 rope_ratio = getattr(config, "rope_ratio", 1.0)
99 max_positions = getattr(config, "seq_length", 8192)
100 rope_parameters = {
101 "rope_type": "default",
102 "rope_theta": 10000 * rope_ratio,
103 "partial_rotary_factor": 0.5,
104 }
105 # NOTE: zai-org/cogagent-9b-20241220 uses original_rope=False,
106 # which is equivalent to is_neox_style=True
107 is_neox_style = not config.original_rope
108 self.rotary_emb = get_rope(
109 self.head_dim,
110 max_position=max_positions,
111 rope_parameters=rope_parameters,
112 is_neox_style=is_neox_style,
113 )
114 self.attn = Attention(
115 self.num_heads,
116 self.head_dim,
117 self.scaling,
118 num_kv_heads=self.num_kv_heads,
119 cache_config=cache_config,
120 quant_config=quant_config,
121 prefix=f"{prefix}.attn",
122 )
123
124 def forward(
125 self,
126 hidden_states: torch.Tensor,
127 position_ids: torch.Tensor,
128 ) -> torch.Tensor:
129 qkv, _ = self.query_key_value(hidden_states)
130 q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
131 q, k = self.rotary_emb(position_ids, q, k)
132 context_layer = self.attn(q, k, v)
133 attn_output, _ = self.dense(context_layer)
134 return attn_output
135
136
137 class GLMMLP(nn.Module):
138 """MLP.
139
140 MLP will take the input with h hidden state, project it to 4*h
141 hidden dimension, perform nonlinear transformation, and project the
142 state back into h hidden dimension.
143 """
144
145 def __init__(
146 self,
147 config: ChatGLMConfig,
148 quant_config: QuantizationConfig | None = None,
149 prefix: str = "",
150 ):
151 super().__init__()
152
153 self.add_bias = config.add_bias_linear
154
155 # Project to 4h.
156 self.dense_h_to_4h = MergedColumnParallelLinear(
157 config.hidden_size,
158 [config.ffn_hidden_size] * 2,
159 bias=config.add_bias_linear,
160 quant_config=quant_config,
161 prefix=f"{prefix}.dense_h_to_4h",
162 )
163
164 self.activation_func = SiluAndMul()
165
166 # Project back to h.
167 self.dense_4h_to_h = RowParallelLinear(
168 config.ffn_hidden_size,
169 config.hidden_size,
170 bias=config.add_bias_linear,
171 quant_config=quant_config,
172 prefix=f"{prefix}.dense_4h_to_h",
173 )
174
175 def forward(self, hidden_states):
176 # [s, b, 4hp]
177 intermediate_parallel, _ = self.dense_h_to_4h(hidden_states)
178 intermediate_parallel = self.activation_func(intermediate_parallel)
179 # [s, b, h]
180 output, _ = self.dense_4h_to_h(intermediate_parallel)
181 return output
182
183
184 class GLMBlock(nn.Module):
185 """A single transformer layer.
186
187 Transformer layer takes input with size [s, b, h] and returns an
188 output of the same size.
189 """
190
191 def __init__(
192 self,
193 config: ChatGLMConfig,
194 cache_config: CacheConfig | None = None,
195 quant_config: QuantizationConfig | None = None,
196 prefix: str = "",
197 ):
198 super().__init__()
199 self.apply_residual_connection_post_layernorm = (
200 config.apply_residual_connection_post_layernorm
201 )
202
203 self.fp32_residual_connection = config.fp32_residual_connection
204
205 layer_norm_func = RMSNorm if config.rmsnorm else LayerNorm
206 # Layernorm on the input data.
207 self.input_layernorm = layer_norm_func(
208 config.hidden_size, eps=config.layernorm_epsilon
209 )
210
211 # Self attention.
212 self.self_attention = GLMAttention(
213 config, cache_config, quant_config, prefix=f"{prefix}.self_attention"
214 )
215 self.hidden_dropout = config.hidden_dropout
216
217 # Layernorm on the attention output
218 self.post_attention_layernorm = layer_norm_func(
219 config.hidden_size, eps=config.layernorm_epsilon
220 )
221
222 # MLP
223 self.mlp = GLMMLP(config, quant_config, prefix=f"{prefix}.mlp")
224
225 def forward(
226 self,
227 hidden_states: torch.Tensor,
228 position_ids: torch.Tensor,
229 ) -> torch.Tensor:
230 # hidden_states: [num_tokens, h]
231 # Layer norm at the beginning of the transformer layer.
232 layernorm_output = self.input_layernorm(hidden_states)
233 # Self attention.
234 attention_output = self.self_attention(
235 hidden_states=layernorm_output,
236 position_ids=position_ids,
237 )
238
239 # Residual connection.
240 if self.apply_residual_connection_post_layernorm:
241 residual = layernorm_output
242 else:
243 residual = hidden_states
244
245 layernorm_input = residual + attention_output
246
247 # Layer norm post the self attention.
248 layernorm_output = self.post_attention_layernorm(layernorm_input)
249
250 # Second residual connection.
251 if self.apply_residual_connection_post_layernorm:
252 residual = layernorm_output
253 else:
254 residual = layernorm_input
255
256 output = self.mlp(layernorm_output) + residual
257
258 return output
259
260
261 class GLMTransformer(nn.Module):
262 """Transformer class."""
263
264 def __init__(
265 self,
266 config: ChatGLMConfig,
267 cache_config: CacheConfig | None = None,
268 quant_config: QuantizationConfig | None = None,
269 prefix: str = "",
270 ):
271 super().__init__()
272 self.post_layer_norm = config.post_layer_norm
273
274 # Number of layers.
275 self.num_layers = config.num_layers
276
277 # Transformer layers.
278 self.start_layer, self.end_layer, self.layers = make_layers(
279 self.num_layers,
280 lambda prefix: GLMBlock(config, cache_config, quant_config, prefix=prefix),
281 prefix=f"{prefix}.layers",
282 )
283
284 if self.post_layer_norm:
285 layer_norm_func = RMSNorm if config.rmsnorm else LayerNorm
286 # Final layer norm before output.
287 self.final_layernorm = layer_norm_func(
288 config.hidden_size, eps=config.layernorm_epsilon
289 )
290
291 self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
292 ["hidden_states"], config.hidden_size
293 )
294
295 def forward(
296 self,
297 hidden_states: torch.Tensor,
298 position_ids: torch.Tensor,
299 ) -> torch.Tensor | IntermediateTensors:
300 for layer in islice(self.layers, self.start_layer, self.end_layer):
301 hidden_states = layer(
302 hidden_states=hidden_states, position_ids=position_ids
303 )
304
305 if not get_pp_group().is_last_rank:
306 return IntermediateTensors({"hidden_states": hidden_states})
307
308 # Final layer norm.
309 if self.post_layer_norm:
310 hidden_states = self.final_layernorm(hidden_states)
311
312 return hidden_states
313
314
315 @support_torch_compile
316 class ChatGLMModel(nn.Module, SupportsQuant):
317 hf_to_vllm_mapper = WeightsMapper(
318 orig_to_new_substr={".word_embeddings": ""},
319 )
320
321 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
322 super().__init__()
323
324 config = vllm_config.model_config.hf_config
325 cache_config = vllm_config.cache_config
326 quant_config = vllm_config.quant_config
327
328 self.config = config
329
330 self.embedding = VocabParallelEmbedding(
331 config.padded_vocab_size,
332 config.hidden_size,
333 quant_config=quant_config,
334 prefix=f"{prefix}.embedding",
335 )
336
337 self.num_layers = config.num_layers
338 self.multi_query_group_num = config.multi_query_group_num
339 self.kv_channels = config.kv_channels
340 self.encoder = GLMTransformer(
341 config, cache_config, quant_config, prefix=f"{prefix}.encoder"
342 )
343
344 self.output_layer = ParallelLMHead(
345 config.padded_vocab_size,
346 config.hidden_size,
347 quant_config=quant_config,
348 prefix=f"{prefix}.output_layer",
349 )
350
351 self.make_empty_intermediate_tensors = (
352 self.encoder.make_empty_intermediate_tensors
353 )
354
355 def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
356 return self.embedding(input_ids)
357
358 def forward(
359 self,
360 input_ids: torch.Tensor | None,
361 positions: torch.Tensor,
362 intermediate_tensors: IntermediateTensors | None = None,
363 inputs_embeds: torch.Tensor | None = None,
364 **kwargs: object,
365 ) -> torch.Tensor | IntermediateTensors:
366 if get_pp_group().is_first_rank:
367 if inputs_embeds is not None:
368 hidden_states = inputs_embeds
369 else:
370 hidden_states = self.embed_input_ids(input_ids)
371 else:
372 assert intermediate_tensors is not None
373 hidden_states = intermediate_tensors["hidden_states"]
374
375 # Run encoder.
376 hidden_states = self.encoder(
377 hidden_states=hidden_states,
378 position_ids=positions,
379 )
380
381 return hidden_states
382
383 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
384 loader = AutoWeightsLoader(self)
385 return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
386
387
388 class ChatGLMBaseModel(nn.Module):
389 def __init__(
390 self,
391 *,
392 vllm_config: VllmConfig,
393 prefix: str = "",
394 transformer_type: type[ChatGLMModel] = ChatGLMModel,
395 ) -> None:
396 super().__init__()
397 config = vllm_config.model_config.hf_config
398 quant_config = vllm_config.quant_config
399
400 multimodal_config = vllm_config.model_config.multimodal_config
401 self.config = config
402 self.multimodal_config = multimodal_config
403
404 self.quant_config = quant_config
405 self.max_position_embeddings = getattr(config, "max_sequence_length", 8192)
406 self.transformer = transformer_type(
407 vllm_config=vllm_config, prefix=maybe_prefix(prefix, "transformer")
408 )
409 if self.config.tie_word_embeddings:
410 self.transformer.output_layer.weight = self.transformer.embedding.weight
411 self.lm_head = self.transformer.output_layer
412 self.logits_processor = LogitsProcessor(config.padded_vocab_size)
413 self.make_empty_intermediate_tensors = (
414 self.transformer.make_empty_intermediate_tensors
415 )
416
417 def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
418 return self.transformer.embed_input_ids(input_ids)
419
420 def compute_logits(
421 self,
422 hidden_states: torch.Tensor,
423 ) -> torch.Tensor | None:
424 logits = self.logits_processor(self.lm_head, hidden_states)
425 return logits
426
427 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
428 loader = AutoWeightsLoader(self)
429 return loader.load_weights(weights)
430
431
432 class ChatGLMForCausalLM(ChatGLMBaseModel, SupportsLoRA, SupportsPP, SupportsQuant):
433 packed_modules_mapping: dict[str, list[str]] = {
434 "query_key_value": ["query_key_value"],
435 "dense_h_to_4h": ["dense_h_to_4h"],
436 }
437
438 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
439 config = vllm_config.model_config.hf_config
440 if hasattr(config, "vision_config"):
441 hf_overrides = {"architectures": ["GLM4VForCausalLM"]}
442 raise RuntimeError(
443 "The configuration of this model indicates that it supports "
444 "vision inputs, but you instantiated the text-only version "
445 "of this model. Please use the vision model by setting "
446 f"`--hf-overrides '{json.dumps(hf_overrides)}'`"
447 )
448
449 super().__init__(vllm_config=vllm_config, prefix=prefix)
450
451 def forward(
452 self,
453 input_ids: torch.Tensor | None,
454 positions: torch.Tensor,
455 intermediate_tensors: IntermediateTensors | None = None,
456 inputs_embeds: torch.Tensor | None = None,
457 ) -> torch.Tensor | IntermediateTensors:
458 hidden_states = self.transformer(
459 input_ids, positions, intermediate_tensors, inputs_embeds
460 )
461 return hidden_states