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

+ Recent posts