메인 플로우는 여기를 따라한다.https://github.com/facebookresearch/pytorch3d/blob/main/INSTALL.md

참고하여  pytorch3d 개발환경 설치

 

1. cuda(권장) : 11.7 설치
2. 11.7 에 맞는 cudnn lib 설치

3. pytorch 설치 (2.0.1) with cuda 11.7 torch 버전은 크게 영향은 없는듯

4. cub 환경 설치 
cuda\inculde\thrust\cuda\version.h 

에 맨 윗출을 추가해놓는다. (#define THRUST_IGNORE_CUB_VERSION_CHECK true)

 

cuda 11.7 의 경우 cub 11.5 를 포함시켜놓았는데, 이 cub 사용시 pytorch3d 빌드시 문제가된다.

#define THRUST_IGNORE_CUB_VERSION_CHECK true
#ifndef THRUST_IGNORE_CUB_VERSION_CHECK

#include <thrust/version.h>
#if THRUST_VERSION != CUB_VERSION
#error The version of CUB in your include path is not compatible with this release of Thrust. CUB is now included in the CUDA Toolkit, so you no longer need to use your own checkout of CUB. Define THRUST_IGNORE_CUB_VERSION_CHECK to ignore this.
#endif

// Make sure the CUB namespace has been declared using the modern macros:
CUB_NAMESPACE_BEGIN
CUB_NAMESPACE_END

 

5.내장된 cub 11.5 를 11.7로 바꾸는 작업을 할것이다. 

방법은 2가지가 있는데, cuda 설치경로에 cub 11.7 을 덮어씌우는 방법과 cub_home 환경변수 등록후

directory 로 빌드시 포함시키는방법

cub 는 아래서 다운받는다.

https://github.com/NVIDIA/cub/releases

 

Releases · NVIDIA/cub

Cooperative primitives for CUDA C++. Contribute to NVIDIA/cub development by creating an account on GitHub.

github.com

 

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\include\cub

로들어가 기존 cub 파일들 빽업시켜놓고 11.7로 바꿔치기 하였다.

 

6.

git clone https://github.com/facebookresearch/pytorch3d.git
cd pytorch3d && pip install -e .

를 이용하여 build 성공!

 

conda 를 이용해서 개발환경 잘 저장해놓자!

 

7. pytorch 3d 를 이용하여 간단한 gif 생성

Wandb 에서 sweep 을 이용하여 autoML 을 제공한다.

 

해당기능을 위해 소스에서는 function 을 호출하고,

sweep_id 

function : wandb 로 실행될 function 객체

count : 반복할 횟수

 sweep_id = wandb.sweep(sweep_config, project=project_name)
 wandb.agent(sweep_id, function=lambda: main(model_name, dataset_name, window=window), count=x_num)

 

config.json 은 아래와 같은 형태로 제공가

{
    "method": "bayes",
    "metric": {"name": "max_auc", "goal": "maximize"},
    "parameters": {
        "learning_rate": {
            "distribution": "uniform",
            "min": 1e-4,
            "max": 1e-3
        },
        "batch_size": {
            "values": [32]
        },
        "num_epochs": {
            "values": [50]
        },
        "optimizer": {
            "values": ["adam"]
        },
        "hidden_size": {
            "values": [64]
        },
        "emb_size": {
            "values": [64]
        },
        "layer_num": {
            "values": [3]
        },
        "dropout": {
            "values" : [0.2]
        },
        "seq_len":{
            "distribution": "q_uniform",
            "min": 50,
            "max": 100
        }
    },
    "early_terminate": {
        "type" : "hyperband",
        "min_iter": 5
    }
}

 

function 안에는 init 과 finish 를 구현하고 사이에 동기화 를 할 수 있다.

wandb.init(project=project_name, entity='id')
learning_rate = wandb.config.learning_rate
    batch_size = wandb.config.batch_size
    num_epochs = wandb.config.num_epochs
    optimizer = wandb.config.optimizer
    logging_epochs = wandb.config.logging_epochs

모델 train

모델 test

 

wandb.finish()

간략하게 이런식으로 구현하면된다.

ref : Hierarchical Latent Vector Model for learning Long-terim Strucutre in Music

 

오늘 리뷰할 논문은 LSTM 구조를 VAE 로 활용해서 Music data Reconstruction 을 시도한 논문을 설명하겠습니다.

 

2.Back ground

2-1.Recap VAE

 

fig.1
fig.2

VAE 에대해서 잘 설명해 놓은 그림이다.

기존 AutoEncoder 는 Encoder 와 Decorder 로 이루어져있는데 잠재공간에 대해서 별다른 제약을 두지 않는다.

VAE 는 잠재공간을 가우시안 분포들로 latent space 를 이룰 것이라 가정하고 출발한다.

VQ-VAE, Diffusion 모델도 이와 비슷한 가정으로 출발 하는 것으로 생각하고있다.

 

VAE는 AE 처럼 직접적으로 latent space 를 맵핑하는 대신, 평균(뮤) 과 분산(시그마) 를 이용해 latent space 를 맵핑하려고합니다. 결과적으로 2번째 scatter plotting 된 것 과 같이, VAE 에서 맵핑된 latent 를 plotting 하면 가우시안(구형분포) 를 가지는 것을 볼 수 있다.

 

 

eq. 1

다시 첫번째 그림+수식으로 설명하자면 

VAE의 목적은 Generative model 을 만드는 것인데, 일단 쉽게 생각해보면 이미지 Reconstruction 하는 것과 유사합니다.

Generative model 은 결국 P(x) 를 1로 만들자(확률분포의 총합은 1), 즉 생성된 데이타 x 의 확률분포가 원래의 x 와 같게 나올 확률을 높게 만드는 것이기 때문에 결국 log p(x) 를 크게 만들면 되는 것입니다.

 

왼쪽에 식은 VAE 의 구조를 이용해서 유도되는 log p(x) 의 하한 선인데, 

VAE = q_lambda(z|x) (Encoder) * p_seta(x) (Decoder) 로 전개 할 수 있는데

 p_seta(x) Basyian rule 을 사용하게되면 eq 1 부등식이 나오게된다.(참고:https://process-mining.tistory.com/161)

 

우리의 목적은 우항을 크게만드는건데 왼쪽항이 lowerbound 역할을 하기때문에 Evidence Lower bound, ELBO 라고한다.(왜굳이 이런 내용을 줄여서말하는지-_-ㅋ)

 

Eq1 에서 좌항은 loss 로 만들기 좋다, 왜냐하면 왼쪽항은 Decoder 를 통해서 나오는 x 의 Reconstruction loss 이며

두번째 Term 인 KL divergence 는 Encoding 되어 만들어진 z와 원래 z 분포의 KL divergence term 이기 때문이다.

 

KL divergence 는 암묵적으로 p(z) 가 평균 0 , 분산 1을 따를것이라고 가정하고 출발 하는듯 싶다.

(p(z) 가 평균 0, 분산 1을 따를 것이라고 가정하는 이유는, VAE 에서는 가능할듯 하다. 왜냐하면 그것에 맞춰서 Network 가 학습될것이기 때문이다.)

그랬을 때, 아래와 같이 Eq.2 와 같은 식이나온다. (가우시안을 따를 것이라고 가정 하기 떄문에 아래와 같이나오고

eq.2

실제로 keras 도 아래와 같이 구현이 되어있다. 

 

    kld_loss = torch.mean(
              -0.5 * torch.sum(1 + log_var - mu**2 - log_var.exp(), dim=1), dim=0
          )

 

다시 돌아가서 VAE 로 돌아가서 하나의 설명을 덧붙이자면

Eq 3 과 같은 Reparametrization trick 을 사용하는데, 그 이유는

1. 단순히 z 를 Noise 없이 분포 시키면, 똑 같은 모델만 Recon 하게 된다.

2. Noise 를 가정하면 부드러운 latent space 분포가 만들어진다.  결국 우리가 하려는 것의 목적은 좋은 Latent space 를 만들고 그곳으로부터 sampling 하여 좋은 sample 를 얻고자 하는 목적에 부합하다.

3. 2에서 부드럽다 라는 말이 참 애매한데, 어찌보면 Overtuning 같은 것일 수도있고, 최근 Contrastive learning Yolo-R 과 같이 Represent learning 을 시도하려는 쪽에서는 이러한 Reparametrization Trick 을 이용해서 우리가 잘 알지못하는 잠재공간의 무엇인가를 모델이 알아서 학습 시키게 하려는 그런 시도라고 생각한다.

Eq.3

2-2. β- VAE

 

Eq4-1
Eq4-2

위에 나온 Loss 에 β 가중치를 곱한다.

β<1 로 만들면 모델이 Reconstruct 에 집중 할수 있도록 한다.

EQ 4-2  같은 경우에는 KL divergence 의 타우라고 하는 Treshold 값을 주었는데, 이 값을 줌으로써, 

모델은 KL 다이버전스가 충분히 낮다(인코딩이 원하는 분포 대로 되었다) 일 경우에 전체적으로 loss 에 집중하고

KL 이 높을 때는 뒤에 term 이 상대적으로 커지게 되어서 무시하려고한다. 

이러한 작업은 모델로부터 더 필요한것에 집중할 수 있도록 추가적인 정보(예산)를 주는 것이라고 해석하였다.

 

2-3. latent space manipulation

AE 의 목적은 compact 한 Representation 을 학습하는 것이고,

그렇다는것은 data 에서 small Perturbation 이 결과적으로 Recon 된 이미지에서 비슷해야한다.

 

그래서 sampling 된 z1,z2 사이에 무수히많은 C_a 를 interpolation 하고, 그것들은 다시 recon 했을 때 모두 Realistic 해야한다.

특히 z 는 가우시안 분포를 따를것이라고 가정했기 때문에, Spherical interporlation (구면을 따라) 하게 된다.

이러한 생성에 대한 실험은 Attribute vectors ( 음악의 속성 vector ) 를만들어서 추가 실험을 해보았다.논문내의 (5-5)

 

 

2-4. Recurrent VAEs

fig. 3

Recurrent VAE 모델을 위 fig 가 삽입된 논문을 refer 한다. (Generating Sentences from a Continuous Space)

특징 1. Encoder 의 LSTM output 중 hidden shell output h_T 를 이용해서 시그마,뮤를 예측한다.

2.Decorder RNN 에서는 잠재벡터 z 를 초기 shell 에서 initial state 로 입력 받고, decoding 한다.

3. 모델은 recon 과 동시에, KL Divergence 를 줄이는 쪽으로 계산된다.

 

하지만 2개의 한계점이 있다.  

1. decorder 자체가 그럴싸하게 recon 은 잘하는데, z latent code 를 무시하는 경향이 있다. z 의 영향이 작아지면 KL도 작아지고 결국 autoencoder 로 서 역할을 못하게된다(?)

2. 모델이 긴 Seq 를 하나의 z space 로 Encoding 하게되므로 한계가 있다.

 

 

3. Model 

Fig.4

그래서 모델은 크게 3개의 part 로 구성되어있다.

Encoder, Conductor, Decorder

input data sequence = [x1,x2....xU] 

Encoder : 2 layer  LSTM 구조이고, 위 Refer 한 논문 과 같이 h_t 를 이용하여 latent code 인 z 를 생성한다.

(decoder) Conductor : Two layer undirectional LSTM 구조이고, 미리 구간 별로 나눠놓은 data sequence 에 대해서 매칭되도록 [c1,c2....cU] 를 generate한다.

Decoder : 2layer lstm 구조이고, 위의 출력인  c1...cu 를 decoder 의 output 과 concat 하여 input 으로 놓고 , initial state 는 모두 z 로 setting 한다. (특이한부분?)

Decorder 에서 이러한 조작을 한이유는 1.latent z 가 RNN 의 뒤로갈수록 limit 가 있었고 CNN 이면 그런 Receptive field 를 쉽게 줄일 수 있으나, RNN 의 경우에는 이게 제한이 없어서 어렵다고 설명하고 있다. 그래서 Decoder 의 ouput sequence 가 들어가는 영향을(concat,initstate)통해서 줄였다고한다.

decoder 의 state 을 conductor 의 state 로 전달 한경우에도 실험이 더 안좋아졌다고한다. Conductor 는 그래서 혼자서 잠재공간을 decoding 하는 역할에만 집중 하게 시켰다고한다.

 

*Multi sound 의 분리를 위해서 Melody, drum, bass 가 섞이는 경우 othgonal dimension 을 분리하였다고한다.

 

4. 결과

4-1 dataset

input : wav(midi) files

2bar , 16 bar 음악에서 마디에 해당되는 듯 싶다.

2bar = 2마디 = 2U = 32T , (1마디에 16개 구간이 존재한다로해석)

16bar = 16마디 = 16U = 256T , (1마디에 16개 구간이 존재한다로해석)

output seq : 마디당 16개의 quantized 된 note 를 16개의 인터발안에서 구분지어놓은 것 같다

 

결과1. Flat 은 seq 를 한번에 넣은경우 Hierachical 은 아까와 같이 subsequence 로 놓은경우

Teacher forcing 은 GT 를 다음 output 의 input 으로 넣어 학습한경우 sampling 의 경우에는 predicted label 을 input 로 넣은경우 이다. 전체적으로 Hierachical-teacher-forcing 의 경우 더 좋은 결과가나온다.

 

결과 2. Interporlation 에 대한 결과이다.

X 는 A,B 로 균일하게 interporlation 한 결과이고, (z 에서 했다고한다.)

결과적으로 나온 y 축의 결과는 propotion of timestep predictions that differ between the interpolation and seq A (시작점)

이라고한다. 

 

아래는 마찬가지로 Language model cost 라고 하는데, 이게 뭔지..

 

결과 3 

latent space 에서 음원에 특징의 방향을 만들어서 그것을 넣고(좌측), 뺏다는(우측) 실험이였다.

음원특징을 latent vector 로 만든것도 재미있고 각각 그 방향으로 벡터를 넣고 뺐을 때, 해당되는 특성이 얼마나 measure 되는지를 측정했다고한다. 이런시도들 이 너무 재밌고 신기하다고 생각한다.

 

결과 4 Listening test

얼마나 진짜 같은지 test 했는데 크게 차이나지 않은것 같다. 

 

 여러 모듈을 붙일 때 중간 Layer 에 Hook_fn  등 을 걸면, 중간 layer 에서 

output 을 불러다 사용가능하고,

뭐 explainable ai 의 activation map 을 볼때 등등 다양한 용도로 사용한다.

 

torch 의 모델은 'dict' 형태로 저장되있으나, 안에 모듈안에 서브모듈등으로 구성되어있어서.

모든 layer 를 검색하려면 계층적으로 탐색해야한다. 

 

어쩃든 머 특정 layer 에서 hook 을 걸려면 아래처럼 register_forward_hook 또는 register_backward_hook

self.DPTbackbone._modules['scratch'].output_conv[6].register_forward_hook(self.forward_hook('output_conv'))


등을 걸면되고, 

그안에 훅 funtion 을 넣어주게되면 이 function 이 해당레이어에 data 가 통과될 때, call back 처리되어 거꾸로 호출된다.

거꾸로 호출될때 특징이 input output 이 같이 호출되는 구조이다.

펑션은 아래처럼 만들어주면된다.

  def forward_hook(self,layer_name):
        def hook(module, input, output):
            self.selected_out[layer_name] = torch.squeeze(output,dim=1)
        return hook
    def get_last_hook(self):
        return self.selected_out['output_conv']

ref : https://medium.com/the-owl/using-forward-hooks-to-extract-intermediate-layer-outputs-from-a-pre-trained-model-in-pytorch-1ec17af78712

 

Using forward_hooks to Extract Intermediate Layer Outputs from a Pre-trained ResNet Model in…

Here we are again with the fourth article in the “Feature Extraction” series. This article will describe another method (and possibly the…

medium.com

https://hongl.tistory.com/157

'Machine.Learning > torch' 카테고리의 다른 글

torch - cnn concatenate 하기 feature 합치기  (0) 2021.01.24

CV 시작하면서 처음으로 해보는 주제인데 흥미롭다.

DL 개발 하면서도 중간중간 구멍이 뚫려있음을 느꼇었는데 그러한부분을 CV 공부좀만 해보니 채워지는걸 느낀다.
누가 나에게 어떤 공부를 해보겟냐고 제안을 한다는것은 무척이나 기쁘고 설레는일이다.


아무튼 전체적으로 이분야가 unsupervised learning 기법하고도 연관을 많이 지을수 있을것 같은분야이다.

대표적인 논문들 위주로. 그리고 주로 2017년 논문들 내용이 아주 근본있고 좋다.
2020년 이후로 나온 논문들 관행이 생략인지 나름 CV domain specific 한 지식들인데 너무당연하다고 써놓는 내용이 많아서 좀 그렇긴 하다.

Depth estimation

논문 내용
MegaDepth pr 12 참고
Guiding Monocular Depth Estimation Using Depth-Attention Volume 실내의 환경에서는 여러개의 plane 이있다고 가정하고, 그 plane 내 같은점들은 linear dependent 할거라 가정하고 출발! 그 것을 기준으로 Attention map 을 만들고 best plane 끼리의 Distance, 각도 등을 구해서 로스로 사용
From Big to Small: Multi-Scale Local Planar Guidance for Monocular Depth Estimation Local planner guidance, U-net decorder 에 Up sampling 대신 LPG 를 넣음, LPG 는 spatial feature -> ray-평면 inter section 의 계수를 예측하여 depth 를 계산
AdaBins: Depth Estimation using Adaptive Bins (근)Unet decorder 쪽 feature 를 Transformer Decorder 써서 depth estimation 및 bin position estimation 한 것이 특징
   
Unsupervised monocular depth estimation with left-right consistency (근근) 좋은내용이나 Towards scene understanding의 하위버전
Depth Map Prediction from a Single Image using a Multi-Scale Deep Network (근근)비교적 간단함, Coarse, Refined network 를 만들어 각각 global, detail 한 정보를 합침- scale invarient 한 loss 생성
FlowNet 근 of GeoNet
GeoNet: Unsupervised Learning of Dense Depth, Optical Flow and Camera Pose 연속된 영상 내가움직인다고 가정했을 때 에서 depth,Optical Flow, Camera Pose 는 모두 연관이 있으며 같이 뽑아야 한다, 움직임에(자율주행 차량) 에 좀더 초첨을 맞춰서 그것을 기반으로 학습을 하려함! pr12 영상 참고
Towards scene understanding: Unsupervised monocular depth estimation with semantic-aware representation region-aware depth estimation by enforcing semantics consistency between stereo pairs. E.G sky - high depth 이런식으로 segment 와 depth 를 연결, e leftright semantic consistency and semantics-guided disparity smoothness 를 이용
Towards robust monocular depth estimation: Mixingdatasets for zero-shot cross-dataset transfer (근)대량의 학습을 통해 영화등 unlabeled data 에서 평가,loss space 별로 비교(여러가지 나열하고 로스에 대한 평가 부분이 있어서 좋음) ,mixing datasets, multi objective optimization loss 를 dataset 별로 세분화시키는것
Excavating the Potential Capacity of Self-Supervised Monocular Depth Estimation (sota2023) data grafting, an exploratory self-distillation loss, nd enhance the representational power of the mode --> streo ->molecure 관점에서 self supervised 로 접근, 지식 총집함이기때문에 첨부터 읽기 힘들수 있음
DwinFormer: Dual Window Transformers for End-to-End Monocular Depth Estimation (sota2023) Swin Trasnfoermer Unet 구조로 쌓은것, Lwin block 조사 필요
Deep Ordinal Regression Network for Monocular Depth Estimation 바로밑의 refer spacing-increasing discretization (SID) strategy to discretize depth and recast depth network earning as an ordinal regression problem, deconv 나 skip connection 을뺏고 ASPP 넣었다. SID 는 로그스케일로 deth map 보는것, ordinal 은 y space 를 퀀타이즈하는것
On the uncertainty of self-supervised monocular depth estimation 멀하겟다는건지.. 그냥베이시안관점으로 uncertainty 를 학습하는듯
Unsupervised learning of depth and ego-motion from video 아래의 선행논문 연속된 video의 차를가지고 Depth 를 추적함 https://www.youtube.com/watch?v=HWu39YkGKvI
Unsupervised learning of geometry from videos with edge-aware 'depth-normal' consistency normal 이 수직방향이라는 뜻, 일단 우리쪽 주제랑 관련이 아주 많아보임
MonoViT: Self-Supervised Monocular Depth Estimation with a Vision Transformer (sota2023)cnn encoding + transformer(섞기) block을 Unet구조로 함

ref : https://www.tensorflow.org/model_optimization

ref : https://www.tensorflow.org/lite/performance/post_training_quantization

1.quantization

1.1 post-train quantization

1.1.1 Dynamic range quantization

  - 용량만 줄이고 실제 동작 할때는 weight 를 다시 floating point 방식으로 변환하여 

  - 속도는 full integer quantization 에 비해 저하됨

1.1.2 full integer quantization

   - model weight , input, activation 등 모두 quantization 작업을 통해 진행됨

   - weight, bias 등은 constant 이기 때문에, 알아서 변한됨

   - input, activation (output of activation layer) 의 경우  일종의 sample dataset 을 넣어주면 모델이 변환하는 과정에서 tensor 를 흘려보내면서 변환시키는 구조

   - 그러므로 tflite 파일에는 모델의 sample input 을 통해 float32→int8 등으로 변환하는 관계식을 포함시킴 
def representative_dataset():
  yield [get_example_input() ]
def get_example_input():

    my_data = np.genfromtxt('Arrhythmia.csv', delimiter=',')
    # my_data = my_data[:,:]
    ratio_konkuk = 500/5000
    my_data = cv2.resize(my_data, None, fx=ratio_konkuk, fy=1, interpolation=cv2.INTER_AREA)
    my_data = preprocessing.minmax_scale(my_data, axis=1)
    my_data = my_data[:, :, np.newaxis]
    my_data = np.array(my_data, dtype=np.float32)
    return my_data

converter = tf.lite.TFLiteConverter.from_keras_model(loaded)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8  # or tf.uint8
converter.inference_output_type = tf.int8

2.Weight clustering

:model 의 weight 등을 비슷한 값 끼리 clustering 한형태로 저장함

cons : 정확도 감소

pros : weight 파일 용량 감소

3.Pruning method

: 필요없는 wegiht 또는 layer 등을 제거하는 방법

ref: https://arxiv.org/abs/1710.01878

1.Related work

Mobilenet V2 - Related work

Develop of NN architecture

-model design

-hyperparameter optimization

-network pruning

-connectiviy learning(?) > shufflenet (?)

-genetic algorithms to optimizer

-reinforcement learning to architectural search

>> too complex

 

2. Architecture Strategy

a.  우린 각각의 NN 의 각 layer가 manifold of interest 를 form 한다고 알고있습니다. (명확하진 않지만 통속적으로)

b.  그 때 manifold of interest 는 더 적은 차원의 subspace 에 embedding 될 수 있다고 오랫동안 가정해왔습니다.

c.  CNN 에서 독립적인 d개의 체널 pixel 을 보면 information 이 이 곳에 Some manifolod를 형성하며 encoded 되어 있습니다.

d. mobilenet v1 에서도 보앗듯이 width multiplyer  manifold of interest 가 dense 하게 span 할 때까지 dimensinality 를 감소시킵니다.

e. 하지만 이것은 NN 이 non-linear transformation 을 포함할 때 깨지게 됩니다. ( 이 논문에서 실험하였음)

f.  Relu 를 예를 들자면, 아래와 같이 Relu 의 output 형태를 보면 1차원이기 때문에  output space 를 보면 , piecewise linear curve 를 형성합니다.

 

 

f -2 . 이것을 다르게 해석하면 Deep network 는 최종 output activation 에 의해  오직 1차원적인 classifier 로서 동작하게됩니다. 이때 output domain 에서 생각해보면 non-zero volume (finte?) 을 형성하게됩니다.

g. 우리는 추가적으로 input manifold 가 low-dimensional subspace 에 embedding 될 수 있다면,  Relu transformation 이

그 information 을 preserve 하는 것을 증명하였습니다.  필요조건이 있는데[그것의 복잡도를 포함하기 위한 set of expressible functions 찾을 수 있다면

 

 

이어서 이 정리에 대한 내용만 설명해보자면

S 는 compact, fB = Relu(BX) : Rn => Rm, P(B) = pdf on Matrix 

>> 결론,  fb 로 부터 유도(collapse~축소)된 m 차원공간 space 의 average n-volume 은, 

V - (Nm,n)/ (2^m) V = V(1-(Nm,n)/ (2^m)) = Vol(S) * 0.xxx 즉  처음 정의한 S 라는 compact 공간에 Embedding 된다.

 

 

#summary for bottleneck

1. If the manifold of interest remains non-zero volume after ReLU transformation, it corresponds to a linear transformation.

2. ReLU is capable of preserving complete information about the input manifold, but only if the input manifold lies in a low-dimensional subspace of the input space.

(3). Experimental evidence suggests that using linear layers is crucial as it prevents nonlinearities from destroying too much information

 

1.  manifold of interest 가 RELU이후 non zero volume 을 남긴다면, 이것은 linear transform에 대응됨

2. RELU 는 information 을 preserve 할 수 있는 가능성이있다, 하지만 오직 input manifold 가 low -dimensinal subspace 의 lie 될 때만

3. Exprimental 이 증명한다, Linear layer 이 information 이 destroy 되는 것을 막아준다고. 

ex

>Bottleneck 은 일종의 최적으로 압축된  Manifold 로 Encoding 된 정보의 집합

ex)CNN , Image recognition 은 2번가정에 매우 적합할 수 밖에 없다.

 

 

#Inverted Residuals

기존에 있던 Residual bolck 을 반대로 하는것이다.

Residual 에 대해서 먼저 이야기 하자면, Residual 이 사용되는 가장 큰이유는 앞서말한 정보 파괴를 막기 위해 Residual 을 만들어 주게 된다.

하지만 이논문에서는 이것을 반대로 뒤집어서 하게되는데,

첫번째 가정이 inverted residual  block 을 돌리기 이전에 이미 bottleneck 을 만든다는 것이다.

 이미 축소된 subspace 로 embedding 시키고 그것을 residual 하게되면 메모리, 연산량 측면에서 많은 이점을 갖게된다.

왜 굳이 conv 할때 expand 하는지에 대해서 묻는다면?

이 channel expand 의 역할은 비선형을 포함 할 수 있도록 도와주는 Detail 의 역할을 한다고한다.

결론적으로 채널수 / memory 수를 비교해보면 더  bottleneck 을 만들어 놨다는 것을 알 수 있다.

 

 

이것을 보면 Stride 가 1/2 일 때  block 이 상이 한데,

Stride 2 는 Residual 이 없는 것을 확인 할 수 있다.

그 말인 즉슨,  Resolution 자체가 줄어들 때는, 체널을 넓늘려가며 충분히 information을 담는 parameter 자체는 늘어나도록 

신경을 썻고, Stride 1  ,Resolution 자체가 유지될 때는, Inverted Residual 을 넣어 원래 정보를 유지시키는 대 집중 하고, 그안에서 더 높은차원의 data 를 expand and squeeze 를 사용해서 추출해서 detail 로 사용 했다고 보면 된다. 

 

Q 64 >96 160 >320 의 역할은 무엇일까. 오히려 체널을 bottleneck 을 했다가 다시 넓히는 이유가 있을까?

 

 

결론 : impressive as our ecg signal 

'Machine.Learning > ML- Models' 카테고리의 다른 글

Mobilenet V1  (0) 2021.01.25
Generative vs Discriminative  (0) 2019.12.22

1.introduction

key = improve of efficiency

 

Related work

method1 : 네트워크자체를 경량화

-Enception and Xception

-Extremely Factorized networks

-Squeezenet

 

method2 : fatorizing pretrained NN

-distilling

-hashing , pruning

-vector quantization

 

mobilenetv1 의 소개와 Related work 시작이다, 

다양한 deeplearning이 발전되면서 당연히 네트워크를 어떻게 효율적으로 만드느냐에 대해서도 발전이되어왔다.

첫번째 방법으로서는 네트워크자체를 경량화하는 방법이있다. 1x1 3x3 등을 섞어서 가볍고 깊은 네트워크를 사용하는 inception 과 그것을 더 개선한 Xception 등이있습니다. Squeezenet 같은 경우에도 그러한 부분을 개선함

 

 

2. Key Architecture

 

a.1x1 convolution (= pointwise convolution) (출처 hwiyong.tistory.com/45)

  1. Channel 수 조절
  2. 연산량 감소(Efficient)
  3. 비선형성(Non-linearity)

 

network 차수는 높아지면서, parameter 는 낮아진다. 

>> 예를 들면 어떤 문제를 f 를 x,y,z의 대한 함수로 근사할 때 

f = x^4 +y^4 +z^4 + x^2yz + xy^2z + xyz^2  대신
f = x^10 + y^10+ z^10 ( 소량의 term ,but high degree) 를 놓는 것이라 생각한다.

 

다만 뭐가 f 에 더 정확하다고 볼수는 없다, 그러나  더 강하게 휘면서도 simple 해진다고 본다. 명확히 분류의 경계가 있는 문제에 대해서는  좋아 질 수 밖에 없다. 

 

b.depthwise convutions

위의 1 by 1 point wise conv 과 모티브는 비슷하다.  depth 가 깊어지고, parameter 는 작아지는(width 가 작아지는)

효과가 있다.

일종의 3 by 3 by #c  의 conv filter 를 가진 cnn 이 3 by 3by 1    * 1 by 1by c 의 두개의 Matrix factorization

로 분해 가 되면서 2개의 cnn 이 원래의 conv filter 역할 을 대체 하는 것이다.

cnn
deptwise

 

 

 

 

test for mnist

원래 CNN

conv1 = nn.Conv2d(1, 6, 5, 1)  # 6@24*24
# activation ReLU
pool1 = nn.MaxPool2d(2)  # 6@12*12
bn1 = nn.BatchNorm2d(6)
conv2 = nn.Conv2d(6, 16, 5, 1)  # 16@8*8
# activation ReLU
bn2 = nn.BatchNorm2d(16)
pool2 = nn.MaxPool2d(2)  # 16@4*4


self.conv_module = nn.Sequential(
conv1,
nn.ReLU(),
bn1,
pool1,
conv2,
nn.ReLU(),
bn2,
pool2
)

deptwiseconv

super(depthwisecnn, self).__init__()
conv1 = nn.Conv2d(1, 1, 5, 1)  # 1@24*24
conv1_2 = nn.Conv2d(1, 6, 1, 1)  # 6@24 24
bn2 = nn.BatchNorm2d(6)

# activation ReLU
pool1 = nn.MaxPool2d(2)  # 16@12*12

conv2 = nn.Conv2d(6, 6, 5, 1)  # 6@8 8
conv2_2 = nn.Conv2d(6, 16, 1, 1)  # 16@8*8
bn3 = nn.BatchNorm2d(16)

# activation ReLU
pool2 = nn.MaxPool2d(2)  # 16@4*4
self.conv_module = nn.Sequential(
  conv1,
  conv1_2,
  nn.ReLU(),
  bn2,
  pool1,
  conv2,
  conv2_2,
  nn.ReLU(),
  bn3,
  pool2
)

# of params

acc 97.16 > 87 (deptwise)

 

*with batch norm

depthwise cnn 이 배치놈의 효과를 많이 받는다. (cnn 은 layer 하나로 처리하는것에 최적화되어있는듯)

97.98 > 97.16 (deptwise)

 

 

 

'Machine.Learning > ML- Models' 카테고리의 다른 글

mobilenet v2, mobilenet v3  (0) 2021.01.28
Generative vs Discriminative  (0) 2019.12.22

discuss.pytorch.org/t/concatenate-layer-output-with-additional-input-data/20462

 

Concatenate layer output with additional input data

I want to build a CNN model that takes additional input data besides the image at a certain layer. To do that, I plan to use a standard CNN model, take one of its last FC layers, concatenate it with the additional input data and add FC layers processing bo

discuss.pytorch.org

사실 간단하지만 궁금했던부분이다.

torch 에서는 이런식으로 layer 를 추가해주고 forward 부분에 

x = torch.cat((x1, x2), dim=1

이런식으로 하는게 특징이다.

 

 

class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.cnn = models.inception_v3(pretrained=False, aux_logits=False)
        self.cnn.fc = nn.Linear(
            self.cnn.fc.in_features, 20)
        
        self.fc1 = nn.Linear(20 + 10, 60)
        self.fc2 = nn.Linear(60, 5)
        
    def forward(self, image, data):
        x1 = self.cnn(image)
        x2 = data
        
        x = torch.cat((x1, x2), dim=1)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

 

'Machine.Learning > torch' 카테고리의 다른 글

pytorch hook 걸기  (0) 2023.04.10

 

1. www.nvidia.com/

에서 os 등 선택 후 드라이버 검색 > 결과 460.32 /  455.45

460.32 = cuda 11.2

455.45 = cuda 11.1 을 포함하고있음

455.45 를 선택하여 설치 함

일단 여기까지 성공

 

1-2. cuda tool kiㅅ  설치  nvidia 드라이버와 맞는 cuda 를 설치

developer.nvidia.com/cuda-downloads?target_os=Linux

 

CUDA Toolkit 11.2 Update 1 Downloads

Select Target Platform Click on the green buttons that describe your target platform. Only supported platforms will be shown. By downloading and using the software, you agree to fully comply with the terms and conditions of the CUDA EULA. Operating System

developer.nvidia.com

아래 명령어등을 이용하여 환경변수등록 필요!

echo 'export PATH=$PATH:/usr/local/cuda-11.2/bin' >> ~/.bash_profile
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-11.2/lib64' >> ~/.bash_profile
echo 'export CUDADIR=/usr/local/cuda-11.2/' >> ~/.bash_profile

 

2. cudnn 설치

developer.nvidia.com/rdp/cudnn-download

마찬가지로 위링크 통해 cudnn 설치 

 

일단 이렇게 많이 뜨는데, Runtime library 로 설치  함//

 

3. 가상환경설정 virtualenv + pip 조합으로 설정

pycharm 을통해 default viertualenv 를 만들고

source /home/sangil/PycharmProjects/PatchNet/t171/bin/activate

을통해 activate

 

4.tf2 , torch 등을 설치

 

pip install 쭉 복사해다가 붙여주면됩니다.

설치완료후 

 

아래 코드를 통해  동작확인 하고 끝!

In [1]: import torch

In [2]: torch.cuda.current_device()
Out[2]: 0

In [3]: torch.cuda.device(0)
Out[3]: <torch.cuda.device at 0x7efce0b03be0>

In [4]: torch.cuda.device_count()
Out[4]: 1

In [5]: torch.cuda.get_device_name(0)
Out[5]: 'GeForce GTX 950M'

In [6]: torch.cuda.is_available()
Out[6]: True

 

4-2. <Tensorflow2 설치>

tf2 를 설치 해보자

tf2 설치는 간소화되어있다. 

pip install tensorflow 

오마이갓 여기 리스트 에 확인된바로는

tensorflow-2.1.0 2.7, 3.5-3.7 GCC 7.3.1 Bazel 0.27.1 7.6 10.1

이게 마지막 버전이라 TF 설치하기위해선 다운그레이드 해야할판이다 ㅎㅎ

tf2 를사용하려면 1번부터 다시 해서 10.1 cuda 에 맞춰서 설치하면 된다.

www.tensorflow.org/install/source#gpu

 

 

소스에서 빌드  |  TensorFlow

소스에서 TensorFlow pip 패키지를 빌드하고 Ubuntu Linux 및 macOS에 설치합니다. 명령어는 다른 시스템에도 적용될 수 있지만, Ubuntu 및 macOS용으로만 테스트되었으며 지원됩니다. 참고: 잘 테스트되고

www.tensorflow.org

 

*solutions for 4-2 

결론적으로 rtx3080 이 cuda 11.1 부터 호환되므로 위의 버전지원등의이유로 tf2 를 깔수 없지만 

이글을 참고해보면

stackoverflow.com/questions/63978039/is-cuda-11-with-rtx-3080-support-tensorflow-and-keras

1. TF 공식홈페이지엔 직접 cuda 버전을 맞추어서 tf 를 빌드에서 쓰라고한다.

 

2. 혹은 docker 를사용하여 빌드하면 된다고한다.

hub.docker.com/r/tensorflow/tensorflow/tags/?page=1&ordering=last_updated&name=2.4

 

Docker Hub

 

hub.docker.com

pip install tensorflow==2.4.1  버전으로 tf 및 Keras 설치 및 실행  성공 , 다만

cuda 버전이 TF 와 정확히 맞지 않아 memory 관련 warning 이 많이 뜬다.

 

그게 껄끄럽다면 아래 개발자버전을 이용하여 설치하면 3080 과 잘 호환되는 것을 알 수 있다.

혹은 tf : pip install tf-nightly==2.5.0.dev20210110

을이용하여 tf-nightly 를 이용해도 되는데 nightly 자체가 버그가 많은것으로 알고 있다.

 

+ Recent posts