main
py 407 lines 13.5 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 # Adapted from
5 # https://github.com/huggingface/transformers/blob/main/src/transformers/models/Glm4v/modeling_Glm4v.py
6 # Copyright 2026 The ZhipuAI Team.
7 # Copyright 2026 The vLLM team.
8 # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
9 # All rights reserved.
10 #
11 # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
12 # and OPT implementations in this library. It has been modified from its
13 # original forms to accommodate minor architectural differences compared
14 # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
15 #
16 # Licensed under the Apache License, Version 2.0 (the "License");
17 # you may not use this file except in compliance with the License.
18 # You may obtain a copy of the License at
19 #
20 # http://www.apache.org/licenses/LICENSE-2.0
21 #
22 # Unless required by applicable law or agreed to in writing, software
23 # distributed under the License is distributed on an "AS IS" BASIS,
24 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 # See the License for the specific language governing permissions and
26 # limitations under the License.
27 """Inference-only GLM-OCR model compatible with HuggingFace weights."""
28
29 from collections.abc import Callable
30 from functools import partial
31 from typing import TYPE_CHECKING
32
33 import torch
34 import torch.nn as nn
35 from einops import rearrange
36
37 if TYPE_CHECKING:
38 from transformers.models.glm_ocr.configuration_glm_ocr import (
39 GlmOcrTextConfig,
40 GlmOcrVisionConfig,
41 )
42
43 from vllm.config import VllmConfig
44 from vllm.distributed import get_tensor_model_parallel_world_size, parallel_state
45 from vllm.distributed import utils as dist_utils
46 from vllm.logger import init_logger
47 from vllm.model_executor.layers.attention.mm_encoder_attention import (
48 MMEncoderAttention,
49 )
50 from vllm.model_executor.layers.conv import Conv2dLayer
51 from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
52 from vllm.model_executor.layers.layernorm import RMSNorm
53 from vllm.model_executor.layers.linear import (
54 QKVParallelLinear,
55 RowParallelLinear,
56 )
57 from vllm.model_executor.layers.quantization import QuantizationConfig
58 from vllm.model_executor.layers.rotary_embedding import get_rope
59 from vllm.model_executor.layers.rotary_embedding.common import (
60 ApplyRotaryEmb,
61 )
62 from vllm.model_executor.models.glm4_1v import (
63 Glm4vDummyInputsBuilder,
64 Glm4vForConditionalGeneration,
65 Glm4vMultiModalProcessor,
66 Glm4vPatchMerger,
67 Glm4vProcessingInfo,
68 Glm4vVisionBlock,
69 Glm4vVisionMLP,
70 Glm4vVisionPatchEmbed,
71 Glm4vVisionTransformer,
72 )
73 from vllm.multimodal import MULTIMODAL_REGISTRY
74 from vllm.utils.torch_utils import PIN_MEMORY
75
76 from .utils import (
77 maybe_prefix,
78 )
79 from .vision import (
80 get_vit_attn_backend,
81 is_vit_use_data_parallel,
82 )
83
84 logger = init_logger(__name__)
85
86
87 class GlmOcrVisionMLP(Glm4vVisionMLP):
88 pass
89
90
91 class GlmOcrVisionAttention(nn.Module):
92 def __init__(
93 self,
94 embed_dim: int,
95 num_heads: int,
96 projection_size: int,
97 quant_config: QuantizationConfig | None = None,
98 prefix: str = "",
99 ) -> None:
100 super().__init__()
101 # Per attention head and per partition values.
102 use_data_parallel = is_vit_use_data_parallel()
103 self.tp_size = (
104 1 if use_data_parallel else get_tensor_model_parallel_world_size()
105 )
106 self.tp_rank = (
107 0 if use_data_parallel else parallel_state.get_tensor_model_parallel_rank()
108 )
109 self.hidden_size_per_attention_head = dist_utils.divide(
110 projection_size, num_heads
111 )
112 self.num_attention_heads_per_partition = dist_utils.divide(
113 num_heads, self.tp_size
114 )
115
116 self.head_dim = embed_dim // num_heads
117
118 self.q_norm = RMSNorm(self.head_dim, eps=1e-5)
119 self.k_norm = RMSNorm(self.head_dim, eps=1e-5)
120
121 self.qkv = QKVParallelLinear(
122 hidden_size=embed_dim,
123 head_size=self.hidden_size_per_attention_head,
124 total_num_heads=num_heads,
125 total_num_kv_heads=num_heads,
126 bias=True,
127 quant_config=quant_config,
128 # Change qkv prefix to align with GLM-4.5V-FP8 quantization cfg
129 prefix=f"{prefix}.qkv_proj" if quant_config else f"{prefix}.qkv",
130 disable_tp=use_data_parallel,
131 )
132 self.proj = RowParallelLinear(
133 input_size=projection_size,
134 output_size=embed_dim,
135 quant_config=quant_config,
136 prefix=f"{prefix}.proj",
137 bias=True,
138 disable_tp=use_data_parallel,
139 )
140
141 self.attn = MMEncoderAttention(
142 num_heads=self.num_attention_heads_per_partition,
143 head_size=self.hidden_size_per_attention_head,
144 scale=self.hidden_size_per_attention_head**-0.5,
145 prefix=f"{prefix}.attn",
146 )
147 self.apply_rotary_emb = ApplyRotaryEmb(enforce_enable=True)
148
149 def split_qkv(self, qkv: torch.Tensor) -> tuple[torch.Tensor, ...]:
150 # [s, b, 3 * head * head_dim]
151 seq_len, bs, _ = qkv.shape
152
153 # [s, b, 3 * head * head_dim] -> 3 * [s, b, head * head_dim]
154 q, k, v = qkv.chunk(3, dim=2)
155
156 # 3 * [s, b, head * head_dim] -> 3 * [s, b, head, head_dim]
157 new_shape = (
158 seq_len,
159 bs,
160 self.num_attention_heads_per_partition,
161 self.hidden_size_per_attention_head,
162 )
163 q, k, v = (x.view(*new_shape) for x in (q, k, v))
164 return q, k, v
165
166 def forward(
167 self,
168 x: torch.Tensor,
169 cu_seqlens: torch.Tensor,
170 rotary_pos_emb_cos: torch.Tensor,
171 rotary_pos_emb_sin: torch.Tensor,
172 max_seqlen: torch.Tensor | None = None, # Only used for Flash Attention
173 ) -> torch.Tensor:
174 # [s, b, c] --> [s, b, head * 3 * head_dim]
175 x, _ = self.qkv(x)
176
177 # [s, b, 3 * head * head_dim] -> 3 * [s, b, head, head_dim]
178 q, k, v = self.split_qkv(x)
179
180 # RMSNorm on q, k
181 q_shape, k_shape = q.shape, k.shape
182 q = self.q_norm(q.reshape(-1, self.head_dim)).view(q_shape)
183 k = self.k_norm(k.reshape(-1, self.head_dim)).view(k_shape)
184
185 q, k, v = (rearrange(x, "s b ... -> b s ...").contiguous() for x in (q, k, v))
186 if rotary_pos_emb_cos is not None and rotary_pos_emb_sin is not None:
187 # [2 * b, s, heads, head_dim]
188 qk_concat = torch.cat([q, k], dim=0)
189 qk_rotated = self.apply_rotary_emb(
190 qk_concat,
191 rotary_pos_emb_cos,
192 rotary_pos_emb_sin,
193 )
194 q, k = torch.chunk(qk_rotated, 2, dim=0)
195
196 context_layer = self.attn(
197 query=q,
198 key=k,
199 value=v,
200 cu_seqlens=cu_seqlens,
201 max_seqlen=max_seqlen,
202 )
203 context_layer = rearrange(context_layer, "b s h d -> s b (h d)").contiguous()
204
205 output, _ = self.proj(context_layer)
206 return output
207
208
209 class GlmOcrVisionBlock(Glm4vVisionBlock):
210 def __init__(
211 self,
212 dim: int,
213 num_heads: int,
214 mlp_hidden_dim: int,
215 norm_layer: Callable[[int], nn.Module] | None = None,
216 quant_config: QuantizationConfig | None = None,
217 prefix: str = "",
218 ) -> None:
219 super().__init__(
220 dim,
221 num_heads,
222 mlp_hidden_dim,
223 norm_layer,
224 quant_config,
225 prefix,
226 )
227 if norm_layer is None:
228 norm_layer = partial(nn.LayerNorm, eps=1e-6)
229 self.norm1 = norm_layer(dim)
230 self.norm2 = norm_layer(dim)
231 self.attn = GlmOcrVisionAttention(
232 embed_dim=dim,
233 num_heads=num_heads,
234 projection_size=dim,
235 quant_config=quant_config,
236 prefix=f"{prefix}.attn",
237 )
238 self.mlp = GlmOcrVisionMLP(
239 dim,
240 mlp_hidden_dim,
241 bias=True,
242 quant_config=quant_config,
243 prefix=f"{prefix}.mlp",
244 )
245
246
247 class GlmOcrPatchMerger(Glm4vPatchMerger):
248 pass
249
250
251 class GlmOcrVisionTransformer(Glm4vVisionTransformer):
252 def __init__(
253 self,
254 text_config: "GlmOcrTextConfig",
255 vision_config: "GlmOcrVisionConfig",
256 norm_eps: float = 1e-5,
257 quant_config: QuantizationConfig | None = None,
258 input_norm: nn.Module | None = None,
259 prefix: str = "",
260 ) -> None:
261 super().__init__(
262 text_config,
263 vision_config,
264 norm_eps,
265 quant_config,
266 input_norm,
267 prefix,
268 )
269
270 del self.post_conv_layernorm
271 del self.embeddings
272
273 patch_size = vision_config.patch_size
274 temporal_patch_size = vision_config.temporal_patch_size
275 in_channels = vision_config.in_channels
276 depth = vision_config.depth
277 self.hidden_size = vision_config.hidden_size
278 self.num_heads = vision_config.num_heads
279
280 self.patch_size = vision_config.patch_size
281 self.spatial_merge_size = vision_config.spatial_merge_size
282 self.out_hidden_size = vision_config.out_hidden_size
283
284 self.patch_embed = Glm4vVisionPatchEmbed(
285 patch_size=patch_size,
286 temporal_patch_size=temporal_patch_size,
287 in_channels=in_channels,
288 hidden_size=self.hidden_size,
289 )
290
291 norm_layer = partial(RMSNorm, eps=norm_eps)
292 head_dim = self.hidden_size // self.num_heads
293 self.rotary_pos_emb = get_rope(
294 head_size=head_dim,
295 max_position=8192,
296 is_neox_style=True,
297 rope_parameters={"partial_rotary_factor": 0.5},
298 )
299 self.blocks = nn.ModuleList(
300 [
301 GlmOcrVisionBlock(
302 dim=self.hidden_size,
303 num_heads=self.num_heads,
304 mlp_hidden_dim=vision_config.intermediate_size,
305 norm_layer=norm_layer,
306 quant_config=quant_config,
307 prefix=f"{prefix}.blocks.{layer_idx}",
308 )
309 for layer_idx in range(depth)
310 ]
311 )
312 self.merger = GlmOcrPatchMerger(
313 d_model=vision_config.out_hidden_size,
314 context_dim=text_config.intermediate_size,
315 quant_config=quant_config,
316 bias=False,
317 prefix=f"{prefix}.merger",
318 )
319
320 self.downsample = Conv2dLayer(
321 in_channels=vision_config.hidden_size,
322 out_channels=vision_config.out_hidden_size,
323 kernel_size=vision_config.spatial_merge_size,
324 stride=vision_config.spatial_merge_size,
325 )
326 self.post_layernorm = RMSNorm(
327 vision_config.hidden_size, eps=vision_config.rms_norm_eps
328 )
329
330 self.attn_backend = get_vit_attn_backend(
331 head_size=head_dim,
332 dtype=torch.get_default_dtype(),
333 )
334
335 def forward(
336 self,
337 x: torch.Tensor,
338 grid_thw: torch.Tensor | list[list[int]],
339 encoder_metadata: dict[str, torch.Tensor] | None = None,
340 ) -> torch.Tensor:
341 del encoder_metadata
342 if isinstance(grid_thw, list):
343 grid_thw = torch.tensor(grid_thw, dtype=torch.int32)
344
345 # patchify
346 x = self.input_norm(x.to(device=self.device), self.dtype)
347 x = self.patch_embed(x)
348
349 # compute position embedding
350 rotary_pos_emb_cos, rotary_pos_emb_sin, image_type_ids = self.rot_pos_emb(
351 grid_thw
352 )
353 # compute cu_seqlens
354 cu_seqlens = torch.repeat_interleave(
355 grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]
356 ).cumsum(dim=0, dtype=torch.int32)
357 # cat straight into a pinned buffer so the H2D copy stays non-blocking.
358 cu_seqlens = torch.cat(
359 [cu_seqlens.new_zeros(1), cu_seqlens],
360 out=cu_seqlens.new_empty(cu_seqlens.numel() + 1, pin_memory=PIN_MEMORY),
361 ).to(self.device, non_blocking=True)
362
363 # pre-compute max_seqlen for attn mask to reduce cuMemcpy operations
364 max_seqlen = self.compute_attn_mask_seqlen(cu_seqlens)
365
366 # transformers
367 x = x.unsqueeze(1)
368 for blk in self.blocks:
369 x = blk(
370 x,
371 cu_seqlens=cu_seqlens,
372 rotary_pos_emb_cos=rotary_pos_emb_cos,
373 rotary_pos_emb_sin=rotary_pos_emb_sin,
374 max_seqlen=max_seqlen,
375 )
376
377 # adapter
378 x = self.post_layernorm(x)
379
380 x = x.view(-1, self.spatial_merge_size, self.spatial_merge_size, x.shape[-1])
381 x = x.permute(0, 3, 1, 2)
382 x = self.downsample(x).view(-1, self.out_hidden_size)
383 x = self.merger(x)
384
385 return x
386
387
388 @MULTIMODAL_REGISTRY.register_processor(
389 Glm4vMultiModalProcessor,
390 info=Glm4vProcessingInfo,
391 dummy_inputs=Glm4vDummyInputsBuilder,
392 )
393 class GlmOcrForConditionalGeneration(Glm4vForConditionalGeneration):
394 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
395 super().__init__(vllm_config=vllm_config, prefix=prefix)
396 config = vllm_config.model_config.hf_config
397 quant_config = vllm_config.quant_config
398
399 with self._mark_tower_model(vllm_config, {"image", "video"}):
400 self.visual = GlmOcrVisionTransformer(
401 config.text_config,
402 config.vision_config,
403 norm_eps=getattr(config, "rms_norm_eps", 1e-5),
404 quant_config=quant_config,
405 input_norm=build_mm_input_norm(self.model_config),
406 prefix=maybe_prefix(prefix, "visual"),
407 )