Skip to content

Vision Transformer

Full source in examples/vit.rs. Run it with cargo run --release --example vit.

What This Shows

  • Combining trainable Tensor parameters (cls_token, pos_emb), sub-modules (TransformerBlock), and plain config fields (patch, heads, head_dim) in one #[module] struct
  • Patchifying images with reshape and permute
  • 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.

let qkv = self
    .qkv
    .forward(&h)
    .reshape(&[b, t, 3, self.heads, self.head_dim])
    .permute(&[2, 0, 3, 1, 4]);

let attn = nn::scaled_dot_product_attention(
    &qkv.index(0),
    &qkv.index(1),
    &qkv.index(2),
    None,
)
.permute(&[0, 2, 1, 3])
.reshape(&[b, t, dim]);