GithubHelp home page GithubHelp logo

1day_1paper's People

Contributors

dhkim0225 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

cameleogrey

1day_1paper's Issues

[7일차] Binarized Neural Networks: Training Deep Neural Networks with Weights and Activations Constrained to +1 or -1

Quantization 최신 논문부터 보려니 너무 배경지식이 딸림.
조금 고전이면서 유명한 논문들 부터 차근차근 보려 함.
거의 이 분야 혁명처럼 나온 벤지오 랩의 논문.

https://arxiv.org/abs/1602.02830

이전에 bengio lab의 binary-connect 라는 논문이 있었는데,
이 논문과는 다르게, activation 까지 binary화 시킨 논문이 본 논문.

Binarization

weight binarization은 말 그대로 weight 에 적용되는거고
activation binarization은 쉽게 생각해서 featuremap 에 적용된다는 것임.

deterministic binarization

image
그냥 요렇게 어떤 기준 점(0) 을 잡고 binarization 하는 방법을 뜻함

stochastic binarization

확률적으로 binarization 하는 방법임.
image
image

이 논문은 hardware 에 random 값을 넣기 힘들기 때문에 deterministic binarization 을 수행함

sigma 는 hard-tanh 함수를 사용함

signal 함수와 hard-tanh 함수를 그래프로 그려보면 다음과 같음
image

signal 함수를 gradient 가 사라지거나 무한대가 되기 때문에, activation binarization에는
hard tanh 를 이용한 STE(Straight Through Estimator) 를 활용해서 training 하는 게 좋다고 함.

Training

image

weight 뿐 아니라 activation 까지 binarization 함.
weight binarization ==> sign function
activation binarization ==> Htanh function
forward 할 때는 binarized 해서 하는데, (gradient도 binarized W 사용)
backward 할 때는 float(real value) gradient 로 backward 시킴.

다른 논문의 좋은 그림.
image
초록 모듈 내에서는 int 나 float 와 같이 non-binary 값들이 intermediate tensor 로 존재할 수 있음.
초록 모듈 바깥은 모두 binary 상태.

Shift based modules

shifting 연산 으로 동작되는 BN 과 Adamax 를 제시하였음.
성능이 좋다고는 하나,, 생략.

Inference

첫 번째 layer ==> image input (non-binary)
other layers ==> binary input (prev-layer-output)

그래서 첫 번째 layer에 다음과 같은 수식을 적용함
image
input 이 8 bit 니까 비트마다 binarized_weight 를 곱하는 방식. (bitwise xnor conv)

전체 inference logic은 다음과 같다
image

Results

초창기 논문이라 imagenet에 까지 이를 실험해 보지는 않았다.
image

참고로 binary weight 는 1bit 에 (-1, 1) 사용.
ternary weight 는 2bit 에 (-1, 0, 1) 사용한다.

결과적으로 기존 네트워크에 비해 7배 속도 향상 가능했다. (Torch7)

추가 참고자료: AI-Robotics-KR NNQ&CND Study

[11] Zero-Shot Text-to-Image Generation (DALL-E)

유명하고 유명한 DALL-E
dVAE 의 경우 #37 에서 path encoder로도 사용되었음.
Text 를 갖고 auto-regressive 하게 이미지를 생성함.

paper
official code
non-official code - with training
official blog
yannic kilcher

충분한 데이터를 넣으면 zero-shot 으로도 좋은 성능을 냄
image
dVAE 학습결과. (생각보다,,, 약한 영역이 있다.)

image
모델 output.

DALL-E

픽셀을 그대로 input 으로 사용하고 likelihood objective 를 사용하면, high frequency 영역을 집중적으로 본다.
low frequency 가 필요하기 때문에 이러한 구조는 computation 낭비.
이를 해결하기 위해 DALL-E는 다음과 같이 구성됨

  1. 256x256x3 이미지를 32x32x8192 grid로 ! (dVAE)
  2. 256 BPE-encoded text token 구함
  3. text-token, image-token concat 해서 decoder 에 넣어줌

그리고 둘의 joint distribution을 모델링하기 위해 ELBO 사용
모델의 lower bound 는 다음과 같음
image
이미지 출처
그냥 x 인데 x제곱은 블로그에서 잘못 그린듯

images x, captions y, and the tokens z

Stage 1 : Learning the Visual Codebook

phi 와 theta 에 대해 ELBO maximization.
initial prior pψ 는 uniform categorical distribution (8192 codebook)
qφ 는 8192 logit에 parameterized 된 categorical distribution
pψ 가 discrete 하니까 gumbel softmax 로 해결

안정적인 학습을 위해 다음과 같은 세 가지가 중요

  1. relaxation temperature과 step size에 대한 annealing schedule
    temperature를 1/16으로 하면 relaxed validation ELBO가 실제 validation ELBO와 거의 유사해짐
  2. encoder 마지막과 decoder 시작점에 1x1 conv 사용
    relaxation 주변의 conv에서 receptive field 크기를 줄였을 때 실제 ELBO로 더 잘 일반화한다
  3. encoder, decoder 의 resblock activation에 작은 상수 곱하기
    시작 부분에서 학습이 안정적
    KL weight beta = 6.6으로 설정했을 때 학습이 끝난 후 reconstruction error가 작다는 것을 실험적으로 발견

Stage 2: Learning the Prior

phi, theta 는 고정해놓고, prior를 학습. ELBO maximization
gpt-3 와 굉장히 유사한 모델인데, input 이 [text-token, image-token] concat 일 뿐.
image-token 은 dVAE logit에서 argmax sampling을 통해 얻음. (gumbel noise를 더하지 않음)
BPE dropout ==> 10%
120억 parameter 의 sparse transformer 사용

image

Appendix

Preprocess image

image

Logit-Laplacian Loss

image
image
log-laplace distribution 이미지다. (구글 이미지)
여기서 ln 부분 대신 logit을 사용하는 것으로 logit-laplacian 구성.
image
우항에 log를 취해서 loss로 활용함

구글리서치 vq-vae 관련 최근 연구에서도 logit-laplacian을 활용중
VECTOR-QUANTIZED IMAGE MODELING WITH IMPROVED VQGAN

TODO LIST

prompt

Calibrate Before Use: Improving Few-Shot Performance of Language Models (https://arxiv.org/abs/2102.09690)
p-tuning (https://arxiv.org/abs/2104.08691)
Do Prompt-Based Models Really Understand the Meaning of their Prompts? (https://arxiv.org/abs/2109.01247)
An Empirical Study on Few-shot Knowledge Probing for Pretrained Language Models (https://arxiv.org/pdf/2109.02772.pdf)
FLAN (https://arxiv.org/pdf/2109.01652.pdf)
Text Style Transfer (https://arxiv.org/abs/2109.03910)
prompt 생성해서 NMT (https://arxiv.org/abs/2110.05448)

LM

BART (https://arxiv.org/abs/1910.13461)
Primer (https://arxiv.org/abs/2109.08668)
NormFormer (https://arxiv.org/abs/2110.09456)
HTLM (https://arxiv.org/abs/2107.06955)

KIE Pretraining

LayoutLM (https://arxiv.org/abs/1912.13318)
LayoutLMv2 (https://arxiv.org/abs/2012.14740)
StructuralLM (https://arxiv.org/abs/2105.11210)
MarkupLM (https://arxiv.org/abs/2110.08518)

[1일차] Learning in the Frequency domain

https://arxiv.org/abs/2002.12416

RGB input 활용이 아니라, YCrCb 를 DCT 후 input으로 씀
더 큰 이미지를 network input으로 활용할 수 있어서 정확도 향상에 좋음
image

resnet50 에 [448, 448, 3]
mobilenet v2 에 [896, 896, 3]

Example

....[448, 448, 3] input => YCrCb 변환
....dct block_size 8
....Y => [8, 8, 56, 56] => [56, 56, 64] (8x8 를 같은 frequency 별로 모음)
....Cr => [8, 8, 56, 56] => [56, 56, 64]
....Cb => [8, 8, 56, 56] => [56, 56, 64]
....총 [8, 8, 192] 에서 senet을 활용한 channel selection. (with gumbel softmax trick)
image

learning 시킨 애들을 validation set에서 보니 맨날 비슷한 frequency 만 뽑아냄
=> 저주파 영역
=> Cr Cb 보다는 Y
=> classification, segmentation 둘 다 비슷한 frequency만 활용.
image

그래서 중요한 frequency 만 갖고도 모델 학습 가능
실제 accuracy가 많이 증가하지는 않고 input 사이즈도 반 정도밖에 줄지 않지만,
서비스 측면으로는 우수할 듯. 이미지를 jpeg binary로 받고 decoding 없이 바로 inference 가 가능하기 때문.
image

이미지와 주파수 blog: https://idlecomputer.tistory.com/120?category=773851
DCT blog: https://idlecomputer.tistory.com/121?category=773851

[16] MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document Understanding

LayoutLM 저자들의 다음 행선지.

paper
code

스크린샷, 2021-10-25 11-16-26

XPath Embedding

html 페이지를 갖고 pretraining 을 하기 위해서 xpath 를 이용한다.
xpath 블로그1.3.3 predicates 부분을 보면 이해에 도움이 된다.

i 번째 input token 에 대해서 xpath expression을 다음과 같이 list로 우선 나타낸다.
논문의 예시를 보면 하나의 node(tree 의 한 가로줄 영역) 을 xpath로 나타내고 /html/body/div/li[1]/div/span[2] 요걸 리스트로 나타낸 거다.
image
여기서 t는 tag_name, s 는 subscript 이다. subscript 가 없다면 0으로 넣어준다고 한다.

tag_name, subscript 각각에 embedding 취해주면 i 번째 token의 j번째 xpath expression 에 대한 embedding 이 완성된다.
tag embedding 크기는 216, subscript embedding 크기는 1001
tag, subscript embedding dimension 모두 32
image

요 녀석을 concat 해주고, linear project 를 해주면 xpath embedding 완성이다.
image
image

요 과정을 이미지 하나에 담아보면, 요렇다.
image

Xpath embedding 수행 시 max depth는 50으로 두었다고 한다.

Pre-training Objectives

3가지 task 를 수행한다. MMLM, NRP, TPM
image
image

MMLM (Masked Markup Language Modeling)

랜덤하게 token masking 15%, webpage 제목 쪽은 TPM을 위해서 masking 하지 않았음.

NRP (Node Relation Prediction)

R ∈ {self, parent, child, sibling, ancestor, descendent, others} 각각의 node 마다 7개의 관계를 할당해 두고 node 의 첫번째 token 들끼리의 관계를 예측하도록 한다.

TPM (Title-Page Matching)

15% 확률로 title 쪽 제목을 랜덤 token으로 바꿔버리고, [CLS] 에 linear 붙여서 title 바뀌었나, 안 바뀌었나 binary classification 수행

Results

image
image

[4일차] Learning to Generalize: Meta-Learning for Domain Generalization (MLDG)

#18 MAML 을 이용해서 domain generalization 을 한다는 논문.

https://arxiv.org/abs/1710.03463

Source domain ==> S
Target domain ==> T
Meta-Train domain ==> S-V (S¯)
Meta-Test domain ==> V (S˘)

라고 하자.

image
알고리즘을 보면 매번 meta-train 과 meta-test 를 나눠서 진행하게 되는데,
매번 샘플링할 때 도메인이 train, test 에 겹칠 수 있는 MAML 과는 다르다.
이건 train-test domain-shifts 를 모방하기 위함이라고 한다.

다른 점은 최종 업데이트 부분도 있는데,
meta-test 에 beta 를 붙여서 바로 업데이트 하는 MAML 과는 다르게
본래 meta-train 까지 함께 업데이트하는 점이 다르다.

최종 test 때는 meta-train, meta-test 에서 본 적도 없는 도메인으로 수행하게 되는데, (Unseen data)
꽤 잘한다.

image

재미있는 논문이였다.

이 MLDG 를 이용한 다양한 후속논문들이 아직까지도 나오고 있다.

[9일차] Learning to Generate Novel Domains for Domain Generalization (L2A-OT)

STARGAN 과 유사한 방식으로 domain 생성.

paper: https://arxiv.org/abs/2007.03304

image
image

Generating Novel-Domain Data

k 가 source domain label, k-틸다 는 novel domain label 이다.
X_k 는 source 에서 뽑아낸 mini-batch 이다.

새로운 도메인을 만들어 내기 위해 L_novel 은 다음과 같이 정의된다.
image

또다른 k 틸다와는 비슷한 도메인이 생성되면 안되니까, L_diversity를 다음과 같이 정의한다.
image

거기에 Cycle Consistency Loss를 추가해 준다.
image
image

Algorithm

image

(6), (7) 식은 각각 다음과 같다.
image
image

(7)의 alpha 값은 0.5 로 고정되었다.

[15] An Empirical Study on Few-shot Knowledge Probing for Pretrained Language Models (TREx-2p data)

조경현 교수님 ...!
paper
code

기존 LAMA dataset 은 1-hop (subject, relation, object) 성능만을 예측했다.
LAMA dataset paper review blog - KR
아래 이미지는 LAMA 의 예시다. LM 도 과연 진짜 DB 정보에 있는 정보들을 잘 뽑아낼까? 하는 것.
image

LAMA 를 간략하게 정리하면,

  1. BERT-large는 relation knowledge 겁나 잘 뽑아냄.
  2. factual knowledge는 pre-trained language model 에서 잘 뽑아내는데, 일부관계(N-to-M 관계)의 성능은 매우 낮음.
  3. BERT-large는 factual, common sense를 회복하는 동시에 다른 언어모델보다 성능이 뛰어나면서 동시에 쿼리 구문에 더욱 강력함.
  4. BERT-large는 task-specific supervised relation extraction을 사용하여 구축된 지식기반의 성능에 비해 더 높은 결과를 달성.

image
<요 이미지는 Improving Multi-hop Question Answering over Knowledge Graphs using Knowledge Base Embeddings - ACL20 논문에서 가져왔다. 3-hop 의 예시이다.>

슬프게도, T-REx dataset 에서 BERT-large 모델의 zero-shot performance 는 처참했다. accuracy 30% 정도. 대부분 틀리는 이유는 object type이 달라서 였음. finetuning 좀 해주니까 성능 확 좋아짐. 아래 그림이 틀리는 예시와, finetuning 예시.
image

해당 논문은 10~20 개의 데이터만을 갖고 finetune 을 해서 few-shot knowledge probing을 수행한다.

  1. 사람도 직관적으로 몇 개의 데이터만을 갖고 정확한 relation-type을 유추할 수 있음
  2. 새로운 relation 과 rare relation type에 대한 성능측정이 가능

contribution 은 3가지임.

  1. 2-hop 데이터셋인 TREx-2p 를 만들었음
  2. few-shot finetune 이 knowledge probing에서 효과적인 것을 보여줌
  3. bias vector 를 효과적으로 finetuning 시켜서 prompt-engineering 성능 압살

image

Few-shot Knowledge Probing

notation 부터 정리한다.

  1. : pretrained model
  2. : Vocabulary
  3. : probing dataset. subject x, relation y, object z 로 이루어짐
  4. : fewshot 용으로 에서 일부분 가져온 데이터 (10~20 개 sample)
  5. : 에서 split 함 (train)
  6. : 에서 split 함 (일종의 validation. parameter tuning 용으로 사용함)
  7. : test-set

아래 그림은 앞으로 설명할 개념들을 이해하는데 도움이 되는 input 예시들이다.
image

Template Options

masked language 모델의 template 도 여러가지로 줄 수 있다.
LAMA 논문에서 했던 것 처럼 manual 하게 주는 방법이 있고, ()
How Can We Know What Language Models Know? 에서 처럼 자동으로 alternative template 을 찾기위한 mining 방법이 될 수 있다. relation r이 있을 때 에서 가장 잘 동작하는 template을 찾아내는 방법을 () 로 하자.
manT 든 mineT 든 human effort가 들어가는 건 마찬가지다. GPT-3 에서처럼 [X] => [Y] template을 만들 수 있다. 요 녀석은 defT라 하자.

In-context Learning

GPT-3 에서 봤듯이, input에 포함된 example로도 LM 은 학습된다. 이 효과를 보기 위해서, 에서 데이터를 뽑아서 long-prefix 로 input에 함께 넣는다. 요런 녀석을 로 두자.

Optimized Prompts

prompt 를 자동으로 찾는 것은 흥미로운 주제이다.
AutoPromptBERTese 는 training set을 이용해서 discrete token 들에 대해 gradient-based search를 수행했었다.
OptiPrompt 는 continuous vector 로 AutoPrompt를 확장했다. 여기서 input 에 추가적으로 5개의 정보가 들어간다 (subject 와 mask token 사이의 relation). 이 5개의 relation token은 learnable 하게 학습된다. 실험에서 initialize는 많이 사용된 10000개 토큰 값을 평균내서 썼다.

이런실험들은 1000 개 sample에 대해서 finetune 을 실행했었지, 이렇게 10~20개의 few shot에서 사용된 적은 없다.
1000개 짜리 scale 실험에서도 BitFit이 효과가 있는 지 report 해주지 이건 또 실험 안했음. BitFit은 아래에서 설명함

Model Bias Finetuning

BitFit 에서는 encoder의 bias 만 finetune 할 것을 제안했다. GLUE 에서도 성능 좋았음.
bias vector 절반만 학습하는 variant를 사용했음. 좀 더 상세하게 말하면, 각 transformer layer에 대해 요렇게만 finetune 함

  1. the bias for the attention query (of length 1024)
  2. the bias for the intermediate layer (of length 4096)
    image

Results

image
Few-shot 에서는 BitFit을 섞어주는게 무조건 좋다.

[3일차] Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks (MAML)

Domain Generalization key concept 중 하나가 MAML 을 활용한 방법이다.
선행학습 차, MAML 논문을 읽어보게 되었다.

https://arxiv.org/abs/1703.03400

인용 수가 엄청나다.

목표는 적은 sample 만으로 finetuning 을 해서 새로운 task에서 좋은 성능을 내겠다는 것이다. (few shot train)

image

여러 task 에 대한 gradient 가 L1, L2, L3 처럼 다를 텐데 이걸 이용해서 meta-learning 학습 후 theta1, theta2, theta3 로의 finetuning을 쉽게 만들어 준다는 것이다.

알고리즘을 더 살펴보자.

image

T 는 모든 테스크가 짬뽕된 데이터이다.
alpha, beta 는 모두 learning rate hyperparmeter.
거기서 batch만큼 sample 해서 gradient descent 로 theta 를 업데이트 시킨 theta'_i 를 얻어낸다.
theta'_i 로 부터 다시 theta 를 업데이트 시킨다.

이게 끝이다. 다른 시각자료로도 이해해 보자.

image
image
image
가장 마지막 이미지가 theta' 을 사용하고 있어서 (위 알고리즘과 notation이 달라서) 조금 헷갈리긴 하지만,
meta learning 중인 target theta 라 생각해주면 편할 것 같다.

[9일차] XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks

https://arxiv.org/abs/1603.05279

binary network 중 처음으로 imagenet에 대해 적용한 논문.
총 2가지 network를 제안한다.

  1. binary network ==> memory efficient 함
  2. XNOR-Net ==> weight와 input을 binarized

binarized neural net 보다 딱 1달 뒤에 나온 논문.
개인적으로 이 논문이 더 수학적으로 잘 증명된 논문이라 생각함.
GPU 보다는 CPU target 으로 진행된 paper

모든 Convolution 내부 구현?

image
내부 구현은 위 이미지에서 볼 수 있듯이 커다란 matrix를 만들고 이걸 matrix multiplication 하는 방식으로 계산됨.

Motivation

Conv 는 binary_count와 xnor 연산으로 나타낼 수 있음.
image

Binary Network

아래와 같이 binarized weight B 와 scale factor alpha 로 weight를 conversion 시킴.
image

실제 계산은 아래와 같이 XNOR Gate 연산을 통해 convolution 이 가능하고 거기에 scale 만 해주면 됨.
image

정확한 alpha 값과 B를 찾기 위해 아래 수식을 전개시킴
image

아래와 같은 수식을 얻을 수 있음.
image

해당 네트워크는 #7 에서 학습시킬 때 처럼, STE (Straight Through Estimator) 를 활용함.
image

W tilda 의 경우 아래와 같은 식이며, binary로 estimated 된 W 임.
즉, alpha와 binarized value를 이용해 계산된 W.
image

XNORNet

xnornet 은 input까지 binarized 시켜야 하기 때문에 약간 식이 복잡해짐.
input X binarized == H
W binarized == B
image
당연히 scale factor도 2개가 사용됨.

image

가장 잘 approximate 하는 값들을 찾기 위해 위 수식을 풀면, 아래처럼 결과가 나타남.
image

근데, convolution은 sliding window 되면서 굉장히 많이 발생하는 oepration 임.
sliding window끼리 겹쳐지면서 computational expansive 한 부분이 있음.
그때마다 alpha, beta 값을 구하기 싫으니, sliding window를 줄이기 위한 방법을 고안.
channel wise 한 정보를 미리 합치고 거기에 sliding window 하는 방식.
Input에 대해 전체 channel 에 대해 평균을 취한 A를 구해놓음
image
그냥 channelwise로 feature map을 mean_reduce 한 것임.

1 / (h * w) 로만 이루어져 있는 k 를 곱해줌으로써 conv를 완성함.
image
이걸 그림으로 나타내면, 다음과 같음. (감사합니다. AI Robotics KR 여러분)
image

Modified Conv Block Order

image
#7 처럼 학습할 때는 real value backprop 이 이루어 짐
또, #7 처럼 binary activation을 통과하였을 때 binary input이 만들어지게 되는데,
binary input이 maxpool에 들어가면 거의 output이 1로 이루어지게 되며 많은 정보가 손실됨.
해서 conv를 거쳐서 non-binary 값이 나왔을 때 거기에 pooling 해야함.

Results

image
이미지넷 실험결과 쪼아요.
image

Reference

blog_kor: https://mc.ai/review-kor-xnor-net%E2%80%8A-%E2%80%8Aeccv16/ (example 부정확)
blog_eng: http://jaewonchung.me/read/papers/XNOR-Nets/ (깔끔 but no detail)
youtube: https://www.youtube.com/watch?v=N6oP-8E5cWA&t=820s (좋은 contents)

[3일차] Categorical Reparameterization with Gumbel-Softmax

https://arxiv.org/abs/1611.01144

킹갓 에릭 장 ....

deepmind maddison 의 논문과 같은 내용.
latent variable 이 categorical distribution 일 때, Gumbel-softmax + relaxation 을 통해 backprop 가능하다는 것을 보임.

#1 에서도 DCT channel을 고를 때 사용함.

image

a) x(θ) 가 deterministic 하고 differentiable 하면 간단히 계산 됨

b) stochastic node z 가 추가되면 backprop이 불가함

θ 에 대해서 미분하는 것은 간단하게 expectation term으로 묶을 수 있어서 monte-carlo sampling으로 해결할 수 있음.

근데, 분포 ø 에 대해서는 expectation term으로 묶여질 수가 없음.

c) score function estimator 활용

이건 REINFORCE에서 활용된 기법이라 익숙함.
NVIL, DARN, MuProp, VIMCO 등에서도 사용됨

variance가 크기 때문에 보통 baseline term을 이용해서 variance를 줄여줌.

d) reparameterization trick

VAE가 바아로 생각나는 유명한 트릭.
x 를 바로 뽑는 게 아니라 standard normal distribution 의 random variable z 를 이용해 reparameterization 하는 방법. 이를 통해 expectation term 을 만들고 monte carlo 사용 가능

Gumbel Softmax trick.

생각보다 지인짜 단순 (증명은 어렵다)
logit 에다가 gumbel distribution random variable을 더해주는 형태 (noise 섞듯이)
이게 discrete categorical distribution에서 sampling 하는 것과 같음
image

argmax 가 미분 불가하기 때문에 temperature 가 있는 softmax 를 활용하게 됨
image

이 temperature가 낮으면 categorical distribution 에 더 근사되지만 variance가 높아짐.
따라서, temperature를 높게 잡았다가 차차 낮게 해 주는 curriculum learning을 활용해도 좋음.

요약한 이미지. (meddison)
image

참고 영상: PR-12 유재준님 영상

[5일차] On Recognizing Texts of Arbitrary Shapes with 2D Self-Attention (SATRN)

SATRN. 2d attention과 transformer를 활용한 OCR Recognition 모델.

https://arxiv.org/pdf/1910.04396.pdf

image
image

shallow cnn의 경우 정말 shallow하다. cnn-maxpool-cnn-maxpool 끝.

transformer의 경우 그림만 봐도 알겠지만 기존 transformer와 약간 다르다.

decoder의 경우 바뀐게 없다.
기존 transformer와 같이 decoder 의 2 번째 multi-head attention module 에서 encoder의 key value를 가져오게 된다.

encoder에서 바뀐 점은 크게 2가지다.

  1. adaptive positional encoding
  2. "point-wise feedforward layer" 부분이 "locality-aware feedforward layer" 로 바뀌었다.

A2DPE (Adaptive 2D Positional Encoding)

일반적인 vision task에서 positional encoding 은 그다지 중요하지 않지만, ocr recognition에서는 상당히 중요하다.
수식으로 보기에는, qkv self attention에서 value에만 postitional encoding을 적용하지 않았다.

Original attention을 다음과 같은 수식으로 정의하자
image
image

positional encoding을 곁들인 attention은 다음과 같이 동작한다.
image

이제 여기서 제안하는 A2DPE (Adaptive 2D Positional Encoding) 은 다음과 같다.
image
image
image

결국 일반적인 positional encoding 의 식인 (5), (6) 뿐만 아니라 weight를 활용해서 (7), (8) 을 만들고 같이 사용하는 것.
E 는 shallow cnn 의 output 이고, g(E) 는 global average pooling 이다.

Locality-aware feedforward layer

일반적인 attention 작업 이후에 적용되는 FF(FeedForward) layer 는 전체적인 long-term dependency를 학습하는데 유용하지만 ocr에서는 다르다.
image

(a) 형식을 (b), 또는 (c) 형태로 바꾸어 구성해 보았고, (c) 가 좋았다

Ablation Study

Positional Encoding은 A2DPE 방식이 좋다.
image

Feed forward 는 (c) 가 좋다.
image

Results

image
image

[8일차] Learning to Learn with Variational Information Bottleneck for Domain Generalization (MetaVIB)

Domain generalization model 들은 unseen domain 에서도 잘 동작하지만, prediction uncertainty 때문에 고통받는다.
uncertainty 까지 동시에 제어하는 방법을 제안한다.
MLDG #19 기반 work.

paper: https://arxiv.org/pdf/2007.07645.pdf

Information Bottleneck

Mutual Information이 클 수록 두 random variable이 independent 하면 0이다.
image

Mutual Information I(Z ; X)를 Minimize 하고 I(Z ; Y)를 Maximization 하는 방법론이다.
image

Algorithm

논문에서는 가장 마지막 섹션이지만, 유도를 보기 전에 전체적인 학습 알고리즘을 살펴보자
image

image
image
image
image

Probabilistic Model

image
image

(x^t, y^t) 는 meta-test에서 sample한 데이터.
z는 latent vector. model parameter로 classifier 직전 output 이라 생각하면 될 듯.
ψ(psi) 는 classifier의 parameter 이고 random variable이다. x^t에 따라 결정된다.
model parameter 인 theta 와 ψ 는 jointly optimize 되고 MLDG에서 하듯이 train-batch 를 meta-train 과 meta-test로 나누어 학습한다.
classifier parameter ψ가 D_s 에 의해서 생성되고 D_t 에 적용된다.

이렇게 모델을 구성해서 학습을 해도 되는데, learned representation z 가 domain에 variant 하다. 따라서 Information Bottleneck 방법론을 일종의 regularizer로 함께 붙이게 된다.

Meta Variational Information Bottleneck (MetaVIB)

그럼 Information Bottleneck을 써야 하는데 각 식을 유도해 보자.
X, Y, Z ==> Input, Output, Feature out
I(Z; Y) 와 I(Z; X) 를 구해야지 IB를 사용할 수 있다.

I(Z; Y)

image

p(y|z) 가 intractable하기 때문에 아래 식을 이용해서
image

이런 form을 만든다
image
image

이걸 또 정리하면 새로운 variational lower bound 를 구할 수 있다.
image

I(Z; X)

image

여기서 KLD[p(Z) || q(Z|Ds)] >= 0 인걸 이용하면 식이 정리된다.
image

Combine

I(Z; X), I(Z; Y)를 이제 합치면 MetaVIB를 정의할 수 있다.
image

이 식을 approximation 하고 monte carlo sampling 을 이용해 식을 정리하고,
VAE 에서 사용했던 re-parameterization trick을 사용해서 최종 objective는 다음과 같이 정의된다.
image
image
image

[13] Multi-Task Deep Neural Networks for Natural Language Understanding (MT-DNN)

paper
code
youtube - TMax AI
blog - 한국어 리뷰

MT-DNN

여러 개의 task 를 multi-task learning 시켜서 BERT 보다 뛰어난 성능 만들기.

image

Classification

image
CLS token 에 Linear 통과 후 softmax

Text Similarity Output

image

Pairwise Text Classification

SAN (Stochastic Answer Network) 을 이용해서 추가적으로 task 풀어냄
CLS token을 쓰지 않고, token embedding vector 를 활용해서 SAN을 태우게 됨.
k번 prediction을 통해 보다 정확한 prediction 수행. (최종 성능은 CLS token 쓸 때보다 1% 정도 올라감)
image
각 문장의 vector, 거리, similarity 를 concat 해서 weight 태움

Relevance Ranking Output

질문 문장이 주어지면, 지문 중 정답이 있는 문장을 ranking을 통해 찾아냄!
Question과 문장 Pair를 Input으로 넣어 생성한 [CLS] Token에 Sigmoid를 취함
image

Algorithm

image
배치는 하나의 task로만 이루어진 상태.
일반적인 MTL setting과는 다른 듯?

Results

image

[9] Learning Transferable Visual Models From Natural Language Supervision (CLIP)

CLIP !!
ImageNet zero-shot으로 resnet50 성능 끌어냄
paper code
한국어-blog
yannic-youtube

CLIP

image

1) contrastive pretraining

구조는 단순함. 4억개의 image-text 데이터를 모으고,
Image Encoder와 Text Encoder 를 통과시켜 얻은 vector들로,
image sample-wise 하게 positive, negative 를 구한다.
이를 이용해서 contrastive learning 을 수행한다.

2) create dataset classifier from label text

zero-shot 을 위해서 heuristic 하게 input text 를 만든다.
예를 들어 3 class classification (개, 사람, 고양이) 라 하면,
A photo of 개, A photo of 사람, A photo of 고양이 3개를 만든다

3) Use for zero-shot prediction

  1. step 에서 만든 3개의 text를 이미지와 함께 clip에 통과시켜 본다.
    probability 가 높은 녀석이 prediction!

image
간단하다 간단해..

Results

성능이 놀랍다. 여러 데이터 셋에서 linear-probing (imagenet pretrained + linear layer 붙이기) ResNet50 보다 clip + zero-shot 이 뛰어난 성능을 보인다.
image

무엇보다 robustness 를 측정한 실험이 압도적이였다 느꼈다.
image

[17] Faster Improvement Rate Population Based Training (FIRE PBT)

기존 PBT 개선논문
PBT 1저자가 교신저자로 참여. (엔비디아에서 딥마인드로 이직했네?)

Abstract

PBT 는 2가지 한계점이 있었음.

  1. 느리다
  2. long-term 성능은 오히려 hand-designed 보다 떨어질 때도 많다.

Fire PBT 는 빠르게 성능이 좋아지는 parameter가 더 좋다 는 특징을 이용한다.
실험 결과, hand-design으로 찾은 parameter와 유사하게 찾는 것을 발견 + PBT imagenet 성능을 뛰어넘는다.
강화학습에도 적용했을 때, 좋은 성능 내는 것을 보인다.

Intro

learning rate 에서 특히 PBT 가 잘 working 하지 못했다.

image
ResNet-50 기준 PBT 는 71.7, Fire-PBT 는 76.5, hand-design 은 76.6

FIRE-PBT

image
그림을 보면 상당히 복잡하다.
Population P1, P2, P3 아래에는 sub-population 들이 있고, 각각의 Population들은 PBT 를 그대로 수행한다.
검은색 동그라미 각각은 population-member 라고 칭한다.

  1. 가장 최근에 evaluation이 수행된 population-member를 선택, 녀석의 weight를 복사한다.
  2. PBT를 수행하다보면 population 마다 가장 잘한 녀석이 있을텐데, 그 잘하는 녀석의 hyper-parameter를 evaluator로 보낸다. 요 단계를 수행할 때는, (1) step 수행 시, 사용했던 population 이전 녀석 것을 사용한다. (그림을 보라! P1 에서 param 뽑고, P2 에서 random weight 뽑는다.)
  3. evaluator에서는 hyperparameter의 성능을 측정한다.
    비슷한 weight 기준으로 보았을 때, validation score 의 그래프를 그려본다. (아래 figure 참고)
    여기서 수행되는 게 강력한 abstract에서도 언급한 강력한 assumption. 비슷한 weight 기준으로 빠르게 성능이 좋아지는 parameter가 더 좋다
    1. Gaussian Process 로 적당히 smooth 한 fitted curve 를 찾아냄
    2. 처음으로 두 그래프의 성능이 맞는 지점을 찾아냄. 그림에서 (2) 지점.
    3. 둘 중 더 그래프 빨리 끝나는 녀석에 맞춰서 동일한 step으로 (3) 지점을 구함.
    4. score gap을 구함 (4)
  4. (3)에서 좋았던 weight 그대로 다시 가져와서 특정 기준에 도달할 때까지 PBT 진행 (explore & exploit)
    1. max_eval_steps 이상의 step 이면서,
    2. (3.1) 에서 뽑아냈던 curve 와 (3.2~3.3) 를 수행했음에도, 겹치는 구간이 없다면, 멈춤
    3. 겹치는 구간 (overlap) 이 있더라도 binom_test 를 이용해 멈출지 여부를 측정한다 (binom_test 설명은 skip 한다)
      image
개인적으로 아쉬운 부분은,
1. 제안하는 많은 것들이 있지만, ablation을 수행하지 않는다. binom_test 가 정말 중요한 지 등이 궁금했다.
2. 방법론이 복잡하기도 하거니와, 아직도 많은 cost를 필요료 한다. 결국 parallelism을 이용하는 방법은 이게 문제 아닐까 싶다.

Reults

RandomSearch (with human) vs PBT vs Fire PBT 수행

Classification

image

model: ResNet50
sub-population: 8 (RL 보다 수가 적음. stable 한 편이기 때문)
num-evaluator: parent-sub-population 의 3/4 (1/4 은 explore&exploit 해서 train이 좀 되어야 하기 때문)
batch-size: 1024
learning-rate: optim-target

objective func 계산을 위한 데이터는 validation에 overfitting 될 것을 고려해서, 50000 개의 val set 중 10000개만 활용했음.
각 search 방법론으로 5 experiment + 50 worker 로 실험을 돌렸고, population size 에 따른 검증을 위해 Fire PBT 를 22, 36 worker로 돌렸음. 제일 좋았던 녀석의 schedule 을 retrace 해서 사용.

RandomSearch 의 경우 Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour 논문처럼 , 을 사용하였다. 첫 5epoch은 warmup 시켰고, 30, 60, 80 에서 1/10으로 줄였다. 여기서 50개의 worker 들로 하여금 1e-2 에서 1e-3 사이로 log-uniform 하게 값을 뽑도록 했다.

PBT, FIRE PBT 또한 비슷하다

  1. eval 은 200 training step 마다 반복
  2. Ready (exploit and explore ready) 상태는 2400 step 마다
  3. Exploit 는 하위 25% 애들 버리고, 상위 25% 에서 변형해서 가져옴
  4. Explore 는 에 [0.5, 0.8, 1.25, 2.0] uniform sample 해서 곱했다.

PBT 에서는 50 worker 가 하나의 population 을 이루었음
FIRE PBT 에서는 22, 36, 50 의 worker 를 사용했고, sub-population 은 각각 8로 사용했고, 나머지 worker는 evaluator 로 사용하였다. max_eval_step 은 7200 으로 맞추었다. min_steps_before_eval 은 sub-population이 금방금방 잘 수렴해서 필요 없었다. PBT 든 FIRE-PBT 든 먼저 학습이 끝나도 synchronous 하게 다음 evolution을 기다리도록 구현했다.

image

RL

자세한 건 skip.
V-MPO loss 에다Ant-v1, Humanoid-v1 실험 수행.
image

[10] BEIT: BERT Pre-Training of Image Transformers

paper code

Image transformers 를 위한 pre-training 을 하자!
scratch train DeiT (81.8%) 보다 성능 좋음 (BEIT - 83.2%)
MIM (Masked Image Modeling) task 제안

BEIT

image

input image size (H, W)
patch size (P, P)
일 때, 다음과 같은 형태로 일정하게 이미지를 나눔
image

실험에서는 (224, 224) 를 16x16 patch 로 14x14 grid 를 만들었음
요 녀석들은 flatten 이후 encoder에 들어감

Image Tokenizer는 DALL-E의 dVAE(#38) 를 활용했음
tokenizer 는 image pixel을 discrete token z 로 mapping 시킴
deocder 는 z 에서 image pixel을 만들어줌
image
image
visual vocab size |V| 는 8192 를 사용했고, 단순히 public 한 pretrained 모델을 사용했음

백본은 ViT 를 사용했음.
transformer input 들어갈 때, image patch들은 linear 하나 거침, 가장 앞에는 eos token [S] 를 붙여줌

MIM (Masked Image Modeling)

Image patch 는 40% random mask
mask embedding e_[m] 은 learnable.

image

Details

12 layer transformer
random resized cropping, horizontal flipping, color jittering
ImageNet-1K (1.2M images)
500k steps (800 epoch)
2k batch-size
Adam (0.9, 0.999) , 1.5e-3 cosine lr, w-decay 0.05
warmup 10epoch
disable dropout
Stochastic Depth 사용 (0.1)
16 V100 5일
image
image
image

Results

Image Classification

Image Classification 은 BEIT output 들에 GAP + softmax
image
image

당연하겠지만 수렴속도도 차이남
image

Semantic Segmentation

Semantic Segmentation 은 SETR 사용 (BEIT encoder + deconv decoder)
ADE 20K에서 좋은 성능.
image

DINO 섞으면 ADE20K 에서 약간 더 좋아짐
image

Ablation

image

[19] ResNet strikes back: An improved training procedure in timm

paper

timm pacakge 의 아버지 Ross Wightman 의 논문. (Individual Researcher. 간지 철철)
training schedule 을 바꿔줌으로써, 224x224 input으로 vanilla ResNet-50에 80.4% top-1 을 찍어버림 (원래가 76.5 인가 그럼)

실험 논문인 만큼 실험결과에 집중하여 post 를 써 보겠음.

Training Procedure

3개의 training procedure 제안 (A1, A2, A3)
image

Loss: multi-label classification objective

cutmix 씀. 기존 cutmix와는 다르게! 개, 고양이가 섞이면 multi-label 로 개 1, 고양이 1 을 준다. 나머지는 0.
각 class 에 대해 BCE 를 썼는데, 이렇게 하니 성능이 더 좋았다고 한다.
추가로 label-smoothing 도 수행했다.

Augmentation

  • Random Resized Crop
  • horizontal flip
  • RandAugment
  • Mixup
  • Cutmix

모두 DEIT 에서도 쓰이던 거다.

Regularization

Repeated augmentation을 썼다. 이게 하나의 이미지에 다양한 augmentation을 적용해서 모두 하나의 batch 안에 넣어버리는 테크닉인데, 효과적이었다. 자세한 건, CVPR20 Augment Your Batch 논문을 보자.

아래 이미지는 stochastic depth 의 figure 이다. training 시킬 때, 랜덤으로 모듈을 skip 시키는 방법. inference 할 때는 전부 다 쓰고. 요즘들어서는 기본적으로 사용하는 테크닉으로 보인다.
image

A1 procedure에는 regularization을 약하게만 넣어서 수렴속도를 빠르게 했다.

Optimization

BCE + SGD 는 별로더라. 요즘 나오는 transformer 는 adamw 나 LAMB를 쓰던데, 이들을 적용해 보았더니 잘 되더라. batch size 를 2048 로 늘려주고, LAMB를 쓰는데 집중했다.

Results

아 이런 그림 너무 좋다. 한 눈에 정리가 된다.
image

모델 family 들에 쭉 적용하니까 전부 성능 오르더라
image
vit 성능은 아직도 압도적이다. ㄷㄷ

재밌는 게 이거다. 같은 training 방법론을 적용해도, set 에 따라 크게 성능이 오르지는 않는다. 데이터 크기와 상관관계가 있는 것으로 보인다.
image

DeiT-S 의 schedule 을 T2 로 표현했다 (둘이 비슷하다)
이를 통해 알 수 있는 것. 당연하지만, 모델별로 필요한 hyperparam 은 다르다. 그래도 cnn 들끼리는 잘 통하는 것 같지만..
image

Ablations

A2 기준 Weight decay 는 넣는게 좋고, Repeated augmentation 도 넣으면 좋다.
image

stochastic depth 와 smoothing 관련 실험.
image

[5일차] FCOS: Fully Convolutional One-Stage Object Detection

https://arxiv.org/pdf/1904.01355.pdf

anchor free 논문
YOLO v1 과 centernet 이 대표적인 anchor-free 모델
anchor-free 논문들에 Adelaide 대학교가 자주 보인다. Hmm...

image

중심점 에 ltrb 값을 regression해서 box를 만들면 어떨까?! 논문.
진짜 simple 한데 잘 된다.

Architecture

image

Resnet-50 backbone 에 retinanet hyperparameter 사용
이 model comparison 방식은 object detection에서는 이제 거의 고정인듯.

box 구성

우선 중심점을 구해야 하는데, 단순히 receptive field 를 고려해서 중심점을 잡게 됨.
scale s 는 input image 와 feature map 사이의 비율.
scale s=8 이면, 현재 feature map이 8배 축소되었다는 것.
이 때 중심점은, 다음과 같음. (x, y 는 feature의 index)
image

regression 하는 박스는 정말 첫 이미지의 ltrb 를 수식화한 형태.
image

ltrb 값은 모두 양수가 나와야 하고 range가 크기 때문에 (0~무한대),
최종 output 에 exp() 를 취해줌으로써 이를 해결함.

Loss

image
classification 과 regression loss 가 lambda를 이용해 연결됨.
classification 은 focal loss 사용. (negative sampling은 이제 사라진 것인가 .. hmm)
regression 은 UnitBox 논문에서 제시한 IOULoss 사용
image

위 수식에 추가로 Centerness를 위한 BCE loss 가 붙음.

1_{Cx,y > 0} term 은 indicator 함수인데, Cx,y > 0 일 때 1 아니면 0 이다.
즉, centerness 가 있으면 loss에 포함 아니면 안 포함.

Centerness

centerness를 함께 학습하지 않으면 잘 학습되지 않음.
object의 center 가 잘못 잡히는 문제가 발생한다는 것.
image
이렇게 과하게 옆으로 center가 잡혀버려서 성능이 떨어지는 것.
저자들은 별다른 hyperparmeter 없이 다음과 같은 수식을 이용함.
image
ltrb의 상하좌우 균형이 맞아야 centerness 가 줄어드는 형태.
gt box가 있기 때문에, 해당 featuremap pixel에 해당하는 target ltrb와 centerness를 구할 수 있음.
그렇게 구한 centerness를 heatmap으로 보면 아래와 같이 나타나는데,
'+' 자 격자문양이 나타나기 때문에 2d gaussian map 을 쓰는게 더 낫지 않나 생각이 들었음
image

이 centerness를 예측하도록 BCELoss 를 위에서 살펴본 loss에 붙여줌.

Results

test 할 때는, centerness를 미리 classification probability에 곱해줌으로써 알아서 center가 제대로 잡히지 않은 box는 걸러냄.
정말 NMS 만으로 이제 후처리가 가능해짐.

image

[6일차] Real-time Scene Text Detection with Differentiable Bianrization

https://arxiv.org/abs/1911.08947

처음 논문 제목을 보고 든 생각은
"헐... 설마 detection 을 binary quantization 한 건가?!?! " 였지만, nono.... naver...
binary quantization 한 논문은 bidet () 이라고 cvpr20 논문이 있다.

image
기존에 파란 라인대로 진행되던 걸, threshold map을 함께 예측하여 한 번에 binarization 함.

저렇게 하면 뭐가 좋냐! (뇌피셜)

  1. network output (text-thresh map) 으로 adaptive thresholding 이 가능
  2. task가 3개로 늘어나면서 multi-task learning 효과도 생김
    ===> (prob map, thresh map, binary map 3개 모두 loss를 태움)

Model

image

백본은 res50, res18 에 "deformable conv 2" 적용시킨 FPN 사용.

Differentiable Binarization

image
P는 prediction map, T 는 threshold map
x 의 값이 다음과 같다면,
image
DB(Differentiable Binarization) 의 그래프는 다음과 같이 그려짐
image
SB == Standard Binarization

만약 binarization 이후에 적용하는게 cross-entropy loss 라고 해보자.
그럼 -log를 붙여줘서 loss 가 다음과 같이 나오게 됨
image
이걸 미분 때려보면,
image

즉, k 값에 의해 loss의 크기가 달라지게 되는데, k는 실험적으로 50 이라고 함.

How to make GT

image
PSENet과 굉장히 유사하게 label을 만들어 냄.

위 GT 그림에서 각각 색깔은 다음과 같음.
G: 빨간색
Gd: 초록색
Gs: 파란색

probability map

Vatti clipping algorithm 으로 original G에서 Gs를 만들어 냄
얼마나 shrinking 할 건지 offset D를 구하는 식은 다음과 같음.
image

threshold map

offset D를 그대로 이용해서 뚱뚱한 Gd를 만들어 냄
threshold map은 G 에서 Gd, Gs 까지의 distance를 heatmap 화 시킨 것임.

저자들이 실험을 해보니, text threshold map GT를 함께 제공해서 학습시키는게 도움이 되었다고 함.

Loss

image
Ls ==> segmentation (prob map) ==> BCELoss
Lb ==> binarized map ==> BCELoss
Lt ==> threshold map ==> L1 Loss
image

Results

Ablation study

CTW1500 기준.
DB를 쓰면
==> resnet18 에서 3.7 gain
==> resnet50 에서 4.9 gain

deformable conv 2 썼을 때
==> resnet18 에서 1.5 gain
==> resnet50 에서 5.0 gain
image

그닥.... 우와 하는 논문은 아니였음.
근데 우리 네트워크에도 응용해서 써볼만함 직한 방법.

[2] Deformable DETR: Deformable Transformers for End-to-End Object Detection

백신 공가 이틀 사용 후 복귀. (21.10.05 - 21.10.06)
포스트가 잘 이해가지 않는다면 #28 을 먼저 볼 것.

Deformable DETR

paper code

DETR 이 hand-designed feature를 없애고 좋은 성능을 내지만 2가지 단점이 있음

  • 느린 수렴속도
  • limited feature space resolution (quadratic 하게 증가하는 attention 계산량)

이를 위해서 deformable DETR 제안.

  • small set을 갖고 efficient attention 수행
  • multi-scale feature 활용

Deformable Attention Module

Deformable Attention 부터 이해해보자

image
x ==> input feature (CHW)
q ==> query index
p_q ==> 2d reference point
z_q ==> content feature
M ==> Num of attention head
K ==> Num total sampled key

M = 8 and K = 4 가 default 값으로 사용됨

이를 그림으로 나타내면 다음과 같다.

image

query feature z_q 를 Linear 태워서 offset 을 구하고 또다른 Linear 를 태워서 attention weight를 구한다. query 만으로 attention weight를 구하는 방식이 lambda network 나 se-module 과 닮았다고 생각할 수 있다.

이것을 약간 더 확장해서 multi-scale 로 가져갈 수 있다.
image

L ==> feature level
φ ==> normalized P^ 포인트들을 원본에 맞게 re-scale 해주는 function

이것만 이해하면 나머지 내용은 쉽게 이해 가능하다.

image

Encoder

ResNet 의 C3, C4, C5, C6 feature map 4개가 encoder input으로 활용됨
input, output featuremap 크기는 동일함
query 별 reference point 는 encoder에서는 해당 point 자체가 됨.
각 query pixel이 어떤 feature level 을 사용하고 있는지 명확히 noti 주기 위해서 scale-level embedding을 더해줌
scale-level embedding은 randomly initialized 되고 jointly 학습됨.

Decoder

Decoder 에 self-attention 부분은 변하지 않음.
cross-attention 부분에는 제안한 모듈을 그대로 적용됨
reference point P^ 은 object-query embedding을 linear-sigmoid 태워서 얻어냄 (0~1)
해당 reference point 를 featuremap size 에 맞게 원복시켜서 offset 얻어냄

Additional Techniques

성능향상을 위해 추가적으로 2가지를 넣었다.

Iterative BBOX Refinement

각각의 decoder layer 가 previous layer 의 box output 을 refine 하는 방식

Two-Stage Deformable DETR

Encoder 에서 region proposal 을 내뱉는 방식.
각 feature point 가 object query 로써 Region Proposal 을 수행함.
NMS 적용하지 않고 바로 second stage 로 넘겨줌

Results

아쉽게도 속도는 더 느리다.
image

FPN 도 붙여보았는데, 이 구조에서는 그닥 필요 없음.
OCR 같이 multi-scale 이슈가 큰 도메인에서는 FPN 실험을 따로 진행해 보는 편이 좋을 것으로 보임.
image

[4] Fast Convergence of DETR with Spatially Modulated Co-Attention (SMCA)

paper code

DETR의 빠른 convergence 를 위해 SMCA (Spatially Modulated Co-Attention) 제안
108epoch 에서 coco17 val 45.6 AP 를 끌어냈는데 deformable DETR 이 44.9 를 끌어냈던 것을 생각하면 SMCA 좋은 성능을 보인다 할 수 있음.
다만,,, DETR 이 handcrafted 들을 모두 없앴는데, 점점 다시 hand-crafted feature 들이 늘어나는 것 같음.
Deformable DETR 짱짱맨

SMCA 방법론에 deformable DETR 에서 사용하던 방법 (self-attention 연산량 줄이기) 를 얹어서 사용할 수 있을 것으로 보이는데
같이 사용하면 어떻게 될 지 궁금함. (intra- multi-scale 방법들 대신 deformable 방식쓰면?)

SMCA

image

먼저, DETR 의 Query 가 수렴이 어렵다는 점에 집중을 함.
object 중심을 예측하는 추가적인 operation 구성.
image
위 그림에서는 주황색 영역의 spatial prior를 뽑아낸다고 볼 수 있음.
O_q 는 object query. MLP 는 2-layer FC.
이를 통해 2d gaussian 을 뽑아내게 됨 (0~1)
beta 값은 hyperparmeter
image
뽑아낸 Gaussian weight에 log 붙여서 attention 구할 때 사용해주면 완료!
image

Multi-Head

multi-head 마다 추가적인 operation 을 둬서 다른 center를 뽑아보기도 했음
다음과 같은 center 변화량을 예측하도록 하고,
image
head마다 다른 gaussian을 적용토록 한 것.
image

Multi-Scale Features

여기에 multi-scale input을 추가로 구성.
각 input 은 intra-scale self-attention 모듈을 통해 feature 별 self-attention이 수행됨. 이는 multi-scale self-attention이 cost가 크기 때문

Decoder에서는 FPN 과는 다르게 scale-selection attention weight를 생성해서 feature들을 적절히 혼합해줌.
이 녀석들 또한 object query로 예측이 되어짐
image

이럴 경우, key와 value 차원이 하나 더 늘어나기 때문에 SMCA 는 다음과 같이 적용됨.
image

Results

object query 100개 대신 300개 사용
Focal Loss 사용
image

이 논문을 읽으며 ablation이 궁금했음
Gaussian의 height, width 를 각각 구하는 것이 independent, 한번에 예측하는게 single 방식임
independence 에 multi-head 별로 gaussian을 구하는게 성능이 도움이 됨
image

다음은, intra-multi- self attention ablation.
아쉽게도 deformable detr 방식과의 비교는 없음.
self attention의 weight는 share 하는 편이 좋음.
image

[8일차] SCATTER: Selective Context Attentional Scene Text Recognizer

https://arxiv.org/abs/2003.11288

image
익숙한 분들이 이렇게 논문들에 등장할 때마다 너무 신기하다. (Baek et al)
감사하며 일해야지.

저자들이 들고온 selective decoder 기법은 pose estimation 에서 많이 사용되는 기법으로 보임.

Contribution

  1. Repetitive processing architecture 제안.
    Intermediate selective decoder를 supervision 으로 학습시켰고,
    해당 architecture로 encoder를 학습시켰다고 함.
  2. Selective attention decoder 는 two-step attention 을 통해 visual, context feature 동시에 뽑음.
    first attn => visaul, context feature 들이 각각 어디에 해당하는지 찾음
    second attn => feature 를 sequence 로 보고 attention

Model

image

  1. Transform: TPS
  2. Feature Extraction: FAN Style Resnet 29 layer
  3. Visual Feature Refinement: CTC
  4. Selective Contextual Refinement Blocks: BiLSTM

1, 2, 3 까지는 지금까지와 같은 모델인데, 4번 모듈이 붙으면서 다른 모델이 되었음.

Two Step Attention

image

First Step Attention

visual feature 에 2 layer bilstm을 통과시키면 contextual feature 가 되는데,
이 둘을 concat 하고 fully connected layer를 통해 attention map을 거치도록 함.

Second Step Attention

그렇게 뽑아낸 feature를 sequence 하게 2 layer bilstm 에 태워서 최종 prediction 을 하도록 함.

첫 모델 그림으로도 알 수 있듯이, contextual feature block 을 여러개 쌓아서 decoder를 쌓아나갈 수 있다.

Loss

그래서 어떻게 학습할 지는 항상 loss 를 보는 게 가장 직관적임
image
예상했겠지만, CTC loss 에다가 여러개의 decoder loss 를 lambda 붙여가면서 함께 학습시킴.
실험적으로, lambda_CTC = 0.1, lambda_attn == 1.0 으로 주었다고 함.

Results

image
image

딱 봐도 속도가 느릴 것 같은데 이 친구들 속도 언급을 안 한다 ㅋㅋ...
또 아쉬운 점은 SynthAdd 함께 학습시킨 점. SynthAdd 데이터 때매 fair comparison이 망가진다.
37 class output인 것도 아쉽다.
아이디어는 좋지만,,, 이게 CVPR 20 논문이라고...?

[2일차] ABCNet: Real-time Scene Text Spotting with Adaptive Bezier-Curve Network

https://arxiv.org/abs/2002.10200

image
image

neural net output 으로 bezier_curve 를 뱉자는 논문.
우선 이것부터 보기를 추천.
중학생도 이해하는 bezier curve blog

실험적으로 3차 bezier-curve면 충분하다는 것을 보임.
(사실 3차 이상으로 표현할 만한 curve text 도 없을 듯 ...)
즉, 4개의 control point를 예측하면 되는 문제임.

박스마다 위 아래의 bezier-curve 를 예측하면 되기 때문에 총 8개의 control point를 예측하면 박스 하나가 딱 나옴.

image

Total text 는 위 아래 5 개씩 annotation (m=5),
CTW1500 은 위 아래 7 개씩 annotation (m=7) 되어 있음
p 가 annotated 되어진 point 이고 basis function B 는 정해져 있기 때문에,
least square method로 기존 GT 와 가장 유사한 control point b 4개를 구할 수 있음.

image
image

image
빨간 점들이 control points.
요것들을 gt 로 두고 regression.
#4 와 regression 방식이 유사함.

image
위와 같은 식으로 16channel output (8 points {x, y}) 을 활용.
즉, feature map 1 칸마다 1개의 detection 을 만들도록 하는 것.

수식을 보면 잉? 이게 뭐지 할 수 있음.
설명이 불친절하다 느꼈음 ㅎㅎ
그냥 x_min, y_min 이 4개 control point 중 가장 작은 x, y 값임.
가장 작은 x, y 값 기준으로 (top-left point) 거리를 계산하고 그걸 prediction 하는 거임.
loss 는 #4 와 같은 smooth ln loss 일 듯 (확인해 봐야 함)
(0, 0) 기준으로 옮겨다 놓고, regression 하겠다는 이야기임.

BezierAlign

BezierAlign 을 제시함, RoiAlign의 개선 버전.
아래 이미지를 보면 딱 느낌이 옴.
image

predicted bezier curve를 그려보고
박스 윗 라인 의 point (upper boundary point) tp와
박스 아래 라인 의 point (lower boundary point) bp를 계산.

다음과 같은 식으로 sampling point op를 계산할 수 있음.
image
이 과정이 그냥 위 BezierAlign 이미지를 수식화한 것.

이제, sampling point op 를 갖고, ROIAlign 하듯이 bilinear interpolation 수행하면 됨.

Recognizer

recognition은 6 conv + 1 bidir-lstm + ctc loss 를 사용했다.
97 characters (eng + digit + symbols)
image

학습 시 recognition 의 입력은 GT bezier controlpoints 로 BezierAlign 한 feature 가 들어감.

Result

SynthText 기법으로 추가 데이터 150k 를 만들었는데, 이것 때문에 fair comparison 은 아닌 듯.
image

공식 구현체: https://github.com/Yuliang-Liu/bezier_curve_text_spotting

[7일차] Learning from Extrinsic and Intrinsic Supervisions for Domain Generalization (EISNet)

MultiTask Learning 을 적용한 논문.

paper: https://arxiv.org/pdf/2007.09316.pdf
code: https://github.com/EmmaW8/EISNet

image

2가지를 동시에 수행해서 multi-domain에서의 성능을 끌어올린다.

  1. Extrinsic Supervision (momentum metric learning)
  2. Intrinsic Supervision (self-supervised auxiliary task)

Extrinsic Supervision

Triplet Loss

원래 Triplet Loss 는 다음과 같다.
positive와 는 가까워지고 negative와는 멀어지도록 loss가 구성된다.
image
image

원래 negative sample을 구할 때는 아래 그림에서 (a) 형태로 랜덤하게 sampling 했다면,
image
쓸모 없는 train step 을 피하기 위해 negative mining을 한다.
그림 (b) (c) 를 보면 직관적으로 이해가 가능하다.

Encoder update

theta_f == Encoder == 학습되는 encoder
theta_g == MUEncoder == moving average of encoder f
image
momentum coefficient δ 를 크게 줘서 천천히 MUEncoder를 학습하는 게 좋았다.

Intrinsic Supervision

Domain Generalization by Solving Jigsaw Puzzles 에서 하듯이 jigsaw 퍼즐 30개 패턴을 풀게 한다.

그니까 permutation 가능한 거 30 개를 미리 정해두고 classification 한다고 보면 된다.
image

결국 auxiliary task 와 classification task 는 cross entropy를 적용하고 끝남.

[3] UP-DETR: Unsupervised Pre-training for Object Detection with Transformers

UP-DETR: Unsupervised Pre-training for Object Detection with Transformers

paper code

당연하게도 DETR에 대해서도 unsupervised training 을 하고자 하는 노력이 있었다.
나름 성능향상을 이끌어 냈지만 같은 시기에 나온, deformable DETR 에 비해 성능향상이 미미하여 묻힌 감이 있다. (Results section 참조)

Random Query Patch Detection

pretraining task 를 넣으면서 2가지 문제를 풀었다.

  • Multi-task learning: pretrain task 가 classification 성능을 떨어뜨리지 않게 하기 위해 backbone을 freeze 시키고, patch feature reconstruction 수행
  • Multi-Query localization: 각각의 다른 object query 는 다른 area 와 boxsize 에 집중함. 이를 보여주기 위해 single-query localization 을 먼저 제시함. multi-query localization 에서는 query patch 와 object query 사이의 assignment 문제를 풀기 위해서 object query shuffleattention mask 를 제시.

image
N 은 총 쿼리 수, M 은 총 random patch 수이다.
random patch를 backbone cnn + GAP 로 (2048 dim) 뽑아내고 나면 query에 더해주는 방식.
image
DETR loss 에 L_rec 하나 추가된 것. reconstruction loss로는 l2를 사용함.
image
즉, DETR output 에 그냥 2048 vector 하나 추가해 주고, regularization 하나 넣어준 것.
위에서도 말했지만, 요 녀석을 넣어서 classification 성능이 덜 떨어지게 하고 싶었다고 함. (ablation 을 보면 최종 성능에는 별로 영향 없어 보이지만, 수렴속도에서 차이가 컸다고 함)

Attention Mask

multi-query로 가면, query patch 간의 independence 를 보장하기 위해 attention mask를 도입.
decoder 의 self attention에 다음과 같이 mask X를 추가함
image
image
그니까 그냥 self-attention 할 때 다른 patch는 안 보는 것.

Param Setup

ImageNet 1K 로 label 없이 pretraining 수행 (?!?!)
PRETRAIN

  1. ResNet 50 BackBone은 SwAV 로 pretrain
  2. shortest length [(H)320, (W)480] largest length 640 으로 resize
  3. query-patch 는 128x128 로 crop, SimCLR augmentation 적용
  4. AdamW 1e-4 (decay 1e-4)
  5. Batch 256, 60 epoch,

FINETUNE

  1. CNN Backbone lr 1e-5
  2. transformer lr 1e-4
  3. 나머지는 DETR과 동일

Results

coco 2017 val 성능
image
참고용으로 deformable detr 테이블도 가져왔음.
image

ablation. freeze backbone은 선택이 아닌 필수.
image
4가지 ablation 모델들의 학습 그래프.
image

[23] Long-Short Transformer: Efficient Transformers for Language and Vision

paper
code

long-range attention 과 short attention 을 각각 보자는 논문

INTRO

  • 다양한 efficient attention 나왔지만 language, vision 둘 다 좋은 성능을 내는 방법들이 없었음.
  • pattern을 박는 sparse attention 방법론은 attention의 가능성을 제한해 버림
  • low-rank projection 은 NLP 진영에서만 검증됨

Contributions

  • Long-Short Transformer (Transformer-LS) 제안
  • Long Range Arena (LRA) benchmark sota (S4 나오기 전까지 ..)
  • Auto-regressive, bidirectional 하게 linear complexity 로 해결 가능

Transformer-LS

image

Notions

image
imagequery, key, value
projection matrix for output
i번째 head (dot-product attn)
head 별 dimension

Short-term Attention via Segment-wise Sliding Window

LongFormer 나 BigBird 처럼 sliding window 수행.
다만, "segment" 기반으로 수행. PyTorch 에서는 단순히 pixel 마다 길이를 상하좌우 w 로 주는 것보다 이게 빨랐음 (?)

  1. input sequence 를 length w 의 disjoint segment로 나눔
  2. segment 내부에서는 전부 attend && home segment 의 좌우 2/w 크기만큼 추가 attend (총 2w 만큼 봄)
    image

아래 이미지는 LongFormer 의 sliding window attn figure
image

물론 이 녀석을 쌓으면 long range 도 볼 수는 있지만, 성능이 떨어지니까 long range attention 관련 method 를 따로 둠.

autoregressive 하게 붙일 때는 attention을 다르게 붙임. 2d 그림으로 보면,
image

Long-range Attention via Dynamic Projection

image
prjection param (Linformer 처럼 learnable)
i번째 head의 dynamic low-rank projection (r << n)
image
image

Aggregating Long-range and Short-term Attention

이제 long 과 short 를 합쳐줘야 하는데, Head마다 다른 attention mechanism 을 두고 합치는 방식이 아니라, local 과 global attn 값이 서로를 이해하는데 도움을 줄 수 있도록 구성했다고 한다.

position t 에서의 i번째 attention 은 다음과 같다.
global low-rank projected keys and values
local keys and values

image
image

Dual LN

학습 초반에 의 norm 값이 다르기 때문에 Dual LN 을 제안

image
image

Results

LRA

image

ImageNet

image
image

AutoRegressive

image
image

RobustNess

image

[20] Patches Are All You Need? (ConvMixer)

ICLR22 submission paper.
아이디어는 간단하다. 아직, accept 된건 아니지만, paper가 재미있어서 가져왔다.
ViT가 잘되는 건, transformer 가 좋아서일까, patch input이 좋아서일까?
저자들은 patch 로 input 넣는 구조 자체가 좋아서라고 말하며, ConvMixer라는 구조를 제안하고 실험해본다.

paper
code

ConvMixer

이 그림으로 설명 가능하다.
patch input에 저런 구조를 넣어서 성능을 재 보았다.
image
image
image

Result

hmmteresting!
image

[8] Pix2seq: A Language Modeling Framework for Object Detection

paper

image
token으로 박스를 뽑아내자!

image
당연하게도 box 좌표를 tokenize 하려면 discretize 는 필수.
위 그림은 quantize size 에 따른 output 형태.
image
제시하는 모델은 2000 quantize bin, longer-size 1333 input임

0번째 토큰은 eos.
prediction은 [ymin, xmin, ymax, xmax, c] 형태로 진행.

모델 갖고 실험하다 보니, autoregressive decoder에서 너무 빨리 generation을 끝마치는 일들이 많더라. precision은 좋은데 recall이 너무 떨어지니까, 이를 해결하기 위해 방법 도입
image
noise box를 만들어내서 모델로 하여금 예측하도록 하는 것.
noise box 는 box 주변에 만들어내기도 하고, 랜덤하게 만들어 내기도 함
얼만큼의 비율로 두 형태의 noise 를 만들어 냈는지는 논문에 작성되어 있지 않음.

image
noise box 의 좌표값들에 대해서는 n/a token을 주고 loss 에서 제외시킴. class 는 noise class를 넣어줌.
랜덤하게 class input token 을 dropout 시켰음 (prob 0.5 - 빡세게 주네)

sequence length 는 500 이고, 100개 object까지 예측 가능.
real object 로 앞부분을 채우고, 나머지는 noise로 채워줌

Results

image
성능은 나쁘지 않음
다만, autoregressive 한 방법이라 상당히 느릴 수 있음.

Ablations

AutoRegressive 방법론이라서 여러가지 형태로 gt box 순서를 주어봤음
image

  1. random
  2. area (i.e., descending object size)
  3. dist2ori (i.e., the distance of top-left corner of the bounding box to the origin)
  4. class (name)
  5. class + area (i.e., the objects are first ordered by their class, and if there are multiple objects of the same class, they are ordered by area)
  6. class + dist2ori.

image
random이 최고!

image
augmentation이 큰 역할을 수행함.

[7] Anchor DETR: Query Design for Transformer-Based Detector

paper code
다들 쿼리에 집중하는 중.
anchor detr 은 multiple object on one position case 도 대응 가능

image
DETR (#28) 에서도 나왔던 figure 인데, 훨씬 query들이 모여있는 걸 볼 수 있음.
green ==> small box
red ==> large horizontal box
blue ==> large vertical box
black (여기서 추가됨) ==> anchor point

Anchor DETR

Anchor

2가지 anchor type 을 시도해 봄
image
anchor 를 이용해 query 를 만들 때는 다음과 같이 만듦
보통 positional encoding function g 를 sinusoid 로 두지만, 여기서는 2 linear neural-net 을 사용함.
image

Pattern Embedding

추가로, 하나의 query에서 여러 object를 볼 수 있도록, pattern embedding 을 놓고, 학습시킴. (그냥 특정 데이터셋 성능 높이려고 넣은거 아닌가? real world scenario 에서도 이게 과연 좋을까?)
최종적인 query는 다음과 같이 구해짐
image
pattern-embedding 크기는 (3, channel) 로 작은 크기임.

Row-Column Decoupled Attention (RCDA)

image
요 녀석을 아래 두개의 식으로 1D global avg pooling 을 활용해서 만들어버림
image
image
그 다음에 row-wise, column-wise attention을 수행함
image

Results

image

Anchor

grid를 쓰든 안쓰든 별차이 없음
learned ==> 300 Dim
grid ==> 17x17 ~= 300
image

Pattern Embedding

image

RCDA

image

anchor 썼더니 성능이 쫙 오르더라.. 를 기대하며 왔지만, 성능향상에 있어서 anchor 의 영향이 커 보이지 않음. 다만, figure 1 은 상당히 인상적임. query 별로 역할이 명확하게 분리가 되는 것이 참 신기함.

[6일차] RAFT: Recurrent All-Pairs Field Transforms for Optical Flow

paper: https://arxiv.org/pdf/2003.12039.pdf
code: https://github.com/princeton-vl/RAFT

Optical Flow란 video 에서 frame 별로 object가 어떻게 움직이는 지 관찰하는 task이다.

아래 두 gif 를 보면 어떤 느낌인지 알 수 있을 것이다.
0
1

RAFT (Recurrent All-Pairs Field Transforms)

image

RAFT 는 크게 3 가지 부분으로 나눌 수 있다.

  1. Feature Encoder, Context Encoder
  2. Correlation Layer ==> 내적을 통해 4D W × H × W × H correlation volume 을 구함.
  3. Update Operator ==> recurrent하게 optical flow를 업데이트함.

i1, i2 가 각각 input1, input2 를 나타내고, i2 는 i1 바로 다음 frame이라고 하자.
i1 에서의 각 pixel이 (u, v) 형태로 존재한다면,
i2 에서의 각 pixel은 다음과 같다.
image
하고 싶은건 f1 와 f2 를 구하는 것이다.

Feature Extraction

image
input의 크기는 따로 preprocess 하지 않는 것으로 보임.
학습 할 때는 random하게 aspect ratio를 조정해서 resize함. 코드 링크
feature extraction을 하면서 총 8배까지 feature map이 줄어든다.

Correlation Layer

image
여기서 Correlation Pyramid 라는 걸 구성하는데,
끝 2개 dimension이 다른 C1, C2, C3, C4를 만들어 낸다.
image

C1 구할 때는 말 그대로 하나하나 내적을 다한다. 여기서 좀 computation이 먹을 것 같은데, 효율적으로 구성하는 것도 간단한 논문거리로 좋을 듯.
C2, C3, C4 에서는 조금 더 계산을 효율적으로 할 수 있다. 내적하기 전 vector들 끼리 평균을 내고 나서 계산하기 방법
image

Update Operator

CNN 을 이용해 recursive하게 쌓아 나가는 방식이다.
전체 그림을 통해 보면 정말 RNN 이 떠오른다.
image
image
전체 그림으로 보면 Hidden-State 가 Final Output이 되는 것 같지만 그게 아니라 h_t 에 추가 conv 를 태우는 형식으로 이루어 진다.
ConvGRU 를 사용하기 때문에 당연히 Hidden-State 가 존재한다.
최종 output 은 0에서 시작되서 점점 더해지게 된다.
FLOW 가 0이란 건 이전 프레임과 다음 프레임이 변화가 없다는 뜻이니까 초기값으로 적절한 선택으로 보인다.
ConvGRU의 경우 5x5로 하면 계산량이 크니까 5x1 과 1x5의 조합으로 사용한다.

뽑은 delta_F 는 아래와 같은 수식으로 FLOW를 업데이트 해 나간다.
image

ConvGRU를 수식으로 나타내면 다음과 같다.
image
image

Convex Upsampling

최종 output featuremap은 기존 heatmap 대비 1/8 크기를 갖게 되어서 upsampling을 하게 되는데, 일반적인 bilinear보다 제안하는 방식이 좋다.
방법은 upsampling 을 배우게 하는 식으로 구성하는데,
image
크기를 예측하도록 하고 아래와 같이 작동하도록 만든다.
pytorch unfold function을 통해 구현한다고 하는데, 이건 써먹을 곳도 많이 있을 것 같다.

image
image

Loss

image
감마는 0.8 사용.
iteration 이 더해질 수록 loss 반영이 커지는 형태이다.

Small Model

image
small model 의 경우는 channel 수가 줄고 convGRU 3x3 을 썼다. 3xx는 오타로 보임.

Ablation Study

image

Results

image
image

[5] PnP-DETR: Towards Efficient Visual Analysis with Transformers

paper code

PNP (Poll aNd Pool)

image
Input에 따라 less informatic 한 부분에는 computation을 적게 주도록 하는 논문

image
poll sampler 를 통해 fine feature 를 뽑아내고,
non-sampled feature 들에 pool sampler를 적용해서 coarse feature 들을 뽑아냄

Poll Sampler

image
scoring network 를 통해 informatic 한 정보를 얼마나 갖고 있는 지 뽑아냄
뽑아낸 score 들을 이용해 top N 개의 feature를 뽑아내는데, 다음과 같은 식으로 뽑아냄
image
다르게 생각하면, attention 줘서 top N 개 뽑아낸 것.

Pool Sampler

learnable weight W^a (C x M) 를 두고 다음과 같이 aggregation weight a_r 을 뽑아냄
image
image

남아 있는 feature도 Linear (C x C) 로 projection 한 번 해주고,
image

a_r 에 softmax 취해주고나서 projected feature 에 곱해준다
image

Results

간단한 방법론. 나쁘지 않은 성능
알파값은 poll ratio 임
image

M 은 coarse (pool sampler) dimension.
image

개인적으로 드는 생각.
그냥 backbone 쪽 효율적으로 만드는 구조 하나 넣어준 거 아닌가 싶음.
resnet 말고 다른 backbone 에 대해서도 잘 동작하는 지 못 보여준 것이 아쉬움
이미 효율적인 feature를 뽑아낼 수 있는 구조에서는 어떻게 동작하려나..

[18] Rethinking Semantic Segmentation from a Sequence-to-Sequence Perspective with Transformers (SETR)

paper
code

Transformer 로 segmentation 하자!

SETR

image
단순하다.

480x480x3 input, 16x16 grid로 나눔. 즉 각 patch 는 (30, 30, 3) 의 크기이다. 요 녀석을 Linear projection 시키고 encoder 24개를 태운다. 그림에서 (a) 에 해당한다. (linear 대신 앞에 CNN 몇 개 쓰는게 더 좋았을 것 같은데)

Decoder

  1. naive upsampling (Naive)
    1. 2 layer (1×1 conv + sync BN + ReLU + 1×1 conv) 를 거치면서 class 개수만큼 channel 늘려줌 (Cityscape ==> 19)
    2. 단순히 binlinear upsample 을 통해 full resolution을 만들어 준다.
  2. Progressive UPsampling (PUP)
    1. 그림에서 (b)에 해당한다.
    2. conv로 차례차례 이미지 resolution 올려줌
  3. Multi-Level feature Aggregation (MLA)
    1. 그림에서 (c)에 해당한다.
    2. 6, 12, 18, 24 layer output 을 활용했음

PSPNet 처럼 auxiliary loss 활용했음
encoder는 다음과 같이 2개를 사용한다.
image
mIOU는 좋은데... 좋은데... 24개라니... ㄷㄷ...

Results

variants.
image
R ==> random initialized.
40k, 80k ==> 학습 iteration
Cityscape train_fine set 으로 학습시키고, validation set 에 적용했음.

random initialized 는 확실히 구리다.

ADE20K

image
image

Pascal Context

image
image

CityScape

image
image
image

[12] GradNorm: Gradient Normalization for Adaptive Loss Balancing in Deep Multitask Networks

paper
youtube-naver_techtalk

간단하고 잘 동작하는 방법.
Uncertainty 대가 Yarin Gal 이 제시한 방법보다 잘 동작하는 편.

관련해서 이후에 나온 work 들은 다음과 같다. (시간날 때 살펴보자)
Multi-Task Learning as Multi-Objective Optimization - NeurIPS18
Multi-Loss Weighting with Coefficient of Variations - WACV21

Cov-weighting (WACV21) 논문을 보면 생각보다 multi-objective (NeurIPS18) 의 성능이 좋지 못하다 (task by task). broad 하게 널리 쓰이고, 검증된 방법은 grad-norm 이라 판단이 된다.

GradNorm

image
아 ㅋㅋ 오캄 면도날 EZ

Task 별로 난이도가 다를 텐데 MTL에서는 요게 문제가 된다.
특정 task 는 너무 빨리 수렴해서 overfitting 이 진행되는 것.
이걸 적당히 normalize 시켜서 adaptive 하게 loss balancing 을 수행한다.

이 문제를 해결하기 위해 task 별로 priority를 정해주는 work 도 있다.
Dynamic-Task-Prioritization-for-Multitask-Learning - ECCV18

Notation

Loss 는 w_i weight 가 곱해져서 최종 loss를 만들게 된다.
image

w_i weight 는 매 step-by-step t 를 이용해 표기할 수 있다.
w_i(t) 는 그니까 t 시점의 i번째 task의 weight
image

hyperparameter α는 원래의 gradient로 되돌리는 복원력의 강도.
α 가 0이면 task-wise grad 가 완전히 같은 크기로 조정된다.
NYU dataset 에서는 1.5 (0~3 모두 성능향상에 도움이 되었음)
toy example 들에서는 0.12
근데 이게 좀 찝찝하다. 결국 데이터마다 알파값을 잘 조정해야하는 것 아닌가

추가적인 notation 들
image
image

Algorithm & Code

바로 algorithm, 코드를 살펴보자.
notation 만 이해하고 봐도 굉장히 직관적이다.
image

코드는 unofficial pytorch code (https://github.com/brianlan/pytorch-grad-norm/blob/master/train.py#L93)를 참고해서 정리해 보았다.

# get layer of shared weights
W = model.get_last_shared_layer()

# get the gradient norms for each of the tasks
# G^{(i)}_w(t) 
norms = []
for i in range(len(task_loss)):
    # get the gradient of this task loss with respect to the shared parameters
    gygw = torch.autograd.grad(task_loss[i], W.parameters(), retain_graph=True)
    # compute the norm
    norms.append(torch.norm(torch.mul(model.weights[i], gygw[0])))
    norms = torch.stack(norms)

# compute the inverse training rate r_i(t) 
loss_ratio = task_loss.data.cpu().numpy() / initial_task_loss  # \curl{L}_i 
inverse_train_rate = loss_ratio / np.mean(loss_ratio)  # r_i(t)

# compute the mean norm \tilde{G}_w(t) 
mean_norm = np.mean(norms.data.cpu().numpy())

# compute the GradNorm loss 
# this term has to remain constant
constant_term = torch.tensor(mean_norm * (inverse_train_rate ** args.alpha), requires_grad=False)
constant_term = constant_term.cuda()

# this is the GradNorm loss itself
grad_norm_loss = torch.tensor(torch.sum(torch.abs(norms - constant_term)))

# compute the gradient for the weights
model.weights.grad = torch.autograd.grad(grad_norm_loss, model.weights)[0]

[4일차] Deep Matching Prior Network: Toward Tighter Multi-oriented Text Detection

https://arxiv.org/pdf/1703.01425.pdf

처음으로 quadrangle text 를 찾는 detection 논문.
#2 에서 이 논문의 regression 방식을 사용했다 하길래 찾아보게 되었음.

논문에서 faster rcnn 등이 sliding window 방식을 취했다고 말해서 조금 헷갈렸음.
prediction 된 regression 값들과 anchor box를 이용해 최종 prediction box를 만드는 과정을 sliding window 방식이라 부르는 듯 ...

새로운 anchor box

image

Shared Monte-Carlo Method

image

그림이 직관적임. prediction 과 iou 계산할 때 사용.
hard negative mining 할 때도 사용됨.

  1. 10,000 개의 point 를 ground truth 에서 sampling 한다.
  2. sampling point 개수 비율로 GT 와 iou 값 구하기

Regression

이 부분이 보고 싶어서 이 논문을 본 것..

Faster-RCNN

Proposed

image

w_chr == circumscribed rectangle의 width
h_chr == circumscribed rectangle의 height

image

즉 center point 하나를 regression하고
그 기준의 point 4개 regression 하는 방식.
FCOS (#5) 가 생각나는 방식...!

Smooth ln loss

그냥 l2 loss 나 smooth l1 loss 보다 좋다는 smooth ln loss 제안
image
image
image

Results

성능은 당연히 그 당시 SOTA.
오랜만에 보이는 모델들이 많다.
image

[22] Perceiver IO: A General Architecture for Structured Inputs & Outputs

Perceiver 의 output 을 arbitrary size 로 만들어서 다양한 task 를 하나의 framework로 해결하자.
image

paper
code
youtube review - The AI Epiphany

RECAP

perceiver 부터 잠깐 recap!
image
byte-array 는 크기가 큰 input이라고 보면 된다. 커다란 input 에 대해서 효율적인 cross attention을 쓰고 점차적으로 query 를 업그레이드 해 나간다고 볼 수 있다. cross-attention 방식과 latent transformer 가 핵심이고 이들은 weight를 공유한다. (sharing 안하면 성능 엄청 떨어짐)
추가로, perceiver에서는 positional-encoding (Fourier Features) 을 query에 더하지 않고, concat 시켜준다.

L 개의 latent transformer layer, M의 key, N의 query 가 있을 때, 총 계산량은 O(MN + LN^2)
블록마다 cross-attention 하나 L개 transformer layer 가 있는 형태.
cross-attention을 수행할 때는 key-value 의 dimension을 기준으로 query dimension을 변화시켜도 되고, query dimension을 기준으로 변화시켜도 되는데, code에서는 default로 key-value의 dimension을 사용하고 있다. (물론 parameter 로 dimension을 정해줄 수도 있다)

DETR decoder 와 굉장히 유사한 면이 있는데 DETR 에서 encoder 만 쏙 빼버리고 image input을 바로 decoder 에 넣는다면 비슷한 구조이다.

perceiver에서 재밌었던 실험 중 하나는, input patch를 permute 해도 ImageNet 성능이 하락하지 않았다는 점.

Perceiver IO

image
perceiver IO block. Encoder 와 Process 는 각각 perceiver 에서의 cross-attention 과 latent-transformer 에 해당한다. 달라지는 부분은 output을 내는 부분!

output query array size 는 task 별로 달라진다. 원하는 shape를 O x E 로 두자.
attention dimension은 논문에 표기되어 있지 않지만 간단히 h 로 두겠다.
그림의 Decode 부분에서

  • query : linear projection (Ox? ==> Oxh)
  • key : linear projection (NxD ==> Nxh)
  • attention score : query * key^T (OxN)
  • value : linear projection (NxD ==> NxE)
  • final output : attn_score * value (OxE)

실험을 위해서는 3개의 모델 아키텍처를 구성했다.
image

이러한 구조로 아래와 같은 여러 task를 풀었다.
image

query array 구성은 다음 그림과 같이 했다고 한다.
image

Results

GLUE

image
UTF-8 byte tokenize 로 실용성을 높였다.

Optical Flow

image

AutoEncoder

image

Classification

pretrained? 는 JFT pretrained.
image

[10일차] Learning to Optimize Domain Specific Normalization for Domain Generalization

domain 별 normalization 을 학습하는 논문

paper: https://arxiv.org/pdf/1907.04275.pdf

image

Motivate

image

BN을 썼을 때보다 BN Fixed 했을 때가 더 성능이 좋았다.
image
axis는 channel이라고 하는데 느낌이 잘 안오긴 함;
암튼 instance norm 을 쓰는 게 class 별 discriminative 를 해치긴 하지만 multi-domain에서는 유용함.

image

그래서 BN과 IN을 결합한 아이디어를 제시한다.

DSON (Domain-Specific Optimized Normalization)

domain d 가 있을 때, 채널별로 존재하는 x_d.
image

x_d 는 DSON을 거쳐 다음과 같이 적용된다.
image
beta_d, gamma_d 는 whitening 단계 뒤에 적용되는 activation을 위한 도메인 별 affine parameter 이다.

image

여기서 mu_dn, sigma_dn 은 domain 별 BN 과 sample 별 Instance norm 을 결합해서 만들어짐.
image

"Domain generalization with domain-specific aggregation modules" 에서 사용한 "leave-one-domain-out validation strategy" 를 사용했다고 한다.

[1] End-to-End Object Detection with Transformers (DETR)

유명한 DETR.
Transformer를 이용해 좋은 성능의 detector를 만들자.

Contribution

  • NMS 와 Anchor generation 과 같은 hand-designed component를 없앰.
  • Transformer를 활용한 유의미한 detection 결과.
    • Bipartite matching
    • Non-autoregressive decoder
  • panoptic segmentation 에서도 유의미한 결과

Method

image
image
image

detection 문제를 direct set prediction problem 로 풀어냄.
DETR 구조가 duplicate prediction을 없애줌

학습할 때 중요한 point 가 있는데, 각 decoder layer 마다 모두 shared FFN 을 통과시키고 Hungarian Loss 를 적용하는 것임.
layernorm 도 shared 됨.
아쉽게도 요 녀석을 뺐을 때의 성능은 논문에서 보이지 않음.
Hugging Face 구현체 를 보면 좀 더 쉽게 이해가 됨.

Loss

N개의 fixed-size prediction 을 수행. (N==100)
prediction 과 정답을 맞추기 위해서 Hungarian Algorithm 사용.

matchin cost L_{match} 를 가장 낮추는 prediction permutation σ 를 찾아냄.
image

class c_i 의 probability 를 고대로 박아 놓은 것이 특징.
논문에서는 이렇게 해야 L_box 와 균형이 잘 맞아졌고 실험적으로 좋았다고 함.

permutation 을 찾아냈다면 loss 를 맥일 수 있음.
image

만약 N prediction에서 no-object가 나왔다면 log-prob term 에 1/10 weight를 주었다고 함 (class imbalance)
이건 Faster-RCNN에서 사용하던 방법과 유사함.

BBOX loss 로는 L1 loss 와 GIOU loss 를 사용했음. (XYWH 0~1 값 pred)

Positional Encoding

중요함. at attn 은 모듈 별로 attention 수행할 때마다 encoding 넣어주는 것.
image

Results

아쉽지만, 많은 수의 object가 있으면 recall 이 떨어짐.
image

ENCODER

Encoder가 두꺼워지면 성능향상
image
학습된 encoder의 self-attention vizualize 해보니까, 이미 잘 뽑아내고 있더라. encoder 중요함!
image

FFN

FFN 도 빼봤더니 param 41.3 => 28.7 대신 AP 2.3 이 줄어들더라.

LOSS

GIOU 도 중요함 !
image

DECODER

image
얇게 decoder 를 쓴다면 NMS 가 도움될 수 있음. 근데 6번째 decoder에서는 도움 x

image
coco 2017 데이터들을 갖고 decoder 앞에서부터 20개의 detection output 을 visualize 해 보았음. box의 center point 들을 점 찍어 준건데, 초록색은 small object, 빨간색이 large horizontal object 파란색이 large vertical object 임.
쿼리마다 다양하게 예측한다는 점을 강조하고 싶어서 넣은 figure.

COCO

Faster RCNN 보다 large object 성능이 좋고, small object 성능은 낮음. large 성능이 좋은 것은 transformer의 global feature extraction 능력 덕분일 것이라고 저자들이 주장함.
DC5 ==> Dilated C5 Stage
image

PANOPTIC SEGMENTATION

Panoptic 도 붙여볼 수 있는데, box랑 seg를 jointly 하게 학습시킬 수도 있고, 2 step으로 해도 되는데, 저자들은 2step으로 실험 진행했음. box쪽 weight fix 하고, 25epoch 추가로 seg 학습시켰음.
image
image

[2일차] Learning to Balance Specificity and Invariance for In and Out of Domain Generalization (DMG)

PAPER: https://arxiv.org/pdf/2008.12839.pdf
CODE: https://github.com/prithv1/DMG

image

Simple idea. Feature extraction 이 되고 나면 domain 별로 masking 하자.
mask 는 학습되어짐.

mask는 단순히 nn.Parameter 에 sigmoid 를 거쳐, bernoulli 분포에서 뽑게 되고
sampling 하면 intractable 하기 때문에 아래와 같이 STE(Straigh Through Estimator)를 이용해 구성하게 됨.

image

그리고 그림만 보면 그냥 feature extractor output 에 적용되는 것 끝! 처럼 보이지만,
중간중간 featuremap 에 mask가 적용됨
코드를 보면 resnet18, resnet50의 경우에 ["layer3", "layer4", "fc"] 에 mask가 적용됨을 알 수 있음.
image

위 그림에서 볼 수 있듯이 SIOU 라는게 추가되었는데, 식은 다음과 같음
image

단순하게 IOU 구하듯이 (겹치는 영역) / (A, B 전체 영역) 인데,
이게 mask 에 대해 적용되는 것.

즉, 해당 regularization term 이 크면 클 수록 mask 는 서로 다른 값을 갖도록 변함.

[14] The Power of Scale for Parameter-Efficient Prompt Tuning

paper
code
code2

T5에 prompt tuning 했더니 GPT3 의 few-shot prompt design 보다 좋더라
image
파란색은 GPT-3
빨강, 주황, 초록은 T5
초록은 추가로, 모든 task에 대해 single frozen model을 reuse 하도록 했는데, 이래 됨.

Prompt Tuning 은 inference 시나리오에서도 효과적임. prompt만 저장해 두면 되기 때문.
image

해당 논문 contribution.

  1. prompt tuning 을 제안하고 LLM (Large Language Models) 에 대한 효과 분석
  2. 많은 design choice 에 대한 ablation study
  3. prompt tuning 이 domain shift problems 도 해결함.
  4. prompt ensembling 을 제안함

Prompt Tuning

T5의 원칙대로 text-to-text 즉, text-generation으로 모든 task 수행
classification 도 generation task 로!

보통 prompting은 model parameter는 froze 시켜놓고, input 의 앞부분에 token 들을 붙여서 수행한다.
GPT-3 에서는, prompt token들의 representation P = {p1, p2, . . . , pn} 가 frozen 모델의 embedding table이었다.
그러다 보니, optimal prompt 를 찾아나가려면 prompt token들을 manual하게 사용해보거나 non-differentiable 하게 search 하는 방법이 필요했다.

Prompt-Tuning 에서는 pompt P 가 model parameter 로 국한되는 제한을 풀어버린다.
Prompt Design 은 고정된 embedding, 고정된 vocab에서 prompt token을 선택해야한다.
Prompt Tuning은 fixed special token prompt을 사용하는 것인데, 요 special token 들의 embedding은 learnable 한 것이다.

n개의 token이 주어졌을 때 {x1, x2, . . . , xn} T5는 token embedding 부터 수행한다.
embedding 이 만들어지고, prompt tuning 을 위해서 soft-prompt embedding 이 만들어진다. 그러고 나선 간단하게 concat 시켜준다. 업데이트 되는 건 오직 P_e 뿐. token embedding은 업데이트 되지 않는다.
image

Design Decisions

prompt token을 initialize 어떻게 할 지, 고민을 하게 되는데, 3가지 방법이 있다.

  1. random initialize
  2. word embedding 중에 랜덤하게 가져와서 initialize
  3. verbalizer 처럼 classification output 을 갖고 initialize 하기

prompt 길이 또한 중요한 옵션이다. embedding 개수가 늘어나는 거라, computation을 고려해야 한다. 관련 실험결과는 result에서 다루자.

Unlearning Span Corruption

GPT-3 와 다르게, T5 는

  1. encoder-decoder 구조를 사용
  2. span-corruption objective 로 학습됨 (masked span reconstruction)

예를 들어, Thank you for inviting me to your party last week 문장이 있다면 T5에서 input, output은 다음과 같음
input: Thank you <X> me to your party <Y> week
output: <X> for inviting <Y> last <Z>

이렇게 학습시키는게 효율적이긴 하지만, 멀쩡한 input을 본 적 없기 때문에 frozen single model을 만들기에는 적합하지 않음.
finetuning 으로는 충분히 좋은 성능을 내고 있지만, 우린 zero-shot을 해봐야 하지 않겠냐.
그래서 3가지를 실험해 보았다.

  1. Span Corruption : pretrained T5 활용
  2. Span Corruption + Sentinel : pretrained T5 + downstream 도 전부 sentinel로 만들어버리기.
  3. LM Adaptation : T5 를 갖고 LM objective 로 pretraining 을 쬐끔만 더 했음.

LM-objective ==> 아래 그림 처럼 다음 output 예측하는 오래된 방식.
image

Results

Ablations

image
a) prompt token length 는 20이면 충분해 보인다.
b) Initialize 는 random 하게만 안 하면 된다.
c) LM 을 조금 섞어주는게 좋다
d) LM은 50k 정도만 더 해주면 되더라.

Zero-Shot performance

image

Domain Shift Problem

image
Prompt Tuning 과 함께라면, QQP로 학습하고 MRPC 로 eval 하든, 거꾸로 하든 잘 된다!

Prompt Ensemble

image
single frozen T5-XXL model 에서 만들어낸 five-prompt tuning 성능. 5개 prompt 각각의 mean, best 성능을 뛰어넘는다.

[21] Focal Self-attention for Local-Global Interactions in Vision Transformers (Focal Transformer)

야심차게 내놓았지만, 사실 swin 과 성능이 비슷? 해서 뜨지는 않은 논문.
paper
code

DeiT 의 layer 별 heatmap 을 보면 점점 local context에서 넓게 넓혀가는 것을 볼 수 있다. 이런 특성을 이용하자.
image

[H x W x 3] 의 이미지는 4x4 patch 로 나누어진다. 그래서 총 patch 개수는 𝐻/4 x 𝑊/4 x d 부터 시작하게 된다.
image

Focal Self Attention은 다음과 같이 구성된다.
image
s_w 는 pooling size
s_r 은 pooled output size
그림에서 level이 3개 쓰였지만, 실재 모델은 2개 사용

image

Result

굉장히 단순한 아이디어, 좋은 성능. but, Swin 보다 같은 flops 에서 조금 더 느리고, parameter도 swin 보다 약간 더 썼다.
image

image

detection, segmentation 에서의 성능향상이 두드러지지 않는 것에 대해 저자들은 이렇게 말한다.

detection, segmentation task 는 좀 더 모델이 coarse feature를 보고 싶어한다. 
coarse feature를 압착해서 가져가다보니, focal-transformer가 크게 힘을 못 쓴 것으로 보인다.

[6] Conditional DETR for Fast Training Convergence

paper code

Decoder Cross Attention 효율화를 통한 training speed 향상
SMCA (#31) 와 유사함

image
그림 하나로 전부 설명이 가능하다.

회색영역 설명
image
이를 query 에 넣어 주었음
FFN ==> FC+ReLU+FC
Transformation FFN 을 지나 얻어내는 것은 256 dim diagonal matrix λ_q.
최종 p_q는 이렇게 구함.
image

Multi-head 마다 따로따로 compute !

Results

제안한 방법론을 CSQ 라고 함.

image

Ablations

image

  1. CSQ-C: decoder content embedding f 만 사용 (DETR)
  2. CSQ-P: positional embedding (DETR + pos-emb)
  3. CSQ-T: transformation λ_q (DETR + transform T)
  4. CSQ-I: 제안한 방법론에서 p_q 를 concat 대신 elementwise

Offset Regression, Focal Loss, CSQ 사용 여부에 따른 성능
image

Transformation은 Diagonal 형태가 가장 좋았음.
image

코드는 Decoder 부분만 확인하면 됨.
https://github.com/Atten4Vis/ConditionalDETR/blob/0b04a859c7fac33a866fcdea06f338610ba6e9d8/models/transformer.py#L141-L156

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.