Reference

Dong, Y., Sun, F., Ping, Z., Ouyang, Q., & Qian, L. (2020). DNA storage: research landscape and future prospects. National Science Review, 7(6), 1092–1107. https://doi.org/10.1093/nsr/nwaa007


Introduction: Information and Storage

  • 문제점:
    • 기존의 저장 방법들은 한계에 직면해 있으며, 유지비용, 데이터 손실 등 여러 문제를 해결할 새로운 솔루션이 요구된다.
  • DNA의 가능성:
    • 자연에서 DNA는 고밀도, 저비용의 안정적인 정보 저장 매체로 사용되고 있으며, 이러한 특성 때문에 차세대 정보 저장 매체로 주목받고 있다.

Overview of DNA Storage

 

Research history

Microvenus

  • In 1953, Watson and Crick revealed the structure of DNA molecules as the carrier of genetic information
  • In 1988, the artist Joe Davis made the first attempt to construct real DNA storage
    • Converted the pixel information of the image 'Microvenus' into a 0-1 sequence arranged in a 5 X7 matrix, where 1 indicated a dark pixel and 0 indicated a bright one.
    • This information was then encoded into a 28-base-pair long DNA molecule and inserted into Escherichia coli
    • After retrieval by DNA sequencing, the original image was successfully restored
  • In 1999, Clelland proposed using a method based on 'DNA micro-dots' like steganography to store information in DNA molecules
    • Steganography: 영상이나 오디오 파일에 비밀 메시지를 감추어 그 정보의 존재 자체를 숨기는 보안 기술
  • In 2001, Bancroft proposed using DNA bases to directly encode English letters, in a way similar to encoding amino acid sequences in DNA
  • 하지만 여태까지 뛰어난 성과를 보여주는 연구는 없었다. DNA molecule에 최대 1KB를 저장하는게 한계였다.
  • Church successfully stored up to 659KB of data in DNA molecules and Goldman stored even more data, reaching 739 KB
    • Not only texts but also images, sounds, PDFs

 

Self-information of DNA molecules:

  • DNA 염기서열의 정보 용량은 Shannon information theory에 의해 측정된다.
    • Shannon information: the maximal amount of self-information ($H$) that a single base can hold is:
      • $H=-\sum_{i}^{A,T,C,G}P\left ( i \right )logP\left ( i \right )\leq log\sum_{i}^{A,T,G,C}P\left ( i \right )\frac{1}{P\left ( i \right )}=log4=2bit$
        • $ P\left ( i \right ) $: the probability of base $i$ to occur at any position
        • $ logP\left ( i \right ) $: the base 2 logarithm as the bit (binary unit) is usually used as a measurement of digital information.
        • If the four bases are equally likely to occur, that is, $P_{i}=1/4$, each base pair int he DNA molecule can provide the largest information capacity (2 bit)
  • By converting the 2 bit/base to physical density:
    • $\rho =\frac{2 bit}{1 base \times 325\frac{Dalton}{base} \times 1.67\times 10^{-24}\frac{g}{Dalton}} = 3.69 \times 10^{21}\frac{bit}{g} = 4.61 \times 10^{20}\frac{Byte}{g}\approx 460\frac{EB}{g}$
      • $ \rho $: density
      • $ 1 \frac{EB}{g} $ = $10^{18} B$
  • 하지만 restrictions on the sequence of DNA molecule에 따라서 Shannon information capacity가 줄어들 수 있다는 점을 유의해야한다.

 

Mutual information and channel capacity

  • Mutual information between channel inputs and outputs is also an important factor in determining information capacity
    • DNA 저장 시스템의 효율성과 신뢰성을 평가하고 최적화하기 위해 Mutual Information과 Channel Capacity를 설명함.
    • Mutual Information: 입력 염기 $X$가 출력 염기 $Y$에 얼마나 많은 정보를 제공하는지
      • 높은 상호 정보량은 시퀀싱 과정에서 적은 오류가 발생하며, 입력 정보가 잘 전달된다는 것을 의미함.
    • Channel Capacity: 주어진 채널을 통해 신뢰성 있게 전송할 수 있는 최대 정보량
      • 채널 용량을 바탕으로 DNA 저장 시스템이 얼마나 잘 정보를 보존하고 복원할 수 있는지?
  • Mutual information:
    • Measures the fidelity with which the channel output $Y = \left\{ y_{i}|A,T,C,G\right\}$ (i.e. the readout of a DNA by sequencing) represents the channel input $X = \left\{ x_{i}|A,T,C,G\right\}$ (i.e. the preset DNA sequence)
    • 주어진 두 변수 $X$와 $Y$ 의 상호 정보량은 한 변수를 알았을 때 다른 변수에 대해 얻을 수 있는 정보의 양을 나타냅니다. 즉, $Y$ (DNA 시퀀싱 결과)가 $X$ (원래 DNA 시퀀스)를 얼마나 잘 나타내는지를 측정합니다.
      • 상호 정보는 두 확률 변수 $X$와 $Y$ 간의 종속성을 측정하는 값입니다. 이는 한 변수 $X$를 통해 다른 변수 $Y$에 대한 불확실성을 얼마나 줄일 수 있는지를 나타냅니다.
    • $I\left ( X;Y \right )=\sum_{i}^{A,T,C,G}\sum_{j}^{A,T,C,G}P\left ( x_{i}y_{j} \right )I\left ( x_{i};y_{j} \right )=\sum_{i}^{A,T,C,G}\sum_{j}^{A,T,C,G}P\left ( x_{i}y_{j} \right )log\frac{P\left ( x_{i}|y_{i} \right )}{P\left ( x_{i} \right )}$
      • $P\left ( x_{i} ,y_{j}\right )$: $X$가 $x_{i}$이고 $Y$가 $y_{j}$일 확률을 나타내는 공동 확률 분
    • $I\left ( X;Y \right )= H\left ( X \right )-H\left ( X|Y \right )\leq H\left ( X \right )$
      • $H(X)$는 $X$의 엔트로피로 $X$의 불확실성을 나타낸다.
      • $H(X|Y)$는 $Y$를 알고 있을 때 $X$의 조건부 엔트로피로, $Y$가 주어졌을 때 $X$의 남아있는 불확실성을 나타낸다.
      • Sequencing 결과가 원본 DNA 서열을 완전히 정확하게 나타내는 경우:
        • $ H\left ( X|Y \right )=0 $이므로 $ I\left ( X;Y \right )= H\left ( X \right ) $
      • Sequencing 과정에서 오류가 발생할 경우:
        • $ H\left ( X|Y \right )>0 $가 되고, 따라서 $ I\left ( X;Y \right ) < H\left ( X \right ) $
          • 상호 정보가 감소함을 나타냄
  • Channel capacity
    • Channel의 역할:
      • 정보가 송신자(입력)로부터 수신자(출력)로 전달되는 매개체를 의미합니다.
      • DNA 저장 시스템에서 채널은 원본 DNA 서열이 시퀀싱 기술을 통해 읽혀질 때 발생하는 변환 과정을 나타냅니다.
    • Can be defined by a 4 X 4 transfer matrix T
      • $XT = Y$
        • $X$: the input set
        • $Y$: the output set
        • $T$: 
          • $T=\begin{bmatrix} P_{AA} & P_{AT} & P_{AC} & P_{AG} \\ P_{TA} & P_{TT} & P_{TC} & P_{TG} \\ P_{CA} & P_{CT} & P_{CC} & P_{CG} \\ P_{GA} & P_{GT} & P_{GC} & P_{GG} \\ \end{bmatrix}$
            • $P_{ij}$: the probability that the input base $i$ is received as base $j$ after channel transmission
              • $\left\{\begin{matrix} P_{ij} = 1, i=j\\ P_{ij} = 0, i\neq j\\ \end{matrix}\right.$
              • Therefore, we can obtain:
                • $H\left ( Y|x_{i} \right )=\sum_{j}^{A,T,C,G}H\left ( P_{ij} \right )$
    • $P_{i}^{'}=\sum_{j}^{A,T,C,G}P_{j}\cdot P_{ji}$
      • $P_{i}$: 채널 입력에서 각 염기(A, T, C, G)의 빈도 (확률)
      • $ P_{i}^{'} $: 채널 출력에서 각 염기(A, T, C, G)의 빈도 (확률)
      • $P_{ji}$: 전이 행렬(transfer matrix) $T$의 요소로, 입력 염기 $j$가 출력 염기 $i$로 변환될 확률
      • Therefore, we can obtain:
        • $H\left ( Y \right )=\sum_{i}^{A,T,C,G}H\left ( P_{i}^{'} \right )$
        • $H\left ( Y|X \right )=\sum_{i}^{A,T,C,G}P_{i}\sum_{j=1}^{A,T,C,G}H\left ( P_{ij} \right )$

The average mutual information

 

 


Implementation of DNA Storage

Source coding: 디지털 정보를 DNA 염기서열로 변환

  • Any digital information can be encoded into the DNA molecule by a simple conversion
    • Bancroft et al.: English letters were directly encoded by base triplets in a manner like the amino acid codon table
      • Codon 'AAA' = Letter 'A'
      • Base 'G': reserved for sequencing primers
      • Three bases can produce a coding space of only $3^{3}=27$ elements
    • Church et al.: used a more scalable approach
      • First converted different files into binary sequences in the HTML format and then converted these into DNA sequences
      • Goldman et al.: applied the Huffman coding scheme in the first step, which employs ternary instead of binary conversion
        • Huffman coding: simultaneously compresses the data and this is the first DNA storage study in which data compression algorithms were used
          • 이 방법은 자주 사용되는 데이터 항목에 짧은 코드, 덜 사용되는 항목에 긴 코드를 할당함으로써 전체 데이터를 효율적으로 압축

Channel Coding

  • 오류가 발생할 수 있는 정보 전달 과정에서 데이터를 보호하기 위해 추가적인 기호를 추가하는 방법
  • For DNA molecules, error may occur during synthesis, replication, and sequencing
  • Two ways to recover new data despite information distortion
    • Physical redundancy:
      • 동일한 정보를 여러 복사본으로 저장하는 것
      • Entails increasing the copy number of DNA molecules that encode the same information
      • However, physical redundancy is not sufficient for achieving lossless data transmission
      • For large volumes, physical redundancy imposes a dramatic increase in costs
    • Logical redundancy:
      • 오류 검출 및 수정 기법을 통해 추가적인 체크 비트를 사용하는 것
      • Add extra symbols, called 'check symbols' or 'supervised symbols', in addition to the symbols encoding information
        • When the information symbols are incorrect, the check symbols can be used to detect or correct errors so that the information can be accurately recovered
      • Linear block code (Figure 4b)
        • If a group of information symbols has a length of $k$, a check symbol of length $r$ can be added sing a specific generator matrix
          • A linear block code with a code length of $n = k + r$
      • Hamming code (Figure 4a)
        • Only one error can be detected in each group of code words
          • 즉, 한 번에 하나의 오류만 검출하고 수정할 수 있다
      • Cyclic code: Bose-Chaudhuri-Hocquenghem (BCH) code
        • A code class that can correct multiple random errors based on the Galois binary field and its extension
    • Quantitative assessments can be performed to compare the usefulness of physical redudancy and logical redundancy

 

Encoding information in DNA sequences

  • After being converted to a binary (or other radix) sequence, the information needs to be transformed into base sequences in DNA
    • The most intuitive conversion: 2 bits with one base
      • Provides the maximal information storage capacity
      • However, it may result in sequences that are difficult to manipulate
        • Long tracts of homopolynucleotides that are error-prone in high-throughput seuencing
        • Church et al., Goldman et al., Erlich et al., tried to solve this problem

 

Information density of DNA storage

  • 이론적 정보 밀도:
    • DNA의 정보 저장 밀도는 이론적으로 매우 높습니다. DNA 분자는 4개의 염기(A, T, C, G)로 구성되어 있으며, 각 염기는 2 비트의 정보를 저장할 수 있다.
  • 실제 정보 밀도:
    • 실제 응용에서는 여러 제약 조건(저장 환경, Physical and logical redundancy, indexing)으로 인해 이론적 밀도를 달성하기 어렵다.

Technical Aspects and Practical Considerations

  • DNA 합성과 조립 기술:
    • 고체상 인산아미드 화학, 배열 기반 DNA 합성, 효소적 합성 등 
  • DNA 시퀀싱 기술
    • Sanger 시퀀싱, 차세대 시퀀싱(NGS), 단분자 시퀀싱 기술의 특성과 성능
  • 비용 분석:
    • 전통적 저장 방법과 비교하여 유지 비용이 낮다는 장점이 있지만, 여전히 실용화에는 높은 비용이 문제이다.
  • 수명:
    • DNA는 안정성이 높아 장기 저장에 유리하다. 낮은 온도에서 보관하면 수천 년 동안 정보를 보존할 수 있다.
  • 생체 내 DNA 저장 (In vivo DNA storage):
    • Compared to in vitro DNA storage, in vivo storage takes advantage of the efficient cellular machineries of DNA replication, proofreading and long-chain DNA maintenance, offers the chance for assembly-free random access of data, and support live recording of biochemical events in situ in living organism

 

Tuning process

 

Hyperparameters

  • $\alpha$: learning rate
  • $\beta$: for momentum
  • $\beta_{1}, \beta_{2} , \epsilon $: for Adam
  • The number of layers (# layer)
  • The number of hidden units (# hidden units)
  • Learning rate decay
  • Mini-batch size

 Try random values: Don't use a grid

Grid Search 모든 가능한 하이퍼파라미터 조합을 일정한 간격으로 시도하는 방법
예를 들어, 두 개의 하이퍼파라미터 $\alpha$ 와 $ \epsilon $이 있을 때, 일정한 간격으로 그리드를 생성하여 모든 조합을 시도

중요한 하이퍼파라미터 조합이 특정 영역에 집중되어 있을 때, 그리드 검색은 비효율적으로 탐색할 수 있다. 즉, 불필요한 조합을 시도하게 될 가능성이 높다.
Random Search 하이퍼파라미터 공간에서 무작위로 점을 선택하여 시도하는 방법
예를 들어, 두 개의 하이퍼파라미터 $\alpha$ 와 $\epsilon$이 있을 때, 무작위로 조합을 선택하여 시도

하이퍼파라미터의 수가 많아질수록 랜덤 검색이 그리드 검색보다 더 효율적이다. 이는 고차원 공간에서 랜덤 검색이 더 많은 유효한 조합을 탐색할 수 있기때문이다.

 

Coarse to fine

  • 이 방법은 처음에는 넓은 범위를 rough하게 탐색한 후, 유망한 영역을 식별하여 세밀하게 탐색하는 방식이다.
  • 장점: 초기 단계에서 넓은 범위를 빠르게 탐색함으로써, 전체 하이퍼파라미터 공간을 전부 탐색하는 것보다 시간을 절약할 수 있다.

Using an appropriate scale to pick hyperparameters

 

Picking hyperparameters at random

  • 특정 하이퍼파라미터를 탐색할 때, 단순히 균일하게 랜덤 샘플링하는 것이 항상 최적의 방법은 아니다. 즉, 적절한 스케일을 사용하여 하이퍼파라미터 공간을 탐색하는 방법을 이해하는 것이 중요하다.

  • 예를 들어, 특정 층 ll의 은닉 유닛 수를 50에서 100 사이로 선택한다고 가정했을 때, 이 경우, 50에서 100 사이의 값들을 균일하게 랜덤으로 샘플링하는 것이 합리적일 수 있다.
  • 예를 들어, 네트워크의 층 수를 2에서 4 사이로 선택한다고 가정했을 때, 2, 3, 4 중에서 균일하게 랜덤으로 샘플링하거나, Grid search을 통해 각각의 값을 평가하는 것이 합리적일 수 있다.

  • 학습률은 어떨까? 학습률을 0.0001에서 1 사이에서 선택한다고 가정했을 때, 그림에서 볼 수 있듯이 만약 이 범위에서 균일하게 랜덤으로 샘플링한다면, 대부분의 값이 0.1에서 1 사이에 집중되게 된다. 이는 0.0001에서 0.1 사이의 범위를 충분히 탐색하지 못하게 된다.

  • 따라서, 학습률과 같은 하이퍼파라미터는 log-scale에서 탐색하는 것이 더 합리적이다.
    • 로그 스케일에서 균일하게 샘플링하면, 0.0001, 0.001, 0.01, 0.1, 1과 같은 값들이 고르게 분포된다.

 

Hyperparameters for exponentially weighted averages

  • $\beta$  값이 0.9에서 0.999 사이의 범위를 탐색할 때, 선형 스케일에서 샘플링하면 주로 0.99에서 0.999 사이의 값을 많이 샘플링하게 되어, $\beta$  값이 작을 때의 탐색이 충분히 이루어지지 않는다.
    • $\beta$값이 0.9에서 0.999로 이동할 때, 값들이 일정한 비율로 변화하지 않기 때문이다. 예를 들어, 0.9와 0.99 사이의 간격은 0.1이지만, 0.99와 0.999 사이의 간격은 0.009이다. 따라서, 선형 스케일에서 균일하게 샘플링하면 $\beta$  값이 작은 구간보다 큰 구간에서 더 조밀하게 샘플링된다
  • 따라서, log-scale에서 샘플링하면 $\beta$  값의 범위를 더 균일하게 탐색할 수 있다.
    • $\beta$  대신 $1-\beta$  값을 로그 스케일에서 샘플링하여 더 효율적인 탐색이 가능하다.

Hyperparameters tuning in practice: Pandas vs. Caviar

 

Approach 1: Babysitting one model

  • 한 번에 하나의 모델을 선택하여 집중적으로 훈련하고 튜닝
  • 각 실험이 끝날 때마다 결과를 확인하고, 하이퍼파라미터를 조정하여 다음 실험을 진행
  • Allows for intensive custumization and tuning

Approach 2: Training many models in parallel

  • 여러 모델을 동시에 병렬로 훈련하고, 각 모델의 성능을 비교하여 최적의 하이퍼파라미터 조합을 찾기
  • Effective hyperparameter tuning often involves exploring a variety of models and strategies
    • 병렬로 실행되기 때문에 전체 튜닝 시간이 크게 단축

Normalizing activations in a network

 

Normalizing inputs to speed up learning

수식 삽입

  • Can we normalize $a^{[2]}$ so as to train $w^{[3]}$, $b^{[3]}$ faster?
    • Normalize $z^{[2]}$, not $a^{[2]}$
      • 즉, activation function 적용 전에 Normalization 해야함.

 

Implementing Batch Norm

  • Given some intermediate values in NN: $z^{(1)}, ..., z^{(m)} $
    • $m$ is the number of training examples

  • $\hat{Z}$: 평균이 0이고 분산이 1인 값으로 변환된 입력 데이터
  • $\tilde{Z}$: 정규화된 값 $\hat{Z}$ 에 배치 정규화의 학습된 파라미터 $\gamma$,  $\beta$ 를 적용하여 최종적으로 스케일링되고 이동된 값
    • $\gamma$,  $\beta$: Learable parameters of model

Batch Normalization

 

Fitting Batch norm into a Neural Network

  • Activation function 적용 전에 Normalization

  • $\gamma$,  $\beta$도 Learnable Parameter이므로 Gradient Descent를 통해 업데이트된다.

 

Working with mini-batches

  • 훈련 시에는 Mini-batch의 평균과 분산을 사용하지만, 테스트 시에는 훈련 동안 축적된 지수 가중 이동 평균( Exponential Moving Average)을 사용하여 입력 데이터를 정규화한다.
  • During training:
    • 훈련 시, 각 mini-batch에서의 입력 데이터 $X^{\left ( 1 \right )},X^{\left ( 2 \right )},...,X^{\left ( m \right )}$를 사용하여 mini-batch의 평균 $\mu$ 과 분산 $\sigma^{2}$ 을 계산한 후, Batch Normalization을 수행한다.
    • 훈련 동안, 각 미니 배치의 평균관 분산을 추적하여 전체 평균 ( $\mu$ )과 분산 ( $\sigma^{2}$ )를 weight average를 통해 업데이트를 한다. 이 과정에서 얻어진 값은 Test에서 사용된다.

$$\hat{X} = \frac{X-\mu}{\sqrt{\sigma ^{2}+\epsilon }}$$

  • During testing:
    • 테스트 시, 단일 입력 데이터에 대해서는 미니배치를 구성할 수 없으므로, 훈련 시 계산된 weighted average을 사용하여 평균 ( $\mu$ )과 분산 ( $\sigma^{2}$ )을 적용한다.
    • 이를 통해 입력 데이터를 정규화 한 후, 정규화된 값에 Bach Nomrlization의 학습된 파라미터 $\gamma$와 $\beta$를 적용하여 최종 출력 게산한다.

$$\tilde{X} = \gamma \hat{X} + \beta$$

 

Implementing gradient descent

 


Why does Batch Norm work?

 

Learning on shifting input distribution

  • 초기 데이터셋에서는 대부분의 고양이 이미지가 검은색 고양이로 구성되어 있고, 고양이가 아닌 이미지가 다양한 물체로 구성되어 있다.
    • 이 경우 모델은 검은색 고양이 이미지를 주로 학습하게 된다.
  • 새로운 데이터셋에서는 초기 데이터셋과는 다른 분포를 띠는 다양한 색상의 고양이 이미지와 고양이가 아닌 이미지가 포함된다.
    • Covariate Shift: 입력 데이터 $X$의 분포가 변화하여 모델의 예측 성능에 영향을 미치는 현상
    • 초기 모델은 검은색 고양이에 대해서만 학습했기 때문에, 새로운 데이터셋의 다양한 색상의 고양이 이미지를 잘 예측하지 못할 수 있다.

 Why is covariate shift a problem with neural networks?

  • 이는 입력 데이터 $X$의 분포 변화로 인해 모델이 기존에 학습한 특징과 다른 특징을 갖는 데이터를 처리하는 데 어려움을 겪는다.

  • Solution:
    • Batch Norm reduces the problem of the input distribution changing

Batch Norm as regularization

  • Each mini-batch is scaled by the mean/variance computed on just that mini-batch
    • This adds some noise to the value $z^{[l]}$ within that mini-batch ($= \tilde{z}^{[l]} $)
    • So similar to dropout, it adds some noise to each hidden layer's activations

Softmax regression

 

Softmax layer

  • Softmax layer는 주로 multiclass classification 문제에서 사용되며, 출력된 확률의 합은 1이 되며, 각 확률은 해당 클래스에 속할 확률을 나타낸다.
  • Softmax 함수는 입력 벡터 $z^{[L]}$를 확률 분포로 변환한다.

$$t=e^{Z^{\left [ L \right ]}}$$

$$a^{\left [ L \right ]} = \frac{e^{Z^{\left [ L \right ]}}}{\sum_{i=1}^{4}t_{i}}$$

 

Softmax examples

  • Decision boundary: 모델이 계산한 확률이 가장 높은 class가 변경되는 지점 
  • Color on the spot
    • 해당 데이터 포인트가 Softmax 함수에 의해 가장 높은 확률을 가지는 class에 해당하는 색으로 변경

Reference

He, K., Chen, X., Xie, S., Li, Y., Dollár, P., & Girshick, R. B. (2021). Masked autoencoders are scalable vision learners. arXiv (Cornell University). https://doi.org/10.48550/arxiv.2111.06377


Problem Statement (Focused Issue)

 

  • Aided by the rapid gains in hardware, models today can easily overfit one million images and begin to demand hundreds of millions of - often publicly inaccessible - labeled images
    • This issue has been successfully addressed in natural language processing (NLP) by self-supervised pre-training: based on autoregressive language modeling in GPT and masked autoencoding in BERT
      • They remove a portion of the data and learn to predict the removed content
      • 이 masked autoenchoder 아이디어를 computer vision에도 적용시킨다면?
Self-supervised pre-training
Self-Supervised Learning은 레이블이 없는 데이터에서 유용한 표현을 학습하는 방법입니다. Pre-Training은 이러한 자기 지도 학습을 통해 초기 모델을 훈련시키는 단계로, 나중에 다른 특정 작업(Supervised Task)을 수행하기 위해 이 모델을 Fine-Tuning할 수 있습니다.
  • BUT! 이 아이디어를 적용시키는 데 NLP만큼 뛰어난 성과를 얻진 못함.
    • Why? What makes masked autoencoding different between vision and language?
      1. 아키텍처의 차이
        • Vision에서는 주로 합성곱 신경망(CNN)이 사용되었으며, 이 합성곱 신경망은 규칙적인 grid에서 작동하므로 mask token이나position embedding을 통합하기 어려웠다. 반면, Natural language processing에서는 BERT와 같은 모델이 사용되었다.
        • 그러나 최근에는 Vision Transformers (ViT)의 도입으로 이 아키텍처의 차이가 해결되었다.
      2. 정보 밀도의 차이
        • 언어는 인간이 생성한 신호로서 높은 의미적 정보를 포함하고 있습니다. 문장에서 몇 개의 단어만 마스킹하더라도 모델은 복잡한 언어 이해 능력을 요구한다.
        • 반면, 이미지에서는 spatial redundancy(공간적 중복)이 많아 높은 비율로 마스킹하더라도 인접한 패치로부터 쉽게 복원될 수 있다.
          • Patch간 상관관계가 존재하기 때문!
        • 이를 극복하기 위해, MAE에서는 높은 비율의 무작위 패치를 마스킹하는 전략을 사용한다.
      3. 디코더의 역할 차이
        • 언어 모델에서는 디코더가 의미적 정보를 많이 포함한 단어를 예측하지만, 시각적 모델에서는 픽셀을 복원한다.
          • 이는 시각적 모델의 디코더 출력이 언어 모델의 디코더 출력보다 의미적 수준이 낮다는 것을 의미한다.
          • BERT에서는 디코더가 매우 단순할 수 있지만, 이미지에서는 디코더의 설계가 중요한 역할을 한다.

Method (Approach)

  • Masked AutoEncoder (MAE)
    • Mask random patches of the input image and reconstruct the missing pixels
    • Based on:
      1. Asymmetric encoder-decoder architecture
        • Encoder: operates only on the visible subset of patches (without mask tokens)
          • Token: 이미지 처리에서 토큰은 이미지의 일부분이나 패치를 의미한다. 이미지를 일정한 크기의 작은 조각으로 분할하여 각각을 토큰으로 간주한다.
          • 즉, 마스킹된 패치는 인코더에 입력되지 않고, 대신 마스킹된 위치를 나타내는 mask token으로 대체됩니다. Encoder 이후 Mask tocken은 introduced 된다.
        • Decoder: reconstructs the original image in pixels  from the latent representation (encoded patches) and mask tokens 
          • Latent Representation은 입력 이미지의 추상적이고 압축된 표현, 즉, 인코더를 통해 입력 이미지가 변환된 후의 상태를 나타냅니다.
          • After pre-training, the decoder is discarded and the encoder is applied to uncorrupted images (full sets of patches) for recognition tasks
      2. Masking a high proportion of the input image (e.g., 75%) yields a nontrivial and meaningful self-supervisory task

 

MAE architecture

 

  • Mechanism of MAE
    1. During pre-training, a large random subset of image patches (75%) is masked out
      • Divide an image into regular non-overlapping patches
      • Then, sample a subset of patches and mask the remaining ones
    2. The encoder is applied to the small subset of visible patches and mask tokens are introduced after the encoder
      • Encoder는 Vision Transformer(ViT)를 기반으로하며, Masking되지 않은 패치에만 적용
        • Patch Embedding: 패치를 linear projection하고 positional embeddings을 추가
        • Transformer blocks: 여러 트랜스포머 블록을 통해 처리
      • 마스킹된 75%의 패치는 인코더에 입력되지 않으며, 대신 마스킹 토큰으로 대체된다.
        • 전체 패치 중 일부(25%)만 처리하기 때문에, 계산 및 메모리 효율성이 높다.
    3. The full set of encoded patches and mask tokens is processed by a small decoder that reconstructs the original image in pixel
      • Positional embeddings 추가: 모든 토큰에 위치 임베딩을 추가하여, 마스크 토큰이 이미지 내 위치 정보를 가질 수 있도록 한다.
        • Without this, mask tokens would have no information about their location in the image
      • Reconstruction target: MAE reconstructs the input by predicting the pixel values for each masked patch
      • Loss function은 원본 이미지와 재구성된 이미지 간의 Mean Squared Error(MSE)를 계산하며, 이는 마스킹된 패치에 대해서만 계산된다.
    4. After pre-training, the decoder is discarded and the encoder is applied to uncorrupted images (full sets of patches) for recognition tasks

Left: the masked image, Middle: MAE reconstruction, Right: the ground-truth (Images are from ImageNet validation images)

 

ViT (Vision Transformer)
Vision Transformer(ViT)는 자연어 처리(NLP)에서 성공을 거둔 Transformer 아키텍처를 Computer Vision 작업에 적용한 모델입니다. Transformer는 주로 텍스트 데이터를 처리하기 위해 설계되었지만, ViT는 이를 이미지 데이터에 적용하여 이미지 분류와 같은 작업을 수행합니다. ViT는 CNN(Convolutional Neural Network)과 달리 전통적인 합성곱 연산을 사용하지 않으며, 대신 Transformer의 Self-Attention 메커니즘을 사용합니다.
  • 왜 Masking ratio를 75%로 했을까?
    • 75% works well for both fine-tuning and linear probing


ImageNet Experiments

  • Self-supervised pre-training on the ImageNet-1K training set => Supervised training to evaluate the representations with:
    1. End-to-end fine-tuning: 사전 학습된 모델의 모든 파라미터를 다시 학습시켜 특정 작업에 맞게 최적화하는 방법
    2. Linear probing: 사전 학습된 모델의 파라미터를 고정시키고, 마지막 레이어에 새로운 선형 분류기를 추가하여 학습하는 방법

  • ViT-Large(ViT-L/16) 모델을 사용하여 MAE를 적용한 결과, 기존 학습된 모델보다 성능이 크게 향상됨.
    • ViT-L을 처음부터 학습하는 것보다 MAE로 사전 학습 후 파인 튜닝하는 것이 성능이 훨씬 높았다 (76.5% → 84.9%).

Main Properties from Ablation experiments

  • Masking ratio:
    • A high masking ratio (75%) works well for both fine-tuning and linear probing

  • Decoder Design:
    • Depth: 깊은 decoder가 linear probing 정확도를 향상시킴.
      • The last several layers in an autoencoder are more specialized for reconstruction but are less relevant for recognition
      • Linear Probing은 사전 학습된 모델의 최종 레이어에 선형 분류기를 추가하는 방법입니다. 우리의 최종 레이어는 디코더와 관련이 있기 때문에, 디코더가 깊어질수록 Linear Probing에서 더 높은 성능 개선이 나타난다.
      • How about fine-tuning?
        • The last layers of the encoder can be tuned to adapt to the recognition task
        • 이는 파인 튜닝 과정에서 전체 모델이 재학습되기 때문에, 디코더의 깊이가 성능에 큰 영향을 주지 않는다.
  • Mask token:
    • 인코더에서 마스크 토큰을 건너뛰고 디코더에서 이를 적용. 이는 훈련 시 계산량을 크게 줄이고 정확도를 향상시킴.
  • Reconstruction Target:
    • Pixel-Based Reconstruction: 이미지 패치를 픽셀 단위로 재구성
      • Normalization: 픽셀 값을 정규화하면 정확도가 향상됩니다. 이는 패치 간의 대비를 높여주기 때문이다.
        • Normalization은 각 패치 내의 픽셀 값들을 일정 범위(예: 0에서 1 사이)로 스케일링하면, 패치 내부의 대비가 증가함에 따라, 동일한 패치 내에서 어두운 부분은 더 어두워지고 밝은 부분은 더 밝아진다.
      • PCA (주성분 분석): 주성분 분석(PCA)을 통해 가장 큰 PCA 계수를 재구성 목표로 사용했지만, 이는 정확도를 저하시켰습니다. 이는 High-frequency component이 재구성에 중요한 역할을 하기 때문이다.
        • PCA: 고차원 데이터의 차원을 축소하여 데이터의 주요 정보를 보존하면서 데이터의 구조를 단순화하는 기법
        • High-frequency component: 밝기나 색상이 급격하게 변하는 부분. 혹은 이미지의 세밀한 부분이나 복잡한 패턴이 포함되는 부분이다.
    • Token-Based Reconstruction: BEiT와 같이 토큰화를 사용한 재구성 방식
      • MAE 디코더가 cross-entropy loss을 사용하여 토큰 인덱스를 예측합니다. 이는 fine-tuning 정확도를 0.4% 향상시키지만, Normlaized pixels과 비교했을 때는 별다른 장점이 없다.
      • 토큰화는 추가적인 사전 학습 단계를 필요로 하며, 큰 계산 비용(예: ViT-L의 40% FLOPs)을 추가합니다. 따라서, 토큰화는 전이 학습(transfer learning)에서 특별한 이점을 제공하지 않았다.
  • Data Augmentation:
    • MAE는 데이터 증강이 거의 필요하지 않으며, 무작위 마스킹이 데이터 증강의 역할을 대체함.
      • Contrastive learning과는 대조적!
        • Contrastive Learning은 인스턴스 간의 유사성과 차이를 학습하여 데이터 표현을 개선하는 자기 지도 학습(self-supervised learning) 기법입니다. 이 접근법은 주로 데이터 포인트 쌍을 사용하여 유사한 쌍을 가까이, 다른 쌍을 멀리 위치시키는 방식으로 작동한다.
        • Contrastive Learning에서 첫번째 단계가 Augmentation인만큼 Augmentation에 의존적.
  • Mask Sampling Strategy:
    • Random Sampling: MAE에서 가장 좋은 성능을 보이며, 높은 마스킹 비율을 사용할 수 있게 함.
    • Block and Grid Sampling: 블록 샘플링은 50% 비율에서만 잘 작동하며, 그리드 샘플링은 더 쉬운 작업을 제공하지만 성능이 낮음.
      • Block-wise masking: reasonably well at a ratio of 50% but degrades at a ratio of 75%
        • Higher training loss is observed
        • The reconstruction is also blurrier
      • Grid-wise sampling: regularly keeps one of every four patches
        • Easier task and has lower training loss
        • The reconstruction is sharper
        • However, the representation quality is lower

  • Training schedules:
    • A longer training schedule gives a noticeable improvement

 

Comparisons with Previous Results

Comparisons with previous results on ImageNet-1K

  • 비교 Model: ViT-B, ViT-L, ViT-H
  • IN1K (ImageNet-1K) 데이터로 사전 학습 후, end-to-end fine-tuning 진행
ViT-B 모든 방법이 비슷한 성능을 보임
ViT-B 방법들 간의 차이가 더 큼, 큰 모델의 경우 과적합을 줄이는 것이 도전 과제
ViT-H MAE가 성능 향상을 보여줌
MAE ViT-H 모델을 사용하여 IN1K 데이터로만 학습했을 때 86.9%의 정확도 달성, 448 크기로 미세 조정했을 때 87.8% 정확도 달성 (이전 최고 기록인 87.1%를 초과)

 

MAE pre-training vs. supervised pre-training

  • MAE 사전 학습 했을 경우, IN1K 데이터로만 학습했을 때 일반화 성능 향상, 더 높은 용량의 모델에서 더 큰 이득을 보임

 

Partial Fine-tuning

  • 사전 학습된 모델의 특정 부분만을 미세 조정하는 방법
    • 사전 학습된 모델의 특정 레이어(예: 초기 레이어 또는 특정 블록)를 고정한 후, 고정되지 않은 나머지 레이어만을 학습하여, 전체 모델을 다시 학습하지 않고도 모델의 성능을 최적화한다.
    • 모델의 특정 블록만을 미세 조정하여, 전체 모델을 다시 학습하는 것보다 효율적으로 모델을 최적화할 수 있음을 확인하였다.
  • MoCo v3와 MAE를 비교하여, MoCo v3가 Linear Probing (Tuning 0 blocks is linear probing)에서 더 높은 정확도를 보이지만, 부분 미세 조정에서는 MAE가 더 나은 성능을 발휘함을 보여준다.
    • MAE의 표현은 Linear Separability이 낮습니다. 이는 Linear Probing에서 MoCo v3보다 낮은 성능을 보이는 이유이다.
      • Linear Separability은 데이터를 선형 경계를 사용하여 두 개 이상의 클래스나 그룹으로 명확하게 구분할 수 있는 능력을 의미한다.
    • MAE는 비선형 특징이 강하여, 비선형 헤드를 튜닝할 때 좋은 성능을 발휘한다.

 

Transfer Learning Experiments

  • MAE는 COCO 객체 탐지 및 분할, ADE20K의 semantic segmentation, 그리고 iNaturalist 및 Places 데이터셋에서 분류 작업에서 강력한 transfer learning 성능을 보이며, 픽셀 기반 MAE는 간단하면서도 빠르고 우수한 성능을 보여줌을 알 수 있다.

Discussion & Conclusion

  • We observe on ImageNet and in transfer learning that an autoencoder - a simple self-supervised method similar to techniques in NLP - provides scalable benefits
  • We note that images and languages are signals of a different nature and this difference must be addressed carefully
    • Image: merely recorded light without a semantic decomposition into the visual analogue of words
      • Remove patches that most likely do not form a semantic segment

Overall Reflection

 

최근에 읽은 논문에서 NLP에서 사용되던 아이디어를 Computer Vision 분야에 적용한 점이 참신하게 느껴졌음. 이를 통해 특정 분야만 공부하는 것이 아니라, 다른 분야도 끊임없이 탐구해야 한다는 중요성을 깨달음. 특히, 논문에서 언급한 것처럼 기존 방법을 응용할 때, 인풋 데이터가 다르다면 그 데이터의 성질을 제대로 파악하고 활용하는 것이 매우 중요하다는 점을 실감했음.

 

여러 논문을 읽으면서 각 분야(Computer Vision, Reinforcement Learning, NLP 등)마다 발전된 정도와 사용하는 방법이 다를 수 있지만, 서로 다른 분야의 아이디어를 융합하는 연구가 활발하게 진행되고 있다는 것을 느꼈음. 이를 통해 다양한 분야의 지식을 통합하여 새로운 연구 방향을 모색하는 것이 중요하다는 생각이 들었음.

 

 

Mini-batch Gradient Descent

Mini-batch gradient descent

Mini-batch

$$ x^{\left ( i \right )}, y^{\left ( i \right )} $$ $ i^{th}$ training example
$$ z^{\left [ l \right ]} $$ $ l^{th} $ layer
$$ X^{\left\{ t\right\}} , Y^{\left\{ t\right\}} $$ $ t^{th} $ mini-batch

 

Mini-batch Gradient Descent

  • 각 mini-batch씩 for 문을 통해 Foward Propagation, Backward Propagation 진행
  • Pass through the whole training set = 1 epoch
    • 전체 Mini-batch, 즉 모든 training set이 Forward, Backward를 완수하면 1 epoch가 마무리 됨.
    • 이 예시에선 총 5000번의 gradient descent가 진행됨.

Understanding mini-batch gradient descent

Training with mini-batch gradient descent

  • Mini-batch gradient descent: Plot $J^{\left\{ t\right\}}$ computed using $ X^{\left\{ t\right\}} , Y^{\left\{ t\right\}} $
  • Mini-batch gradient descent에서 Noise가 발생되는 이유?
    • Batch의 Composition에 따라 우연히 Cost가 높을수도, 낮을수도 있기 때문!

 

Choosing your mini-batch size

  • If mini-batch size = m (# of training examples): Batch gradient descent
  • If mini-batch size = 1: Stochastic gradient descent
    • Every batch is own
  • In practice: in-between 1 and m

Batch gradient descent 데이터셋 전체를 한 번에 처리하여 모델을 학습시키는 방식
* Mini-batch size = m
* Too long per iteration
In-between mini-batch 데이터셋을 작은 부분들로 나누어 각각의 부분에 대해 학습을 진행하는 방식
일반적으로 배치 크기(batch size)로 설정된 크기만큼의 데이터 묶음을 사용
* Make progress without processing entire training set
Stochastic gradient descent * Lose Speed up from vectorization, 즉 vectorization의 장점(효율성)을 이용하지 못한다.

 

 

Choosing your mini-batch size

  • If a small training set ($ m \leq 2000 $): Use batch gradient descent
  • Typical mini-batch sizes: 64, 128, 256, 512 (power of 2)
  • Make sure the mini-batch fits in CPU/GPU memory

Exponentially weighted averages

  • Purpose of this average method?
    • For smoothing estimation: 데이터의 노이즈나 변동을 줄여줌으로써, 학습과정이 더 부드럽고 안정적으로 진행됨.

 

Example) Temperature in London

  • Formular:

$$ V_{t} = \beta V_{t-1} + \left ( 1-\beta  \right )\theta _{t} $$

  • 여기서 $ V_{t} $는 시간 $ t $에서의 지수 가중 평균, $\beta$는 가중치를 조절하는 파라미터, $\theta$는 시간 $ t $ 에서의 실제 값
    • $V_{t}$: 새로 가중 평균화된 $\theta _{t}$  

  • 값이 클수록(즉, 0.98) 더 길게 과거의 데이터를 반영하므로 더 부드러운 곡선을 생성
  • β 값이 작을수록(즉, 0.5) 과거 데이터의 반영 비율이 줄어들어 더 짧은 기간의 변동을 반영하게 됩니다.
  • 평균 기간:
    • $ \frac{1}{1-\beta } $
    • 예를 들어, $\beta = 0.98$인 경우 평균 기간은 $\frac{1}{1-0.98} = 50$일입니다. 이는 약 50일간의 데이터를 반영한다는 의미입니다.

 

Implementing exponentially weighted average


Bias correction in exponentially weighted average

Bias correction

  • 표시된 부분을 보면 Purple graph와 실제 data값들은 차이를 보이기에, Bias Correction이 필요함.
    • Bias correction: 초기 값의 영향을 줄여 정확한 평균 값을 계산하도록 하는 것.

  • 초기 단계에서는 $v_0$가 0이기 때문에, 계산된 $v_t$ 값이 실제보다 작게 나옵니다. 이는 초기 몇 번의 계산에서 $v_t$가 제대로 된 값을 반영하지 못하고, 낮은 값을 가질 수 있음을 의미합니다.
    • Bias correction에 의해 수정된 식:
      • $v_{t}=\frac{v_{t}}{1-\beta ^{t}}$


  • Red line: 모멘텀은 이 과정에 관성을 추가하여 학습 속도를 높이고, 지역 최소값(local minima)에서 벗어나도록 합니다.
    • 기울기를 누적하고, 이를 기반으로 업데이트 방향을 조정하여 더 빠른 수렴을 돕습니다.
  • Momentum Formula:
    • $V_{dw}=\beta V_{dw}+\left ( 1-\beta  \right )dw$
    • $V_{db}=\beta V_{db}+\left ( 1-\beta  \right )db$
      • $V_{db}$는 각각 가중치 $w$와 편향 $b$의 업데이트 방향(속도)을 나타냄
      • 는 모멘텀을 조절하는 하이퍼파라미터로, 0과 1 사이의 값을 가집니다. (대체로 0.9)
      • 와 $db$는 현재 Mini-batch에서 계산된 기울기
      • 물리 관점) β: Friction, $V_{dw} & V_{db} $ : velocity, $dw & db$: acceloration
      • 현재 기울기뿐만 아니라 이전 기울기들의 방향과 크기도 고려함
  • Update Formula:
    • $w=w-\alpha V_{dw}$
      • 여기서 α는 learning rate

RMSprop

  • RMSprop: Root Mean Square propagation
    • 각 파라미터의 기울기의 제곱의 이동 평균을 유지하여 학습률을 조정하는 것
  • RMSprop Formula:
    • $S_{dw}=\beta _{2}S_{dw}+\left ( 1-\beta _{2} \right )\left ( dw \right )^{2}$
    • $S_{db}=\beta _{2}S_{db}+\left ( 1-\beta _{2} \right )\left ( db \right )^{2}$
      • 여기서 $S_{dw}$$S_{db}$는 각각 weight $w$와 bias $b$의 기울기 제곱의 이동 평균을 나타냄
        • 이동 평균은 기울기 값이 어떻게 변화하는지를 반영
        • 각 파라미터에 대해 기울기 제곱의 이동 평균을 계산하여 학습률을 조정합니다. 기울기가 큰 파라미터는 학습률이 감소하고, 기울기가 작은 파라미터는 학습률이 증가합니다.
      • 는 모멘텀을 조절하는 하이퍼파라미터로, 일반적으로 0.9로 설정
      • 와 d는 현재 미니배치에서 계산된 기울기
  • Update Formula:
    • $w:=w-\alpha \frac{dw}{\sqrt{S_{dw}+\epsilon }}$
    • $b:=b-\alpha \frac{db}{\sqrt{S_{db}+\epsilon }}$
      • 여기서 $\alpha$는 학습률(learning rate), $\epsilon$은 매우 작은 값으로 0으로 나누는 것을 방지하기 위해 사용됩니다. 일반적으로 $\epsilon = 10^{-8}$로 설정됩니다.

Adam Optimization Algorithm

  • Adam: Adaptive Moment Estimation = Momentum + RMSprop
    1. 초기화:
      • , $S_{dw} = 0$
      • , $S_{db} = 0$
    2. Momentum 계산 (요소들은 위에 참고)
      • $V_{dw}=\beta V_{dw}+\left ( 1-\beta  \right )dw$
      • $V_{db}=\beta V_{db}+\left ( 1-\beta  \right )db$
    3. 기울기 제곱의 이동 평균 계산 (요소들은 위에 참고)
      • $S_{dw}=\beta _{2}S_{dw}+\left ( 1-\beta _{2} \right )\left ( dw \right )^{2}$
      • $S_{db}=\beta _{2}S_{db}+\left ( 1-\beta _{2} \right )\left ( db \right )^{2}$
    4. Bias Correction
      • 초기 단계에서 $V$$S$ 값이 0에 가까운 값을 갖기 때문에, 이를 보정하기 위해 다음과 같은 보정 수식을 사용
      • $V_{dw}^{corrected}=\frac{V_{dw}}{1-\beta _{1}^{t}}$
      • $V_{db}^{corrected}=\frac{V_{db}}{1-\beta _{1}^{t}}$
      • $S_{dw}^{corrected}=\frac{S_{dw}}{1-\beta _{2}^{t}}$
      • $S_{db}^{corrected}=\frac{S_{db}}{1-\beta _{2}^{t}}$
    5. 업데이트
      • $w:=w-\alpha \frac{V_{dw}^{corrected}}{\sqrt{S_{dw}^{corrected}}+\epsilon }$
      • $b:=b-\alpha \frac{V_{db}^{corrected}}{\sqrt{S_{db}^{corrected}}+\epsilon }$

Learning rate decay

  • slowly reduce the learning rate

$$\alpha =\frac{1}{1+\left ( decay-rate \right )\ast \left ( epoch-num \right )}\alpha _{0}$$

 

Other learning rate decay methods

Exponential decay
$$\alpha =\alpha _{0}\cdot 0.95^{epoch}$$

Inverse scaling decay $$ \alpha =\frac{k}{\sqrt{epoch}}\cdot \alpha _{0}$$
Step decay or Discrete staircase decay

 


The problem of local optima

Problem of plateaus

  • Plateaus 영역은 기울기(gradient)가 매우 작아지는 구간(0에 가깝게)으로, 최적화 과정에서 학습 속도를 크게 저하시킬 수 있습니다.
  • 장점: 모델이 나쁜 지역 최소값(local minima)에 갇히지 않게 도와줍니다.
  • 단점: 학습 속도가 매우 느려지기 때문에, 전체 학습 과정이 지연될 수 있습니다.

이 기록은 내가 학기 중에 수강했던 Coursera의 'Deep learning specialization' 강의를 다시 복습하는 용도이다. 이미 2번 정도 학습을 마친 상태이고, 내 기준 헷갈리거나 메모하면 좋을 핵심 내용 위주로만 작성했다. 즉, 처음 수강하는 사람들에겐 내 복습 기록들이 도움이 되진 않을 수 있다. 그런 사람들에겐 직접 수강하고 자신만의 복습 노트를 만드는 것을 추천한다.

 

Train / Development / Test sets

  • Mostly used ratio:
    • Train : Test = 70 : 30 (%)
    • Train : Development : Test = 60 : 20 : 20 %
  • Big Data (e.g., 1,000,000)
    • Train : Development : Test = 98 : 1 : 1 (%)

 

  • Mismatched train / test distribution
    • Make sure dev and test come from the same distribution

Bias / Variance

  • High bias = Underfitting
  • Just Right
  • High variance = Overfitting

  • Example:
    • Low train set error & High dev set error: Overfitting
    • High train set error & High dev set error: Underfitting

 

Regularization

  • Logistic Regression:

L2 Regularization


(Mostly used)
L1 Regularization
  • Application of L2 regularization in neural network
    • During gradient descent, weight decay가 일어남.

Weight Decay
손실 함수(loss function)에 가중치의 제곱합(term)을 추가하여 가중치가 너무 커지는 것을 방지하는 정규화 방법
일반적으로 L2 정규화라고도 불림

λ값이 클수록 가중치가 더 많이 감소하며 이는 가중치의 크기를 제어하여 과적합을 방지함.
가중치가 너무 커지면 모델이 학습 데이터에 과도하게 맞춰질 수 있음. Weight Decay는 가중치가 작아지도록 유도하여 모델이 더 일반화된 성능을 갖도록 함

 

Why regularization reduces overfitting

  • λ값이 크게 될수록 weight가 0에 가까워져서 hidden unit을 simplification.

 

Dropout Regularization

    • 특정 removing chance을 설정하여 units을 randomly하게 dropout함
      • Intuition: Can't rely on any one feature, so have to spread out weights

hidden unit의 개수가 많을 수록 keep-prob 작게하여 overfitting 방지하기
keep-prob: unit을 유지할 확률

 

Other regularization methods

  • Data augmentation
    • flipping, randomly zooming, ...

  • Early stopping

 

Normalizing inputs

  • Subtract mean

  • Normalize variance

  • Why normalize input?
    • For more fast optimization!

 

Gradient checking: Numerical approximation of gradients

  • Checking your derivative computation:

Reference

Yoon, T., Myoung, K., Lee, K., Cho, J., No, A., & Ryu, E. K. (2023). Censored sampling of diffusion models using 3 minutes of human feedback. arXiv (Cornell University). https://doi.org/10.48550/arxiv.2307.02770

 

Article

  • Global Issue
    • Diffusion probabilistic models have recently shown remarkable success in high-quality image generation
  • Focused Issue
    1. A pre-trained diffusion model exhibits partial misalignment with goals specified before or after the training process
      • Before training: Text-guided diffusion model이 의도하지 않은 콘텐츠 생성
        • Text-guided diffusion models occasionally generate content with nudity despite the text prompt containing no such request
      • After training: 특정 개념을 포함하지 않는 이미지 생성
        • 특정 개념에 대해 훈련된 모델이 특정 개념을 포함하지 않는 이미지를 생성해야 할 때, 기존 학습 데이터와의 불일치가 발생할 수 있음.
    2. Fixing misalignment directly through training may require an impractical cost of computing and data
      • Such costly measures are unnecessary when the pre-trained model is already capable of sometimes generating 'good' images
        • If so, we simply need to prevent the generation of 'bad' images = task censoring
  • Method
    • Goal:
      • Given a pre-trained diffusion model that is partially misaligned in the sense that generates both 'good' and 'bad' images, fix/modify the generation process so that only good images are produced
    • Censored generation with a pre-trained diffusion model using a reward model trained on minimal human feedback
    • Instead of fine-tuning the pre-trained diffusion model, we train a reward model on labels generated with a few minutes of human feedback and perform guided generation
    • [Overview] Censored sampling with human feedback:
      1. Mathematical formalism
        • Suppose a pre-trained diffusion model generates images from distribution p_data(x) containing both benign (good) and malign (bad) images
        • Assume there is a function r(x) (0< r(x) <1) representing the likelihood of x being benign
          • r(X) = P(Y = 1 | X)
            • r(x) = 1 means image x is benign and should be considered for sampling
            • r(x) = 0 means image x is malgn and should not be sampled
        • Mathematically formalize: 
          • Sample from the censored distribution: p_censor_(x) ∝ p_data_(x)r(x)
      2. Human Feedback
        • The definition of benign and malign images are specified through human feedback
          • Human annotators provide binary feedback Y ∈ {0, 1} for each image X through a simple graphical user interface
          • Using the feedback data, a reward model r_ψ ≈ r is trained
      3. Evaluation
        • Human time spent providing feedback
          • Quantified by direct measurement and sample quality
          • Quantified by precision and recall
            • Precision: the proportion of benign images (more focused)
            • Recall: the sample diversity of the censored generation
    • Reward Model: Diffusion Model의 생성 과정에 통합되어 좋은 이미지를 생성하도록 안내
      • Binary Classifier: Reward model은 Binary Classifier로 작동하여 이미지가 benign일 확률을 예측
      • Ensemble Method: Benign 이미지가 더 많은 경우, Reward Model Ensembling을 통해 정확도를 더 높임
        • 여러 개의 Reward Model(여기선 여러 개의 Binary Classifier)을 학습하고, 이들의 예측 결과를 결합하여 최종 예측을 수행
          • 예측 결합은 보통 개별 Model의 예측 값을 평균 내거나, 다수결 투표 방식을 사용하여 최종 결정을 내림
      • Imitation learning: Malignant 이미지가 더 많은 경우, 여러 번의 feedback round를 통해 Reward model을 반복적으로 개선하는 Imitation model을 사용
        1. Pre-trained model εθ 준비
        2. 데이터를 저장할 Buffer 'D' 초기화
        3. Sampling: Pre-trained model εθ를 사용하여 샘플을 생성
        4. Feedback 수집: Human Feedback 를 수집하고, 이를 Buffer 에 추가
          • 이 데이터는 D←{(X(i),Y(i))} (i=1,...,N1) 형태로 저장
            • Buffer D는 기존 데이터를 유지하면서 새로운 데이터를 추가하는 방식으로 업데이트 됨 (Reward Model은 더 많은 데이터를 학습하게 되어 점점 더 정확한 예측을 하게 됨)
        5. Reward Model 학습: 업데이트 데이터 D를 사용하여 Reward Model 를 학습
        6. 반복 학습: 3~5의 단계를 여러번의 round를 통해 반복

Reward Model Ensemble Algorithm
Imitation Learning Algorithm

 

  • Limitation
    1. Require a non-trivial amount of human feedback for objective evaluation
      • 아직 인간의 개입이 들어감 (subjective)
    2. Does not consider how to train new capabilities into the base model or improve the quality of generated images

 

Overall Reflection

  • Human Feedback을 이용하여 업데이트한 데이터를 이용해 Reward model을 학습한다는 점이 새로웠다. 'Reward'라는 키워드를 보면서 떠오른 건, Human Feedback을 최소화 시키기 위해서 Reinforce Learning과 결합하는건 어떨까? 이를 구체적으로 어떻게 적용시켜야 하는지는 아직 잘 모르지만, Reinforce Learning에 대한 논문들을 조사하고나서 한번 도전해볼만한 Topic인 것 같다.  

이 기록은 내가 학기 중에 수강했던 Coursera의 'Deep learning specialization' 강의를 다시 복습하는 용도이다. 이미 2번 정도 학습을 마친 상태이고, 내 기준 헷갈리거나 메모하면 좋을 핵심 내용 위주로만 작성했다. 즉, 처음 수강하는 사람들에겐 내 복습 기록들이 도움이 되진 않을 수 있다. 그런 사람들에겐 직접 수강하고 자신만의 복습 노트를 만드는 것을 추천한다.

 

Deep L-layer Neural Network

 

Forward Propagation in a Deep Network

[l]: l-th layer

 

  • Matrix Dimensions of 'w' and 'b' in Neural Netowork:

  • Matrix Dimensions of 'z' and 'a' in Neural Netowork:
Single training example
Multiple training examples

 

Importance of Deep Representations

 

 

Building Blocks of Deep Neural Networks

 

 

Parameters vs. Hyperparameters

Parameters

Hyperparameters

이 기록은 내가 학기 중에 수강했던 Coursera의 'Deep learning specialization' 강의를 다시 복습하는 용도이다. 이미 2번 정도 학습을 마친 상태이고, 내 기준 헷갈리거나 메모하면 좋을 핵심 내용 위주로만 작성했다. 즉, 처음 수강하는 사람들에겐 내 복습 기록들이 도움이 되진 않을 수 있다. 그런 사람들에겐 직접 수강하고 자신만의 복습 노트를 만드는 것을 추천한다.

 

Neural Networks Overview

Neural Network Representation

  • Neural Network는 Input layer, Hidden layer, 그리고 Output layer로 이루어져 있다.
    • 이건 two layer로 이루어진 NN이다. (input layer는 고려하지 않음)

Computing a Neural Network's Output

  • After computation of the linear formula, put it into activation function
  • Vectorization for one single training example:

  • Vectorizing across multiple examples:

Activation Functions

  • Introducing non-linearity
    • Why do we need non-linear activation functions?
      • 만약 activation function이 linear이라면 layer가 몇개 있어도 결국 최종 식은 linear임. 즉, 복잡한 계산을 못하게 되어 복잡한 feature 추출이 불가능하게 됨.

 

Random Initialization

    • to avoid symmetry issues and facilitate effective learning
      • Symmetry Issue:
        • 만약 Network의 모든 weights를 0으로 initialization하면, 모든 neuron들이 동일한 입력을 받고 동일한 출력을 생성하게 됨.
          • 즉, neuron들이 서로 구별되지 않고 동일하게 학습됨.
        • Weights가 모두 0일 때, 각 weight에 대한 gradient도 동일하게 계산됨.
          • 이는 뉴런들이 같은 방향으로 업데이트된다는 것을 의미함. 따라서, weight가 초기화된 값에서 벗어나지 못하고 학습이 제대로 이루어지지 않음.
      • Weights를 무작위로 초기화하면, neuron들이 서로 다른 입력을 받아 서로 다른 출력을 생성하게 됨. 이는 neuron들이 독립적으로 학습할 수 있게 하여, 대칭성 문제를 해결할 수 있음.
        • We prefer very small number for random initialization
          • 크게 잡게 되면 Gradient가 작아져 속도가 느려짐. (Random Initilization Figure 참)

Weight를 0으로 initialization 했을 경우
Random Initilization

+ Recent posts