xiangan commited on
Commit
c2b8f87
·
verified ·
1 Parent(s): 85b5620

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+
5
+
6
+ ### ⚡ Quick Start
7
+
8
+ > **Note:** This model supports native resolution input. For optimal performance:
9
+ > - **Image**: 448×448 resolution (pre-trained)
10
+ > - **Video**: 224×224 resolution with 256 tokens per frame (pre-trained)
11
+ >
12
+ > Use CLIP preprocessing from the [model repository](https://huggingface.co/lmms-lab/onevision-encoder-large).
13
+
14
+ ```python
15
+ from transformers import AutoModel, AutoImageProcessor
16
+ from PIL import Image
17
+ import torch
18
+
19
+ # Load model and preprocessor
20
+ model = AutoModel.from_pretrained(
21
+ "lmms-lab-encoder/onevision-encoder-large",
22
+ trust_remote_code=True,
23
+ attn_implementation="flash_attention_2"
24
+ ).to("cuda").eval()
25
+
26
+ preprocessor = AutoImageProcessor.from_pretrained(
27
+ "lmms-lab-encoder/onevision-encoder-large",
28
+ trust_remote_code=True
29
+ )
30
+
31
+ # Image inference: [B, C, H, W]
32
+ image = Image.open("path/to/your/image.jpg") # Replace with your image path
33
+ pixel_values = preprocessor(images=image, return_tensors="pt")["pixel_values"].to("cuda")
34
+ with torch.no_grad():
35
+ outputs = model(pixel_values)
36
+ # outputs.last_hidden_state: [B, num_patches, hidden_size]
37
+ # outputs.pooler_output: [B, hidden_size]
38
+
39
+ # Video inference: [B, C, T, H, W] with visible_indices
40
+ num_frames, frame_tokens, target_frames = 16, 256, 64
41
+ # Load video frames and preprocess each frame (replace with your video frame paths)
42
+ frames = [Image.open(f"path/to/frame_{i}.jpg") for i in range(num_frames)]
43
+ video_pixel_values = preprocessor(images=frames, return_tensors="pt")["pixel_values"]
44
+ # Reshape from [T, C, H, W] to [B, C, T, H, W]
45
+ video = video_pixel_values.unsqueeze(0).permute(0, 2, 1, 3, 4).to("cuda")
46
+
47
+ # Build visible_indices for temporal sampling
48
+ frame_pos = torch.linspace(0, target_frames - 1, num_frames).long().cuda()
49
+ visible_indices = (frame_pos.unsqueeze(-1) * frame_tokens + torch.arange(frame_tokens).cuda()).reshape(1, -1)
50
+ # visible_indices example (with 256 tokens per frame):
51
+ # Frame 0 (pos=0): indices [0, 1, 2, ..., 255]
52
+ # Frame 1 (pos=4): indices [1024, 1025, 1026, ..., 1279]
53
+ # Frame 2 (pos=8): indices [2048, 2049, 2050, ..., 2303]
54
+ # ...
55
+ # Frame 15 (pos=63): indices [16128, 16129, ..., 16383]
56
+
57
+ with torch.no_grad():
58
+ outputs = model(video, visible_indices=visible_indices)
59
+ ```
60
+
61
+
62
+ ### LMM Probe Results
63
+
64
+ Training on a mixed dataset of 740K samples from LLaVA-OneVision and 800K samples from LLaVA-Video SFT. The training pipeline proceeds directly to Stage 2 fine-tuning. We adopt a streamlined native-resolution strategy inspired by LLaVA-OneVision: when the input frame resolution matches the model's native input size, it is fed directly—without tiling or cropping—to evaluate the ViT's native resolution capability.
65
+
66
+ <p align="center">
67
+ <picture>
68
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/anxiangsir/asset/main/OneVision/probe_lmm_github_dark_fixed.png">
69
+ <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/anxiangsir/asset/main/OneVision/probe_lmm_github_light.png">
70
+ <img alt="LMM Probe Results" src="https://raw.githubusercontent.com/anxiangsir/asset/main/OneVision/probe_lmm_github_light.png" width="800" style="max-width: 100%;">
71
+ </picture>
72
+ </p>
73
+
74
+ ### Attentive Probe Results
75
+
76
+ Performance comparison of different vision encoders using Attentive Probe evaluation. Models are evaluated using single clip input and trained for 10 epochs across 8 action recognition datasets. Results show average performance and per-dataset scores for 8-frame and 16-frame configurations.
77
+
78
+ <p align="center">
79
+ <picture>
80
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/anxiangsir/asset/main/OneVision/fix_00_probe_video_github_dark.png">
81
+ <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/anxiangsir/asset/main/OneVision/fix_00_probe_video_github_light.png">
82
+ <img alt="LMM Probe Results" src="https://raw.githubusercontent.com/anxiangsir/asset/main/OneVision/probe_lmm_github_light.png" width="900" style="max-width: 100%;">
83
+ </picture>
84
+ </p>
85
+
86
+
87
+ ### Codec Input
88
+
89
+ > **TODO:** Add codec-style input documentation for temporal saliency-based patch selection.
90
+
91
+ ---
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "OneVisionEncoderModel"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "dtype": "bfloat16",
7
+ "hidden_act": "gelu",
8
+ "hidden_size": 1024,
9
+ "image_size": 448,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 4096,
12
+ "layer_norm_eps": 1e-06,
13
+ "layer_norm_type": "layer_norm",
14
+ "model_type": "onevision_encoder",
15
+ "num_attention_heads": 16,
16
+ "num_channels": 3,
17
+ "num_hidden_layers": 24,
18
+ "patch_size": 14,
19
+ "rope_theta": 10000.0,
20
+ "rope_temporal_size": 64,
21
+ "transformers_version": "4.57.1",
22
+ "use_head": true,
23
+ "auto_map": {
24
+ "AutoConfig": "configuration_onevision_encoder.OneVisionEncoderConfig",
25
+ "AutoModel": "modeling_onevision_encoder.OneVisionEncoderModel"
26
+ }
27
+ }
configuration_onevision_encoder.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+
7
+ class OneVisionEncoderConfig(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`OneVisionEncoderModel`]. It is used to instantiate a
10
+ OneVision Encoder model according to the specified arguments, defining the model architecture. Instantiating a configuration
11
+ with the defaults will yield a similar configuration to that of the OneVision Encoder architecture.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+ Args:
17
+ hidden_size (`int`, *optional*, defaults to 1024):
18
+ Dimensionality of the encoder layers and the pooler layer.
19
+ intermediate_size (`int`, *optional*, defaults to 4096):
20
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
21
+ num_hidden_layers (`int`, *optional*, defaults to 24):
22
+ Number of hidden layers in the Transformer encoder.
23
+ num_attention_heads (`int`, *optional*, defaults to 16):
24
+ Number of attention heads for each attention layer in the Transformer encoder.
25
+ num_channels (`int`, *optional*, defaults to 3):
26
+ The number of input channels.
27
+ image_size (`int`, *optional*, defaults to 224):
28
+ The size (resolution) of each image.
29
+ patch_size (`int`, *optional*, defaults to 16):
30
+ The size (resolution) of each patch.
31
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
32
+ The non-linear activation function (function or string) in the encoder and pooler.
33
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
34
+ The epsilon used by the layer normalization layers.
35
+ layer_norm_type (`str`, *optional*, defaults to `"layer_norm"`):
36
+ The type of layer normalization to use. Supported values: `"layer_norm"`, `"rms_norm"`.
37
+ attention_dropout (`float`, *optional*, defaults to 0.0):
38
+ The dropout ratio for the attention probabilities.
39
+ initializer_range (`float`, *optional*, defaults to 0.02):
40
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
41
+ rope_theta (`float`, *optional*, defaults to 10000.0):
42
+ The base period of the RoPE embeddings.
43
+ use_head (`bool`, *optional*, defaults to `True`):
44
+ Whether to use the pooling head.
45
+
46
+ Example:
47
+
48
+ ```python
49
+ >>> from configuration_onevision_encoder import OneVisionEncoderConfig
50
+ >>> from modeling_onevision_encoder import OneVisionEncoderModel
51
+
52
+ >>> # Initializing a OneVisionEncoder configuration
53
+ >>> configuration = OneVisionEncoderConfig()
54
+
55
+ >>> # Initializing a model (with random weights) from the configuration
56
+ >>> model = OneVisionEncoderModel(configuration)
57
+
58
+ >>> # Accessing the model configuration
59
+ >>> configuration = model.config
60
+ ```
61
+ """
62
+
63
+ model_type = "onevision_encoder"
64
+
65
+ def __init__(
66
+ self,
67
+ hidden_size=1024,
68
+ intermediate_size=4096,
69
+ num_hidden_layers=24,
70
+ num_attention_heads=16,
71
+ num_channels=3,
72
+ image_size=448,
73
+ patch_size=16,
74
+ hidden_act="gelu",
75
+ layer_norm_eps=1e-6,
76
+ layer_norm_type="layer_norm",
77
+ attention_dropout=0.0,
78
+ initializer_range=0.02,
79
+ rope_theta=10000.0,
80
+ rope_temporal_size=64,
81
+ use_head=True,
82
+ **kwargs,
83
+ ):
84
+ super().__init__(**kwargs)
85
+ self.hidden_size = hidden_size
86
+ self.intermediate_size = intermediate_size
87
+ self.num_hidden_layers = num_hidden_layers
88
+ self.num_attention_heads = num_attention_heads
89
+ self.num_channels = num_channels
90
+ self.image_size = image_size
91
+ self.patch_size = patch_size
92
+ self.hidden_act = hidden_act
93
+ self.layer_norm_eps = layer_norm_eps
94
+ self.layer_norm_type = layer_norm_type
95
+ self.attention_dropout = attention_dropout
96
+ self.initializer_range = initializer_range
97
+ self.rope_theta = rope_theta
98
+ self.rope_temporal_size = rope_temporal_size # None=use actual frames, int=fixed size (legacy: 64)
99
+ self.use_head = use_head
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ac558e40e4f8569dd126763141f3edd747f63f076dcffb217844ef8589274a6
3
+ size 631063168
modeling_onevision_encoder.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers.modeling_outputs import (BaseModelOutput,
6
+ BaseModelOutputWithPooling)
7
+ from transformers.modeling_utils import PreTrainedModel
8
+ from transformers.models.siglip.modeling_siglip import SiglipMLP
9
+ from transformers.utils import (add_start_docstrings,
10
+ add_start_docstrings_to_model_forward, logging,
11
+ replace_return_docstrings)
12
+
13
+ from .configuration_onevision_encoder import OneVisionEncoderConfig
14
+
15
+ try:
16
+ from flash_attn import flash_attn_func
17
+ _flash_attn_available = True
18
+ except ImportError:
19
+ _flash_attn_available = False
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Model Docstrings
26
+ # ---------------------------------------------------------------------------
27
+
28
+ ONEVISION_ENCODER_START_DOCSTRING = r"""
29
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
30
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
31
+ etc.)
32
+
33
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
34
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
35
+ and behavior.
36
+
37
+ Parameters:
38
+ config ([`OneVisionEncoderConfig`]): Model configuration class with all the parameters of the model.
39
+ Initializing with a config file does not load the weights associated with the model, only the
40
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
41
+ """
42
+
43
+ ONEVISION_ENCODER_INPUTS_DOCSTRING = r"""
44
+ Args:
45
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch_size, num_channels, num_frames, height, width)`):
46
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`].
47
+ visible_indices (`torch.Tensor`, *optional*):
48
+ Indices of visible patches for masking. Used in MAE-style pretraining or inference.
49
+ output_attentions (`bool`, *optional*):
50
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
51
+ tensors for more detail.
52
+ output_hidden_states (`bool`, *optional*):
53
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
54
+ more detail.
55
+ return_dict (`bool`, *optional*):
56
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
57
+ """
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Helper Functions & Layers
62
+ # ---------------------------------------------------------------------------
63
+
64
+ def get_norm_layer(config):
65
+ if config.layer_norm_type == "rms_norm":
66
+ return nn.RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
67
+ else:
68
+ return nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
69
+
70
+
71
+ def rotate_half(x):
72
+ """
73
+ Interleaved rotation to match Source model's implementation.
74
+ (x1, x2, x3, x4) -> (-x2, x1, -x4, x3)
75
+ """
76
+ x_even = x[..., ::2]
77
+ x_odd = x[..., 1::2]
78
+ return torch.stack((-x_odd, x_even), dim=-1).flatten(-2)
79
+
80
+
81
+ def apply_rotary_pos_emb(q, k, freqs):
82
+ # q, k: (B, H, L, D)
83
+ # freqs: (B, L, D)
84
+
85
+ # We need to broadcast freqs to match heads
86
+ # (B, L, D) -> (B, 1, L, D)
87
+
88
+ # !!! CRITICAL FIX: Cast cos/sin to q.dtype (bf16/fp16) immediately
89
+ # freqs are typically float32, so cos() returns float32.
90
+ # Without this cast, (q * cos) upcasts q to float32, causing FlashAttention to fail.
91
+ cos = freqs.cos().unsqueeze(1).to(q.dtype)
92
+ sin = freqs.sin().unsqueeze(1).to(q.dtype)
93
+
94
+ q_embed = (q * cos) + (rotate_half(q) * sin)
95
+ k_embed = (k * cos) + (rotate_half(k) * sin)
96
+ return q_embed, k_embed
97
+
98
+
99
+ class VideoRotaryEmbeddingSplit466(nn.Module):
100
+ """
101
+ 3D (T,H,W) Rotary frequency constructor with 4:6:6 split.
102
+ """
103
+ def __init__(self, config: OneVisionEncoderConfig):
104
+ super().__init__()
105
+ head_dim = config.hidden_size // config.num_attention_heads
106
+ base = config.rope_theta
107
+
108
+ assert head_dim % 2 == 0, "head_dim must be even for rotary."
109
+ assert head_dim % 16 == 0, "head_dim must be divisible by 16."
110
+ half = head_dim // 2
111
+ assert half % 16 == 0, "head_dim//2 must also be divisible by 16 to split into 4:6:6."
112
+
113
+ self.head_dim = head_dim
114
+ self.half = half
115
+
116
+ unit = half // 16
117
+ self.t_size = 4 * unit
118
+ self.h_size = 6 * unit
119
+ self.w_size = 6 * unit
120
+
121
+ self.register_buffer("inv_freq_t", 1.0 / (base ** (torch.arange(self.t_size, dtype=torch.float32) / self.t_size)), persistent=False)
122
+ self.register_buffer("inv_freq_h", 1.0 / (base ** (torch.arange(self.h_size, dtype=torch.float32) / self.h_size)), persistent=False)
123
+ self.register_buffer("inv_freq_w", 1.0 / (base ** (torch.arange(self.w_size, dtype=torch.float32) / self.w_size)), persistent=False)
124
+
125
+ def forward(self, t: int, h: int, w: int, device=None):
126
+ if device is None: device = self.inv_freq_t.device
127
+
128
+ inv_t = self.inv_freq_t.to(device=device)
129
+ inv_h = self.inv_freq_h.to(device=device)
130
+ inv_w = self.inv_freq_w.to(device=device)
131
+
132
+ ft = torch.outer(torch.arange(t, device=device, dtype=torch.float32), inv_t)
133
+ fh = torch.outer(torch.arange(h, device=device, dtype=torch.float32), inv_h)
134
+ fw = torch.outer(torch.arange(w, device=device, dtype=torch.float32), inv_w)
135
+
136
+ t_ids = torch.arange(t, device=device).repeat_interleave(h * w)
137
+ h_ids = torch.arange(h, device=device).repeat_interleave(w).repeat(t)
138
+ w_ids = torch.arange(w, device=device).repeat(h).repeat(t)
139
+
140
+ freqs = torch.cat([ft[t_ids], fh[h_ids], fw[w_ids]], dim=-1)
141
+ return freqs
142
+
143
+
144
+ class Siglip2MultiheadAttentionPoolingHead(nn.Module):
145
+ """
146
+ Multi-Head Attention Pooling with a learned probe (PMA-style).
147
+ """
148
+ def __init__(self, config: OneVisionEncoderConfig):
149
+ super().__init__()
150
+ self.embed_dim = config.hidden_size
151
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
152
+ self.attention = nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
153
+ self.norm = nn.RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
154
+ self.mlp = SiglipMLP(config)
155
+
156
+ def forward(self, hidden_states):
157
+ batch_size = hidden_states.shape[0]
158
+ probe = self.probe.repeat(batch_size, 1, 1)
159
+
160
+ attn_output, _ = self.attention(probe, hidden_states, hidden_states)
161
+
162
+ residual = attn_output
163
+ attn_output = self.norm(attn_output)
164
+ attn_output = residual + self.mlp(attn_output)
165
+
166
+ return attn_output[:, 0]
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # Modeling Components
171
+ # ---------------------------------------------------------------------------
172
+
173
+ class OneVisionEncoderEmbeddings(nn.Module):
174
+ def __init__(self, config: OneVisionEncoderConfig):
175
+ super().__init__()
176
+ self.config = config
177
+ self.embed_dim = config.hidden_size
178
+ self.image_size = config.image_size
179
+ self.patch_size = config.patch_size
180
+
181
+ self.patch_embedding = nn.Conv2d(
182
+ in_channels=config.num_channels,
183
+ out_channels=self.embed_dim,
184
+ kernel_size=self.patch_size,
185
+ stride=self.patch_size,
186
+ bias=False,
187
+ )
188
+
189
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
190
+ # Handle 4D (B, C, H, W) or 5D (B, C, T, H, W) inputs
191
+ if pixel_values.dim() == 4:
192
+ pixel_values = pixel_values.unsqueeze(2) # (B, C, 1, H, W)
193
+
194
+ batch_size, channels, t_frames, height, width = pixel_values.shape
195
+
196
+ # Merge time into batch for Conv2d
197
+ x_2d = pixel_values.permute(0, 2, 1, 3, 4).reshape(batch_size * t_frames, channels, height, width)
198
+
199
+ # Patch Embed
200
+ embeddings = self.patch_embedding(x_2d) # (B*T, C, Hp, Wp)
201
+ embeddings = embeddings.flatten(2).transpose(1, 2) # (B*T, L_frame, C)
202
+
203
+ # Flatten all patches
204
+ total_patches = t_frames * (height // self.patch_size) * (width // self.patch_size)
205
+ embeddings = embeddings.reshape(batch_size, total_patches, self.embed_dim)
206
+
207
+ return embeddings
208
+
209
+
210
+ class OneVisionEncoderAttention(nn.Module):
211
+ """Multi-headed attention with RoPE support"""
212
+ def __init__(self, config: OneVisionEncoderConfig):
213
+ super().__init__()
214
+ self.config = config
215
+ self.embed_dim = config.hidden_size
216
+ self.num_heads = config.num_attention_heads
217
+ self.head_dim = self.embed_dim // self.num_heads
218
+ if self.head_dim * self.num_heads != self.embed_dim:
219
+ raise ValueError(
220
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
221
+ )
222
+
223
+ self.scale = self.head_dim**-0.5
224
+ self.dropout = config.attention_dropout
225
+
226
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
227
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
228
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
229
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
230
+
231
+
232
+ def forward(
233
+ self,
234
+ hidden_states: torch.Tensor,
235
+ attention_mask: Optional[torch.Tensor] = None,
236
+ rotary_pos_emb: Optional[torch.Tensor] = None,
237
+ output_attentions: bool = False,
238
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
239
+
240
+ batch_size, q_len, _ = hidden_states.size()
241
+
242
+ query_states = self.q_proj(hidden_states)
243
+ key_states = self.k_proj(hidden_states)
244
+ value_states = self.v_proj(hidden_states)
245
+
246
+ # (B, L, H, D) -> Transpose to (B, H, L, D)
247
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
248
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
249
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
250
+
251
+ if rotary_pos_emb is not None:
252
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, rotary_pos_emb)
253
+
254
+ # Calculate attention scores
255
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
256
+
257
+ if attention_mask is not None:
258
+ if attention_mask.size() != (batch_size, 1, q_len, q_len):
259
+ if attention_mask.dim() == 3:
260
+ attention_mask = attention_mask.unsqueeze(1)
261
+ attn_weights = attn_weights + attention_mask
262
+
263
+ # FIX: Remove dtype=torch.float32 to stay in original dtype (bf16/fp16)
264
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
265
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
266
+
267
+ attn_output = torch.matmul(attn_weights, value_states)
268
+
269
+ attn_output = attn_output.transpose(1, 2).contiguous()
270
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
271
+
272
+ attn_output = self.out_proj(attn_output)
273
+
274
+ return attn_output, attn_weights if output_attentions else None
275
+
276
+
277
+ class OneVisionEncoderFlashAttention2(nn.Module):
278
+ """
279
+ Multi-headed attention with RoPE support using Flash Attention 2.
280
+ This module implements the same attention mechanism as OneVisionEncoderAttention but uses
281
+ Flash Attention for improved performance and memory efficiency.
282
+ """
283
+ def __init__(self, config: OneVisionEncoderConfig):
284
+ super().__init__()
285
+ self.config = config
286
+ self.embed_dim = config.hidden_size
287
+ self.num_heads = config.num_attention_heads
288
+ self.head_dim = self.embed_dim // self.num_heads
289
+ if self.head_dim * self.num_heads != self.embed_dim:
290
+ raise ValueError(
291
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
292
+ )
293
+
294
+ self.scale = self.head_dim**-0.5
295
+ self.dropout = config.attention_dropout
296
+
297
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
298
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
299
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
300
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
301
+
302
+ def forward(
303
+ self,
304
+ hidden_states: torch.Tensor,
305
+ attention_mask: Optional[torch.Tensor] = None,
306
+ rotary_pos_emb: Optional[torch.Tensor] = None,
307
+ output_attentions: bool = False,
308
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
309
+ """
310
+ Forward pass using Flash Attention 2.
311
+ """
312
+ batch_size, q_len, _ = hidden_states.size()
313
+
314
+ query_states = self.q_proj(hidden_states)
315
+ key_states = self.k_proj(hidden_states)
316
+ value_states = self.v_proj(hidden_states)
317
+
318
+ # Flash Attention requires (B, L, H, D) format
319
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim)
320
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim)
321
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim)
322
+
323
+ # Apply RoPE if provided
324
+ if rotary_pos_emb is not None:
325
+ # Transpose for RoPE application: (B, L, H, D) -> (B, H, L, D)
326
+ query_states = query_states.transpose(1, 2)
327
+ key_states = key_states.transpose(1, 2)
328
+ # NOTE: apply_rotary_pos_emb now ensures NO float32 cast happens
329
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, rotary_pos_emb)
330
+ # Transpose back: (B, H, L, D) -> (B, L, H, D)
331
+ query_states = query_states.transpose(1, 2)
332
+ key_states = key_states.transpose(1, 2)
333
+
334
+ # Flash Attention forward pass
335
+ if not _flash_attn_available:
336
+ raise ImportError("flash_attn is not installed. Please install it to use OneVisionEncoderFlashAttention2.")
337
+
338
+ attn_output = flash_attn_func(
339
+ query_states,
340
+ key_states,
341
+ value_states,
342
+ dropout_p=self.dropout if self.training else 0.0,
343
+ softmax_scale=self.scale,
344
+ causal=False,
345
+ )
346
+
347
+ # Reshape to (B, L, embed_dim)
348
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
349
+
350
+ # No extra casting here.
351
+ attn_output = self.out_proj(attn_output)
352
+
353
+ return attn_output, None
354
+
355
+
356
+ ONEVISION_ENCODER_ATTENTION_CLASSES = {
357
+ "eager": OneVisionEncoderAttention,
358
+ "flash_attention_2": OneVisionEncoderFlashAttention2,
359
+ }
360
+
361
+
362
+ class OneVisionEncoderEncoderLayer(nn.Module):
363
+ def __init__(self, config: OneVisionEncoderConfig):
364
+ super().__init__()
365
+ self.embed_dim = config.hidden_size
366
+ # Get attention implementation from config, default to "flash_attention_2"
367
+ attn_implementation = getattr(config, "_attn_implementation", "flash_attention_2")
368
+ if attn_implementation not in ONEVISION_ENCODER_ATTENTION_CLASSES:
369
+ # Fallback to eager if flash_attention_2 is not available
370
+ if not _flash_attn_available and attn_implementation == "flash_attention_2":
371
+ attn_implementation = "eager"
372
+ else:
373
+ raise ValueError(
374
+ f"Unknown attention implementation: {attn_implementation}. "
375
+ f"Available implementations: {list(ONEVISION_ENCODER_ATTENTION_CLASSES.keys())}"
376
+ )
377
+ self.self_attn = ONEVISION_ENCODER_ATTENTION_CLASSES[attn_implementation](config)
378
+ self.layer_norm1 = get_norm_layer(config)
379
+ self.mlp = SiglipMLP(config)
380
+ self.layer_norm2 = get_norm_layer(config)
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states: torch.Tensor,
385
+ attention_mask: Optional[torch.Tensor] = None,
386
+ rotary_pos_emb: Optional[torch.Tensor] = None,
387
+ output_attentions: bool = False,
388
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
389
+
390
+ residual = hidden_states
391
+ hidden_states = self.layer_norm1(hidden_states)
392
+
393
+ hidden_states, attn_weights = self.self_attn(
394
+ hidden_states=hidden_states,
395
+ attention_mask=attention_mask,
396
+ rotary_pos_emb=rotary_pos_emb,
397
+ output_attentions=output_attentions,
398
+ )
399
+ hidden_states = residual + hidden_states
400
+
401
+ residual = hidden_states
402
+ hidden_states = self.layer_norm2(hidden_states)
403
+ hidden_states = self.mlp(hidden_states)
404
+ hidden_states = residual + hidden_states
405
+
406
+ outputs = (hidden_states, attn_weights) if output_attentions else (hidden_states,)
407
+ return outputs
408
+
409
+
410
+ class OneVisionEncoderEncoder(nn.Module):
411
+ def __init__(self, config: OneVisionEncoderConfig):
412
+ super().__init__()
413
+ self.config = config
414
+ self.layers = nn.ModuleList([OneVisionEncoderEncoderLayer(config) for _ in range(config.num_hidden_layers)])
415
+
416
+ def forward(
417
+ self,
418
+ hidden_states: torch.Tensor,
419
+ attention_mask: Optional[torch.Tensor] = None,
420
+ rotary_pos_emb: Optional[torch.Tensor] = None,
421
+ output_attentions: bool = False,
422
+ output_hidden_states: bool = False,
423
+ return_dict: bool = True,
424
+ ) -> Union[Tuple, BaseModelOutput]:
425
+
426
+ all_hidden_states = () if output_hidden_states else None
427
+ all_self_attentions = () if output_attentions else None
428
+
429
+ for layer in self.layers:
430
+ if output_hidden_states:
431
+ all_hidden_states = all_hidden_states + (hidden_states,)
432
+
433
+ layer_outputs = layer(
434
+ hidden_states,
435
+ attention_mask=attention_mask,
436
+ rotary_pos_emb=rotary_pos_emb,
437
+ output_attentions=output_attentions,
438
+ )
439
+
440
+ hidden_states = layer_outputs[0]
441
+
442
+ if output_attentions:
443
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
444
+
445
+ if output_hidden_states:
446
+ all_hidden_states = all_hidden_states + (hidden_states,)
447
+
448
+ if not return_dict:
449
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
450
+
451
+ return BaseModelOutput(
452
+ last_hidden_state=hidden_states,
453
+ hidden_states=all_hidden_states,
454
+ attentions=all_self_attentions,
455
+ )
456
+
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # Main Models
460
+ # ---------------------------------------------------------------------------
461
+
462
+ @add_start_docstrings(
463
+ "The bare OneVision Encoder Model outputting raw hidden-states without any specific head on top.",
464
+ ONEVISION_ENCODER_START_DOCSTRING,
465
+ )
466
+ class OneVisionEncoderPreTrainedModel(PreTrainedModel):
467
+ config_class = OneVisionEncoderConfig
468
+ base_model_prefix = "onevision_encoder"
469
+ supports_gradient_checkpointing = True
470
+ _no_split_modules = ["OneVisionEncoderEncoderLayer"]
471
+ _supports_flash_attn_2 = True
472
+
473
+ def _init_weights(self, module):
474
+ """Initialize the weights"""
475
+ std = self.config.initializer_range
476
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
477
+ module.weight.data.normal_(mean=0.0, std=std)
478
+ if module.bias is not None:
479
+ module.bias.data.zero_()
480
+ elif isinstance(module, nn.Embedding):
481
+ module.weight.data.normal_(mean=0.0, std=std)
482
+ if module.padding_idx is not None:
483
+ module.weight.data[module.padding_idx].zero_()
484
+ elif isinstance(module, (nn.LayerNorm, nn.RMSNorm)):
485
+ # Fix: RMSNorm doesn't have bias, must check hasattr first
486
+ module.weight.data.fill_(1.0)
487
+ if hasattr(module, 'bias') and module.bias is not None:
488
+ module.bias.data.zero_()
489
+
490
+
491
+ @add_start_docstrings(
492
+ "OneVision Encoder Model with a vision transformer encoder.",
493
+ ONEVISION_ENCODER_START_DOCSTRING,
494
+ )
495
+ class OneVisionEncoderModel(OneVisionEncoderPreTrainedModel):
496
+ def __init__(self, config: OneVisionEncoderConfig):
497
+ super().__init__(config)
498
+ self.config = config
499
+
500
+ self.embeddings = OneVisionEncoderEmbeddings(config)
501
+ self.layernorm_pre = get_norm_layer(config)
502
+ self.encoder = OneVisionEncoderEncoder(config)
503
+ self.video_rope = VideoRotaryEmbeddingSplit466(config)
504
+
505
+ if config.use_head:
506
+ self.layernorm_post = get_norm_layer(config)
507
+ self.head = Siglip2MultiheadAttentionPoolingHead(config)
508
+ else:
509
+ self.layernorm_post = None
510
+ self.head = None
511
+
512
+ self.post_init()
513
+
514
+
515
+ @add_start_docstrings_to_model_forward(ONEVISION_ENCODER_INPUTS_DOCSTRING)
516
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=OneVisionEncoderConfig)
517
+ def forward(
518
+ self,
519
+ pixel_values: torch.Tensor,
520
+ visible_indices: Optional[torch.Tensor] = None,
521
+ output_attentions: Optional[bool] = None,
522
+ output_hidden_states: Optional[bool] = None,
523
+ return_dict: Optional[bool] = None,
524
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
525
+ r"""
526
+ Returns:
527
+
528
+ Examples:
529
+
530
+ ```python
531
+ >>> from transformers import AutoModel, AutoImageProcessor
532
+ >>> from PIL import Image
533
+
534
+ >>> model = AutoModel.from_pretrained("lmms-lab-encoder/onevision-encoder-large", trust_remote_code=True)
535
+ >>> preprocessor = AutoImageProcessor.from_pretrained("lmms-lab-encoder/onevision-encoder-large", trust_remote_code=True)
536
+ >>> image = Image.open("path/to/your/image.jpg") # Replace with your image path
537
+ >>> pixel_values = preprocessor(images=image, return_tensors="pt")["pixel_values"]
538
+ >>> outputs = model(pixel_values)
539
+ >>> last_hidden_states = outputs.last_hidden_state
540
+ >>> pooled_output = outputs.pooler_output
541
+ ```
542
+ """
543
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
544
+ output_hidden_states = (
545
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
546
+ )
547
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
548
+
549
+ # Determine video dimensions for RoPE
550
+ # Note: pixel_values passed to embeddings can be 4D or 5D
551
+ if pixel_values.dim() == 5:
552
+ # Use config.rope_temporal_size if set, otherwise use actual frame count
553
+ t_frames = self.config.rope_temporal_size if self.config.rope_temporal_size is not None else pixel_values.shape[2]
554
+ height = pixel_values.shape[3]
555
+ width = pixel_values.shape[4]
556
+ else:
557
+ t_frames = 1
558
+ height = pixel_values.shape[2]
559
+ width = pixel_values.shape[3]
560
+
561
+ # 1. Embeddings
562
+ hidden_states = self.embeddings(pixel_values)
563
+ batch_size, total_patches, _ = hidden_states.shape
564
+
565
+ # 2. Visible Indices Handling
566
+ if visible_indices is None:
567
+ visible_indices = torch.arange(total_patches, device=pixel_values.device).unsqueeze(0).expand(batch_size, -1)
568
+
569
+ # 3. RoPE Construction
570
+ freqs_full = self.video_rope(
571
+ t=t_frames,
572
+ h=height // self.config.patch_size,
573
+ w=width // self.config.patch_size,
574
+ device=pixel_values.device
575
+ )
576
+ freqs_visible = freqs_full[visible_indices]
577
+
578
+ # Concatenate D/2 + D/2 -> D for applying rope
579
+ freqs_visible = torch.cat([freqs_visible, freqs_visible], dim=-1)
580
+
581
+ # 4. Pre-Norm & Encoder
582
+ hidden_states = self.layernorm_pre(hidden_states)
583
+
584
+ # fix: gather hidden_states to match freqs_visible when using sparse visible_indices
585
+ num_visible = visible_indices.shape[1]
586
+ if num_visible != total_patches:
587
+ # sparse mode: select only visible patches
588
+ hidden_states = hidden_states.gather(
589
+ 1, visible_indices.unsqueeze(-1).expand(-1, -1, hidden_states.shape[-1])
590
+ )
591
+
592
+ encoder_outputs = self.encoder(
593
+ hidden_states,
594
+ attention_mask=None,
595
+ rotary_pos_emb=freqs_visible,
596
+ output_attentions=output_attentions,
597
+ output_hidden_states=output_hidden_states,
598
+ return_dict=return_dict,
599
+ )
600
+
601
+ sequence_output = encoder_outputs[0]
602
+
603
+ # Apply post-norm if configured
604
+ if self.layernorm_post is not None:
605
+ sequence_output = self.layernorm_post(sequence_output)
606
+
607
+ # 5. Pooling Head
608
+ pooled_output = None
609
+ if self.head is not None:
610
+ pooled_output = self.head(sequence_output)
611
+
612
+ if not return_dict:
613
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
614
+
615
+ return BaseModelOutputWithPooling(
616
+ last_hidden_state=sequence_output,
617
+ pooler_output=pooled_output,
618
+ hidden_states=encoder_outputs.hidden_states,
619
+ attentions=encoder_outputs.attentions,
620
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": {
3
+ "height": 448,
4
+ "width": 448
5
+ },
6
+ "do_center_crop": true,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "image_mean": [
12
+ 0.48145466,
13
+ 0.4578275,
14
+ 0.40821073
15
+ ],
16
+ "image_processor_type": "CLIPImageProcessor",
17
+ "image_std": [
18
+ 0.26862954,
19
+ 0.26130258,
20
+ 0.27577711
21
+ ],
22
+ "resample": 3,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "shortest_edge": 448
26
+ }
27
+ }