Git Product home page Git Product logo

cvt's Introduction

Introduction

This is an official implementation of CvT: Introducing Convolutions to Vision Transformers. We present a new architecture, named Convolutional vision Transformers (CvT), that improves Vision Transformers (ViT) in performance and efficienty by introducing convolutions into ViT to yield the best of both designs. This is accomplished through two primary modifications: a hierarchy of Transformers containing a new convolutional token embedding, and a convolutional Transformer block leveraging a convolutional projection. These changes introduce desirable properties of convolutional neural networks (CNNs) to the ViT architecture (e.g. shift, scale, and distortion invariance) while maintaining the merits of Transformers (e.g. dynamic attention, global context, and better generalization). We validate CvT by conducting extensive experiments, showing that this approach achieves state-of-the-art performance over other Vision Transformers and ResNets on ImageNet-1k, with fewer parameters and lower FLOPs. In addition, performance gains are maintained when pretrained on larger dataset (e.g. ImageNet-22k) and fine-tuned to downstream tasks. Pre-trained on ImageNet-22k, our CvT-W24 obtains a top-1 accuracy of 87.7% on the ImageNet-1k val set. Finally, our results show that the positional encoding, a crucial component in existing Vision Transformers, can be safely removed in our model, simplifying the design for higher resolution vision tasks.

Main results

Models pre-trained on ImageNet-1k

Model Resolution Param GFLOPs Top-1
CvT-13 224x224 20M 4.5 81.6
CvT-21 224x224 32M 7.1 82.5
CvT-13 384x384 20M 16.3 83.0
CvT-21 384x384 32M 24.9 83.3

Models pre-trained on ImageNet-22k

Model Resolution Param GFLOPs Top-1
CvT-13 384x384 20M 16.3 83.3
CvT-21 384x384 32M 24.9 84.9
CvT-W24 384x384 277M 193.2 87.6

You can download all the models from our model zoo.

Quick start

Installation

Assuming that you have installed PyTorch and TorchVision, if not, please follow the officiall instruction to install them firstly. Intall the dependencies using cmd:

python -m pip install -r requirements.txt --user -q

The code is developed and tested using pytorch 1.7.1. Other versions of pytorch are not fully tested.

Data preparation

Please prepare the data as following:

|-DATASET
  |-imagenet
    |-train
    | |-class1
    | | |-img1.jpg
    | | |-img2.jpg
    | | |-...
    | |-class2
    | | |-img3.jpg
    | | |-...
    | |-class3
    | | |-img4.jpg
    | | |-...
    | |-...
    |-val
      |-class1
      | |-img5.jpg
      | |-...
      |-class2
      | |-img6.jpg
      | |-...
      |-class3
      | |-img7.jpg
      | |-...
      |-...

Run

Each experiment is defined by a yaml config file, which is saved under the directory of experiments. The directory of experiments has a tree structure like this:

experiments
|-{DATASET_A}
| |-{ARCH_A}
| |-{ARCH_B}
|-{DATASET_B}
| |-{ARCH_A}
| |-{ARCH_B}
|-{DATASET_C}
| |-{ARCH_A}
| |-{ARCH_B}
|-...

We provide a run.sh script for running jobs in local machine.

Usage: run.sh [run_options]
Options:
  -g|--gpus <1> - number of gpus to be used
  -t|--job-type <aml> - job type (train|test)
  -p|--port <9000> - master port
  -i|--install-deps - If install dependencies (default: False)

Training on local machine

bash run.sh -g 8 -t train --cfg experiments/imagenet/cvt/cvt-13-224x224.yaml

You can also modify the config parameters from the command line. For example, if you want to change the lr rate to 0.1, you can run the command:

bash run.sh -g 8 -t train --cfg experiments/imagenet/cvt/cvt-13-224x224.yaml TRAIN.LR 0.1

Notes:

  • The checkpoint, model, and log files will be saved in OUTPUT/{dataset}/{training config} by default.

Testing pre-trained models

bash run.sh -t test --cfg experiments/imagenet/cvt/cvt-13-224x224.yaml TEST.MODEL_FILE ${PRETRAINED_MODLE_FILE}

Citation

If you find this work or code is helpful in your research, please cite:

@article{wu2021cvt,
  title={Cvt: Introducing convolutions to vision transformers},
  author={Wu, Haiping and Xiao, Bin and Codella, Noel and Liu, Mengchen and Dai, Xiyang and Yuan, Lu and Zhang, Lei},
  journal={arXiv preprint arXiv:2103.15808},
  year={2021}
}

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

cvt's People

Contributors

awindsor avatar lmk123568 avatar microsoft-github-operations[bot] avatar microsoftopensource avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cvt's Issues

Regarding the FLOPs

Hi,

I wonder how you computed the FLOPs. I used FlopCountAnalysis from fvcore.nn and it is larger than you reported.

bugs when eval

2021-06-26 22:30:03,174:[P:3190309]:Rank[0/5] => switch to eval mode
2021-06-26 22:30:03,175:[P:3190312]:Rank[3/5] => Epoch[0]: train end, duration: 8942.97s
2021-06-26 22:30:03,176:[P:3190312]:Rank[3/5] => Epoch[0]: validate start
2021-06-26 22:30:03,176:[P:3190312]:Rank[3/5] => switch to eval mode
Traceback (most recent call last):
  File "tools/train.py", line 211, in <module>
    main()
  File "tools/train.py", line 153, in main
    args.distributed
  File "/python3.6/site-packages/torch/autograd/grad_mode.py", line 26, in decorate_context
    return func(*args, **kwargs)
  File "/CvT/tools/../lib/core/function.py", line 133, in test
    loss = criterion(outputs, y)

22k model

Hi,thanks for your work, could you release the 22k model?

How to calculate the flops of the model?

Hello, thanks for the great work, how to calculate the flops of the model. I have noticed that you report the flops of transformer based model, but I only found some tools of cnn models.

code mismatch with the theory

Hi All,

Thanks for providing the code.
I come across the mismatch between the code and the theory you proposed for the transformer block. The paper says "Instead, we propose to replace the original position-wise linear projection for Multi-Head Self-Attention (MHSA)", but lines 198-200 in https://github.com/leoxiaobin/CvT/blob/main/lib/models/cls_cvt.py still projects q,k,v through linear layers. Have you missed an else statement there? why are you projecting q,k,v values twice?

Please correct me if I have misunderstood it.

Thanks,
Basavaraj

Hyperparameters

Hi, thanks for this repo!
Could you please share the configuration for ImageNet experiments? I suppose the config file here is not the one used for ImageNet, or at least doesn't reflect what is written in the paper (please correct me if I'm wrong).
Many thanks!

As for Cifar10 or Cifar100

请问有适合关于Cifar10 或者Cifar100的模型 SPEC吗?

Is there a model SPEC for Cifar10 or Cifar100?

Thank you very much!

What's the accuracy of CvT-13 without pre-trained on CIFAR10

Hi,

What's the accuracy of CvT-13 without pre-trained on CIFAR10? Mine is only 79.6. Would you like to told me yours? And what are the hyper-parameters for fine-tuning on CIFAR10 without pre-trained ? I can't find it in detail in the paper.

Thanks.

精度

你好,请问我用imagenet1k进行训练时候,test精度好像完全没有变化,一直保持0.1左右,这是什么情况呢?

Recommend change the code

recommend change the following code int lib/models/cls_cvt.py:611
x = torch.squeeze(x) change to x = torch.squeeze(x, dim=1)
Otherwise, an error will occur when bachsize = 1

recommended torch version may be wrong

After installing torch 1.7.1, I got an ERROR:
ModuleNotFoundError: No module named 'torch.fx
What I find on stackoverflow is that torch.fx was added in PyTorch 1.8.0., so may be recommended version is wrong?

the flops computed by this code don't match that in the paper

2021-07-20 16:52:11,694:[P:33903]:Rank[0/4] == get_model_complexity_info by ptflops ==
2021-07-20 16:52:11,796:[P:33903]:Rank[0/4] => FLOPs: 4.06 GMac, params: 20.0 M
2021-07-20 16:52:11,796:[P:33903]:Rank[0/4] == get_model_complexity_info by ptflops ==

while the paper shows the flops of CvT-13 is 4.5G

About Cls_cvt.py

I want to konw why there isn't any to the function get_cls_model and compute_macs

model release

Hi,would you like to provide a classification model on ImageNet22k?

NAN loss

Hi, I just trained cvt13-224 model with the default settings, but got NAN loss after several epochs.
Does anyone have trained this model sucessfully?
图片

About the pretrained model

I use the pretrained model CvT-13-224x224-IN-1k.pth, and test on Imagenet as the guide, but the result is terrible
"TEST: Loss 8.5690 Error@1 98.926% Error@5 97.844% Accuracy@1 1.074% Accuracy@5 2.156%"

Does anyone else have tested? Why is it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.