Xinjie-Q commited on
Commit
28ba2c0
·
verified ·
1 Parent(s): 27709a6

Upload Mage-ViT: standalone codec-native visual encoder (ViT pre-training only)

Browse files
README.md CHANGED
@@ -1,3 +1,132 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ library_name: transformers
4
+ pipeline_tag: image-feature-extraction
5
+ tags:
6
+ - mage-vl
7
+ - vision-encoder
8
+ - codec-vit
9
+ - video-understanding
10
  ---
11
+
12
+ <h1 align="center">Mage-ViT<br><span style="font-size: 0.55em; font-weight: normal;">A Codec-Native Visual Encoder Trained from Scratch</span></h1>
13
+
14
+ <p align="center">
15
+ <a href="https://microsoft.github.io/Mage"><img alt="Project Page" src="https://img.shields.io/badge/%F0%9F%8C%90-Project%20Page-blue" height="22" /></a>
16
+ <a href="https://github.com/microsoft/Mage"><img src="https://img.shields.io/badge/Code-GitHub-181717?logo=github" alt="GitHub" height="22"></a>
17
+ <a href="https://huggingface.co/microsoft/Mage-VL"><img alt="Mage-VL" src="https://img.shields.io/badge/%F0%9F%A4%97-Mage--VL-yellow" height="22" /></a>
18
+ <a href="https://huggingface.co/microsoft/Mage-ViT"><img alt="Mage-ViT" src="https://img.shields.io/badge/%F0%9F%A4%97-Mage--ViT-yellow" height="22" /></a>
19
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/License-Apache%202.0-green" alt="License: Apache 2.0" height="22"></a>
20
+ </p>
21
+
22
+ ---
23
+
24
+ **Mage-ViT** is the visual encoder at the core of **[Mage-VL](https://huggingface.co/microsoft/Mage-VL)**. It is a *Codec-ViT* built primarily for video, where a single image is simply the degenerate one-frame case. Mage-ViT follows a **codec-aligned sparsity** principle: visual tokens should be spent where a video codec spends bits, since codec bit-allocation is a natural proxy for spatio-temporal importance. On a shared `16×16` patch grid it keeps every anchor (I-frame) patch and only the motion-salient predicted (P-frame) patches, while a shared **3D rotary position encoding** preserves spatio-temporal structure even after large fractions of the grid are dropped.
25
+
26
+ This repository is the **ViT-pre-trained checkpoint only** — it has not gone through the joint VLM training with the language model. Use it as a data-efficient, codec-native visual encoder, or as a drop-in ViT for your own multimodal training.
27
+
28
+ ## ✨ Highlights
29
+
30
+ - **Codec-driven patchifier.** Patches are selected by a per-patch importance map derived from the codec — motion vectors + P-frame residual energy for HEVC/H.265, or the learned rate map of the neural codec DCVC-RT. For a 64-frame clip it keeps all I-frame patches plus the top-*k* P-frame patches within a **4096-token budget (~75% token reduction)**. Chunk-wise and collage patchification are also supported.
31
+ - **Codec-agnostic.** The same interface accepts a traditional codec (HEVC/H.265) or a neural codec (DCVC-RT) with no architecture or retraining change.
32
+ - **Trained from scratch.** No billion-scale image-text ViT initialization — Mage-ViT is optimized with a large-scale **cluster-discrimination** objective on **~100M unlabeled images/videos**.
33
+
34
+ ## 🏗️ Architecture
35
+
36
+ A **24-layer pre-norm Vision Transformer** trunk (hidden size `1024`, `16` attention heads, GELU MLP at 4× expansion) processes the variable-length token sequence produced by the codec-driven patchifier, followed by a multi-head attention pooling head. The standalone encoder in this repo consumes `pixel_values` (and optional `patch_positions`); codec-driven patch **selection** is applied upstream in the Mage-VL data pipeline.
37
+
38
+ Pre-training is a two-stage, from-scratch recipe in bf16: **(1)** variable-resolution image pre-training (224–448), then **(2)** joint image + video pre-training (video at resolution 256, 64 frames per clip, 4096-token budget).
39
+
40
+ ## 📦 Installation
41
+
42
+ Mage-ViT follows the Mage-VL runtime:
43
+
44
+ ```bash
45
+ pip install "transformers>=5.7" torch torchvision pillow
46
+ # optional, for the fastest GPU attention path:
47
+ # pip install flash-attn --no-build-isolation
48
+ ```
49
+
50
+ Attention is dispatched internally to `sdpa` (default) → `flash_attention_2` → `eager`, so **flash-attn is optional** and the model runs on CPU or GPU out of the box.
51
+
52
+ ## 🚀 Encoding an image
53
+
54
+ ```python
55
+ import torch
56
+ from PIL import Image
57
+ from transformers import AutoModel, AutoImageProcessor
58
+
59
+ model = AutoModel.from_pretrained(
60
+ "microsoft/Mage-ViT", trust_remote_code=True
61
+ ).to("cuda").eval()
62
+ processor = AutoImageProcessor.from_pretrained(
63
+ "microsoft/Mage-ViT", trust_remote_code=True
64
+ )
65
+
66
+ image = Image.open("your_image.jpg")
67
+ pixel_values = processor(images=image, return_tensors="pt")["pixel_values"].to("cuda")
68
+
69
+ with torch.no_grad():
70
+ out = model(pixel_values) # pixel_values: [B, 3, H, W]
71
+
72
+ patch_features = out.last_hidden_state # [B, num_patches, 1024]
73
+ pooled_feature = out.pooler_output # [B, 1024]
74
+ ```
75
+
76
+ Pass `attn_implementation="flash_attention_2"` (or `"sdpa"` / `"eager"`) to `from_pretrained` to pick the attention backend.
77
+
78
+ ## 🎞️ Encoding a video
79
+
80
+ Stack the preprocessed frames into `[B, C, T, H, W]` and pass a `patch_positions` tensor of shape `[B, T * tokens_per_frame, 3]` giving the `(t, h, w)` grid coordinate of every patch:
81
+
82
+ ```python
83
+ import torch
84
+ from PIL import Image
85
+
86
+ PATCH = 16
87
+
88
+ def build_patch_positions(num_frames, target_frames, grid_h, grid_w, device="cuda"):
89
+ # temporal index for each frame, spread across the target timeline
90
+ t = torch.linspace(0, target_frames - 1, num_frames, device=device).long()
91
+ t = t.repeat_interleave(grid_h * grid_w) # [T * H * W]
92
+ h = torch.arange(grid_h, device=device).repeat_interleave(grid_w).repeat(num_frames)
93
+ w = torch.arange(grid_w, device=device).repeat(grid_h).repeat(num_frames)
94
+ return torch.stack([t, h, w], dim=-1).unsqueeze(0) # [1, T*H*W, 3]
95
+
96
+ frames = [Image.open(f"frame_{i}.jpg") for i in range(16)] # your sampled frames
97
+ pv = processor(images=frames, return_tensors="pt")["pixel_values"] # [T, C, H, W]
98
+ video = pv.unsqueeze(0).permute(0, 2, 1, 3, 4).to("cuda") # [1, C, T, H, W]
99
+
100
+ gh, gw = video.shape[-2] // PATCH, video.shape[-1] // PATCH
101
+ patch_positions = build_patch_positions(num_frames=16, target_frames=64,
102
+ grid_h=gh, grid_w=gw)
103
+
104
+ with torch.no_grad():
105
+ out = model(video, patch_positions=patch_positions)
106
+ ```
107
+
108
+ ## 📤 Outputs
109
+
110
+ | Field | Shape | Description |
111
+ | ----- | ----- | ----------- |
112
+ | `last_hidden_state` | `[B, num_patches, 1024]` | per-patch features after the final layer norm |
113
+ | `pooler_output` | `[B, 1024]` | global feature from the multi-head attention pooling head |
114
+
115
+ ## 📋 Specifications
116
+
117
+ | | |
118
+ | --- | --- |
119
+ | Architecture | Codec-ViT (pre-norm ViT, SigLIP-style MLP) |
120
+ | Parameters | ~316M |
121
+ | Hidden size / MLP | 1024 / 4096 |
122
+ | Layers / heads | 24 / 16 |
123
+ | Patch size | 16 |
124
+ | Position encoding | shared 3D rotary (4:6:6 split over T:H:W) |
125
+ | Pooling | learned-probe multi-head attention head |
126
+ | Pre-training resolution | images 224–448 (variable), video 256 |
127
+ | Weights dtype | bfloat16 |
128
+ | License | Apache-2.0 |
129
+
130
+ ## 📄 License
131
+
132
+ Released under the [Apache-2.0 License](https://www.apache.org/licenses/LICENSE-2.0).
__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .configuration_mage_vit import MageViTConfig
2
+ from .modeling_mage_vit import MageViTModel
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MageViTModel"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "dtype": "bfloat16",
7
+ "hidden_act": "gelu",
8
+ "hidden_size": 1024,
9
+ "image_size": 256,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 4096,
12
+ "layer_norm_eps": 1e-06,
13
+ "layer_norm_type": "layer_norm",
14
+ "model_type": "mage_vit",
15
+ "num_attention_heads": 16,
16
+ "num_channels": 3,
17
+ "num_hidden_layers": 24,
18
+ "patch_size": 16,
19
+ "rope_theta": 10000.0,
20
+ "rope_temporal_size": 64,
21
+ "transformers_version": "5.7.0",
22
+ "use_head": true,
23
+ "auto_map": {
24
+ "AutoConfig": "configuration_mage_vit.MageViTConfig",
25
+ "AutoModel": "modeling_mage_vit.MageViTModel"
26
+ }
27
+ }
configuration_mage_vit.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try: # transformers >= 5
2
+ from transformers.configuration_utils import PreTrainedConfig
3
+ except ImportError: # transformers < 5
4
+ from transformers.configuration_utils import PretrainedConfig as PreTrainedConfig
5
+
6
+ from transformers.utils import logging
7
+
8
+
9
+ logger = logging.get_logger(__name__)
10
+
11
+
12
+ class MageViTConfig(PreTrainedConfig):
13
+ r"""
14
+ This is the configuration class to store the configuration of a [`MageViTModel`]. It is used to instantiate a
15
+ Mage-ViT model according to the specified arguments, defining the model architecture. Instantiating a configuration
16
+ with the defaults will yield a similar configuration to that of the Mage-ViT architecture.
17
+
18
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
19
+ documentation from [`PreTrainedConfig`] for more information.
20
+
21
+ Args:
22
+ hidden_size (`int`, *optional*, defaults to 1024):
23
+ Dimensionality of the encoder layers and the pooler layer.
24
+ intermediate_size (`int`, *optional*, defaults to 4096):
25
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
26
+ num_hidden_layers (`int`, *optional*, defaults to 24):
27
+ Number of hidden layers in the Transformer encoder.
28
+ num_attention_heads (`int`, *optional*, defaults to 16):
29
+ Number of attention heads for each attention layer in the Transformer encoder.
30
+ num_channels (`int`, *optional*, defaults to 3):
31
+ The number of input channels.
32
+ image_size (`int`, *optional*, defaults to 256):
33
+ The size (resolution) of each image.
34
+ patch_size (`int`, *optional*, defaults to 16):
35
+ The size (resolution) of each patch.
36
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
37
+ The non-linear activation function (function or string) in the encoder and pooler.
38
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
39
+ The epsilon used by the layer normalization layers.
40
+ layer_norm_type (`str`, *optional*, defaults to `"layer_norm"`):
41
+ The type of layer normalization to use. Supported values: `"layer_norm"`, `"rms_norm"`.
42
+ attention_dropout (`float`, *optional*, defaults to 0.0):
43
+ The dropout ratio for the attention probabilities.
44
+ initializer_range (`float`, *optional*, defaults to 0.02):
45
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
46
+ rope_theta (`float`, *optional*, defaults to 10000.0):
47
+ The base period of the RoPE embeddings.
48
+ rope_temporal_size (`int` or `None`, *optional*, defaults to 64):
49
+ Fixed temporal grid size used to build RoPE positions when a 5D video tensor is passed without explicit
50
+ `patch_positions`. Set to `None` to use the actual number of frames.
51
+ use_head (`bool`, *optional*, defaults to `True`):
52
+ Whether to use the multi-head attention pooling head.
53
+
54
+ Example:
55
+
56
+ ```python
57
+ >>> from configuration_mage_vit import MageViTConfig
58
+ >>> from modeling_mage_vit import MageViTModel
59
+
60
+ >>> # Initializing a Mage-ViT configuration
61
+ >>> configuration = MageViTConfig()
62
+
63
+ >>> # Initializing a model (with random weights) from the configuration
64
+ >>> model = MageViTModel(configuration)
65
+
66
+ >>> # Accessing the model configuration
67
+ >>> configuration = model.config
68
+ ```
69
+ """
70
+
71
+ model_type = "mage_vit"
72
+
73
+ def __init__(
74
+ self,
75
+ hidden_size=1024,
76
+ intermediate_size=4096,
77
+ num_hidden_layers=24,
78
+ num_attention_heads=16,
79
+ num_channels=3,
80
+ image_size=256,
81
+ patch_size=16,
82
+ hidden_act="gelu",
83
+ layer_norm_eps=1e-6,
84
+ layer_norm_type="layer_norm",
85
+ attention_dropout=0.0,
86
+ initializer_range=0.02,
87
+ rope_theta=10000.0,
88
+ rope_temporal_size=64,
89
+ use_head=True,
90
+ **kwargs,
91
+ ):
92
+ super().__init__(**kwargs)
93
+ self.hidden_size = hidden_size
94
+ self.intermediate_size = intermediate_size
95
+ self.num_hidden_layers = num_hidden_layers
96
+ self.num_attention_heads = num_attention_heads
97
+ self.num_channels = num_channels
98
+ self.image_size = image_size
99
+ self.patch_size = patch_size
100
+ self.hidden_act = hidden_act
101
+ self.layer_norm_eps = layer_norm_eps
102
+ self.layer_norm_type = layer_norm_type
103
+ self.attention_dropout = attention_dropout
104
+ self.initializer_range = initializer_range
105
+ self.rope_theta = rope_theta
106
+ self.rope_temporal_size = rope_temporal_size # None=use actual frames, int=fixed size (legacy: 64)
107
+ self.use_head = use_head
108
+
109
+
110
+ __all__ = ["MageViTConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7848ad33832ef5a49c58c0d67a83d9269ace91349585e9a797364f8a0c535799
3
+ size 631420552
modeling_mage_vit.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mage-ViT — the standalone vision encoder of the Mage-VL family.
3
+
4
+ The implementation is adapted from the vision tower of Mage-VL (``modeling_mage_vl.py``):
5
+
6
+ * fused ``qkv`` / ``proj`` self-attention,
7
+ * 3D (T,H,W) rotary position embeddings with a 4:6:6 split (``VisionRotaryEmbedding``),
8
+ * SigLIP-style MLP blocks and a multi-head attention pooling head.
9
+
10
+ It is written to be transformers-version agnostic (works with both ``transformers>=5``
11
+ and ``transformers==4.57.x``): attention is dispatched internally across
12
+ ``sdpa`` / ``flash_attention_2`` / ``eager`` without relying on any transformers-5-only
13
+ symbols, and it does not require ``flash-attn`` to be installed (``sdpa`` is the default).
14
+ """
15
+
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.models.siglip.modeling_siglip import SiglipMLP
25
+ from transformers.utils import logging
26
+
27
+ from .configuration_mage_vit import MageViTConfig
28
+
29
+
30
+ try:
31
+ from flash_attn import flash_attn_func
32
+
33
+ _flash_attn_available = True
34
+ except ImportError:
35
+ _flash_attn_available = False
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Helper Functions & Layers
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def get_norm_layer(config):
46
+ if config.layer_norm_type == "rms_norm":
47
+ return nn.RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
48
+ else:
49
+ return nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
50
+
51
+
52
+ def rotate_half(x):
53
+ """
54
+ Interleaved rotation matching the training-time implementation.
55
+ (x1, x2, x3, x4) -> (-x2, x1, -x4, x3)
56
+ """
57
+ x_even = x[..., ::2]
58
+ x_odd = x[..., 1::2]
59
+ return torch.stack((-x_odd, x_even), dim=-1).flatten(-2)
60
+
61
+
62
+ def apply_rotary_pos_emb(q, k, freqs):
63
+ # q, k: (B, H, L, D); freqs: (B, L, D) or (1, L, D)
64
+ orig_q_dtype = q.dtype
65
+ orig_k_dtype = k.dtype
66
+ q, k = q.float(), k.float()
67
+ cos = freqs.cos().unsqueeze(1).float() # (B, 1, L, D)
68
+ sin = freqs.sin().unsqueeze(1).float()
69
+
70
+ q_embed = (q * cos) + (rotate_half(q) * sin)
71
+ k_embed = (k * cos) + (rotate_half(k) * sin)
72
+ return q_embed.to(orig_q_dtype), k_embed.to(orig_k_dtype)
73
+
74
+
75
+ def eager_attention_forward(
76
+ module: nn.Module,
77
+ query: torch.Tensor,
78
+ key: torch.Tensor,
79
+ value: torch.Tensor,
80
+ attention_mask: Optional[torch.Tensor],
81
+ scaling: float,
82
+ dropout: float = 0.0,
83
+ ):
84
+ """Eager attention; query/key/value are expected as ``(B, H, L, D)``."""
85
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
86
+ if attention_mask is not None:
87
+ attn_weights = attn_weights + attention_mask
88
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
89
+ attn_weights = F.dropout(attn_weights, p=dropout, training=module.training)
90
+ attn_output = torch.matmul(attn_weights, value)
91
+ attn_output = attn_output.transpose(1, 2).contiguous() # (B, L, H, D)
92
+ return attn_output, attn_weights
93
+
94
+
95
+ class VisionRotaryEmbedding(nn.Module):
96
+ """
97
+ 3D (T,H,W) Rotary frequency constructor with a 4:6:6 split for T:H:W.
98
+ """
99
+
100
+ def __init__(self, config: MageViTConfig):
101
+ super().__init__()
102
+ head_dim = config.hidden_size // config.num_attention_heads
103
+ base = config.rope_theta
104
+
105
+ assert head_dim % 2 == 0, "head_dim must be even for rotary."
106
+ assert head_dim % 16 == 0, "head_dim must be divisible by 16."
107
+ half = head_dim // 2
108
+ assert half % 16 == 0, "head_dim//2 must also be divisible by 16 to split into 4:6:6."
109
+
110
+ self.head_dim = head_dim
111
+ self.half = half
112
+ self.base = base
113
+
114
+ unit = half // 16
115
+ self.t_size = 4 * unit
116
+ self.h_size = 6 * unit
117
+ self.w_size = 6 * unit
118
+
119
+ self.register_buffer(
120
+ "inv_freq_t",
121
+ 1.0 / (base ** (torch.arange(self.t_size, dtype=torch.float32) / self.t_size)),
122
+ persistent=False,
123
+ )
124
+ self.register_buffer(
125
+ "inv_freq_h",
126
+ 1.0 / (base ** (torch.arange(self.h_size, dtype=torch.float32) / self.h_size)),
127
+ persistent=False,
128
+ )
129
+ self.register_buffer(
130
+ "inv_freq_w",
131
+ 1.0 / (base ** (torch.arange(self.w_size, dtype=torch.float32) / self.w_size)),
132
+ persistent=False,
133
+ )
134
+
135
+ def forward_with_thw(self, t: int, h: int, w: int, device=None) -> torch.Tensor:
136
+ """Build RoPE frequencies for a full (t, h, w) patch grid -> [t*h*w, half]."""
137
+ if device is None:
138
+ device = self.inv_freq_t.device
139
+
140
+ inv_t = self.inv_freq_t.to(device=device)
141
+ inv_h = self.inv_freq_h.to(device=device)
142
+ inv_w = self.inv_freq_w.to(device=device)
143
+
144
+ ft = torch.outer(torch.arange(t, device=device, dtype=torch.float32), inv_t)
145
+ fh = torch.outer(torch.arange(h, device=device, dtype=torch.float32), inv_h)
146
+ fw = torch.outer(torch.arange(w, device=device, dtype=torch.float32), inv_w)
147
+
148
+ t_ids = torch.arange(t, device=device).repeat_interleave(h * w)
149
+ h_ids = torch.arange(h, device=device).repeat_interleave(w).repeat(t)
150
+ w_ids = torch.arange(w, device=device).repeat(h).repeat(t)
151
+
152
+ return torch.cat([ft[t_ids], fh[h_ids], fw[w_ids]], dim=-1)
153
+
154
+ def forward_from_positions(self, patch_positions: torch.Tensor) -> torch.Tensor:
155
+ """
156
+ Build RoPE frequencies from explicit patch positions.
157
+
158
+ Args:
159
+ patch_positions: [seq_len, 3] or [batch_size, seq_len, 3] with [t, h, w] per patch.
160
+
161
+ Returns:
162
+ freqs with a leading batch dim: [batch_size, seq_len, half].
163
+ """
164
+ if patch_positions.dim() == 2:
165
+ patch_positions = patch_positions.unsqueeze(0)
166
+
167
+ device = patch_positions.device
168
+ inv_t = self.inv_freq_t.to(device=device)
169
+ inv_h = self.inv_freq_h.to(device=device)
170
+ inv_w = self.inv_freq_w.to(device=device)
171
+
172
+ t_pos = patch_positions[..., 0].float() # [B, L]
173
+ h_pos = patch_positions[..., 1].float()
174
+ w_pos = patch_positions[..., 2].float()
175
+
176
+ ft = torch.einsum("bs,d->bsd", t_pos, inv_t)
177
+ fh = torch.einsum("bs,d->bsd", h_pos, inv_h)
178
+ fw = torch.einsum("bs,d->bsd", w_pos, inv_w)
179
+
180
+ return torch.cat([ft, fh, fw], dim=-1)
181
+
182
+
183
+ class Siglip2MultiheadAttentionPoolingHead(nn.Module):
184
+ """Multi-Head Attention Pooling with a learned probe (PMA-style)."""
185
+
186
+ def __init__(self, config: MageViTConfig):
187
+ super().__init__()
188
+ self.embed_dim = config.hidden_size
189
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
190
+ self.attention = nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
191
+ self.norm = nn.RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
192
+ self.mlp = SiglipMLP(config)
193
+
194
+ def forward(self, hidden_states):
195
+ batch_size = hidden_states.shape[0]
196
+ probe = self.probe.repeat(batch_size, 1, 1)
197
+
198
+ attn_output, _ = self.attention(probe, hidden_states, hidden_states)
199
+
200
+ residual = attn_output
201
+ attn_output = self.norm(attn_output)
202
+ attn_output = residual + self.mlp(attn_output)
203
+
204
+ return attn_output[:, 0]
205
+
206
+
207
+ # ---------------------------------------------------------------------------
208
+ # Modeling Components
209
+ # ---------------------------------------------------------------------------
210
+
211
+
212
+ class MageViTEmbeddings(nn.Module):
213
+ """Conv2d patch embedding for pixel-value inputs (4D image or 5D video)."""
214
+
215
+ def __init__(self, config: MageViTConfig):
216
+ super().__init__()
217
+ self.config = config
218
+ self.embed_dim = config.hidden_size
219
+ self.image_size = config.image_size
220
+ self.patch_size = config.patch_size
221
+
222
+ self.patch_embedding = nn.Conv2d(
223
+ in_channels=config.num_channels,
224
+ out_channels=self.embed_dim,
225
+ kernel_size=self.patch_size,
226
+ stride=self.patch_size,
227
+ bias=False,
228
+ )
229
+
230
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
231
+ # Handle 4D (B, C, H, W) or 5D (B, C, T, H, W) inputs
232
+ if pixel_values.dim() == 4:
233
+ pixel_values = pixel_values.unsqueeze(2) # (B, C, 1, H, W)
234
+
235
+ batch_size, channels, t_frames, height, width = pixel_values.shape
236
+ target_dtype = self.patch_embedding.weight.dtype
237
+
238
+ # Merge time into batch for Conv2d
239
+ x_2d = pixel_values.permute(0, 2, 1, 3, 4).reshape(batch_size * t_frames, channels, height, width)
240
+
241
+ embeddings = self.patch_embedding(x_2d.to(dtype=target_dtype)) # (B*T, C, Hp, Wp)
242
+ embeddings = embeddings.flatten(2).transpose(1, 2) # (B*T, L_frame, C)
243
+
244
+ total_patches = t_frames * (height // self.patch_size) * (width // self.patch_size)
245
+ embeddings = embeddings.reshape(batch_size, total_patches, self.embed_dim)
246
+
247
+ return embeddings
248
+
249
+
250
+ class MageViTAttention(nn.Module):
251
+ """
252
+ Multi-headed attention with fused ``qkv`` / ``proj`` projections and RoPE support.
253
+
254
+ Attention is dispatched internally across ``sdpa`` (default) / ``flash_attention_2`` /
255
+ ``eager`` based on ``config._attn_implementation``.
256
+ """
257
+
258
+ def __init__(self, config: MageViTConfig):
259
+ super().__init__()
260
+ self.config = config
261
+ self.embed_dim = config.hidden_size
262
+ self.num_heads = config.num_attention_heads
263
+ self.head_dim = self.embed_dim // self.num_heads
264
+ if self.head_dim * self.num_heads != self.embed_dim:
265
+ raise ValueError(
266
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and "
267
+ f"`num_heads`: {self.num_heads})."
268
+ )
269
+
270
+ self.scale = self.head_dim**-0.5
271
+ self.attention_dropout = config.attention_dropout
272
+ self.qkv = nn.Linear(self.embed_dim, self.embed_dim * 3)
273
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
274
+
275
+ def _attn_impl(self) -> str:
276
+ impl = getattr(self.config, "_attn_implementation", None) or "sdpa"
277
+ if impl == "flash_attention_2" and not _flash_attn_available:
278
+ logger.warning_once("flash-attn is not installed; falling back to `sdpa` attention.")
279
+ impl = "sdpa"
280
+ return impl
281
+
282
+ def forward(
283
+ self,
284
+ hidden_states: torch.Tensor,
285
+ attention_mask: Optional[torch.Tensor] = None,
286
+ rotary_pos_emb: Optional[torch.Tensor] = None,
287
+ output_attentions: bool = False,
288
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
289
+ batch_size, q_len, _ = hidden_states.size()
290
+
291
+ # (B, L, 3*H*D) -> (B, L, 3, H, D) -> 3 x (B, H, L, D)
292
+ q, k, v = (
293
+ self.qkv(hidden_states)
294
+ .reshape(batch_size, q_len, 3, self.num_heads, self.head_dim)
295
+ .permute(2, 0, 1, 3, 4)
296
+ .unbind(0)
297
+ )
298
+ query_states = q.transpose(1, 2)
299
+ key_states = k.transpose(1, 2)
300
+ value_states = v.transpose(1, 2)
301
+
302
+ if rotary_pos_emb is not None:
303
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, rotary_pos_emb)
304
+
305
+ dropout = self.attention_dropout if self.training else 0.0
306
+ impl = self._attn_impl()
307
+ attn_weights = None
308
+
309
+ if output_attentions or impl == "eager":
310
+ attn_output, attn_weights = eager_attention_forward(
311
+ self, query_states, key_states, value_states, attention_mask, self.scale, dropout
312
+ )
313
+ elif impl == "flash_attention_2":
314
+ # flash-attn expects (B, L, H, D)
315
+ attn_output = flash_attn_func(
316
+ query_states.transpose(1, 2),
317
+ key_states.transpose(1, 2),
318
+ value_states.transpose(1, 2),
319
+ dropout_p=dropout,
320
+ softmax_scale=self.scale,
321
+ causal=False,
322
+ ) # (B, L, H, D)
323
+ else: # sdpa
324
+ attn_output = F.scaled_dot_product_attention(
325
+ query_states,
326
+ key_states,
327
+ value_states,
328
+ attn_mask=attention_mask,
329
+ dropout_p=dropout,
330
+ scale=self.scale,
331
+ ) # (B, H, L, D)
332
+ attn_output = attn_output.transpose(1, 2) # (B, L, H, D)
333
+
334
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
335
+ attn_output = self.proj(attn_output)
336
+
337
+ return attn_output, attn_weights if output_attentions else None
338
+
339
+
340
+ class MageViTEncoderLayer(nn.Module):
341
+ """Vision encoder layer with pre-norm attention and MLP."""
342
+
343
+ def __init__(self, config: MageViTConfig):
344
+ super().__init__()
345
+ self.embed_dim = config.hidden_size
346
+ self.self_attn = MageViTAttention(config)
347
+ self.layer_norm1 = get_norm_layer(config)
348
+ self.mlp = SiglipMLP(config)
349
+ self.layer_norm2 = get_norm_layer(config)
350
+
351
+ def forward(
352
+ self,
353
+ hidden_states: torch.Tensor,
354
+ attention_mask: Optional[torch.Tensor] = None,
355
+ rotary_pos_emb: Optional[torch.Tensor] = None,
356
+ output_attentions: bool = False,
357
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
358
+ residual = hidden_states
359
+ hidden_states = self.layer_norm1(hidden_states)
360
+ hidden_states, attn_weights = self.self_attn(
361
+ hidden_states=hidden_states,
362
+ attention_mask=attention_mask,
363
+ rotary_pos_emb=rotary_pos_emb,
364
+ output_attentions=output_attentions,
365
+ )
366
+ hidden_states = residual + hidden_states
367
+
368
+ residual = hidden_states
369
+ hidden_states = self.layer_norm2(hidden_states)
370
+ hidden_states = self.mlp(hidden_states)
371
+ hidden_states = residual + hidden_states
372
+
373
+ outputs = (hidden_states, attn_weights) if output_attentions else (hidden_states,)
374
+ return outputs
375
+
376
+
377
+ class MageViTEncoder(nn.Module):
378
+ def __init__(self, config: MageViTConfig):
379
+ super().__init__()
380
+ self.config = config
381
+ self.layers = nn.ModuleList([MageViTEncoderLayer(config) for _ in range(config.num_hidden_layers)])
382
+ self.gradient_checkpointing = False
383
+
384
+ def forward(
385
+ self,
386
+ hidden_states: torch.Tensor,
387
+ attention_mask: Optional[torch.Tensor] = None,
388
+ rotary_pos_emb: Optional[torch.Tensor] = None,
389
+ output_attentions: bool = False,
390
+ output_hidden_states: bool = False,
391
+ return_dict: bool = True,
392
+ ) -> Union[tuple, BaseModelOutput]:
393
+ all_hidden_states = () if output_hidden_states else None
394
+ all_self_attentions = () if output_attentions else None
395
+
396
+ for layer in self.layers:
397
+ if output_hidden_states:
398
+ all_hidden_states = all_hidden_states + (hidden_states,)
399
+
400
+ if self.gradient_checkpointing and self.training:
401
+ layer_outputs = self._gradient_checkpointing_func(
402
+ layer.__call__,
403
+ hidden_states,
404
+ attention_mask,
405
+ rotary_pos_emb,
406
+ output_attentions,
407
+ )
408
+ else:
409
+ layer_outputs = layer(
410
+ hidden_states,
411
+ attention_mask=attention_mask,
412
+ rotary_pos_emb=rotary_pos_emb,
413
+ output_attentions=output_attentions,
414
+ )
415
+
416
+ hidden_states = layer_outputs[0]
417
+
418
+ if output_attentions:
419
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
420
+
421
+ if output_hidden_states:
422
+ all_hidden_states = all_hidden_states + (hidden_states,)
423
+
424
+ if not return_dict:
425
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
426
+
427
+ return BaseModelOutput(
428
+ last_hidden_state=hidden_states,
429
+ hidden_states=all_hidden_states,
430
+ attentions=all_self_attentions,
431
+ )
432
+
433
+
434
+ # ---------------------------------------------------------------------------
435
+ # Main Models
436
+ # ---------------------------------------------------------------------------
437
+
438
+
439
+ class MageViTPreTrainedModel(PreTrainedModel):
440
+ config_class = MageViTConfig
441
+ base_model_prefix = "mage_vit"
442
+ supports_gradient_checkpointing = True
443
+ _no_split_modules = ["MageViTEncoderLayer"]
444
+ _supports_flash_attn_2 = True
445
+ _supports_flash_attn = True
446
+ _supports_sdpa = True
447
+
448
+ def _init_weights(self, module):
449
+ """Initialize the weights."""
450
+ std = self.config.initializer_range
451
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
452
+ module.weight.data.normal_(mean=0.0, std=std)
453
+ if module.bias is not None:
454
+ module.bias.data.zero_()
455
+ elif isinstance(module, nn.Embedding):
456
+ module.weight.data.normal_(mean=0.0, std=std)
457
+ if module.padding_idx is not None:
458
+ module.weight.data[module.padding_idx].zero_()
459
+ elif isinstance(module, (nn.LayerNorm, nn.RMSNorm)):
460
+ module.weight.data.fill_(1.0)
461
+ if hasattr(module, "bias") and module.bias is not None:
462
+ module.bias.data.zero_()
463
+ elif isinstance(module, VisionRotaryEmbedding):
464
+ # inv_freq buffers are registered with persistent=False, so they are not in the
465
+ # checkpoint. When `from_pretrained` materializes the model from meta tensors these
466
+ # buffers would otherwise stay uninitialized; re-fill them so RoPE is correct post-load.
467
+ base = module.base
468
+ with torch.no_grad():
469
+ inv_t = 1.0 / (base ** (torch.arange(module.t_size, dtype=torch.float32) / module.t_size))
470
+ inv_h = 1.0 / (base ** (torch.arange(module.h_size, dtype=torch.float32) / module.h_size))
471
+ inv_w = 1.0 / (base ** (torch.arange(module.w_size, dtype=torch.float32) / module.w_size))
472
+ module.inv_freq_t.copy_(inv_t.to(module.inv_freq_t.device))
473
+ module.inv_freq_h.copy_(inv_h.to(module.inv_freq_h.device))
474
+ module.inv_freq_w.copy_(inv_w.to(module.inv_freq_w.device))
475
+
476
+
477
+ class MageViTModel(MageViTPreTrainedModel):
478
+ """Mage-ViT vision transformer encoder."""
479
+
480
+ def __init__(self, config: MageViTConfig):
481
+ super().__init__(config)
482
+ self.config = config
483
+
484
+ self.embeddings = MageViTEmbeddings(config)
485
+ self.layernorm_pre = get_norm_layer(config)
486
+ self.encoder = MageViTEncoder(config)
487
+ self.video_rope = VisionRotaryEmbedding(config)
488
+
489
+ if config.use_head:
490
+ self.layernorm_post = get_norm_layer(config)
491
+ self.head = Siglip2MultiheadAttentionPoolingHead(config)
492
+ else:
493
+ self.layernorm_post = None
494
+ self.head = None
495
+
496
+ self.post_init()
497
+
498
+ def forward(
499
+ self,
500
+ pixel_values: torch.Tensor,
501
+ visible_indices: Optional[torch.Tensor] = None,
502
+ patch_positions: Optional[torch.Tensor] = None,
503
+ output_attentions: Optional[bool] = None,
504
+ output_hidden_states: Optional[bool] = None,
505
+ return_dict: Optional[bool] = None,
506
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
507
+ r"""
508
+ Examples:
509
+
510
+ ```python
511
+ >>> from transformers import AutoModel, AutoImageProcessor
512
+ >>> from PIL import Image
513
+
514
+ >>> model = AutoModel.from_pretrained("microsoft/Mage-ViT", trust_remote_code=True)
515
+ >>> preprocessor = AutoImageProcessor.from_pretrained("microsoft/Mage-ViT", trust_remote_code=True)
516
+ >>> image = Image.open("path/to/your/image.jpg")
517
+ >>> pixel_values = preprocessor(images=image, return_tensors="pt")["pixel_values"]
518
+ >>> outputs = model(pixel_values)
519
+ >>> last_hidden_states = outputs.last_hidden_state
520
+ >>> pooled_output = outputs.pooler_output
521
+ ```
522
+ """
523
+ output_attentions = (
524
+ output_attentions if output_attentions is not None else getattr(self.config, "output_attentions", False)
525
+ )
526
+ output_hidden_states = (
527
+ output_hidden_states
528
+ if output_hidden_states is not None
529
+ else getattr(self.config, "output_hidden_states", False)
530
+ )
531
+ return_dict = True if return_dict is None else return_dict
532
+
533
+ # Determine grid dimensions for RoPE (pixel_values may be 4D or 5D)
534
+ if pixel_values.dim() == 5:
535
+ t_frames = (
536
+ self.config.rope_temporal_size if self.config.rope_temporal_size is not None else pixel_values.shape[2]
537
+ )
538
+ height, width = pixel_values.shape[3], pixel_values.shape[4]
539
+ else:
540
+ t_frames = 1
541
+ height, width = pixel_values.shape[2], pixel_values.shape[3]
542
+
543
+ # 1. Embeddings
544
+ hidden_states = self.embeddings(pixel_values)
545
+ batch_size, total_patches, _ = hidden_states.shape
546
+
547
+ # 2. Visible-index handling (defaults to all patches)
548
+ if visible_indices is None:
549
+ visible_indices = torch.arange(total_patches, device=pixel_values.device).unsqueeze(0).expand(
550
+ batch_size, -1
551
+ )
552
+
553
+ # 3. RoPE construction
554
+ if patch_positions is not None:
555
+ freqs_visible = self.video_rope.forward_from_positions(patch_positions) # (B, L, half)
556
+ else:
557
+ freqs_full = self.video_rope.forward_with_thw(
558
+ t=t_frames,
559
+ h=height // self.config.patch_size,
560
+ w=width // self.config.patch_size,
561
+ device=pixel_values.device,
562
+ )
563
+ freqs_visible = freqs_full[visible_indices] # (B, L, half)
564
+
565
+ # Concatenate half + half -> head_dim
566
+ freqs_visible = torch.cat([freqs_visible, freqs_visible], dim=-1)
567
+
568
+ # 4. Pre-norm & encoder
569
+ hidden_states = self.layernorm_pre(hidden_states)
570
+
571
+ # Sparse mode: gather only visible patches to match freqs_visible
572
+ if visible_indices.shape[1] != total_patches:
573
+ hidden_states = hidden_states.gather(
574
+ 1, visible_indices.unsqueeze(-1).expand(-1, -1, hidden_states.shape[-1])
575
+ )
576
+
577
+ encoder_outputs = self.encoder(
578
+ hidden_states,
579
+ attention_mask=None,
580
+ rotary_pos_emb=freqs_visible,
581
+ output_attentions=output_attentions,
582
+ output_hidden_states=output_hidden_states,
583
+ return_dict=True,
584
+ )
585
+ sequence_output = encoder_outputs.last_hidden_state
586
+
587
+ if self.layernorm_post is not None:
588
+ sequence_output = self.layernorm_post(sequence_output)
589
+
590
+ pooled_output = self.head(sequence_output) if self.head is not None else None
591
+
592
+ if not return_dict:
593
+ outputs = (sequence_output, pooled_output)
594
+ if output_hidden_states:
595
+ outputs = outputs + (encoder_outputs.hidden_states,)
596
+ if output_attentions:
597
+ outputs = outputs + (encoder_outputs.attentions,)
598
+ return outputs
599
+
600
+ return BaseModelOutputWithPooling(
601
+ last_hidden_state=sequence_output,
602
+ pooler_output=pooled_output,
603
+ hidden_states=encoder_outputs.hidden_states,
604
+ attentions=encoder_outputs.attentions,
605
+ )
606
+
607
+
608
+ __all__ = ["MageViTModel", "MageViTPreTrainedModel"]
preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": {
3
+ "height": 256,
4
+ "width": 256
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": 256
26
+ }
27
+ }