vimod
What is this?
vimod provides clean, modular building blocks for custom Vision Transformers in PyTorch. No model zoos, no pretrained weights, no heavy frameworks - just readable, production-grade components designed to be mixed, matched, and hacked on.
Quickstart
pip install vimod
Examples
See full example codes in examples.
Transformer Block with Pre-Norm and DropPath
class Block(nn.Module):
def __init__(self, dim, heads, drop_path=0.0):
super().__init__()
self.attn = Attention(dim, heads, pre_norm_layer=nn.LayerNorm)
self.mlp = MLP(dim, pre_norm_layer=nn.LayerNorm)
self.drop_path = DropPath(drop_path)
def forward(self, x):
x = x + self.drop_path(self.attn(x))
x = x + self.drop_path(self.mlp(x))
return x
ViT Architecture with Patch Embedding, Positional Embedding, and Classification Head
class ViT(nn.Module):
def __init__(self, image_size, patch_size, dim, depth, heads, num_classes):
super().__init__()
grid = image_size // patch_size
self.patch_embed = PatchEmbed(3, dim, patch_size)
self.pos_embed = SinCosPosEmbed(dim, grid)
self.blocks = Stack(Block, depth=depth, dim=dim, heads=heads, drop_path=0.1)
self.head = MeanPoolHead(dim, num_classes)
def forward(self, x):
x = self.patch_embed(x)
x = self.pos_embed(x)
x = self.blocks(x)
return self.head(x)
Optimizer with proper Weight Decay Handling
optimizer = Optimizer(model, torch.optim.AdamW, lr=3e-4, weight_decay=0.05)
Modules
| Module |
What it does |
PatchEmbed |
Projects image patches into token embeddings. |
PrefixTokens |
Prepends learned prefix tokens (e.g., class or register tokens). |
LearnedAbsolutePosEmbed |
Adds learned absolute position embeddings to tokens. |
SinCosPosEmbed |
Adds fixed 2D sinusoidal position codes to tokens. |
RoPE2D |
Applies axial 2D rotary position embeddings to queries and keys. |
Attention |
Supports MHA, GQA, pre-norm, QK-norm, and RoPE integration. |
MLP / SwiGLU |
Feed-forward blocks with optional pre-norm and activation layers. |
MeanPoolHead |
Mean-pools spatial tokens and projects to output classes. |
DropPath |
Applies per-sample stochastic depth (drop path). |
Stack |
Repeats any block class for a specified depth. |
Optimizer |
Wraps any torch.optim class with automatic weight-decay grouping. |
Changelog
0.1.0
- Initial release: PatchEmbed, LearnedAbsolutePosEmbed, SinCosPosEmbed, RoPE2D, Attention, MLP, SwiGLU, MeanPoolHead, PrefixTokens, DropPath, Stack, Optimizer
⭐ Support the Project
Find it useful? Drop a star ⭐ to help others discover it.
License
The project is licensed under the Apache License 2.0.