test_vit.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import re
  2. import pytest
  3. import torch
  4. from flash_attn.models.vit import vit_base_patch16_224 as flash_vit_base_patch16_224
  5. from timm.models.vision_transformer import vit_base_patch16_224
  6. @pytest.mark.parametrize("fused_mlp", [False, True])
  7. # @pytest.mark.parametrize('fused_mlp', [False])
  8. @pytest.mark.parametrize("optimized", [False, True])
  9. # @pytest.mark.parametrize('optimized', [True])
  10. def test_vit(optimized, fused_mlp):
  11. """Check that our implementation of ViT matches the timm's implementation:
  12. the output of our forward pass in fp16 should be around the same as
  13. timm' forward pass in fp16, when compared to timm's forward pass in fp32.
  14. """
  15. dtype = torch.float16
  16. device = "cuda"
  17. kwargs = {}
  18. if optimized:
  19. kwargs = dict(use_flash_attn=True, fused_bias_fc=True, fused_dropout_add_ln=True)
  20. kwargs["fused_mlp"] = fused_mlp
  21. model = flash_vit_base_patch16_224(**kwargs).to(device=device, dtype=dtype)
  22. model_ref = vit_base_patch16_224(pretrained=True).to(device=device)
  23. model_timm = vit_base_patch16_224(pretrained=True).to(device=device, dtype=dtype)
  24. model.load_state_dict(model_ref.state_dict())
  25. model.eval()
  26. model_ref.eval()
  27. model_timm.eval()
  28. torch.manual_seed(0)
  29. batch_size = 2
  30. x = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)
  31. out = model(x)
  32. out_timm = model_timm(x)
  33. out_ref = model_ref(x.float())
  34. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  35. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  36. print(f"timm fp16 max diff: {(out_timm - out_ref).abs().max().item()}")
  37. print(f"timm fp16 mean diff: {(out_timm - out_ref).abs().mean().item()}")
  38. rtol = 2 if not fused_mlp else 8
  39. assert (out - out_ref).abs().max().item() < rtol * (out_timm - out_ref).abs().max().item()