r/MachineLearning • • 14d ago

Discussion Why are ViTs so popular? [D]

I deploy CNN + Attention stack models on edge devices, to great effect. Taking advantage of convs and reducing the spatial dimensionality makes all the sense in the world to me.

Having vanilla ViTs learning the inductive biases from scratch makes none to me. Is it really a case of "because I can"? Avoiding padding along borders is the only advantage I can see to a tokenizer stem, and that has never been a huge issue to me.

Am I missing something that has people reaching for ViTs instead of hybrid models for e.g. SSL/foundation models?

In my mind it's just a case of people using the status quo, and more of a historical accident that these models have become so popular. Iirc levit showed data/time efficiency boosts with a convolutional stem. I just don't work on the same datasets or tasks that most research does, so I'm genuinely curious if anyone else thinks vanilla ViTs seem excessive. Guess compute is cheap and the answer would just be distillation.

120 Upvotes

70 comments sorted by

9

u/Ok-Introduction9593 14d ago

A lot of it just comes down to tooling unification. When your entire infra stack is heavily tuned for Transformers - FlashAttention, tensor parallelism, all that - it's way easier to just patchify images and push them through the same pipeline than to balance hybrid bottlenecks across GPUs

3

u/terrrp 14d ago

That's a good point, probably the correct answer. Most foundational vision models are probably for VLM integration, or at least that is at the back of the researchers' mind.

140

u/impatiens-capensis 14d ago

A ViT with enough attention heads can mathematically express any convolutional layer. A CNN fixes you to that prior ahead of time, but given enough data it might not be the correct one. The reason they are so popular is because there are large ViTs trained on an enormous amount of data so you don't have to do it. But on a small edge device, a small ViT might not have enough params to express what you need so a CNN holds that prior for you.

50

u/Ok-Introduction9593 14d ago

Btw there's a cool paper from DeepMind called ConvNets Match Vision Transformers at Scale where they showed the issue isn't really with convs themselves but how we used to train them. On a huge dataset modern ConvNets hit the same performance, it's just that transformers are easier to hook up with language models

5

u/fordat1 13d ago

This. ViTs have an advantage because the crowd is there sharing findings on that as a base

9

u/SlayahhEUW Researcher 13d ago

Convnets are a strict subset of ViTs, this has been proven. You can always reach equal or better results with ViTs, it's just that they are computationally more expensive so they might not be relevant for the task at hand.

1

u/DooDooSlinger 8d ago

They are not even much more expensive. These days with efficient attention kernels etc and hardware that is increasingly targeting attention computations, they are incredibly fast as well.

4

u/adrianchase_alt 14d ago

idt this is true. if youre talking about convnext the key was increasing the throughput near the middle of the model by increasing hidden dimension like an MLP rather than pooling or shrinking it as with typical resnets or cnns beforehand.

0

u/[deleted] 13d ago

[deleted] — view deleted comment

1

u/DooDooSlinger 8d ago

The concept has existed for far longer than fb even existed and imagenet, the first really performant and trainable one, was created by the guy who later joined fb

2

u/impatiens-capensis 13d ago

You need to qualify this, because it's not a general phenomenon. That paper only demonstrates this for ImageNet classification. So for a single task on a single dataset, the architectures are matched at scale. 

1

u/Ok-Introduction9593 8d ago

Fair call, I probably should've qualified that. I mainly brought it up because for OP's kind of edge perception tasks, it shows convs aren't fundamentally broken. For video, generative stuff, or heavy multimodal models, ViTs are pretty much in a different league

1

u/DooDooSlinger 8d ago

This is a 2023 paper that is outdated beyond words. Trust me if convnets were as good as vits, they would be used a lot more. There's a reason we switched from unets to vits after sdxl. They just aren't as good at modeling complex long range relationships. You can finetune sdxl as much as you want on as much data as every subsequent vit, you won't match them.

4

u/Mr_Fragwuerdig 14d ago

That's a theoretical argument, which doesn't bring you far. ViTs or CNNs, neither are superior to each other, each has their advantage. But ViT+CNN (hybrid) is the strongest architecture.

Overall, if you don't care about efficiency, ViTs are the easy way to go. However a ViT will usually lose against a hybrid model in speed-accuracy tradeoff.

And if you look how Dino doesn't generalize to any unseen data, completely deteriorating, maybe a bit of generalization in Foundation models would be reasonable. After all, we can't train on all possibilities of what a camera could capture.

2

u/Honest-Finish3596 11d ago

Dino does generalise very well? I used dinov2 for a lot of different things it wasn't trained on at all a few years back. It's a very good general purpose extractor for visual features.

1

u/Mr_Fragwuerdig 11d ago

To a certain degree yes, but performance can drop significantly for out-of-distribution data, on which it did not train.

2

u/Honest-Finish3596 11d ago

Sure but that's obvious, it would have to be actual magic for anything else to be true.

It works way better on OOD data than the pretrained ImageNet Pytorch has which is what everyone used before that.

1

u/Mr_Fragwuerdig 11d ago

That's true.

1

u/DooDooSlinger 8d ago

I don't think this is true, the only paper that kinda combines them with decent perf is EfficientViT as far as I know but with extensive training a vit can model anything a conv can - efficientvit is an exception because it used linear attention which is much poorer at modeling local patterns, rather global semantic dependencies, but is much faster

1

u/Mr_Fragwuerdig 7d ago

There are literally dozens of papers in that area. And EfficientViT is a strong between them, but not the best. And ViTs and other older backbones are beaten in Speed-Accuracy tradeoff with a clear margin. And CoatNet has shown how helpful the combination of convolution and attention is, also on bigger datasets. But yeah, nobody has trained a hybrid backbone on dino-level training data, so we can't know how hybrids would perform.

5

u/AuspiciousApple 14d ago

Any universal function approximator is a universal function approximator 

7

u/parlancex 13d ago edited 13d ago

Indeed. Why not just build the world's widest MLP and call it a day? It IS a universal function approximator after all /s. Efficiency matters.

A CNN fixes you to that prior ahead of time, but given enough data it might not be the correct one.

Translation equivariance is an extremely mild prior that is very obviously valid for natural signals and images, at the highest resolution levels / before down-sampling or patching at least.

2

u/Honest-Finish3596 11d ago

CNNs are not just translation equivariant, they also have a strong bias to local textural features.

1

u/idontcareaboutthenam 12d ago

I think that the main drawback of CNNs is that need a really big depth until different parts of the image start exchanging information. To grow the receptive field of a CNN neuron you need to stack many convolutions, while the patches of a ViT can attend to each other from the very first attention layer

1

u/DooDooSlinger 8d ago

More than number of heads, positional encodings reduce spectral bias massively and allow modeling the high frequency spatial relationships that CNN's are good at, except also being able to model complex long range relationships that CNN's cannot

9

u/RedEyed__ 14d ago

Hello!
I had the same question, and I also use CNN + transformers on edge devices.

My models are tiny, I tried ViTs and never was able to beat CNNs.
In my understanding, ViTs scales much better than CNNs, but CNNs are better below a certain point of model size.

5

u/Mr_Fragwuerdig 14d ago

Pure scaled CNNs can also be better than ViTs.

4

u/AuspiciousApple 14d ago

I agree on tiny models. I also haven't really seen gains from adding transformer/attn to the CNN 

2

u/Honest-Finish3596 11d ago edited 11d ago

Very rarely do people have the dataset size and amount of compute for training ViTs to work well. They picked up popularity in the era of 1% improvements to ImageNet scores being what very well-financed labs pursued, prior to LLMs sucking the air out of that.

They only make sense for general purpose pretrained models like Dinov2 or CLIP.

8

u/sjdubya 14d ago

How big does the dataset need to be relative to the model in order to fully take advantage of ViTs? are there any good scaling laws on this?

2

u/Honest-Finish3596 11d ago

Yes there were a lot of papers on this 5-6 years ago. The answer is "big" for pretraining. However they were not called scaling laws back then.

1

u/sjdubya 10d ago

If you have any good ones to recommend I'd appreciate it

41

u/longgamma 14d ago

If you have a big dataset, vit will outperform CNN's. Transformers don't have much inductive bias so technically they need more data

32

u/Distinct-Cattle1088 14d ago

That is not necessarily true. With enough training data CNNs can match the performance of vision transformer. https://arxiv.org/abs/2310.16764
The advantage of vision transformer is that their architecture suits pretraining mechanisms like MAE. Also they encode information in images in token which can then be used by an LLM. For a pure vision classification task a CNN with enough training data should perform just as well.

0

u/impatiens-capensis 10d ago

CNNs can match the performance of vision transformer.

... on ImageNet classification.

I'd want to see more convincing data to accept that as a general claim. I wouldn't expect a CNN to match a transformer on dense tasks that require long range communication between regions, like in monocular depth estimation or something.

8

u/murrdpirate 14d ago

The inductive bias of convolution is indeed useful for limiting the number of parameters without too much sacrifice in accuracy.

However, it is a less flexible representation. Some images may have more complex relationships between image regions that convolution doesn't fit well.

For edge devices where you are probably dealing with a fairly narrow task and/or limited training data, CNNs may be better. For general vision and/or huge training data sets, a ViT can potentially fit the data better.

3

u/Mr_Fragwuerdig 14d ago

It's not that CNNs are better, it's that hybrid models are better than ViTs.

4

u/Chocolate_Pickle 14d ago

CNN + Attention sounds like the smart play.

I'm having a hard time picturing why early layers would ever benefit from long-range information.

4

u/Mr_Fragwuerdig 14d ago

Exactly. And cutting down an Image to 16x16 blocks instantly, is just madness.

2

u/bikeranz 14d ago

At >= 768 dim, 16x16 patchification is (potentially) lossless.

1

u/Mr_Fragwuerdig 14d ago

What about an object between patches? Coatnet for example showed how important overlapping patch embeddings (convs) are.

1

u/bikeranz 14d ago

I was responding to "cutting down", since that informally implies information loss. Object placement is irrelevant in this sense.

2

u/Mr_Fragwuerdig 14d ago

That is true. But this cutting down, as explained, has another problem: overlapping objects between patches.

1

u/williams_mia45 9d ago

That late attention stage is the useful split: convolutions build local features first, then attention mixes distant ones across far fewer spatial positions.

10

u/sqweeeeeeeeeeeeeeeps 14d ago

You can view keys & values as data-dependent weights, whereas CNNs and traditional MLPs are learned fixed weights

1

u/ProfMasterBait 14d ago

Hi, is there more on this perspective?

1

u/idontcareaboutthenam 12d ago

The gist of it is that you can view the attention pattern as a mechanism that adapts the weights of the value matrix, and the attention pattern is dependent on the input data, so the operation is effectively a data-dependent tensor multiplication.

This paper links transformers to an older computational model that was actually modifying network weights on the fly: https://arxiv.org/abs/2102.11174

1

u/ProfMasterBait 12d ago

Ok that makes sense. Thanks

1

u/AuspiciousApple 14d ago

What form of attention are you using? "Plain" CNN works quite well in my experience, SE blocks are good, too, but do you use transformer style attn in your cnns?

1

u/terrrp 14d ago

I use standard pre norm MHA, usually around 512 channels at 32x reduction, usually with a qkv pool at end.

I see huge gains with the attention stack

1

u/AuspiciousApple 14d ago

Interesting, I'll give it a shot. I have played around with the hybrid versions of mnv4 as well as custom simple ViT/transformer blocks at the highest reduction, but it never worked better on my data than the plain versions.

Do you use multiple MHA blocks, but not MLPs/transformer style blocks?

1

u/Mr_Fragwuerdig 14d ago

Probably. They are called hybrid models.

4

u/moschles 14d ago

OP, Have you read this paper yet?

Masked Autoencoders Are Scalable Vision Learners

Kaiming He;y Xinlei Chen; Saining Xie; Yanghao Li; Piotr Dollar; Ross Girshick

Facebook AI Research (FAIR)

arXiv:2111.06377v3 [cs.CV] 19 Dec 2021

2

u/Mr_Fragwuerdig 14d ago

With lots of training data, ViTs can match conv/hybrid models. And if you only care about accuracy, there is not a strong reason to switch to hybrids. Hybrids are however always the best in speed-accuracy tradeoff. We just can't test that well, because the foundation models are mostly pure ViTs. And the general interest in efficiency is not very big in companies that create insanely big foundation models.

And the only big advantage of ViTs is the things you can do with the tokens. That makes it quite flexible.

2

u/glowing_danio_rerio 14d ago

i also think the move to not building symmetries into the models is insane but what do I know gpu go brr

1

u/hoaeht 14d ago

with enough data they tend to perform better. As they are also much more inefficient, it's probably not relevant for your edge deployment. Also check receiptive field as it can make a huge difference for some use cases

1

u/NanoAlpaca 13d ago

CNN + Attention heads are a great combination on the edge. ViTs can be great, if you are aiming for the highest possible quality and have lots of data and don’t care about latency. And they can look great from a naive flops/quality perspective, when people are just counting flops and not considering that 3x3 convs are usually efficiency monsters on edge hardware, while windowed attention or things like that might look theoretical great, but usually does not run efficiently on edge hardware.

1

u/Honest-Finish3596 11d ago

ViTs have an inductive bias, they're not fully connected networks.

1

u/AkiDenim 9d ago

I think one thing may be scalability
But since ViTs are VERY data hungry in most practical sized engineering tasks CNNs are enough

1

u/pm_me_your_pay_slips ML Engineer 14d ago

There are things a convnet can't represent that a ViT can. But on the contrary everything that can be represented by a convnet can be represented by a ViT.

1

u/Mr_Fragwuerdig 14d ago

That's why conv+att.

1

u/Dihedralman 14d ago

Transformers have larger capacity and thus can captured more nuanced relationships. 

The simplest way to think about the inductive bias is that convolution gives importance to the relationship of nearby pixels out the gate, while attention allows the model to consider a greater range of possibilities. 

In CNNs you are essentially training a filter blocks while ViTs are using patch relations. 

Most applications use large pretrained models for a general purpose setup to scale. 

ViTs are likely excessive for what you do. 

0

u/qu3tzalify Student 14d ago edited 14d ago

Transformers are also one of the most optimized for architecture in modern hardware. By using ViT you unify the architecture and optimizations between the vision encoders and the language backbone.

Edit: highlighted "optimized for" because I feel like readers think I'm saying they are the most optimized.

4

u/Dihedralman 14d ago

ViTs are less performant by quite a bit and don't use a language backbone. They can but that isn't the architecture. 

Look into the underlying matrix operations and remember that images aren't sparse. 

1

u/qu3tzalify Student 14d ago

I didn't say ViT use a language backbone, I said that they use the same architecture. For VLMs that means you can optimize the hardware for the Transformer architecture and reap the benefits for both the vision encoders and the language backbone.

Look into the underlying matrix operations and remember that images aren't sparse. 

You can optimize the kernels a lot if you zoom out of a simply a chain of matrix operations.

1

u/Mr_Fragwuerdig 14d ago

This is only true for huge transformers, because they utilize GEMM well (though they were never optimized for it). Attention with an Embedding size < 512 does not map well to GPU.

The unification between vision and language is rather the strong reason.

1

u/qu3tzalify Student 14d ago

How would you define huge? 1B and above or larger?

0

u/Mr_Fragwuerdig 14d ago

It depends on the Embedding size, as I wrote.

1

u/norpadon 13d ago

Hardware doesn’t care about transformers vs CNNs. But implementing efficient inference and training for transformers is much easier

0

u/norpadon 13d ago edited 13d ago

Transformers are neural networks which repeat the same block many times, processing the input of the same shape over and over again

It makes them incredibly convenient to train (you have very few hyperparameters whose behaviour is very predictable and well-studied), easy to scale, and it makes inference very easy to optimize. Also, their flops are linearly related to the number of parameters.

CNNs, on the other hand, are a huge mess because of downsampling. If you want to make a scaling ladder for a CNN, which layers at which resolutions do you scale and at which rates?

And what should you scale, parameters or flops? How do you implement muP for CNNs? How do you adapt Muon? How do you do pipeline parallelism if different layers have very different latency profiles?