Vision Transformer¶
Full source in examples/vit.rs. Run it with cargo run --release --example vit.
What This Shows¶
- Combining trainable
Tensorparameters (cls_token,pos_emb), sub-modules (TransformerBlock), and plain config fields (patch,heads,head_dim) in one#[module]struct - Patchifying images with
reshapeandpermute - Running multi-head attention via
nn::scaled_dot_product_attention
Model Structure¶
Plain config fields like usize pass through #[module] automatically without skip annotations.
#[module]
struct TinyViT {
patch_proj: Linear,
cls_token: Tensor,
pos_emb: Tensor,
block: TransformerBlock,
norm: LayerNorm,
head: Linear,
patch: usize,
}
Multi-Head Self-Attention¶
Inside TransformerBlock::forward, the fused QKV projection splits cleanly into heads and flows into nn::scaled_dot_product_attention.