Download models/encoder/qwen3_vl.py from ZenoNing/ConsDrive: direct link, hf CLI and curl.
- Browser
- Download file 5.07 kB
-
https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/encoder/qwen3_vl.py
- Command line
-
hf download hf://ZenoNing/ConsDrive/models/encoder/qwen3_vl.py
-
curl -L -o qwen3_vl.py https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/encoder/qwen3_vl.py
5.07 kB
| from typing import Optional | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| from transformers import AutoConfig | |
| from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel | |
| from models.qwen_utils import build_empty_module, load_prefixed_safetensors | |
| from utils.logging_project import rank_zero_print | |
| class Qwen3VLEncoderModel(nn.Module): | |
| """ | |
| Qwen3-VL vision encoder in native video mode. | |
| Consumes video patches (pixel_values_videos) with video_grid_thw and returns: | |
| - merged video token embeddings [B, N, out_hidden_size] | |
| - attention mask [B, N] | |
| - deepstack features: list of 3 tensors [B, N, out_hidden_size] | |
| (from vision blocks 8/16/24, already projected by deepstack mergers) | |
| """ | |
| def __init__( | |
| self, | |
| variant: str, | |
| freeze: bool = False, | |
| max_visual_tokens: Optional[int] = None, | |
| local_files_only: bool = True, | |
| use_global_img: bool = False, | |
| torch_dtype: str = "bfloat16", | |
| ): | |
| super().__init__() | |
| self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only) | |
| dtype = getattr(torch, torch_dtype) | |
| self.config.vision_config._attn_implementation = "flash_attention_2" | |
| self.config.vision_config.dtype = dtype | |
| rank_zero_print("Loading Qwen3-VL vision encoder (meta init)...", flush=True) | |
| self.image_encoder = build_empty_module(Qwen3VLVisionModel, self.config.vision_config) | |
| rank_zero_print("Loading vision weights...", flush=True) | |
| load_prefixed_safetensors(self.image_encoder, variant, "model.visual.", torch_dtype=dtype) | |
| rank_zero_print("Vision encoder ready.", flush=True) | |
| self.token_size = self.config.vision_config.out_hidden_size | |
| self.spatial_merge_size = self.config.vision_config.spatial_merge_size | |
| self.num_deepstack_layers = len(self.config.vision_config.deepstack_visual_indexes) | |
| self.max_visual_tokens = max_visual_tokens | |
| self.use_global_img = use_global_img | |
| if freeze: | |
| for param in self.parameters(): | |
| param.requires_grad = False | |
| def forward(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor = None): | |
| """ | |
| Args: | |
| pixel_values: [total_patches, patch_dim] video patches from Qwen3VLVideoProcessor | |
| (concatenated over the batch). | |
| image_sizes: video_grid_thw. Either [B, 3] (one video per sample) or | |
| [B, 1, 3]. | |
| """ | |
| if image_sizes is None: | |
| raise ValueError("Qwen3-VL vision encoder requires video_grid_thw in image_sizes.") | |
| if image_sizes.ndim == 3: | |
| video_grid_thw = image_sizes.reshape(-1, 3) | |
| elif image_sizes.ndim == 2: | |
| video_grid_thw = image_sizes | |
| else: | |
| raise ValueError(f"Unexpected image_sizes shape: {tuple(image_sizes.shape)}") | |
| batch_size = video_grid_thw.shape[0] | |
| device = next(self.image_encoder.parameters()).device | |
| dtype = next(self.image_encoder.parameters()).dtype | |
| pixel_values = pixel_values.to(device=device, dtype=dtype) | |
| video_grid_thw = video_grid_thw.to(device=device) | |
| outputs = self.image_encoder(pixel_values, grid_thw=video_grid_thw) | |
| video_embeds = outputs.pooler_output # [total_merged_tokens, out_hidden_size] | |
| deepstack_features = outputs.deepstack_features # list of [total_merged_tokens, out_hidden_size] | |
| split_sizes = ( | |
| video_grid_thw.prod(-1) // (self.spatial_merge_size ** 2) | |
| ).tolist() | |
| split_sizes = [int(s) for s in split_sizes] | |
| video_embeds = torch.split(video_embeds, split_sizes) | |
| deepstack_split = [torch.split(feat, split_sizes) for feat in deepstack_features] | |
| max_tokens = max(int(s) for s in split_sizes) | |
| if self.max_visual_tokens is not None: | |
| max_tokens = min(max_tokens, self.max_visual_tokens) | |
| padded_embeds = [] | |
| padded_deepstack = [[] for _ in range(len(deepstack_features))] | |
| attention_masks = [] | |
| for sample_idx in range(batch_size): | |
| sample = video_embeds[sample_idx][:max_tokens] | |
| valid = sample.shape[0] | |
| pad = max_tokens - valid | |
| if pad > 0: | |
| sample = F.pad(sample, (0, 0, 0, pad)) | |
| padded_embeds.append(sample) | |
| attention_masks.append(torch.arange(max_tokens, device=sample.device) < valid) | |
| for layer_idx in range(len(deepstack_features)): | |
| ds = deepstack_split[layer_idx][sample_idx][:max_tokens] | |
| if pad > 0: | |
| ds = F.pad(ds, (0, 0, 0, pad)) | |
| padded_deepstack[layer_idx].append(ds) | |
| video_embeds = torch.stack(padded_embeds, dim=0) # [B, N, C] | |
| attention_mask = torch.stack(attention_masks, dim=0) # [B, N] | |
| deepstack_embeds = [torch.stack(layer, dim=0) for layer in padded_deepstack] # 3 x [B, N, C] | |
| return video_embeds, attention_mask, deepstack_embeds | |