반응형

 

Abstract

핵심 idea: Transformer 아키텍처를 사용하는 self-distillation 모델로 입력의 마스킹된 부분을 기반으로 이미지, 자연어, 스피치 전체(multimodal)의 input data의 latent representations를 예측하는 것이다.

  • Knowledge distillation이란: 큰 모델에서 작은 모델을 학습하는 것 (Hinton et al., 2015)

 

1. Introduction

학습 알고리즘은 통합적이지만 여전히 representation은 각 modality의 양식에 대해 개별적으로 학습한다.

https://arxiv.org/pdf/2202.03555.pdf

  1. teacher model: original data를 입력하여 representation을 생성
  2. student model: masked data를 입력하여 original input의 representation을 예측
    → self-distillation

 

2. Related Work

Self-supervised Learning 이란 | CV, NLP, Speech

Self-supervised Learning 이란

 

Self-supervised Learning 이란 | CV, NLP, Speech

왜 Self-supervised learning을 할까? Issue: 일반적으로 labeled data는 비싸고 대용량 데이터를 구하기 어렵다. Solution Downstream task: 대용량 데이터로 pre-training을 하고 풀고자하는 task에 맞는 데이터..

everyday-deeplearning.tistory.com

Multimodal pre-training

Goal: Modality가 다르더라도 동일한 self-supervised learning을 할 수 있는 방법론을 제안 ⇒ predict : contextualized representations
- modality specific: data2vec에서는 feature 추출하는 부분까지만 각각 task별로 다르게 생성

 

3. Method & 4. Experimental setup

훈련 샘플의 모든 정보를 인코딩하고 student 모델은 부분적인 보기가 주어지면 이러한 표현을 예측한다.

Model Architecture

https://arxiv.org/pdf/1706.03762.pdf

표준 Transformer 아키텍처를 사용한다.

Masking

token 단위의 일부를 masking하고 sequence를 transformer 네트워크에 공급한다.

 

Computer Vision
BEiT masking 방법을 따른다.
image patches를 임의로 masking하는 방법을 사용하는데 인접한 블록을 masking하는 blockwise방법을 사용한다.

 

Speech processing
wave2vec masking 방법을 따른다.
latent speech representation을 추출하기 위해 cnn 구조를 사용하고 n개의 token을 연속적으로 masking한다.

 

Natural language processing
RoBERTa masking 방법을 따른다.
BERT에서는 한번만 random masking을 하고 모든 epoch에서 동일한 mask를 반복하지만 RoBERTa에서는 매 epoch마다 다른 masking을 수행하는 dynamic masking 방법을 사용한다. 또한 BERT와 달리 다음 문장을 예측하는 방법은 사용하지 않는다.

 

Training targets

masking된 time-steps부분의 representations만 예측한다.

 

Teacher parameterization

  • EMA(Exponentially Moving Average)
    $\triangle \leftarrow \tau\triangle + (1-\tau)\theta$
    • $\triangle$ : teacher model weight, $\theta$ : student model weight, $\tau$ : target value
      → 학생만 선생님을 통해서 배우는 것이 아니라 선생님도 학생을 통해서 배움(smoothing)
    • $\tau$: 1인경우 teacher model weight만 사용, 0인경우 student weight만 사용
  • BYOL
    : EMA를 제시한 논문https://arxiv.org/pdf/2006.07733.pdf
    • oneline networks를 target networks의 representation을 예측하도록 학습함
    • target networks의 weights는 online networks의 weight와 EMA로 업데이트 시킴

 

Targets

normalizing targets

$y_t = \frac{1}{K}\Sigma_{l=L-k+1}^L \hat{a}_t^l$

  • K: top k layer
    • k test 결과 in Result ) Layer-averaged targets.

      : 여러 계층을 기반으로 하는 대상이 모든 modalities에 대해 최상위 계층(k=1)만 사용하는 것보다 향상되었다.

 

Objective

Smooth L1 loss

$L(y+t, f_t(x)) = \begin{cases} \frac{1}{2}(y_t - f_t(x))^2 / \beta \ \ \ \ \ \ |y_t-f_t(s)| \le \beta \\ (|y_t-f_t(s)| - \frac{1}{2}\beta)\ \ \ \ otherwise\end{cases}$

 

5. Result

  • data2vec Base: L = 12(Transformer blocks), H = 768(hidden dimension)
  • data2vec Large: L = 24, H = 1024
    : 모든 modal에서 sota를 준하는 or 뛰어넘는 결과를 얻음

** error점수라서 낮을수록 좋은 것

 

6. Discussion

Structured and contextualized targets.

NLP에서 data2vec은 target units(word/sub-word/character/byte)를 미리 정의하지 않아도 되는 첫 모델이다.

Representation collapse.

  • Representation collapse: input에 상관 없이 모두 같은(비슷한) constant vector를 뱉는 현상
  • 논문에서 collapse가 발생하는 시나리오를 찾았다.
    1. the learning rate is too large or the learning rate warmup is too short which can often be solved by tuning the respective hyperparameters.
    2. τ is too low which leads to student model collapse and is then propagated to the teacher.
    3. we found collapse to be more likely for modalities where adjacent targets are very correlated and where longer spans need to be masked, e.g., speech.

 

7. Conclusion

data2vec의 접근 방식은 여전히 modality-specific 인풋 인코더를 사용하고 각 modality별로 masking 방법을 채택했다.
향후 작업에서는 여러 modality를 통합적으로 훈련할 뿐 아니라 modality에 구애받지 않는 단일 마스킹 전략을 조사할 수 있다.

  • (Jaegle et al., 2021): 다양한 modality의 raw data에서 작동할 수 있는 Transformer 아키텍처에 대한 task, classification에 대한 supervised learning에 중점을 둠
반응형
반응형

왜 Self-supervised learning을 할까?

  • Issue: 일반적으로 labeled data는 비싸고 대용량 데이터를 구하기 어렵다.
  • Solution
    1. Downstream task: 대용량 데이터로 pre-training을 하고 풀고자하는 task에 맞는 데이터로 fin-tuning하는 방법
    2. Self-supervised learning: Unlabeled data에서 자체적으로 label(pseudo label)을 만들어서 모델을 supervised learning방식으로 학습하는 방법

 

Self-supervised learning 예시

  1. teacher labeled data 학습
    https://youtu.be/QHXvAaptdqs?t=1261
  2. 학습한 teacher로 unlabeled data에서 pseudo label 생성
    • pseudo label: softmax를 이용하여 label로 사용
    • 단점: teacher가 부정확한 경우 student는 잘못된 label을 학습할 수 있음
  3. child model 학습
    https://youtu.be/QHXvAaptdqs?t=1261

 

Self-supdervised learning in Computer Vision

  1. jigsaw puzzle
    https://arxiv.org/pdf/1603.09246.pdf

    (1) 이미지를 split하고 patch를 섞는다. (2) Model로 몇 번째 위치에 해당하는 patch인지 분류한다.
  2. contrastive learning
    https://arxiv.org/pdf/2011.10566.pdf

    (1) data augumentation을 통해 data를 생성하고 (2) Model(with Negative Sampling)을 이용하여 Feature Extraction을 학습한다.
    : 같은 label에서 나온 데이터(positive)를 더 가깝게, 다른 데이터(negative)를 더 멀어지도록 학습한다.
  3. masked image
    https://arxiv.org/pdf/2106.08254.pdf, https://arxiv.org/pdf/2111.06377.pdf

    (1) 이미지를 split하고 patch를 임의로 (blockwise or random) masking한다. (2) Model로 masking된 부분의 representation을 예측한다.

 

Self-supervised learning in Natural Language Processing

NLP에서는 대표적으로 BERT가 있다.

https://wikidocs.net/115055

BERT: pretraining 방법으로 Masked Language Model(MLM)과 next sentence prediction을 사용했다.

  1. Masked Language Model(MLM)
    (1) input에서 token을 임의로 masking하고 (2) 주변 단어의 context만 보고 mask된 단어를 예측한다.
  2. Next sentence prediction: 두 문장을 같이 넣고 이어지는 문장인지 아닌지 맞춘다.

 

Self-supervised Learning in Speech

Speech에서도 BERT의 MLM을 적용한 방법을 사용했다.

https://arxiv.org/pdf/2006.11477.pdf,%20https://arxiv.org/pdf/2106.07447.pdf

 

wave2vec: (1) n개의 token을 연속적으로 masking한다. (2) 예측한 vector와 context vector간의 contrastiv loss로 학습한다.


 

최근 Self-supervised Learning, Semi-supervised Learning에 관한 논문이 많이 보여 간략하게 개념을 정리하였다.

반응형
반응형

참고: vanilla knowledge distillation를 위주로 knowledge distillation 구조를 살펴보고자 합니다

** 아래의 내용과 이미지는 위의 논문을 기반으로 작성하였습니다.

** 수정할 부분이나 의견이 있다면 댓글로 달아주세요~

 

Abstract

큰 성공을 이룬 deep learning은 주로 encode large scale 데이터와 billions of model parameters를 가진다. 하지만 디바이스의 한정된 resources측면에서 challenge다.

knowledge distillation은 small model이 large teacher model로 부터 효과적으로 학습할 수 있다.

The great success of deep learning is mainly due to its scalability to encode large-scale data and to maneuver billions of model parameters. However, it is a challenge to deploy these cumbersome deep models on devices with limited resources.

As a representative type of model compression and acceleration, knowledge distillation effectively learns a small student model from a large teacher model.

 

1 Introduction

  • original paper: Distilling the Knowledge in a Neural Network

더 나은 성능과 경쟁력을 얻기위한 main idea는 student model이 teacher model을 모방하는 것이다. key problem는 transfer the knowledge를 하는 방법이다.

The main idea is that the student model mimics the teacher model in order to obtain a competitive or even a superior performance. The key problem is how to transfer the knowledge from a large teacher model to a small student model.

Fig1

기본적으로 knowledge distillation system은 3가지 components로 구성되어있다.

  1. knowledge, 2. distillation algorithm, 3. teacher-student architecture.

Basically, a knowledge distillation system is composed of three key components: knowledge, distillation algorithm, and teacher-student architecture.

 

2. Knowledge

2.1 Response-Based Knowledge

초기 knowledge distillation은 large deep model의 teacher knowledge로 logits을 사용했다.

A vanilla knowledge distillation uses the logits of a large deep model as the teacher knowledge.

Fig4

Specifically, soft targets are the probabilities that the input belongs to the classes and can be estimated by a softmax function as

$p(z_i, T) = \frac{exp(z_i/T)}{\Sigma_j exp(z_j/T)}$, (2)

where zi is the logit for the i-th class, and a temperature factor T is introduced to control the importance of each soft target.

Accordingly, the distillation loss for soft logits can be rewritten as
$L_{ResD}(p(z_t, T ), p(z_s, T )) = L_R(p(z_t, T ), p(z_s, T ))$ . (3)

Generally, $L_R$ often employs Kullback Leibler divergence loss.

 

참고) Methods

source: http://cs230.stanford.edu/files_winter_2018/projects/6940224.pdf

$L_{KD}(W_{student}) = \alpha T^2 \times CrossEntropy(Q_S,Q_T) + (1-\alpha )\times CrossEntropy(Q_S,y_{true})$

  • Qs : student target, Qt: teature target
  • T: temperature(T≥1)
  • alpha: hyperparameter tunes the weighted average between two components of the loss
    • euni: T, alpha는 teature를 얼마나 배울것인가?

(semi-cusomized KD loss)

  • KLDivergence Loss (wiki)쿨백-라이블러 발산은 비대칭으로, 두 값의 위치를 바꾸면 함수값도 달라진다. 따라서 이 함수는 거리 함수는 아니다.
  • $Loss = y_{true} * log(y_{true} / y_{pred})$
  • 쿨백-라이블러 발산(Kullback–Leibler divergence, KLD)은 확률분포의 차이를 계산하는 데에 사용하는 함수로, 어떤 이상적인 분포에 대해, 그 분포를 근사하는 다른 분포를 사용해 샘플링을 한다면 발생할 수 있는 정보 엔트로피 차이를 계산한다.

 

3. Distillation Schemes

Fig8

3.1 Offline Distillation

초기 knowledge distillation은 pre-trained teacher model의 teacher knowledge를 student model로 transffered함.

따라서 2가지 stage의 training 프로세스가 있음.

1) distillation 전에 large teacher model을 먼저 훈련함

2) 앞서 언급했듯 teacher model의 logits이나 intermediate features를 knowledge로 추출하여 student model의 distillation 훈련시 가이드로 사용함

In vanilla knowledge distillation, the knowledge is transferred from a pre-trained teacher model into a student model.

Therefore, the whole training process has two stages, namely:

1) the large teacher model is first trained on a set of training samples before distillation;

2) the teacher model is used to extract the knowledge in the forms of logits or the intermediate features, which are then used to guide the training of the student model during distillation.

3.2 Online Distillation

In online distillation, both the teacher model and the student model are updated simultaneously, and the whole knowledge distillation framework is end-to-end trainable.

3.3 Self-Distillation

In self-distillation, the same networks are used for the teacher and the student models.

(self-distillation means student learn knowledge by oneself)

 

4. Teacher-Student Architecture

knowledge distillation에서 teacher-student 구조는 일반적으로 knwledge transfer하는 form이다. 다시 말해, knowledge acquisition과 distillation의 질(quality)은 teacher-student networks를 어떻게 구성하는지에 따라 결정된다.

In knowledge distillation, the teacher-student architecture is a generic carrier to form the knowledge transfer. In other words, the quality of knowledge acquisition and distillation from teacher to student is also determined by how to design the teacher and student networks.

 

Fig9

 

5 Distillation Algorithms

knowledge transfer 프로세스를 향상시키기위한 많은 다양한 algorithms이 제안되어왔다.

Many different algorithms have been proposed to improve the process of transferring knowledge in more complex settings.

5.1 Adversarial Distillation

teacher model을 모방하기 위해 student model을 훈련하는 다른 방법이 이미 존재한다. 최근 adversarial learning은 generative networks에서 큰 성공을 거둬 주목받아왔다.

Are there other ways of training the student model in order to mimic the teacher model? Recently, adversarial learning has received a great deal of attention due to its great success in generative networks, i.e., generative adversarial networks or GANs (Goodfellow et al., 2014).

Fig10

GAN은 teacher knowledge transfer하여 student learning 능력을 강화할 수 있는 효과적인 tool이다.

GAN is an effective tool to enhance the power of student learning via the teacher knowledge transfer; joint GAN and KD can generate the valuable data for improving the KD performance and overcoming the limitations of unusable and unaccessible data; KD can be used to compress GANs.

 

7. Applications

7.1 KD in Visual Recognition

We summarize two main observations of distillationbased visual recognition applications, as follows.

  • Knowledge distillation provides efficient and effective teacher-student learning for a variety of different visual recognition tasks, because a lightweight student network can be easily trained under the guidance of the high-capacity teacher networks.
  • Knowledge distillation can make full use of the different types of knowledge in complex data sources, such as cross-modality data, multi-domain data and
    multi-task data and low-resolution data, because of flexible teacher-student architectures and knowledge transfer.

7.2 KD in NLP

Several observations about knowledge distillation for natural language processing are summarized as follows.

  • Knowledge distillation provides efficient and effective lightweight language deep models. The large-capacity teacher model can transfer the rich knowledge from
    a large number of different kinds of language data to train a small student model, so that the student can quickly complete many language tasks with effective performance.
  • The teacher-student knowledge transfer can easily and effectively solve many multilingual tasks, considering that knowledge from multilingual models can be transferred and shared by each other.
  • In deep language models, the sequence knowledge can be effectively transferred from large networks into small networks.

추가) Sample Codes

  • keras
      ## Loss
      student_loss_fn=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
      distillation_loss_fn=tf.keras.losses.KLDivergence()
      alpha=0.1
      temperature=10
    
      # Compute losses
      student_loss = student_loss_fn(y, student_predictions)
      distillation_loss = distillation_loss_fn(
          tf.nn.softmax(teacher_predictions / temperature, axis=1),
          tf.nn.softmax(student_predictions / temperature, axis=1),
                  )
      loss = alpha * student_loss + (1 - alpha) * distillation_loss
    
  • torch
    ## Loss
    # NOTE: the KL Divergence for PyTorch comparing the softmaxs of teacher
    #     and student expects the input tensor to be log probabilities!
    log_p = torch.log_softmax(y_pred_pair_1 / self.temp, dim=1)
    q = torch.softmax(y_pred_pair_2 / self.temp, dim=1)
    loss = (
        nn.KLDivLoss(reduction="sum")(log_p, q)
        * (self.temp ** 2)
        / y_pred_pair_1.size(0)
    )
반응형
반응형

AN IMAGE IS WORTH 16X16 WORDS: TRANSFORMERS FOR IMAGE RECOGNITION AT SCALE

** 아래의 내용과 이미지는 위의 논문을 기반으로 작성하였습니다.

** 수정할 부분이나 의견이 있다면 댓글로 달아주세요~

 

ABSTRACT

Transfomer architecture는 NLP task에서 공공연히 standard한 모델이 되어왔지만 CV(Computer Vision) task에서는 여전히 한계가 있다.

우리는 CNN을 사용할 필요없이 image를 sequcese of patches로 직접 적용하는 transformer 모델 자체가 classification task에서 좋은 성능을 보인다는 것을 보여준다.

대량의 data를 pre-trained하고 multiple mid-sized or small images를 banchmarks (ImageNet, CIFAR-100, VTAB, etc.)로 transferred할 때 ViT는 적은 computational resource를 사용하여 훈련하여도 SOTA와 비교해도 좋은 결과를 얻을 수 있다.

 

 

1 INTORDUCTION

Transformer(Self-attention-based architectures)가 large dataset으로 훈련된 pre-trained모델로 NLP task에서 많이 채택되고 있다.

CV에서는 CNN을 사용하는 경우가 여전히 우세하다. attention aptterns을 사용할 때 여러 test가 있었지만 아직 충분히 scaled dffectively 모델이 없다.

우리는 image를 잘라서 patches(treated the same way as tokens (words))로 만들고 sequence를 linear ebedding로 만들어 transformer에 넣었다. ViT는 충분한 scale로 pre-trained하고 fewer datapoints로 task를 trasnferred할때 상당히 좋은 결과를 달성할 수 있다.

 

 

2 RELATED WORK

Naive application of self-attention to images would require that each pixel attends to every other pixel. With quadratic cost in the number of pixels, this does not scale to realistic input sizes. Thus, to apply Transformers in the context of image processing, several approximations have been tried in the past.

Many of these specialized attention architectures demonstrate promising results on computer vision tasks, but require complex engineering to be implemented efficiently on hardware accelerators.

Most related to ours is the model of Cordonnier et al. (2020), which extracts patches of size 2 × 2 from the input image and applies full self-attention on top. This model is very similar to ViT, but our work goes further to demonstrate that large scale pre-training makes vanilla transformers competitive with (or even better than) state-of-the-art CNNs. Moreover, Cordonnier et al. (2020) use a small patch size of 2 × 2 pixels, which makes the model applicable only to small-resolution images, while we handle medium-resolution images as well.

We focus on these two latter(ImageNet-21k and JFT-300M) datasets as well, but train Transformers instead of ResNet-based models used in prior works.

 

 

3 METHOD

In model design we follow the original Transformer (Vaswani et al., 2017) as closely as possible. An advantage of this intentionally simple setup is that scalable NLP Transformer architectures – and their efficient implementations – can be used almost out of the box.

 

3.1 VISION TRANSFORMER (ViT)

ViT Architecture

standard Transformer는 input으로 1D sequnce of token embeddings을 가지기 때문에 2D images를 다루기 위해 patches(이미지를 자른 것)를 flatten하고 trainable linear projection을 사용하여 D 차원에 mapping한다.

potision embeddings(1D)는 위치 정보를 유지하기 위해 patch embeddings에 합산한다. sequence of embedding vectors는 encoder의 입력으로 사용된다.

  • linear projection (Eq. 1).the patch embedding projection E (Eq. 1) is applied to patches extracted from a CNN feature map.
    • $z_0 = [x_{class}; x^1_pE;x^2_pE; ...;x^N_pE] + E_{pos}, E \in \mathbb{R}^{(P^2C) \times D}, E_{pos} \in \mathbb{R}^{(N+1)\times D}$

 

BERT의 [class] token과 비슷하게, (Transformer encoder $(z^0_L)$ 의 output 상태가 image representation y 역할을 하는) sequnce of embedded patches 앞에 learnable embedding을 추가한다.

  • (Eq.4)
    • $y = LN(z^0_L)$ , Layernorm (LN)

 

Transformer Encoder는 Multihead self-attention(MSA) 과 MLP block (Eq. 2, 3)의 layers로 구성된다. Layernorm (LN)은 모든 block 이전에 적용되고 residual connection (+ 기호 사용)은 모든 block 이후에 적용된다.

  • (Eq.2)Multihead self-attention(MSA) is an extension of SA in which we run k self-attention operations, called “heads”, in parallel, and project their concatenated outputs. (in Appendix A)
    • $z'l = MSA(LN(z{l-1})) + z_{l-1}$ $l = 1 ... L$
  • (Eq.3)MLP에는 2개의 GELU layers 사용

 

Inductive bias.

CNN에서는 locality, 2D neighborhood structure, and translation equivariance가 전체 모델을 통해 각 layer로 다시 들어간다.

ViT에서는 MLP layers만 local and translationally equivariant이고, self-attention layers는 global이다.

 

Hybrid Architecture.

hybrid model에서는 patch embedding projection E(Eq. 1)에 CNN feature map으로 부터 추출된 patches가 적용된다. 특별한 경우로, patches는 spatial size 1x1 가질수 있다. input sequence는 단순히 spatial dimensions of the feature map을 flattening하고 Transformer dimesion을 projecting하여 얻는다. ( Abstract 에서는 CNN 필요없다고 했지만...)

 

3.2 FINE-TUNING AND HIGHER RESOLUTION

일반적으로 대규모 데이터셋에 대해 ViT를 pre-train하고 (smaller) downstream task로 fine-tune한다. 이를 위해 pre-trained prediction head를 제거하고 zero-initialize된 DxK(K: the number of downstream classes) feedforward layer를 연결한다. 종종 higer resolution으로 fine-tune하는 것이 도움이 된다.

hider resolution을 사용할 때는 patch size를 같게 유지하기 때문에 effective sequence length가 커진다. ViT는 임의의 sequence length를 처리할 수 있지만 pre-trained position embeddings가 더 이상 의미가 없을 수 있다. 따라서 원본에서 location에 따라 pre-trained position embeddings의 2D interpolation을 수행한다. (수동으로 bias 넣음)

 

 

4 EXPERIMENTS

ViT Table1
ViT Figure3, 4

ViT-L/16 means the “Large” variant with 16×16 input patch size.

Note that the Transformer’s sequence length is inversely proportional to the square of the patch size, thus models with smaller patch size are computationally more expensive.

 

ViT attention

Globally, we find that the model attends to image regions that are semantically relevant for classification (Figure 6).

 

 

5 CONCLUSION

image recognition을 Transformers에 직접 적용해보았다. 기존 computer vision에서 self-attention을 사용하는 방법과 달리, 이 논문에서는 image를 a sequence of patches로서 NLP에서 사용되는 standard Transformer encoder로 처리한다.

  • Challenges
    1. 다른 CV task(detection and segmentation)에 ViT 적용하기
    2. self-supervised pre-training 방법 탐색하기

 

나의 결론

  • 최근 동향을 보면, Transformer는 CNN, LSTM 과 같은 general deep learning model이 되었다. 오히려 NLP, CV 등 task에 국한되지 않고 대체적으로 (SOTA에 준하는 혹은 뛰어넘는) 좋은 성능을 보이고 있다. (nlp와 달리 image는 local&global(position) feature(information)가 중요함)
  • 이 논문에서는 image input을 transformer model에 어떻게 넣어야 효과적일까? 에 대한 방법을 소개한다.
    • 방법요약: patch로 이미지를 잘라서(or CNN으로 feature map 생성해서-hybrid architecture) 1dim으로 flatten 시키고 (Transformer가 1d를 input으로 받음) 각 patch별로 position embedding을 붙여서 transformer에 넣는다. (idea는 단순함)
    • 다만, 데이터셋이 적으면 train 하기 어려움 → (google에서 ViT를 large dataset으로 pre-train함) fine-tuning(transferred learning)해서 사용하면 좋은 성능 기대할 수 있음

 

 

반응형

+ Recent posts