[Çeviri] Vision Transformer için Görsel Rehber (A Visual Guide to Vision Transformers)
(discuss.pytorch.kr)-
ℹ️ xguru’nun tanıttığı Visual Transformers görsel rehberi yazısını gördükten sonra, yazarı Data Scientist ve Software Engineer olan Dennis Turp’un izniyle, onun kaleme aldığı Vision Transformer(ViT) için görsel açıklama yazısını (A Visual Guide to Vision Transformers) çevirdim.
-
Vision Transformer(ViT), Transformer’ı CV(Computer Vision) alanına uygulayan ve nesne tespiti ile görüntü sınıflandırma gibi alanlarda yüksek performans gösteren bir modeldir. Özellikle görüntülerden özellik(feature) çıkarmak için bir Visual Encoder olarak sıkça kullanılır.
-
Orijinal metindeki açıklamalar kısa olduğundan anlaşılması zor olabilecek yerlerde, anlaşılmayı kolaylaştırmak için bazı notlar eklendi.
Vision Transformer(ViT) için Görsel Açıklama
Bu yazı, görüntü sınıflandırma görevlerinde son teknoloji (SotA, State-of-the-Art) performans gösteren derin öğrenme modeli sınıfı Vision Transformers(ViTs) için görsel bir açıklamadır. Vision Transformer, başlangıçta doğal dil işleme (NLP) için tasarlanan Transformer mimarisinin görüntü verisine uygulanmış hâlidir. Bu yazıda, verinin akışını anlamaya yardımcı olan görselleştirmeler ve basit açıklamalarla, Vision Transformer’ın nasıl çalıştığını anlamanıza yardımcı olunacaktır. (:pytorch::kr:: Burada kaydırmalı anlatımı vermek zor olduğu için bunun yerine görsel ekran görüntüleri kullanılmıştır. Orijinal metne birlikte bakmanız faydalı olabilir.)
> This is a visual guide to Vision Transformers (ViTs), a class of deep learning models that have achieved state-of-the-art performance on image classification tasks. Vision Transformers apply the transformer architecture, originally designed for natural language processing (NLP), to image data. This guide will walk you through the key components of Vision Transformers in a scroll story format, using visualizations and simple explanations to help you understand how these models work and how the flow of the data through the model looks like.
0. Veriye bakalım / Lets start with the data
Tıpkı klasik evrişimli sinir ağları (CNN) gibi, Vision Transformer da denetimli öğrenme (Supervised Learning) yöntemiyle eğitilir. Yani model, görüntüler ve onlara karşılık gelen etiketlerden oluşan bir veri kümesi üzerinde eğitilir.
> Like normal convolutional neural networks, vision transformers are trained in a supervised manner. This means that the model is trained on a dataset of images and their corresponding labels.
1. Tek bir veri noktasına odaklanalım / Focus on one data point
Vision Transformer’ın içeride nasıl çalıştığını daha iyi anlamak için, önce yalnızca tek bir veriye (batch size 1) odaklanalım. Ve şu soruyu soralım: Bu veri, Transformer’ın girdi olarak kullanabilmesi için nasıl hazırlanır (ön işlenir)?
> To get a better understanding of what happens inside a vision transformer lets focus on a single data point (batch size of 1). And lets ask the question: How is this data point prepared in order to be consumed by a transformer?
2. Şimdilik etiketi bir kenara bırakalım / Forget the label for the moment
Etikete daha sonra, daha anlamlı bir bağlamda döneceğiz. Şimdilik elimizde yalnızca tek bir görüntü kaldığını düşünelim.
> The label will become more relevant later. For now the only thing that we are left with is a single image.
3. Görüntüyü patch’lere ayırmak / Create patches of the image
Tüm görüntüyü, Transformer içinde kullanılabilecek şekilde hazırlamak için eşit boyutlu p x p patch’lere ayırırız.
> To prepare the image for the use inside the transformer we divide the image into equally sized patches of size p x p.
4. Görüntü patch’lerini düzleştirmek / Flatting of the image patches
Patch’ler, p' = p² x c boyutunda vektörlere düzleştirilir (flatten). Burada p patch’in bir kenar uzunluğu, c ise kanal sayısıdır. (:pytorch::kr:: Örneğin RGB görüntülerde kanal sayısı 3’tür.)
> The patches are now flattened into vectors of dimension p'= p²*c where p is the size of the patch and c is the number of channels.
5. Patch’lerden embedding oluşturmak / Creating patch embeddings
Önceki adımda görüntü patch’lerinden oluşturulan bu vektörler, doğrusal bir dönüşümle encode edilir. Ortaya çıkan Patch Embedding Vector, sabit d boyutuna sahiptir.
> These image patch vectors are now encoded using a linear transformation. The resulting Patch Embedding Vector has a fixed size d.
6. Tüm patch’leri embedding’e dönüştürmek / Embedding all patches
Tüm görüntü patch’lerini sabit boyutlu vektörlere dönüştürdüğümüzde, elimizde n x d boyutunda bir dizi kalır. Burada n görüntü patch’i sayısı, d ise tek bir patch embedding boyutudur.
> Now that we have embedded our image patches into vectors of fixed size, we are left with an array of size n x d where n is the the number of image patches and d is the size of the patch embedding
7. Sınıflandırma token’ı (CLS) eklemek / Appending a classification token
Modeli etkili biçimde eğitmek için, patch embedding’lere ek olarak sınıflandırma token’ı (CLS token) adı verilen bir vektör ekleriz. Bu vektör, sinir ağının öğrenilebilir bir parametresidir ve rastgele başlatılır. Not olarak, yalnızca bir CLS token vardır ve tüm veriler için aynı vektörü ekleriz. (:pytorch::kr:: Buraya kadar geldiğimizde, n adet patch embedding’e CLS token eklenmiş olur; böylece embedding boyutu d olan (n+1) x d boyutunda bir yapı elde ederiz.)
> In order for us to effectively train our model we extend the array of patch embeddings by an additional vector called classification token (cls token). This vector is a learnable parameter of the network and is randomly initialized. Note: We only have one cls token and we append the same vector for all data points.
8. Konumsal embedding vektörleri ekleme / Add positional embedding Vectors
Şu ana kadar patch embedding’lerde herhangi bir konum bilgisi yoktur. Bu sorunu, tüm patch embedding’lere öğrenilebilir ve rastgele başlatılan bir Konumsal Embedding Vektörü (Positional Embedding Vector) ekleyerek çözeriz. Ayrıca, daha önce eklediğimiz sınıflandırma token’ına (CLS token) da böyle bir konumsal vektör ekleriz. (:pytorch::kr:: Transformer’da Positional Encoding değerleri vektöre 'eklenir'. Bu nedenle vektörün boyutu değişmez.)
> Currently our patch embeddings have no positional information associated with them. We remedy that by adding a learnable randomly initialized positional embedding vector to all our patch embeddings. We also add a such a positional embedding vector to our classification token.
9. Transformer’a giriş / Transformer Input
Konumsal embedding vektörleri eklendikten sonra elimizde (n+1) x d boyutunda bir dizi kalır. Bu dizi Transformer için giriş olacaktır; bunu sonraki adımlarda daha ayrıntılı açıklayacağız.
> After the positional embedding vectors have been added we are left with an array of size (n+1) x d. This will be our input for the transformer which will be explained in greater detail in the next steps.
10.1. Transformer: QKV oluşturma / QKV Creation
Transformer giriş patch embedding vektörleri, doğrusal olarak birden çok büyük vektöre gömülür. Bu yeni vektörler daha sonra eşit boyutlu üç parçaya ayrılır. Bunlar sırasıyla Q, sorgu (Query) vektörü, K, anahtar (Key) vektörü ve V, değer (Value) vektörüdür. Bu vektörlerin her birinden (n+1) adet elde ederiz.
> Our transformer input patch embedding vectors are linearly embedded into multiple large vectors. These new vectors are than separated into three equal sized parts. The Q - Query Vector, the K - Key Vector and the V - Value Vector . We will have (n+1) of a all of those vectors.
10.2. Transformer: attention score hesaplama / Attention Score Calculation
Önce attention skoru A’yı hesaplamak için tüm sorgu vektörleri Q ile tüm anahtar vektörleri K’yı çarparız.
> To calculate our attention scores A we will now multiply all of our query vectors Q with all of our key vectors K.
10.3. Transformer: attention score matrisi / Attention Score Matrix
Böylece attention score matrisi A’yı elde ettikten sonra, her satırın toplamı 1 olacak şekilde tüm satırlara softmax fonksiyonunu uygularız.
> Now that we have the attention score matrix A we apply a softmax function to every row such that every row sums up to 1.
10.4. Transformer: toplanmış bağlamsal bilgi hesaplama / Aggregated Contextual Information Calculation
İlk patch embedding vektörü için toplanmış bağlamsal bilgiyi (aggregated contextual information) hesaplamak amacıyla attention matrisinin ilk satırına odaklanırız. Buradaki değerleri değer vektörleri V için ağırlık olarak kullanır ve ilk görüntü patch embedding’i için toplanmış bağlamsal bilgi vektörünü (aggregated vector) üretiriz.
> To calculate the aggregated contextual information for the first patch embedding vector. We focus on the first row of the attention matrix. And use the entires as weights for our Value Vectors V. The result is our aggregated contextual information vector for the first image patch embedding.
10.5. Transformer: her patch için toplanmış bağlamsal bilgi / Aggregated Contextual Information for every patch
Attention score matrisinin diğer satırları için de aynı süreci tekrarlarız ve sonuçta N+1 adet toplanmış bağlamsal bilgi vektörü elde ederiz. Yani her patch için bir tane (=N adet) ve sınıflandırma token’ı (CLS Token) için bir tane (=1 adet). Bu aşama, ilk Attention Head’in tamamlandığı adımdır.
> Now we repeat this process for every row of our attention score matrix and the result will be N+1 aggregated contextual information vectors. One for every patch + one for the classification token. This steps concludes our first Attention Head.
10.6. Transformer: multi-head attention / Multi-Head Attention
(Transformer’ın) multi-head attention yapısıyla çalıştığımız için, farklı bir QKV eşlemesiyle 10.1’den 10.5’e kadar olan tüm süreci tekrarlarız. Yukarıdaki görselde açıklama amacıyla 2 head varsayılmıştır, ancak tipik olarak bir ViT çok daha fazla head’e sahiptir. Sonuçta birden fazla toplanmış bağlamsal bilgi vektörü (Multiple Aggregated Contextual Information Vectors) oluşur.
> Now because we are dealing multi head attention we repeat the entire process from step 10.1 - 10-5 again with a different QKV mapping. For our explanatory setup we assume 2 Heads but typically a VIT has many more. In the end this results in multiple Aggregated contextual information vectors.
10.7. Transformer: son attention katmanı adımı / Last Attention Layer Step
Bu şekilde oluşturulan birden çok head üst üste yığılır ve patch embedding’lerimizle aynı boyutta olan d boyutunda vektörlere eşlenir.
> These heads are stacked together and are mapped to vectors of size d which was the same size as our patch embeddings had.
10.8. Transformer: Attention katmanı sonucunu elde etme / Attention Layer Result
Böylece önceki adımda attention katmanı tamamlanmış olur ve elimizde girişte kullandığımız embedding’lerle tam olarak aynı boyutta embedding’ler kalır.
> The previous step concluded the attention layer and we are left with the same amount of embeddings of exactly the same size as we used as input.
10.9. Transformer: Artık bağlantıları / Residual connections
Transformer’larda artık bağlantılar (Residual Connection) yoğun biçimde kullanılır; bu, basitçe bir önceki katmanın girişini mevcut katmanın çıkışına eklemek anlamına gelir. Burada da artık bağlantı uygulayacağız.
> Transformers make heavy use of residual connections which simply means adding the input of the previous layer to the output the current layer. This is also something that we will do now.
10.10. Transformer: Artık bağlantı sonucu / Residual connection Result
Bu artık bağlantılar sayesinde (aynı d boyutundaki vektörler birbirine eklenerek) yine aynı boyutta vektörler üretilir.
> The addition results in vectors of the same size.
10.11. Transformer: Feed-forward ağa aktarma / Feed Forward Network
Şimdiye kadarki sonuçları (output), doğrusal olmayan aktivasyon fonksiyonlarına sahip bir feed-forward yapay sinir ağından geçiririz.
> Now these outputs are feed through a feed forward neural network with non linear activation functions
10.12. Transformer: Nihai sonucu elde etme / Final Result
Transformer’da bu ana kadarki işlemlerden sonra bir artık bağlantı daha bulunur; ancak burada açıklamayı sadeleştirmek için bunu atlayıp Transformer katmanı işlemini tamamlayacağız. Sonuçta Transformer, girişle aynı boyutta bir çıktı üretir.
> After the transformer step there is another residual connections which we will skip here for brevity. And so the last step concluded the transformer layer. In the end the transformer produced outputs of the same size as input.
11. Transformer işlemini tekrarlama / Repeat Transformers
Şimdiye kadar anlattığımız 10.1’den 10.12’ye kadar olan tüm Transformer işlemleri birkaç kez tekrarlanır. Burada örnek olarak 6 kez gösterilmiştir.
> Repeat the entire transformer calculation Steps 10.1 - Steps 10.12 for the Transformer several times e.g. 6 times.
12. Sınıflandırma token çıktısını belirleme / Identify Classification token output
Son adım, sınıflandırma token’ının (CLS token) çıktısını belirlemektir. Bu vektör, Vision Transformer yolculuğumuzun son aşamasında kullanılacaktır.
> Last step is to identify the classification token output. This vector will be used in the final step of our Vision Transformer journey.
13. Son adım: Sınıflandırma olasılıklarını tahmin etme / Final Step: Predicting classification probabilities
En son aşamada sınıflandırma çıktı token’ını ve tam bağlı (fully-connected) başka bir yapay sinir ağını kullanarak giriş görüntümüz için sınıflandırma olasılıklarını tahmin ederiz.
> In the final and last step we use this classification output token and another fully connected neural network to predict the classification probabilities of our input image.
14. Vision Transformer’ın eğitimi / Training of the Vision Transformer
Vision Transformer’ı, tahmin edilen sınıf olasılıklarını ve gerçek sınıf etiketlerini karşılaştıran standart bir cross-entropy loss function kullanarak eğitiriz. Model, backpropagation ve gradient descent kullanarak kayıp fonksiyonunu en aza indirecek şekilde parametrelerini güncelleyerek öğrenir.
> We train the Vision Transformer using a standard cross-entropy loss function, which compares the predicted class probabilities with the true class labels. The model is trained using backpropagation and gradient descent, updating the model parameters to minimize the loss function.
Sonuç / Conclusion
Bu görsel rehberde, veri hazırlığından modelin eğitimine kadar Vision Transformer’ın temel bileşenlerini adım adım inceledik. Bu anlatımın, Vision Transformer’ların nasıl çalıştığını ve görüntüleri sınıflandırmak için nasıl kullanılabildiğini anlamanıza yardımcı olduğunu umuyoruz.
> In this visual guide, we have walked through the key components of Vision Transformers, from the data preparation to the training of the model. We hope this guide has helped you understand how Vision Transformers work and how they can be used to classify images.
Vision Transformer’ı daha iyi anlayabilmeniz için küçük bir Colab Notebook da hazırladım. Lütfen 'Blogpost' yorumuna da göz atın. Kod, @lucidrains’in harika VIT Pytorch implementation çalışmasından alınmıştır; onun çalışmalarına da mutlaka göz atın.
> I prepared this little Colab Notebook to help you understand the Vision Transformer even better. Please have look for the 'Blogpost' comment. The code was taken from @lucidrains great VIT Pytorch implementation be sure to checkout his work.
Sorularınız veya geri bildiriminiz varsa benimle istediğiniz zaman iletişime geçebilirsiniz. Okuduğunuz için teşekkürler! (yazarın GitHub, X(Twitter), Threads, LinkedIn)
> Herhangi bir sorunuz veya geri bildiriminiz varsa, lütfen benimle iletişime geçmekten çekinmeyin. Okuduğunuz için teşekkürler!
Teşekkürler / Acknowledgements
- @lucidrains'in VIT PyTorch implementasyonu
- Tüm görseller Wikipedia'dan alınmıştır ve CC BY-SA 4.0 lisansı kapsamında lisanslanmıştır.
> * VIT Pytorch implementation
> * Tüm görseller Wikipedia'dan alınmıştır ve Creative Commons Attribution-Share Alike 4.0 International lisansı kapsamında lisanslanmıştır.
Daha fazla okuma
Orijinal metin
https://blog.mdturp.ch/posts/…
Özet yazı
https://tr.news.hada.io/topic?id=14370
Vision Transformer makalesi
https://arxiv.org/abs/2010.11929v2
PR12'nin Vision Transformer makale inceleme videosu
https://www.youtube.com/watch?v=D72_Cn-XV1g
Google Research'ün Vision Transformer deposu
https://github.com/google-research/vision_transformer
PapersWithCode'da derlenen Vision Transformer ile ilgili makaleler, kodlar vb.
https://paperswithcode.com/method/vision-transformer
⚠️Reklam⚠️: :pytorch:PyTorch Kore Kullanıcı Topluluğu tarafından derlenen bu yazıyı faydalı buldunuz mu? Üye olursanız önemli yazıları size e-postayla göndeririz! (Varsayılan olarak haftalıktır, ancak günlük olarak da değiştirebilirsiniz.)
1 yorum
Yararlı kaynak için emeğinize sağlık.^