Vishva R commited on
Upload folder using huggingface_hub
Browse filesFiles changed (13)
- .gitattributes+1
- chat_template.jinjaAdded+2
- config.jsonAdded+101
- configuration_dots.pyAdded+78
- generation_config.jsonAdded+9
- model.safetensorsAdded+3
- modeling_dots_ocr.pyAdded+131
- modeling_dots_vision.pyAdded+404
- preprocessor_config.jsonAdded+22
- processor_config.jsonAdded+66
- quantization_config.jsonAdded+13
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+31
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text12{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{%- for m in messages %}{%- if m.role == 'system' %}{{- '<|system|>' + m.content + '<|endofsystem|>' }}{%- elif m.role == 'user' %}{% if m.content is string %}{{- '<|user|>' + m.content + '<|endofuser|>' }}{% else %}{{- '<|user|>' }}{% for content in m.content %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|img|><|imgpad|><|endofimg|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|img|><|video_pad|><|endofimg|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}{{- '<|endofuser|>' }}{%- endif %}{%- elif m.role == 'assistant' %}{{- '<|assistant|>' + m.content }}{%- if not loop.last %}{{- '<|endofassistant|>' }}{%- endif %}{%- endif %}{%- endfor %}{%- if messages[-1].role != 'assistant' %}{{- '<|assistant|>' }}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101{ "architectures": [ "DotsOCRForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_dots.DotsOCRConfig", "AutoModelForCausalLM": "modeling_dots_ocr.DotsOCRForCausalLM" }, "bos_token_id": null, "dtype": "bfloat16", "eos_token_id": null, "hidden_act": "silu", "hidden_size": 1536, "image_token_id": 151665, "initializer_range": 0.02, "intermediate_size": 8960, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "max_position_embeddings": 131072, "max_window_layers": 28, "model_type": "dots_ocr", "num_attention_heads": 12, "num_hidden_layers": 28, "num_key_value_heads": 2, "pad_token_id": null, "quantization_config": { "autoround_version": "0.16.0", "bits": 4, "block_name_to_quantize": "model.layers", "data_type": "int", "group_size": 16, "iters": 1000, "packing_format": "auto_round:auto_gptq", "quant_method": "auto-round", "static_attention_granularity": "tensor", "static_kv_granularity": "tensor", "sym": true }, "rms_norm_eps": 1e-06, "rope_parameters": { "rope_theta": 1000000, "rope_type": "default" }, "sliding_window": null, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "use_sliding_window": false, "video_token_id": 151656, "vision_config": { "attn_implementation": "flash_attention_2", "embed_dim": 1536, "gradient_checkpointing": false, "hidden_size": 1536, "init_merger_std": 0.02, "initializer_range": 0.02, "intermediate_size": 4224, "is_causal": false, "model_type": "dots_vit", "num_attention_heads": 12, "num_channels": 3, "num_hidden_layers": 42, "patch_size": 14, "post_norm": true, "rms_norm_eps": 1e-05, "spatial_merge_size": 2, "temporal_patch_size": 1, "use_bias": false }, "vocab_size": 151936}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778from typing import Any, Optionalfrom transformers.configuration_utils import PretrainedConfigfrom transformers.models.qwen2 import Qwen2Configfrom transformers import Qwen2_5_VLProcessor, AutoProcessorfrom transformers.models.auto.configuration_auto import CONFIG_MAPPING
class DotsVisionConfig(PretrainedConfig): model_type: str = "dots_vit"
def __init__( self, embed_dim: int = 1536, # vision encoder embed size hidden_size: int = 1536, # after merger hidden size intermediate_size: int = 4224, num_hidden_layers: int = 42, num_attention_heads: int = 12, num_channels: int = 3, patch_size: int = 14, spatial_merge_size: int = 2, temporal_patch_size: int = 1, rms_norm_eps: float = 1e-5, use_bias: bool = False, attn_implementation="flash_attention_2", # "eager","sdpa","flash_attention_2" initializer_range=0.02, init_merger_std=0.02, is_causal=False, # ve causal forward post_norm=True, gradient_checkpointing=False, **kwargs: Any, ): super().__init__(**kwargs) self.embed_dim = embed_dim self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_channels = num_channels self.patch_size = patch_size self.spatial_merge_size = spatial_merge_size self.temporal_patch_size = temporal_patch_size self.rms_norm_eps = rms_norm_eps self.use_bias = use_bias self.attn_implementation = attn_implementation self.initializer_range = initializer_range self.init_merger_std = init_merger_std self.is_causal = is_causal self.post_norm = post_norm self.gradient_checkpointing = gradient_checkpointing
class DotsOCRConfig(Qwen2Config): model_type = "dots_ocr" def __init__(self, image_token_id = 151665, video_token_id = 151656, vision_config: Optional[dict] = None, *args, **kwargs): super().__init__(*args, **kwargs) self.image_token_id = image_token_id self.video_token_id = video_token_id self.vision_config = DotsVisionConfig(**(vision_config or {}))
def save_pretrained(self, save_directory, **kwargs): self._auto_class = None super().save_pretrained(save_directory, **kwargs)
class DotsVLProcessor(Qwen2_5_VLProcessor): def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs): super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template) self.image_token = "<|imgpad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token self.image_token_id = 151665 self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token self.video_token_id = 151656
AutoProcessor.register("dots_ocr", DotsVLProcessor)CONFIG_MAPPING.register("dots_ocr", DotsOCRConfig)123456789{ "eos_token_id": [ 151643, 151672, 151673 ], "max_length": 32768, "transformers_version": "5.17.0"}123version https://git-lfs.github.com/spec/v1oid sha256:f0224aa99cd0a57b0c5a191f6064d77b0252203dddf03a7eed221c0fbb697aa8size 4317899464123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131from typing import List, Optional, Tuple, Union
import torchfrom transformers.modeling_outputs import CausalLMOutputWithPastfrom transformers.models.qwen2 import Qwen2ForCausalLM
from .configuration_dots import DotsVisionConfig, DotsOCRConfigfrom .modeling_dots_vision import DotsVisionTransformer
DOTS_VLM_MAX_IMAGES = 200
class DotsOCRForCausalLM(Qwen2ForCausalLM): config_class = DotsOCRConfig
def __init__(self, config: DotsOCRConfig): super().__init__(config)
if isinstance(self.config.vision_config, dict): vision_config = DotsVisionConfig(**self.config.vision_config) self.config.vision_config = vision_config else: vision_config = self.config.vision_config
self.vision_tower = DotsVisionTransformer(vision_config)
def prepare_inputs_embeds( self, input_ids: torch.LongTensor, pixel_values: Optional[torch.FloatTensor] = None, grid_thw: Optional[torch.FloatTensor] = None, img_mask: Optional[torch.BoolTensor] = None, ) -> torch.Tensor: inputs_embeds = self.get_input_embeddings()(input_ids)
if pixel_values is not None: assert img_mask is not None if grid_thw.shape[0] > DOTS_VLM_MAX_IMAGES: print( f"Num image exceeded: {grid_thw.shape[0]} > {DOTS_VLM_MAX_IMAGES}, which may cause FSDP hang" )
vision_embeddings = self.vision_tower(pixel_values, grid_thw)
true_indices = torch.nonzero(img_mask).squeeze() if len(true_indices) > vision_embeddings.size(0): print( f"img_mask sum > VE and will be truncated, mask.sum()={len(true_indices)} {vision_embeddings.size(0)=}" ) true_indices = true_indices[: vision_embeddings.size(0)] new_img_mask = torch.zeros_like(img_mask, device=img_mask.device) new_img_mask[true_indices[:, 0], true_indices[:, 1]] = True else: new_img_mask = img_mask
assert ( vision_embeddings.size(0) == new_img_mask.sum() ), f"{vision_embeddings.size(0)=}, {new_img_mask.sum()=}"
inputs_embeds = inputs_embeds.masked_scatter( new_img_mask.to(inputs_embeds.device).unsqueeze(-1).expand_as(inputs_embeds), vision_embeddings.to(inputs_embeds.device).type(inputs_embeds.dtype), )
return inputs_embeds
def forward( self, input_ids: torch.LongTensor, pixel_values: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, use_cache: Optional[bool] = None, logits_to_keep: int = 0, **loss_kwargs, ) -> Union[Tuple, CausalLMOutputWithPast]: return_dict = return_dict if return_dict is not None else self.config.use_return_dict assert len(input_ids) >= 1, f"empty input_ids {input_ids.shape=} will cause gradnorm nan" if inputs_embeds is None: img_mask = input_ids == self.config.image_token_id inputs_embeds = self.prepare_inputs_embeds(input_ids, pixel_values, image_grid_thw, img_mask)
outputs = super().forward( inputs_embeds=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, labels=labels, use_cache=use_cache if use_cache is not None else self.config.use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, # return_dict=return_dict, logits_to_keep=logits_to_keep, **loss_kwargs, )
return outputs
def prepare_inputs_for_generation( self, input_ids, past_key_values=None, inputs_embeds=None, pixel_values=None, attention_mask=None, cache_position=None, num_logits_to_keep=None, **kwargs, ): model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, num_logits_to_keep=num_logits_to_keep, **kwargs, )
if cache_position[0] == 0: model_inputs["pixel_values"] = pixel_values
return model_inputs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404import math
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpointfrom flash_attn import flash_attn_varlen_funcfrom torch.nn import LayerNormfrom transformers.modeling_utils import PreTrainedModelfrom .configuration_dots import DotsVisionConfig
def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor: orig_dtype = tensor.dtype tensor = tensor.float()
cos = freqs.cos() sin = freqs.sin()
cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
output = (tensor * cos) + (rotate_half(tensor) * sin)
output = output.to(orig_dtype)
return output
class VisionRotaryEmbedding(nn.Module): def __init__(self, dim: int, theta: float = 10000.0) -> None: super().__init__() inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, seqlen: int) -> torch.Tensor: seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype) freqs = torch.outer(seq, self.inv_freq) return freqs
class PatchMerger(nn.Module): def __init__( self, dim: int, context_dim: int, spatial_merge_size: int = 2, pre_norm="layernorm", init_merger_std=None, ) -> None: super().__init__() self.hidden_size = context_dim * (spatial_merge_size ** 2) self.pre_norm = pre_norm if self.pre_norm == "layernorm": self.ln_q = LayerNorm(context_dim, eps=1e-6) elif self.pre_norm == "rmsnorm": self.ln_q = RMSNorm(context_dim, eps=1e-6) else: print("no norm in patch merger")
self.mlp = nn.Sequential( nn.Linear(self.hidden_size, self.hidden_size), nn.GELU(), nn.Linear(self.hidden_size, dim), )
if init_merger_std is not None: nn.init.normal_(self.mlp[0].weight, mean=0.0, std=init_merger_std) nn.init.zeros_(self.mlp[0].bias) nn.init.normal_(self.mlp[2].weight, mean=0.0, std=init_merger_std) nn.init.zeros_(self.mlp[2].bias)
def forward(self, x: torch.Tensor) -> torch.Tensor: if self.pre_norm: x = self.mlp(self.ln_q(x).view(-1, self.hidden_size)) else: x = self.mlp(x.view(-1, self.hidden_size)) return x
class VisionAttention(nn.Module): def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None: super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.qkv = nn.Linear(dim, dim * 3, bias=bias) self.proj = nn.Linear(dim, dim, bias=bias)
def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None, ) -> torch.Tensor: seq_length = hidden_states.shape[0]
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0) k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
attention_mask = torch.full( [1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype ) for i in range(1, len(cu_seqlens)): attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = 0
q = q.transpose(0, 1) k = k.transpose(0, 1) v = v.transpose(0, 1) attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim) attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype) attn_output = torch.matmul(attn_weights, v) attn_output = attn_output.transpose(0, 1) attn_output = attn_output.reshape(seq_length, -1) attn_output = self.proj(attn_output) return attn_output
class VisionFlashAttention2(nn.Module): def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None: super().__init__() self.num_heads = num_heads self.qkv = nn.Linear(dim, dim * 3, bias=bias) self.proj = nn.Linear(dim, dim, bias=bias) self.config = config self.is_causal = config.is_causal
def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None, ) -> torch.Tensor: seq_length = hidden_states.shape[0] q, k, v = ( self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) ) # 'shd' q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0) k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0) max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item() attn_output = flash_attn_varlen_func( q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, causal=self.is_causal ).reshape(seq_length, -1) attn_output = self.proj(attn_output)
return attn_output
class VisionSdpaAttention(nn.Module): def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None: super().__init__() self.num_heads = num_heads self.qkv = nn.Linear(dim, dim * 3, bias=bias) self.proj = nn.Linear(dim, dim, bias=bias) self.config = config
def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None, ) -> torch.Tensor: seq_length = hidden_states.shape[0] q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0) k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool) for i in range(1, len(cu_seqlens)): attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = True
q = q.transpose(0, 1) k = k.transpose(0, 1) v = v.transpose(0, 1)
attn_output = F.scaled_dot_product_attention(q, k, v, attention_mask, dropout_p=0.0) attn_output = attn_output.transpose(0, 1) attn_output = attn_output.reshape(seq_length, -1)
attn_output = self.proj(attn_output) return attn_output
DOTS_VISION_ATTENTION_CLASSES = { "eager": VisionAttention, "flash_attention_2": VisionFlashAttention2, "sdpa": VisionSdpaAttention,}
class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: output = self._norm(x.float()).type_as(x) return output * self.weight
def extra_repr(self) -> str: return f"{tuple(self.weight.shape)}, eps={self.eps}"
def _norm(self, x: torch.Tensor) -> torch.Tensor: return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
class DotsSwiGLUFFN(nn.Module): def __init__(self, config): super().__init__() hidden_features = config.intermediate_size in_features = config.embed_dim bias = config.use_bias
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) self.fc2 = nn.Linear(hidden_features, in_features, bias=bias) self.fc3 = nn.Linear(in_features, hidden_features, bias=bias)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = F.silu(self.fc1(x)) * self.fc3(x) x = self.fc2(x) return x
class DotsPatchEmbed(nn.Module): def __init__(self, config): super().__init__() self.num_channels = config.num_channels self.patch_size = config.patch_size self.temporal_patch_size = config.temporal_patch_size self.embed_dim = config.embed_dim self.config = config self.proj = nn.Conv2d( config.num_channels, config.embed_dim, kernel_size=(config.patch_size, config.patch_size), stride=(config.patch_size, config.patch_size), ) self.norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor: x = x.view(-1, self.num_channels, self.temporal_patch_size, self.patch_size, self.patch_size)[:, :, 0] x = self.proj(x).view(-1, self.embed_dim) x = self.norm(x) return x
class DotsViTPreprocessor(nn.Module): def __init__(self, config): super().__init__() self.patch_h = config.patch_size self.patch_w = config.patch_size self.embed_dim = config.embed_dim self.config = config self.patchifier = DotsPatchEmbed(config)
def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor: tokens = self.patchifier(x, grid_thw) return tokens
class DotsVisionBlock(nn.Module): def __init__(self, config, attn_implementation: str = "flash_attention_2"): super().__init__() self.attn = DOTS_VISION_ATTENTION_CLASSES[attn_implementation]( config, config.embed_dim, num_heads=config.num_attention_heads, bias=config.use_bias ) self.norm1 = RMSNorm(config.embed_dim, eps=config.rms_norm_eps) self.mlp = DotsSwiGLUFFN(config) self.norm2 = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> torch.Tensor: hidden_states = hidden_states + self.attn( self.norm1(hidden_states), cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb ) hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) return hidden_states
class DotsVisionTransformer(PreTrainedModel): def __init__(self, config: DotsVisionConfig) -> None: super().__init__(config) self.config = config self.spatial_merge_size = config.spatial_merge_size
self.patch_embed = DotsViTPreprocessor(config) self._init_weights(self.patch_embed.patchifier.proj)
head_dim = config.embed_dim // config.num_attention_heads
self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
_num_hidden_layers = config.num_hidden_layers self.blocks = nn.ModuleList( [DotsVisionBlock(config, config.attn_implementation) for _ in range(_num_hidden_layers)] )
if self.config.post_norm: self.post_trunk_norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
self.merger = PatchMerger( dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size, init_merger_std=self.config.init_merger_std, )
self.gradient_checkpointing = False self._gradient_checkpointing_func = torch.utils.checkpoint.checkpoint
def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, (nn.Linear, nn.Conv3d)): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
@property def dtype(self) -> torch.dtype: return self.blocks[0].mlp.fc2.weight.dtype
@property def device(self) -> torch.device: return self.blocks[0].mlp.fc2.weight.device
def get_pos_ids_by_grid(self, grid_thw): pos_ids = [] for t, h, w in grid_thw: hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) hpos_ids = hpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) hpos_ids = hpos_ids.permute(0, 2, 1, 3) hpos_ids = hpos_ids.flatten()
wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) wpos_ids = wpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) wpos_ids = wpos_ids.permute(0, 2, 1, 3) wpos_ids = wpos_ids.flatten() pos_ids.append( torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1) )
return pos_ids
def rot_pos_emb(self, grid_thw): pos_ids = self.get_pos_ids_by_grid(grid_thw) pos_ids = torch.cat(pos_ids, dim=0) max_grid_size = grid_thw[:, 1:].max() rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size) rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1) return rotary_pos_emb
def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, bf16=True) -> torch.Tensor: if bf16: hidden_states = hidden_states.bfloat16() hidden_states = self.patch_embed(hidden_states, grid_thw)
rotary_pos_emb = self.rot_pos_emb(grid_thw)
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum( dim=0, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
for blk in self.blocks: if self.gradient_checkpointing and self.training: hidden_states = self._gradient_checkpointing_func( blk.__call__, hidden_states, cu_seqlens, rotary_pos_emb, ) else: hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb)
if self.config.post_norm: hidden_states = self.post_trunk_norm(hidden_states)
hidden_states = self.merger(hidden_states) return hidden_states12345678910111213141516171819202122{ "auto_map": { "AutoProcessor": "configuration_dots.DotsVLProcessor" }, "min_pixels": 3136, "max_pixels": 11289600, "patch_size": 14, "temporal_patch_size": 1, "merge_size": 2, "image_mean": [ 0.48145466, 0.4578275, 0.40821073 ], "image_std": [ 0.26862954, 0.26130258, 0.27577711 ], "image_processor_type": "Qwen2VLImageProcessor", "processor_class": "DotsVLProcessor"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "image_processor": { "auto_map": { "AutoProcessor": "configuration_dots.DotsVLProcessor" }, "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.48145466, 0.4578275, 0.40821073 ], "image_processor_type": "Qwen2VLImageProcessor", "image_std": [ 0.26862954, 0.26130258, 0.27577711 ], "merge_size": 2, "patch_size": 14, "resample": 3, "rescale_factor": 0.00392156862745098, "size": { "longest_edge": 11289600, "shortest_edge": 3136 }, "temporal_patch_size": 1 }, "processor_class": "DotsVLProcessor", "video_processor": { "auto_map": { "AutoProcessor": "configuration_dots.DotsVLProcessor" }, "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_sample_frames": false, "image_mean": [ 0.48145466, 0.4578275, 0.40821073 ], "image_std": [ 0.26862954, 0.26130258, 0.27577711 ], "max_frames": 768, "max_video_tokens": 128000, "merge_size": 2, "min_frames": 4, "patch_size": 14, "resample": 3, "rescale_factor": 0.00392156862745098, "return_metadata": false, "size": { "longest_edge": 11289600, "shortest_edge": 3136 }, "temporal_patch_size": 1, "video_processor_type": "Qwen2VLVideoProcessor" }}12345678910111213{ "bits": 4, "data_type": "int", "group_size": 16, "sym": true, "iters": 1000, "static_attention_granularity": "tensor", "static_kv_granularity": "tensor", "autoround_version": "0.16.0", "block_name_to_quantize": "model.layers", "quant_method": "auto-round", "packing_format": "auto_round:auto_gptq"}123version https://git-lfs.github.com/spec/v1oid sha256:d705e829c2087a40edbce49df91b0762ddfee650a126d5120da87e1b51950c16size 1142624712345678910111213141516171819202122232425262728293031{ "add_prefix_space": false, "backend": "tokenizers", "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "errors": "replace", "extra_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "is_local": true, "local_files_only": false, "model_max_length": 131072, "pad_token": "[PAD]", "processor_class": "DotsVLProcessor", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}.gitattributes+1
chat_template.jinjaAdded+2
config.jsonAdded+101
configuration_dots.pyAdded+78
generation_config.jsonAdded+9
model.safetensorsAdded+3
modeling_dots_ocr.pyAdded+131
modeling_dots_vision.pyAdded+404
preprocessor_config.jsonAdded+22
processor_config.jsonAdded+66
quantization_config.jsonAdded+13
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+31