Instructions to use zenosai/MonkeyOCRv2-B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use zenosai/MonkeyOCRv2-B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-feature-extraction", model="zenosai/MonkeyOCRv2-B", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("zenosai/MonkeyOCRv2-B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse files- config.json +29 -0
- configuration_monkeyocrv2vit.py +49 -0
- model.safetensors +3 -0
- modeling_monkeyocrv2_vision.py +525 -0
- preprocessor_config.json +22 -0
- processor_config.json +6 -0
config.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"MonkeyOCRv2VisionTransformer"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_monkeyocrv2vit.MonkeyOCRv2VisionConfig",
|
| 7 |
+
"AutoModel": "modeling_monkeyocrv2_vision.MonkeyOCRv2VisionTransformer"
|
| 8 |
+
},
|
| 9 |
+
"vision_attn_implementation": "flash_attention_2",
|
| 10 |
+
"dtype": "bfloat16",
|
| 11 |
+
"embed_dim": 768,
|
| 12 |
+
"gradient_checkpointing": false,
|
| 13 |
+
"hidden_size": 1024,
|
| 14 |
+
"init_merger_std": 0.02,
|
| 15 |
+
"initializer_range": 0.02,
|
| 16 |
+
"intermediate_size": 3072,
|
| 17 |
+
"is_causal": false,
|
| 18 |
+
"model_type": "monkeyocr_vit",
|
| 19 |
+
"num_attention_heads": 12,
|
| 20 |
+
"num_channels": 3,
|
| 21 |
+
"num_hidden_layers": 12,
|
| 22 |
+
"pad_token_id": 151643,
|
| 23 |
+
"patch_size": 14,
|
| 24 |
+
"post_norm": true,
|
| 25 |
+
"rms_norm_eps": 1e-05,
|
| 26 |
+
"spatial_merge_size": 2,
|
| 27 |
+
"temporal_patch_size": 1,
|
| 28 |
+
"use_bias": false
|
| 29 |
+
}
|
configuration_monkeyocrv2vit.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 3 |
+
from transformers.models.auto.configuration_auto import CONFIG_MAPPING
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MonkeyOCRv2VisionConfig(PretrainedConfig):
|
| 7 |
+
model_type = "MonkeyOCRv2VisionTransformer"
|
| 8 |
+
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
embed_dim: int = 1536,
|
| 12 |
+
hidden_size: int = 1536,
|
| 13 |
+
intermediate_size: int = 4224,
|
| 14 |
+
num_hidden_layers: int = 42,
|
| 15 |
+
num_attention_heads: int = 12,
|
| 16 |
+
num_channels: int = 3,
|
| 17 |
+
patch_size: int = 14,
|
| 18 |
+
spatial_merge_size: int = 2,
|
| 19 |
+
temporal_patch_size: int = 1,
|
| 20 |
+
rms_norm_eps: float = 1e-5,
|
| 21 |
+
use_bias: bool = False,
|
| 22 |
+
vision_attn_implementation="flash_attention_2", # "eager","sdpa","flash_attention_2"
|
| 23 |
+
initializer_range=0.02,
|
| 24 |
+
init_merger_std=0.02,
|
| 25 |
+
is_causal=False,
|
| 26 |
+
post_norm=True,
|
| 27 |
+
gradient_checkpointing=False,
|
| 28 |
+
**kwargs: Any,
|
| 29 |
+
):
|
| 30 |
+
super().__init__(**kwargs)
|
| 31 |
+
self.embed_dim = embed_dim
|
| 32 |
+
self.hidden_size = hidden_size
|
| 33 |
+
self.intermediate_size = intermediate_size
|
| 34 |
+
self.num_hidden_layers = num_hidden_layers
|
| 35 |
+
self.num_attention_heads = num_attention_heads
|
| 36 |
+
self.num_channels = num_channels
|
| 37 |
+
self.patch_size = patch_size
|
| 38 |
+
self.spatial_merge_size = spatial_merge_size
|
| 39 |
+
self.temporal_patch_size = temporal_patch_size
|
| 40 |
+
self.rms_norm_eps = rms_norm_eps
|
| 41 |
+
self.use_bias = use_bias
|
| 42 |
+
self.vision_attn_implementation = vision_attn_implementation
|
| 43 |
+
self.initializer_range = initializer_range
|
| 44 |
+
self.init_merger_std = init_merger_std
|
| 45 |
+
self.is_causal = is_causal
|
| 46 |
+
self.post_norm = post_norm
|
| 47 |
+
self.gradient_checkpointing = gradient_checkpointing
|
| 48 |
+
|
| 49 |
+
CONFIG_MAPPING.register("MonkeyOCRv2VisionTransformer", MonkeyOCRv2VisionConfig)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c61ccbd8db2e0f655565d8502256f9fb75f2f24491e8b0d2f2f9a28ca4c354a7
|
| 3 |
+
size 454882592
|
modeling_monkeyocrv2_vision.py
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
import torch.utils.checkpoint
|
| 7 |
+
|
| 8 |
+
flash_attn_available = True
|
| 9 |
+
npu_available = True
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from flash_attn import flash_attn_varlen_func
|
| 13 |
+
except ImportError:
|
| 14 |
+
flash_attn_available = False
|
| 15 |
+
|
| 16 |
+
from torch.nn import LayerNorm
|
| 17 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 18 |
+
from .configuration_monkeyocrv2vit import MonkeyOCRv2VisionConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import torch_npu
|
| 23 |
+
except ImportError:
|
| 24 |
+
npu_available = False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def rotate_half(x):
|
| 29 |
+
"""Rotates half the hidden dims of the input."""
|
| 30 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 31 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 32 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
| 36 |
+
orig_dtype = tensor.dtype
|
| 37 |
+
tensor = tensor.float()
|
| 38 |
+
|
| 39 |
+
cos = freqs.cos()
|
| 40 |
+
sin = freqs.sin()
|
| 41 |
+
|
| 42 |
+
cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
|
| 43 |
+
sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
|
| 44 |
+
|
| 45 |
+
output = (tensor * cos) + (rotate_half(tensor) * sin)
|
| 46 |
+
|
| 47 |
+
output = output.to(orig_dtype)
|
| 48 |
+
|
| 49 |
+
return output
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class VisionRotaryEmbedding(nn.Module):
|
| 53 |
+
def __init__(self, dim: int, theta: float = 10000.0) -> None:
|
| 54 |
+
super().__init__()
|
| 55 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
| 56 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 57 |
+
|
| 58 |
+
def forward(self, seqlen: int) -> torch.Tensor:
|
| 59 |
+
seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
| 60 |
+
freqs = torch.outer(seq, self.inv_freq)
|
| 61 |
+
return freqs
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PatchMerger(nn.Module):
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
dim: int,
|
| 68 |
+
context_dim: int,
|
| 69 |
+
spatial_merge_size: int = 2,
|
| 70 |
+
pre_norm="layernorm",
|
| 71 |
+
init_merger_std=None,
|
| 72 |
+
) -> None:
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.hidden_size = context_dim * (spatial_merge_size ** 2)
|
| 75 |
+
self.pre_norm = pre_norm
|
| 76 |
+
if self.pre_norm == "layernorm":
|
| 77 |
+
self.ln_q = LayerNorm(context_dim, eps=1e-6)
|
| 78 |
+
elif self.pre_norm == "rmsnorm":
|
| 79 |
+
self.ln_q = RMSNorm(context_dim, eps=1e-6)
|
| 80 |
+
else:
|
| 81 |
+
print("no norm in patch merger")
|
| 82 |
+
|
| 83 |
+
self.mlp = nn.Sequential(
|
| 84 |
+
nn.Linear(self.hidden_size, self.hidden_size),
|
| 85 |
+
nn.GELU(),
|
| 86 |
+
nn.Linear(self.hidden_size, dim),
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if init_merger_std is not None:
|
| 90 |
+
nn.init.normal_(self.mlp[0].weight, mean=0.0, std=init_merger_std)
|
| 91 |
+
nn.init.zeros_(self.mlp[0].bias)
|
| 92 |
+
nn.init.normal_(self.mlp[2].weight, mean=0.0, std=init_merger_std)
|
| 93 |
+
nn.init.zeros_(self.mlp[2].bias)
|
| 94 |
+
|
| 95 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 96 |
+
if self.pre_norm:
|
| 97 |
+
x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
|
| 98 |
+
else:
|
| 99 |
+
x = self.mlp(x.view(-1, self.hidden_size))
|
| 100 |
+
return x
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class VisionAttention(nn.Module):
|
| 104 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
| 105 |
+
super().__init__()
|
| 106 |
+
self.num_heads = num_heads
|
| 107 |
+
self.head_dim = dim // num_heads
|
| 108 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
| 109 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
| 110 |
+
|
| 111 |
+
def forward(
|
| 112 |
+
self,
|
| 113 |
+
hidden_states: torch.Tensor,
|
| 114 |
+
cu_seqlens: torch.Tensor,
|
| 115 |
+
rotary_pos_emb: torch.Tensor = None,
|
| 116 |
+
) -> torch.Tensor:
|
| 117 |
+
seq_length = hidden_states.shape[0]
|
| 118 |
+
|
| 119 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 120 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 121 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 122 |
+
|
| 123 |
+
attention_mask = torch.full(
|
| 124 |
+
[1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
|
| 125 |
+
)
|
| 126 |
+
for i in range(1, len(cu_seqlens)):
|
| 127 |
+
attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = 0
|
| 128 |
+
|
| 129 |
+
q = q.transpose(0, 1)
|
| 130 |
+
k = k.transpose(0, 1)
|
| 131 |
+
v = v.transpose(0, 1)
|
| 132 |
+
attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim)
|
| 133 |
+
attn_weights = attn_weights + attention_mask
|
| 134 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 135 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 136 |
+
attn_output = attn_output.transpose(0, 1)
|
| 137 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
| 138 |
+
attn_output = self.proj(attn_output)
|
| 139 |
+
return attn_output
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class VisionFlashAttention2(nn.Module):
|
| 143 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
| 144 |
+
super().__init__()
|
| 145 |
+
self.num_heads = num_heads
|
| 146 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
| 147 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
| 148 |
+
self.config = config
|
| 149 |
+
self.is_causal = config.is_causal
|
| 150 |
+
|
| 151 |
+
def forward(
|
| 152 |
+
self,
|
| 153 |
+
hidden_states: torch.Tensor,
|
| 154 |
+
cu_seqlens: torch.Tensor,
|
| 155 |
+
rotary_pos_emb: torch.Tensor = None,
|
| 156 |
+
) -> torch.Tensor:
|
| 157 |
+
seq_length = hidden_states.shape[0]
|
| 158 |
+
q, k, v = (
|
| 159 |
+
self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 160 |
+
) # 'shd'
|
| 161 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 162 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 163 |
+
max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
|
| 164 |
+
attn_output = flash_attn_varlen_func(
|
| 165 |
+
q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, causal=self.is_causal
|
| 166 |
+
).reshape(seq_length, -1)
|
| 167 |
+
attn_output = self.proj(attn_output)
|
| 168 |
+
|
| 169 |
+
return attn_output
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class VisionAttentionV2(nn.Module):
|
| 173 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
| 174 |
+
super().__init__()
|
| 175 |
+
self.num_heads = num_heads
|
| 176 |
+
self.head_dim = dim // num_heads
|
| 177 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
| 178 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
| 179 |
+
|
| 180 |
+
def forward(
|
| 181 |
+
self,
|
| 182 |
+
hidden_states: torch.Tensor,
|
| 183 |
+
cu_seqlens: torch.Tensor,
|
| 184 |
+
rotary_pos_emb: torch.Tensor = None,
|
| 185 |
+
) -> torch.Tensor:
|
| 186 |
+
seq_length = hidden_states.shape[0]
|
| 187 |
+
|
| 188 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 189 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 190 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 191 |
+
|
| 192 |
+
seqlens = torch.diff(cu_seqlens).tolist()
|
| 193 |
+
|
| 194 |
+
q_list = torch.split(q, seqlens, 0)
|
| 195 |
+
k_list = torch.split(k, seqlens, 0)
|
| 196 |
+
v_list = torch.split(v, seqlens, 0)
|
| 197 |
+
outputs = []
|
| 198 |
+
for q_i, k_i, v_i in zip(q_list, k_list, v_list):
|
| 199 |
+
q_i = q_i.transpose(0, 1)
|
| 200 |
+
k_i = k_i.transpose(0, 1)
|
| 201 |
+
v_i = v_i.transpose(0, 1)
|
| 202 |
+
out = torch.matmul(q_i, k_i.transpose(1, 2)) / math.sqrt(self.head_dim)
|
| 203 |
+
out = nn.functional.softmax(out, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 204 |
+
out = torch.matmul(out, v_i)
|
| 205 |
+
out = out.transpose(0, 1)
|
| 206 |
+
outputs.append(out)
|
| 207 |
+
|
| 208 |
+
attn_output = torch.concat(outputs, dim=0)
|
| 209 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
| 210 |
+
attn_output = self.proj(attn_output)
|
| 211 |
+
return attn_output
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class VisionAscendAttention(nn.Module):
|
| 215 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.num_heads = num_heads
|
| 218 |
+
self.head_dim = dim // num_heads
|
| 219 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
| 220 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
| 221 |
+
self.config = config
|
| 222 |
+
|
| 223 |
+
def forward(
|
| 224 |
+
self,
|
| 225 |
+
hidden_states: torch.Tensor,
|
| 226 |
+
cu_seqlens: torch.Tensor,
|
| 227 |
+
rotary_pos_emb: torch.Tensor = None,
|
| 228 |
+
) -> torch.Tensor:
|
| 229 |
+
seq_length = hidden_states.shape[0]
|
| 230 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 231 |
+
|
| 232 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 233 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 234 |
+
|
| 235 |
+
attention_mask = torch.ones([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
|
| 236 |
+
for i in range(1, len(cu_seqlens)):
|
| 237 |
+
attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = False
|
| 238 |
+
|
| 239 |
+
q = q.transpose(0, 1).unsqueeze(0)
|
| 240 |
+
k = k.transpose(0, 1).unsqueeze(0)
|
| 241 |
+
v = v.transpose(0, 1).unsqueeze(0)
|
| 242 |
+
|
| 243 |
+
attn_output = torch_npu.npu_prompt_flash_attention(q, k, v,
|
| 244 |
+
atten_mask=attention_mask,
|
| 245 |
+
num_heads=self.num_heads, input_layout="BNSD",
|
| 246 |
+
scale_value=self.head_dim ** -0.5)
|
| 247 |
+
attn_output = attn_output.squeeze(0).transpose(0, 1)
|
| 248 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
| 249 |
+
attn_output = self.proj(attn_output)
|
| 250 |
+
return attn_output
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class VisionSdpaAttention(nn.Module):
|
| 254 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
| 255 |
+
super().__init__()
|
| 256 |
+
self.num_heads = num_heads
|
| 257 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
| 258 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
| 259 |
+
self.config = config
|
| 260 |
+
|
| 261 |
+
def forward(
|
| 262 |
+
self,
|
| 263 |
+
hidden_states: torch.Tensor,
|
| 264 |
+
cu_seqlens: torch.Tensor,
|
| 265 |
+
rotary_pos_emb: torch.Tensor = None,
|
| 266 |
+
) -> torch.Tensor:
|
| 267 |
+
seq_length = hidden_states.shape[0]
|
| 268 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 269 |
+
|
| 270 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 271 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 272 |
+
|
| 273 |
+
attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
|
| 274 |
+
for i in range(1, len(cu_seqlens)):
|
| 275 |
+
attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = True
|
| 276 |
+
|
| 277 |
+
q = q.transpose(0, 1).unsqueeze(0)
|
| 278 |
+
k = k.transpose(0, 1).unsqueeze(0)
|
| 279 |
+
v = v.transpose(0, 1).unsqueeze(0)
|
| 280 |
+
|
| 281 |
+
if attention_mask.stride(-1) != 1:
|
| 282 |
+
attention_mask = torch.empty_like(attention_mask, memory_format=torch.contiguous_format).copy_(attention_mask)
|
| 283 |
+
|
| 284 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 285 |
+
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
|
| 286 |
+
attn_output = F.scaled_dot_product_attention(q, k, v, attention_mask, dropout_p=0.0)
|
| 287 |
+
|
| 288 |
+
attn_output = attn_output.squeeze(0).transpose(0, 1)
|
| 289 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
| 290 |
+
|
| 291 |
+
attn_output = self.proj(attn_output)
|
| 292 |
+
return attn_output
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
VISION_ATTENTION_CLASSES = {
|
| 296 |
+
"eager": VisionAttention,
|
| 297 |
+
"eager_v2": VisionAttentionV2,
|
| 298 |
+
"flash_attention_2": VisionFlashAttention2,
|
| 299 |
+
"sdpa": VisionSdpaAttention,
|
| 300 |
+
"ascend_fa": VisionAscendAttention,
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class RMSNorm(nn.Module):
|
| 305 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 306 |
+
super().__init__()
|
| 307 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 308 |
+
self.eps = eps
|
| 309 |
+
|
| 310 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 311 |
+
output = self._norm(x.float()).type_as(x)
|
| 312 |
+
return output * self.weight
|
| 313 |
+
|
| 314 |
+
def extra_repr(self) -> str:
|
| 315 |
+
return f"{tuple(self.weight.shape)}, eps={self.eps}"
|
| 316 |
+
|
| 317 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
| 318 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class SwiGLUFFN(nn.Module):
|
| 322 |
+
def __init__(self, config):
|
| 323 |
+
super().__init__()
|
| 324 |
+
hidden_features = config.intermediate_size
|
| 325 |
+
in_features = config.embed_dim
|
| 326 |
+
bias = config.use_bias
|
| 327 |
+
|
| 328 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
|
| 329 |
+
self.fc2 = nn.Linear(hidden_features, in_features, bias=bias)
|
| 330 |
+
self.fc3 = nn.Linear(in_features, hidden_features, bias=bias)
|
| 331 |
+
|
| 332 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 333 |
+
x = F.silu(self.fc1(x)) * self.fc3(x)
|
| 334 |
+
x = self.fc2(x)
|
| 335 |
+
return x
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class PatchEmbed(nn.Module):
|
| 339 |
+
def __init__(self, config):
|
| 340 |
+
super().__init__()
|
| 341 |
+
self.num_channels = config.num_channels
|
| 342 |
+
self.patch_size = config.patch_size
|
| 343 |
+
self.temporal_patch_size = config.temporal_patch_size
|
| 344 |
+
self.embed_dim = config.embed_dim
|
| 345 |
+
self.config = config
|
| 346 |
+
self.proj = nn.Conv2d(
|
| 347 |
+
config.num_channels,
|
| 348 |
+
config.embed_dim,
|
| 349 |
+
kernel_size=(config.patch_size, config.patch_size),
|
| 350 |
+
stride=(config.patch_size, config.patch_size),
|
| 351 |
+
)
|
| 352 |
+
self.norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
|
| 353 |
+
|
| 354 |
+
def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor:
|
| 355 |
+
x = x.view(-1, self.num_channels, self.temporal_patch_size, self.patch_size, self.patch_size)[:, :, 0]
|
| 356 |
+
x = self.proj(x).view(-1, self.embed_dim)
|
| 357 |
+
x = self.norm(x)
|
| 358 |
+
return x
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class ViTPreprocessor(nn.Module):
|
| 362 |
+
def __init__(self, config):
|
| 363 |
+
super().__init__()
|
| 364 |
+
self.patch_h = config.patch_size
|
| 365 |
+
self.patch_w = config.patch_size
|
| 366 |
+
self.embed_dim = config.embed_dim
|
| 367 |
+
self.config = config
|
| 368 |
+
self.patchifier = PatchEmbed(config)
|
| 369 |
+
|
| 370 |
+
def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor:
|
| 371 |
+
tokens = self.patchifier(x, grid_thw)
|
| 372 |
+
return tokens
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class VisionBlock(nn.Module):
|
| 376 |
+
def __init__(self, config, attn_implementation: str = "flash_attention_2"):
|
| 377 |
+
super().__init__()
|
| 378 |
+
|
| 379 |
+
if attn_implementation == "flash_attention_2" and not flash_attn_available:
|
| 380 |
+
if npu_available:
|
| 381 |
+
attn_implementation = "ascend_fa"
|
| 382 |
+
print("flash attention not available! fallback to ascend flash attention implementation ")
|
| 383 |
+
else:
|
| 384 |
+
# fallback to eager
|
| 385 |
+
attn_implementation = "sdpa"
|
| 386 |
+
print("flash attention not available! fallback to sdpa implementation ")
|
| 387 |
+
|
| 388 |
+
if attn_implementation == "ascend_fa" and not npu_available:
|
| 389 |
+
attn_implementation = "sdpa"
|
| 390 |
+
print("flash attention not available! fallback to sdpa implementation ")
|
| 391 |
+
|
| 392 |
+
self.attn = VISION_ATTENTION_CLASSES[attn_implementation](
|
| 393 |
+
config, config.embed_dim, num_heads=config.num_attention_heads, bias=config.use_bias
|
| 394 |
+
)
|
| 395 |
+
self.norm1 = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
|
| 396 |
+
self.mlp = SwiGLUFFN(config)
|
| 397 |
+
self.norm2 = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
|
| 398 |
+
|
| 399 |
+
def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> torch.Tensor:
|
| 400 |
+
hidden_states = hidden_states + self.attn(
|
| 401 |
+
self.norm1(hidden_states), cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb
|
| 402 |
+
)
|
| 403 |
+
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
|
| 404 |
+
return hidden_states
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class MonkeyOCRv2VisionTransformer(PreTrainedModel):
|
| 408 |
+
config_class = MonkeyOCRv2VisionConfig
|
| 409 |
+
_supports_flash_attn = True
|
| 410 |
+
_supports_sdpa = True
|
| 411 |
+
_no_split_modules = ["VisionBlock"]
|
| 412 |
+
def __init__(self, config: MonkeyOCRv2VisionConfig) -> None:
|
| 413 |
+
super().__init__(config)
|
| 414 |
+
|
| 415 |
+
self.config = config
|
| 416 |
+
self.spatial_merge_size = config.spatial_merge_size
|
| 417 |
+
|
| 418 |
+
self.patch_embed = ViTPreprocessor(config)
|
| 419 |
+
self._init_weights(self.patch_embed.patchifier.proj)
|
| 420 |
+
|
| 421 |
+
head_dim = config.embed_dim // config.num_attention_heads
|
| 422 |
+
|
| 423 |
+
self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
|
| 424 |
+
|
| 425 |
+
_num_hidden_layers = config.num_hidden_layers
|
| 426 |
+
|
| 427 |
+
self.blocks = nn.ModuleList(
|
| 428 |
+
[VisionBlock(config, config.vision_attn_implementation) for _ in range(_num_hidden_layers)]
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
if self.config.post_norm:
|
| 432 |
+
self.post_trunk_norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
self.gradient_checkpointing = False
|
| 436 |
+
self._gradient_checkpointing_func = torch.utils.checkpoint.checkpoint
|
| 437 |
+
|
| 438 |
+
def _init_weights(self, module):
|
| 439 |
+
std = self.config.initializer_range
|
| 440 |
+
if isinstance(module, (nn.Linear, nn.Conv3d)):
|
| 441 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 442 |
+
if module.bias is not None:
|
| 443 |
+
module.bias.data.zero_()
|
| 444 |
+
elif isinstance(module, nn.Embedding):
|
| 445 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 446 |
+
if module.padding_idx is not None:
|
| 447 |
+
module.weight.data[module.padding_idx].zero_()
|
| 448 |
+
|
| 449 |
+
@property
|
| 450 |
+
def dtype(self) -> torch.dtype:
|
| 451 |
+
return self.blocks[0].mlp.fc2.weight.dtype
|
| 452 |
+
|
| 453 |
+
@property
|
| 454 |
+
def device(self) -> torch.device:
|
| 455 |
+
return self.blocks[0].mlp.fc2.weight.device
|
| 456 |
+
|
| 457 |
+
def get_pos_ids_by_grid(self, grid_thw):
|
| 458 |
+
pos_ids = []
|
| 459 |
+
for t, h, w in grid_thw:
|
| 460 |
+
hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
|
| 461 |
+
hpos_ids = hpos_ids.reshape(
|
| 462 |
+
h // self.spatial_merge_size,
|
| 463 |
+
self.spatial_merge_size,
|
| 464 |
+
w // self.spatial_merge_size,
|
| 465 |
+
self.spatial_merge_size,
|
| 466 |
+
)
|
| 467 |
+
hpos_ids = hpos_ids.permute(0, 2, 1, 3)
|
| 468 |
+
hpos_ids = hpos_ids.flatten()
|
| 469 |
+
|
| 470 |
+
wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
|
| 471 |
+
wpos_ids = wpos_ids.reshape(
|
| 472 |
+
h // self.spatial_merge_size,
|
| 473 |
+
self.spatial_merge_size,
|
| 474 |
+
w // self.spatial_merge_size,
|
| 475 |
+
self.spatial_merge_size,
|
| 476 |
+
)
|
| 477 |
+
wpos_ids = wpos_ids.permute(0, 2, 1, 3)
|
| 478 |
+
wpos_ids = wpos_ids.flatten()
|
| 479 |
+
|
| 480 |
+
pos_ids.append(
|
| 481 |
+
torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
return pos_ids
|
| 486 |
+
|
| 487 |
+
def rot_pos_emb(self, grid_thw):
|
| 488 |
+
pos_ids = self.get_pos_ids_by_grid(grid_thw)
|
| 489 |
+
pos_ids = torch.cat(pos_ids, dim=0)
|
| 490 |
+
max_grid_size = grid_thw[:, 1:].max()
|
| 491 |
+
rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
|
| 492 |
+
|
| 493 |
+
emb = rotary_pos_emb_full[pos_ids]
|
| 494 |
+
rotary_pos_emb = torch.stack([emb[:,0], emb[:,1]], dim=2).reshape(emb.shape[0], -1)
|
| 495 |
+
return rotary_pos_emb
|
| 496 |
+
|
| 497 |
+
def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, bf16=True) -> torch.Tensor:
|
| 498 |
+
|
| 499 |
+
if bf16:
|
| 500 |
+
hidden_states = hidden_states.bfloat16()
|
| 501 |
+
hidden_states = self.patch_embed(hidden_states, grid_thw)
|
| 502 |
+
|
| 503 |
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
| 504 |
+
|
| 505 |
+
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
|
| 506 |
+
dim=0,
|
| 507 |
+
dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
|
| 508 |
+
)
|
| 509 |
+
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
|
| 510 |
+
|
| 511 |
+
for blk in self.blocks:
|
| 512 |
+
if self.gradient_checkpointing and self.training:
|
| 513 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 514 |
+
blk.__call__,
|
| 515 |
+
hidden_states,
|
| 516 |
+
cu_seqlens,
|
| 517 |
+
rotary_pos_emb,
|
| 518 |
+
)
|
| 519 |
+
else:
|
| 520 |
+
hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb)
|
| 521 |
+
|
| 522 |
+
if self.config.post_norm:
|
| 523 |
+
hidden_states = self.post_trunk_norm(hidden_states)
|
| 524 |
+
|
| 525 |
+
return hidden_states
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoProcessor": "configuration_monkeyocrv2vit.MonkeyOCRv2Processor"
|
| 4 |
+
},
|
| 5 |
+
"min_pixels": 3136,
|
| 6 |
+
"max_pixels": 11289600,
|
| 7 |
+
"patch_size": 14,
|
| 8 |
+
"temporal_patch_size": 1,
|
| 9 |
+
"merge_size": 2,
|
| 10 |
+
"image_mean": [
|
| 11 |
+
0.48145466,
|
| 12 |
+
0.4578275,
|
| 13 |
+
0.40821073
|
| 14 |
+
],
|
| 15 |
+
"image_std": [
|
| 16 |
+
0.26862954,
|
| 17 |
+
0.26130258,
|
| 18 |
+
0.27577711
|
| 19 |
+
],
|
| 20 |
+
"image_processor_type": "Qwen2VLImageProcessor",
|
| 21 |
+
"processor_class": "MonkeyOCRv2Processor"
|
| 22 |
+
}
|
processor_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoProcessor": "configuration_monkeyocrv2vit.MonkeyOCRv2Processor"
|
| 4 |
+
},
|
| 5 |
+
"processor_class": "MonkeyOCRv2Processor"
|
| 6 |
+
}
|