Instructions to use immanuelpeter/DeepSeek-ViT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use immanuelpeter/DeepSeek-ViT with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-feature-extraction", model="immanuelpeter/DeepSeek-ViT")# pip install -U transformers accelerate # Load model directly from transformers import DeepSeekV41ViT model = DeepSeekV41ViT.from_pretrained("immanuelpeter/DeepSeek-ViT", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add immanuelpeter/DeepSeek-ViT vision tower
Browse files- LICENSE +21 -0
- README.md +61 -0
- config.json +10 -0
- examples/inference.py +63 -0
- model.safetensors +3 -0
- projector.safetensors +3 -0
- vision.py +129 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2023 DeepSeek
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
pipeline_tag: image-feature-extraction
|
| 4 |
+
library_name: transformers
|
| 5 |
+
tags:
|
| 6 |
+
- vision
|
| 7 |
+
base_model:
|
| 8 |
+
- deepseek-ai/DeepSeek-V4.1-Flash
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# DeepSeek-ViT
|
| 12 |
+
|
| 13 |
+
This repository packages DeepSeek-ViT and the two-layer MLP projector from
|
| 14 |
+
[DeepSeek-V4.1-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash).
|
| 15 |
+
|
| 16 |
+
## Contents
|
| 17 |
+
|
| 18 |
+
| File | Tensors | What it holds |
|
| 19 |
+
|---|---|---|
|
| 20 |
+
| `model.safetensors` | 259 | DeepSeek-ViT Tower, extracted from source shard 1 |
|
| 21 |
+
| `projector.safetensors` | 4 | Two-layer MLP Aligner |
|
| 22 |
+
| `config.json` | | Vision-only `DeepSeekV41ViT` |
|
| 23 |
+
| `vision.py` | | Standalone ViT and Aligner used by `examples/inference.py` |
|
| 24 |
+
|
| 25 |
+
This repository does not include Transformers modeling files or a preprocessor
|
| 26 |
+
config. `AutoModel.from_pretrained` will not work.
|
| 27 |
+
|
| 28 |
+
## Architecture
|
| 29 |
+
|
| 30 |
+
| Component | Details |
|
| 31 |
+
|---|---|
|
| 32 |
+
| Tower | 32 layers, 1024 hidden, 16 heads, 2816 intermediate, patch size 14, 2D-RoPE |
|
| 33 |
+
| Token compression | 3x3 unfold / pixel-unshuffle with padding |
|
| 34 |
+
| Aligner | `Linear(9216, 5120)`, GELU, `Linear(5120, 5120)`, both with bias |
|
| 35 |
+
|
| 36 |
+
## Usage
|
| 37 |
+
|
| 38 |
+
See [`examples/inference.py`](examples/inference.py) for image feature extraction.
|
| 39 |
+
`AutoModel.from_pretrained` will not load this repository. The example uses
|
| 40 |
+
[`vision.py`](vision.py) in this repo.
|
| 41 |
+
|
| 42 |
+
## Validation
|
| 43 |
+
|
| 44 |
+
The [parity script](https://github.com/immanuel-peter/vision-tower-bench/blob/main/tests/test_parity.py)
|
| 45 |
+
compares all 259 Tower tensors and 4 Aligner tensors with the pinned parent checkpoint
|
| 46 |
+
using `torch.equal`.
|
| 47 |
+
|
| 48 |
+
## Reproduction
|
| 49 |
+
|
| 50 |
+
The [export script](https://github.com/immanuel-peter/vision-tower-bench/blob/main/scripts/export_deepseek_v41_vision.py)
|
| 51 |
+
reads `vision.*` and `aligner.*` from shard 1 of `deepseek-ai/DeepSeek-V4.1-Flash`,
|
| 52 |
+
removes the prefixes, and writes the original BF16 tensors.
|
| 53 |
+
|
| 54 |
+
## Credits
|
| 55 |
+
|
| 56 |
+
DeepSeek released the DeepSeek-V4.1-Flash weights. DeepSeek-ViT is described in
|
| 57 |
+
[DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression](https://www.alphaxiv.org/abs/2609.deepseek-v4-1-flash).
|
| 58 |
+
|
| 59 |
+
## License
|
| 60 |
+
|
| 61 |
+
[MIT License](LICENSE), the same license as the source model.
|
config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"DeepSeekV41ViT"
|
| 4 |
+
],
|
| 5 |
+
"vision_n_layers": 32,
|
| 6 |
+
"vision_dim": 1024,
|
| 7 |
+
"vision_patch_size": 14,
|
| 8 |
+
"vision_downsample_ratio": 3,
|
| 9 |
+
"aligner_dim": 5120
|
| 10 |
+
}
|
examples/inference.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import torch
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
from safetensors.torch import load_file
|
| 9 |
+
from torchvision import transforms
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 12 |
+
from vision import Aligner, ViT
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
MODEL_ID = "immanuelpeter/DeepSeek-ViT"
|
| 16 |
+
PATCH_SIZE = 14
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def bundle_file(model: str, name: str) -> Path:
|
| 20 |
+
path = Path(model)
|
| 21 |
+
if path.is_dir():
|
| 22 |
+
return path / name
|
| 23 |
+
return Path(hf_hub_download(model, name))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main() -> None:
|
| 27 |
+
parser = argparse.ArgumentParser(description="Extract DeepSeek-ViT visual features.")
|
| 28 |
+
parser.add_argument("image", type=Path)
|
| 29 |
+
parser.add_argument("--model", default=MODEL_ID)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 33 |
+
dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
|
| 34 |
+
tower = ViT()
|
| 35 |
+
tower.load_state_dict(load_file(bundle_file(args.model, "model.safetensors")))
|
| 36 |
+
tower = tower.to(device=device, dtype=dtype).eval()
|
| 37 |
+
aligner = Aligner()
|
| 38 |
+
aligner.load_state_dict(load_file(bundle_file(args.model, "projector.safetensors")))
|
| 39 |
+
aligner = aligner.to(device=device, dtype=dtype).eval()
|
| 40 |
+
|
| 41 |
+
image = Image.open(args.image).convert("RGB")
|
| 42 |
+
pixels = transforms.Compose([
|
| 43 |
+
transforms.Resize(448, interpolation=transforms.InterpolationMode.BICUBIC),
|
| 44 |
+
transforms.CenterCrop(448),
|
| 45 |
+
transforms.ToTensor(),
|
| 46 |
+
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
|
| 47 |
+
])(image)
|
| 48 |
+
channels, height, width = pixels.shape
|
| 49 |
+
rows, cols = height // PATCH_SIZE, width // PATCH_SIZE
|
| 50 |
+
patches = pixels.reshape(channels, rows, PATCH_SIZE, cols, PATCH_SIZE)
|
| 51 |
+
patches = patches.permute(1, 3, 0, 2, 4).reshape(rows * cols, channels, PATCH_SIZE, PATCH_SIZE)
|
| 52 |
+
patches = patches.to(device=device, dtype=dtype)
|
| 53 |
+
|
| 54 |
+
with torch.inference_mode():
|
| 55 |
+
tokens = tower(patches, rows, cols)
|
| 56 |
+
projected = aligner(tokens, rows, cols)
|
| 57 |
+
|
| 58 |
+
print("tower", tokens.shape)
|
| 59 |
+
print("projected", projected.shape)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
main()
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:906c78518dd52c5b4d33134b3a23bf211b7c792ce8f1260733836a21fdb766c0
|
| 3 |
+
size 823710304
|
projector.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f1b43b61bf52d83b849afb456105569c9bafe58cfc1a7225cdf32f90bda84143
|
| 3 |
+
size 146821472
|
vision.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import nn
|
| 7 |
+
|
| 8 |
+
ARGS = SimpleNamespace(
|
| 9 |
+
vision_dim=1024,
|
| 10 |
+
vision_n_heads=16,
|
| 11 |
+
vision_n_layers=32,
|
| 12 |
+
vision_inter_dim=2816,
|
| 13 |
+
vision_patch_size=14,
|
| 14 |
+
vision_downsample_ratio=3,
|
| 15 |
+
vision_rope_theta=10000,
|
| 16 |
+
dim=5120,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@lru_cache(8)
|
| 21 |
+
def get_vision_cos_sin(n_h: int, n_w: int, dim: int, theta: float):
|
| 22 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
|
| 23 |
+
hpos = torch.arange(n_h).unsqueeze(1).expand(n_h, n_w)
|
| 24 |
+
wpos = torch.arange(n_w).unsqueeze(0).expand(n_h, n_w)
|
| 25 |
+
freqs = torch.stack([hpos, wpos], dim=-1).reshape(-1, 2, 1).float() * inv_freq
|
| 26 |
+
freqs = freqs.flatten(1)
|
| 27 |
+
return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 31 |
+
dtype = x.dtype
|
| 32 |
+
x1, x2 = x.float().chunk(2, dim=-1)
|
| 33 |
+
return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1).to(dtype)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class RMSNorm(nn.Module):
|
| 37 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.eps = eps
|
| 40 |
+
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
|
| 41 |
+
|
| 42 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 43 |
+
dtype = x.dtype
|
| 44 |
+
x = x.float()
|
| 45 |
+
x = x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps)
|
| 46 |
+
return (self.weight * x).to(dtype)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PatchEmbed(nn.Module):
|
| 50 |
+
def __init__(self, args):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.proj = nn.Linear(3 * args.vision_patch_size ** 2, args.vision_dim)
|
| 53 |
+
|
| 54 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 55 |
+
return self.proj(x.flatten(1))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Attention(nn.Module):
|
| 59 |
+
def __init__(self, args):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.n_heads = args.vision_n_heads
|
| 62 |
+
self.head_dim = args.vision_dim // args.vision_n_heads
|
| 63 |
+
self.wqkv = nn.Linear(args.vision_dim, 3 * args.vision_dim)
|
| 64 |
+
self.wo = nn.Linear(args.vision_dim, args.vision_dim)
|
| 65 |
+
|
| 66 |
+
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 67 |
+
n = x.size(0)
|
| 68 |
+
q, k, v = (t.view(n, self.n_heads, self.head_dim) for t in self.wqkv(x).chunk(3, dim=-1))
|
| 69 |
+
q = apply_rotary(q, cos.to(device=x.device), sin.to(device=x.device))
|
| 70 |
+
k = apply_rotary(k, cos.to(device=x.device), sin.to(device=x.device))
|
| 71 |
+
o = F.scaled_dot_product_attention(q.transpose(0, 1), k.transpose(0, 1), v.transpose(0, 1))
|
| 72 |
+
return self.wo(o.transpose(0, 1).reshape(n, -1))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class MLP(nn.Module):
|
| 76 |
+
def __init__(self, args):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.w1 = nn.Linear(args.vision_dim, 2 * args.vision_inter_dim, bias=False)
|
| 79 |
+
self.w2 = nn.Linear(args.vision_inter_dim, args.vision_dim, bias=False)
|
| 80 |
+
|
| 81 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 82 |
+
gate, up = self.w1(x).chunk(2, dim=-1)
|
| 83 |
+
return self.w2(F.silu(gate) * up)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Block(nn.Module):
|
| 87 |
+
def __init__(self, args):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.norm1 = RMSNorm(args.vision_dim)
|
| 90 |
+
self.attn = Attention(args)
|
| 91 |
+
self.norm2 = RMSNorm(args.vision_dim)
|
| 92 |
+
self.mlp = MLP(args)
|
| 93 |
+
|
| 94 |
+
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 95 |
+
x = x + self.attn(self.norm1(x), cos, sin)
|
| 96 |
+
return x + self.mlp(self.norm2(x))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class ViT(nn.Module):
|
| 100 |
+
def __init__(self, args=ARGS):
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.rope_dim = args.vision_dim // args.vision_n_heads // 2
|
| 103 |
+
self.rope_theta = args.vision_rope_theta
|
| 104 |
+
self.patch_embed = PatchEmbed(args)
|
| 105 |
+
self.blocks = nn.ModuleList([Block(args) for _ in range(args.vision_n_layers)])
|
| 106 |
+
self.norm = RMSNorm(args.vision_dim)
|
| 107 |
+
|
| 108 |
+
def forward(self, patches: torch.Tensor, n_h: int, n_w: int) -> torch.Tensor:
|
| 109 |
+
x = self.patch_embed(patches)
|
| 110 |
+
cos, sin = get_vision_cos_sin(n_h, n_w, self.rope_dim, self.rope_theta)
|
| 111 |
+
for block in self.blocks:
|
| 112 |
+
x = block(x, cos, sin)
|
| 113 |
+
return self.norm(x)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Aligner(nn.Module):
|
| 117 |
+
def __init__(self, args=ARGS):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.downsample_ratio = args.vision_downsample_ratio
|
| 120 |
+
in_dim = args.vision_dim * self.downsample_ratio ** 2
|
| 121 |
+
self.w1 = nn.Linear(in_dim, args.dim)
|
| 122 |
+
self.w2 = nn.Linear(args.dim, args.dim)
|
| 123 |
+
|
| 124 |
+
def forward(self, x: torch.Tensor, n_h: int, n_w: int) -> torch.Tensor:
|
| 125 |
+
r = self.downsample_ratio
|
| 126 |
+
x = x.view(n_h, n_w, -1).permute(2, 0, 1)
|
| 127 |
+
x = F.pad(x, (0, -n_w % r, 0, -n_h % r))
|
| 128 |
+
x = F.unfold(x.unsqueeze(0), r, stride=r).squeeze(0).transpose(0, 1)
|
| 129 |
+
return self.w2(F.gelu(self.w1(x)))
|