반응형

Keras Tuner Tutorial

https://www.tensorflow.org/tutorials/keras/keras_tuner?hl=ko

keras tuner를 사용하면 하이퍼파라미터 최적화를 쉽게 할 수 있다.

 

Hyperparameter tuning이란

신경망을 훈련하는 동안 손실, 훈련/검증 정확도를 모니터링하여 적절한 훈련이 되도록 hyper-parameters를 제어해야한다. (다른 parameters의 값은 훈련을 통해 도출된다.)

Neural Networks 훈련의 성공에 올바른 hyperparameters 선택이 중요한 영향을 끼진다. 하이퍼파라미터를 선택하는 과정을 하이퍼파라미터 튜닝이라고 한다.

  • Hyperparameters: learning rate, lr decay schedule, dropout rate 등!

source: https://cs231n.github.io/neural-networks-3

Overfitting(과적합)이란 모델이 train dataset에는 높은 정확도를 가졌지만 일반화되지 않았다는 의미로 test data를 잘 예측하지 못할 가능성이 높다.

 

Code 예시

https://blog.tensorflow.org/2020/01/hyperparameter-tuning-with-keras-tuner.html

import tensorflow as tf

# model 정의
# : 튜닝할 hyperparmeter를 여기서 정의
# 튜닝하는 방법 예시)
# hp.Int(hp_name, min_value, max_value, step)
# hp.Float(hp_name, min_value, max_value, sampling)
# hp.Choice(hp_name, values)

def build_model(hp):
  inputs = tf.keras.Input(shape=(32, 32, 3))
  x = inputs
  for i in range(hp.Int('conv_blocks', 3, 5, default=3)):
    filters = hp.Int('filters_' + str(i), 32, 256, step=32)
    for _ in range(2):
      x = tf.keras.layers.Convolution2D(
        filters, kernel_size=(3, 3), padding='same')(x)
      x = tf.keras.layers.BatchNormalization()(x)
      x = tf.keras.layers.ReLU()(x)
    if hp.Choice('pooling_' + str(i), ['avg', 'max']) == 'max':
      x = tf.keras.layers.MaxPool2D()(x)
    else:
      x = tf.keras.layers.AvgPool2D()(x)
  x = tf.keras.layers.GlobalAvgPool2D()(x)
  x = tf.keras.layers.Dense(
      hp.Int('hidden_size', 30, 100, step=10, default=50),
      activation='relu')(x)
  x = tf.keras.layers.Dropout(
      hp.Float('dropout', 0, 0.5, step=0.1, default=0.5))(x)
  outputs = tf.keras.layers.Dense(10, activation='softmax')(x)

  model = tf.keras.Model(inputs, outputs)
  model.compile(
    optimizer=tf.keras.optimizers.Adam(
      hp.Float('learning_rate', 1e-4, 1e-2, sampling='log')),  # 참고: 적절한 learning_rate = 10 ** uniform(-6, 1)
    loss='sparse_categorical_crossentropy', 
    metrics=['accuracy'])
  return model
import kerastuner as kt

# Keras Tuner에는 RandomSearch, Hyperband, BayesianOptimization 및 Sklearn의 네 가지 튜너가 있음
tuner = kt.Hyperband(
    build_model,  # model compile까지 포함
    objective='val_accuracy',  # best val_accuracy 기준으로 최적화
    max_epochs=30,
    hyperband_iterations=2,
    directory='my_dir',
    project_name='tuner'
)
import tensorflow_datasets as tfds
import IPython
class ClearTrainingOutput(tf.keras.callbacks.Callback):
    def on_train_end(*args, **kwargs):
        IPython.display.clear_output(wait = True)

data = tfds.load('cifar10')
train_ds, test_ds = data['train'], data['test']

def standardize_record(record):
  return tf.cast(record['image'], tf.float32) / 255., record['label']

train_ds = train_ds.map(standardize_record).cache().batch(64).shuffle(10000)
test_ds = test_ds.map(standardize_record).cache().batch(64)

## Hyperparameter Search (Train)
tuner.search(train_ds,
             validation_data=test_ds,
             epochs=30,
             callbacks=[tf.keras.callbacks.EarlyStopping(patience=1),
                                                 ClearTrainingOutput()])
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
# best_model = tuner.get_best_models(1)[0]

 

Hyperparmeter Tuning 과정 예시

  • cifa10, resnet50으로 테스트 결과
    • 튜닝한 hyperparameter
    • : dense units, kernel_rate(lr regularizer), dropout, learning rate

keras tuner test

반응형
반응형

 

Abstract

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

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

 

1. Introduction

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

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

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

 

2. Related Work

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

Self-supervised Learning 이란

 

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

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

everyday-deeplearning.tistory.com

Multimodal pre-training

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

 

3. Method & 4. Experimental setup

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

Model Architecture

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

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

Masking

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

 

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

 

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

 

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

 

Training targets

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

 

Teacher parameterization

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

 

Targets

normalizing targets

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

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

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

 

Objective

Smooth L1 loss

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

 

5. Result

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

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

 

6. Discussion

Structured and contextualized targets.

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

Representation collapse.

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

 

7. Conclusion

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

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

왜 Self-supervised learning을 할까?

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

 

Self-supervised learning 예시

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

 

Self-supdervised learning in Computer Vision

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

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

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

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

 

Self-supervised learning in Natural Language Processing

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

https://wikidocs.net/115055

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

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

 

Self-supervised Learning in Speech

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

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

 

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


 

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

반응형
반응형

참고: https://tutorials.pytorch.kr/intermediate/flask_rest_api_tutorial.html

장점

  1. 데이터의 전, 후 처리를 할 수 있다.
  2. 쉽게 API를 사용할 수 있어 범용성이 좋다.

 

Flask

아주 가벼운 웹프레임워크로 비교적 쉽게 배워서 사용할 수 있다.

$ pip install flask

 

1. 간단하게 웹서버 구성하기

from flask import Flask
# app = Flask("test")  # 설치 test용
app = Flask(__name__)

@app.route("/ping", methods=['GET'])
def ping():
    return "pong"

if __name__ == '__main__':
    app.run()

 

2. API 실행하기

$ Flask_APP=app.py FLASK_DEBUG=1 flask run

* 참고: window에서 실행 $ python app.py

 

3. 응답 확인하기

1) 웹 브라우저로 확인하기 : http://localhost:5000/ping 에 접속하면 pong 이 표시됨

2) httpie로 확인하기 : http -v GET http://localhost:5000/ping

3) python으로 확인하기

import requests

resp = requests.get("http://localhost:5000/ping")

 


Pytorch Rest API 배포하기

 

1. pytorch 모델 API 서버에 통합하기

from flask import Flask, jsonify, request
from PIL import Image
import torch
import torchvision.transforms as imtransforms


app = Flask(__name__)

# custom model 선언 & weight load
PATH = '{Mymodel_pretrained_weight}.pt'
model = Mymodel()
model.load_state_dict(torch.load(PATH, map_location=device), strict=False)
model.eval()


def transform_image(image_bytes):
    image = Image.open(io.BytesIO(image_bytes))  # byte file open
    image = imtransforms.Resize((imsize, imsize))(image)
    image = imtransforms.ToTensor()(image)
    return image.unsqueeze(0).to(device, torch.float)

def get_prediction(image_bytes):
    tensor = transform_image(image_bytes)
    outputs = model(tensor)  # predict
    ...
    return class_id, class_name  # 자유롭게 return 가능


@app.route('/predict', methods=['POST'])
def predict():
    file = request.files['file']
    image_bytes = file.read()
    class_id, class_name = get_prediction(image_bytes)
    return jsonify({'class_id':class_id, 'clss_name': class_name})

 

2. API 실행하기

$ FLASK_ENV=development FLASK_APP=app.py flask run

flask run

 

3. predict 하기

import requests
import json

resp = requests.post("http://localhost:5000/predict", 
		       files={"file": open('{file_name}.jpg', 'rb')})

# model predict 결과 확인하기
# 200: success
print(json.loads(resp.content))
반응형

+ Recent posts