Vision Transformers (ViT) typically produce outputs in the shape BATCH x N x C (e.g., BATCH x 197 x 192), where the first element is the class token and the remaining elements are spatial patches. To use GradCAM, you must provide a reshape_transform function to the GradCAM constructor to convert these patch sequences into 2D spatial images with channels in the first dimension (similar to CNNs).
Target Layer Selection:
Do not select the very last layer if the classification is performed solely on the class token, as the gradients for the spatial patches in that layer will be zero. Instead, choose a layer from a preceding attention block, such as model.blocks[-1].norm1.
# Example reshape_transform for ViT
def reshape_transform(tensor, height=14, width=14):
# tensor shape: [batch, 197, 192]
# Remove the class token (index 0) and reshape patches to 2D
result = tensor[:, 1:, :].reshape(tensor.size(0), height, width, tensor.size(2))
# Transpose to bring channels to the first dimension: [batch, channels, height, width]
result = result.transpose(2, 3).transpose(1, 2)
return result
# Initialize GradCAM with the transform
GradCAM(model=model, target_layers=target_layers, reshape_transform=reshape_transform)
# Recommended target layer
target_layers = [model.blocks[-1].norm1]