StyleGAN(스타일갠)

생성모델쟁이·2020년 11월 4일
17

GAN

목록 보기
3/9
post-thumbnail

작성자 : 서울시립대학교 경제학부 박준영

StyleGAN(스타일 갠) seminar 목차

  1. gan 개선방안
  2. style gan 활용
  3. style gan의 사업적 측면
  4. style gan의 의의
  5. style gan의 구조
    1) progressive growing
    2) noise mapping network
    • z vector와 w vector의 차이점
    • style gan에서 w vector의 역할
    3) synthesis network
    • AdaIN
    • style mixing
    • stochastic variation
  6. style gan이 제안한 latent space disentanglement 측정법
    • perceptual path length
    • linear separability
  7. style gan 총 정리
  8. style gan의 한계
  9. style gan 2

1. gan의 개선 방안

_출처:cousera DeepLearning.AI <https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans?utm_source=deeplearningai&utm_medium=institutions&utm_campaign=DLWebGANsMain_>

위의 사진은 gan의 발전과정이다.
흑백, 저화질의 사진에서 컬러 고화질의 사진으로 2014년부터 2018년까지 4년사이 놀라운 발전이 이루어졌다.


Gan이 많이 발전해왔지만 여전히 개선점이 존재한다.
2주차 강의에서부터 계속 강조해왔던

  1. stability(안정성)
  2. capacity(gan의 능력)
  3. diversity(다양성)
    이다.

_출처:cousera DeepLearning.AI <https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans?utm_source=deeplearningai&utm_medium=institutions&utm_campaign=DLWebGANsMain_>

왼쪽이미지는 잘 학습된 생성 이미지/ 오른쪽 이미지는 local minimum에 빠진 mode collapse 생성 이미지이다.
즉, 왼쪽이미지는 샘플 전체의 표준편차가 높고. 오른쪽 이미지는 샘플 전체의 표준 편차가 낮다.

이 모델의 stability를 개선하기 위한 방법으로

  1. minibatch

  2. Wasserstein loss
    2주차 신민정님 자료:(https://velog.io/@tobigs-gm1/basicofgan)

  3. spectral normalization

  4. exponential averaging (style gan)

_출처:cousera DeepLearning.AI <https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans?utm_source=deeplearningai&utm_medium=institutions&utm_campaign=DLWebGANsMain_>
  1. progressive growing (style gan)
_출처:cousera DeepLearning.AI <https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans?utm_source=deeplearningai&utm_medium=institutions&utm_campaign=DLWebGANsMain_>

1,2번은 이미 배웠으니 넘어가도록 하고 4,5번은 stlye gan에서 자세히 설명하도록하겠다

spectral normalization에 대해 설명하자면 batch normalization과 매우 비슷하다.
hyper-parameter에서 Lipschitz constant만 조정하면 되기때문에 실행이 간단하고 추가적인 계산량이 적다는 장점이있다.
pytorch와 tensor flow는 구현이 되어 있어서 그냥 사용하면된다.

pytorch : TORCH.NN.UTILS.SPECTRALNORM()
tensorflow : tfa.layers.SpectralNormalization()_

![spectral normalization 논문]: (https://arxiv.org/abs/1802.05957/)
![spectral normalization 설명]: (https://hichoe95.tistory.com/60?category=783893/)
![spectral normalization 구현 코드]: (https://github.com/christiancosgrove/pytorch-spectral-normalization-gan/)





_출처:cousera DeepLearning.AI <https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans?utm_source=deeplearningai&utm_medium=institutions&utm_campaign=DLWebGANsMain_>

gan 자체의 capacity를 올리기 위해서

  1. 하드웨어 GPU 성능 개선
  2. 고해상도의 data set사용

위 2가지 방법이 capacity 개선방법이다.

_출처:cousera DeepLearning.AI <https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans?utm_source=deeplearningai&utm_medium=institutions&utm_campaign=DLWebGANsMain_>

Diversity를 개선하기 위해서 더 많은 범위의 data set을 사용해야한다.


gan의 개선 방안
stability는 longer training and better images일때 개선
capacity는 lager models and higher resoulution image일때 개선
diversity는 increasing variety in generated images일때 개선

style gan은 stability, capacity, diversity를 개선한 모델이다.



2. style gan의 활용

style gan을 활용하여 이미지, text를 생성하는 사이트들이 있다.

3. style gan의 사업적 측면

실제로 style gan 어떤 사업에 활용을 할 수 있을지 살펴보자.

  • 의류피팅 모델

    가상 피팅모델 예시 https://www.instagram.com/lilmiquela/

  • 현실에 존재하지 않는 세련된 피팅 모델을 생성한다. 다양한 핏을 가진 피팅 모델을 생성하여 옷에 맞는 모델을 이용하거나 자신과 비슷한 핏을 가진 모델을 생성하여 옷이 자신의 핏과 맞는지 비교.
    이는 모델을 많이 고용할 수 없는 중소규모의 쇼핑몰의 경우 다양하게 생성된 피팅 모델을 활용할 수 있다.

  • 가상의공간 생성
    제품을 팔때 생성된 수백 가지의 가상의 공간에 물건을 배치하여 다양한 공간에 따라 제품을 보여주어 다양한 느낌으로 제품을 보여줄 수 있다.

  • AI앵커가 전하는 뉴스
    앵커 대신 AI앵커가 뉴스를 대신 전달하게 된다.
    https://www.youtube.com/watch?v=IZg4YL2yaM0



4. stlye gan의 의의

  • 기존 PGGAN의 구조 개선

  • image 합성 과정에서 scale-spcific control 가능

    • scale-specific control이란?
      이미지 합성과정에서 specific한 scale로 자유롭게 조절가능하다는 의미
  • 이미지를 합쳐보니 새로운 이미지를 잘 생성해내는것을 발견

  • Latent space의 disentanglement 측정방법 제안
    (perseptual path length, linear separability)

  • 고화질이고 다양한 사람 얼굴을 포함하는 FFHQ 데이터셋 공개



5. style gan의 구조

1) progressive growing

style gan의 구조를 살펴보자

출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

style gan의 progressive growing은 PGGAN을 base로 한다.

출처: PROGRESSIVE GROWING OF GANS FOR IMPROVED QUALITY, STABILITY, AND VARIATION
 <https://arxiv.org/abs/1710.10196>

<PGGAN의 progressive growing 구조>

기존의 gan 모델은 고해상도 이미지를 생성하기 어렵다는 문제점이 있었다.

gan 모델이 고해상도 이미지를 생성하기 어려운 이유는 고해상도 일수록 fake image를 구분하기 쉬워지고 큰 메모리를 생성할때 메모리 문제가 있기 때문에 작은 크기의 mini-batch를 사용할 수 밖에 없다.
이렇게 mini-batch의 크기가 작아지면 mode collapse 문제가 발생한다.그래서 Gan의 고해상도 이미지 생성 문제를 해결하기 위한 모델이 PGGAN이다.

PGGAN의 progressive growing을 먼저 보면 알겠지만 PGGAN은 한 번에 전체 크기의 이미지 feature를 학습시키는게 아니라 4X4 저해상도 이미지에서부터 시작해서 점진적으로 layer를 추가하며 1024X1024의 고해상도 이미지를 만든다.

출처: PROGRESSIVE GROWING OF GANS FOR IMPROVED QUALITY, STABILITY, AND VARIATION
<https://arxiv.org/abs/1710.10196>

<PGGAN의 upsampling 구조>

PGGAN을 upsampling 할때 1-a 부분은 학습된 파라메터 없이 upsampling만 하는 부분이고 a부분은 학습된 파라메터를 가지고 있습니다.
점차 학습된 파라메터에 의존하게끔 upsampling을 한다

여기서 PGGAN 문제가 발생하게 되는데
PGGAN은 latent vector z가 normalization을 거쳐 모델에 input value로 들어간다.
이렇게 latent vector z가 input으로 들어가게 되면, latent space는 반드시 traning data의 probability density를 따라야한다.

그렇기 때문에 PGGAN은 progressive growing 구조를 따라 고해상도의 이미지를 생성하지만 생성된 이미지의 feature들이 entanglement하게 만들어진다

다시말하면, input을 조금이라도 조정하게 되면 동시에 여러 특징이 영향을 받는다.

출처: https://velog.io/@chy0428/StyleGAN-A-Style-Based-Generator-Architecture-for-Generative-Adversarial-Networks-%EB%85%BC%EB%AC%B8-%EC%A0%95%EB%A6%AC

위 사진은 PGGAN의 latent space interpolation 결과이다. 압축한 정보를 복원하기위해 알려진 지점 값 사이에 중간에 위치한 값으로 추정하는 interpolation과정에서 상당히 어색한 이미지가 생성되는 것을 볼 수 있다.

그 이유는 feature들이 entanglement하기 때문이다.

interpolation 설명: <https://darkpgmr.tistory.com/117>
PGGAN 설명: <https://sensibilityit.tistory.com/508>


이제 style gan에 적용된 progressive growing을 알아보자
style gan의 구조는 다음과 같다.

출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

synthesis network 부분에 progressive growing이 적용되었다.

2) mapping network

  • z vector와 w vector의 차이점

오른쪽 그림의 1. mapping network를 보시면
input vector가 직접 convolution으로 들어가지 않고
fully connected layer로 구성된 mapping network를 통과하여 비선형 w vector로 변화 시킨다.

mapping network를 사용하여 입력 z vector를 각각의 요소가 다른 visual feature를 control하게 만드는 intermediate vector로 변환시킨다.
이때 intermediate vector w는 정규분포를 따를 필요가 없다. 그래서 data set을 훨씬 유동적인 공간(intermediate latent space)에 mapping 할 수 있게 된다.

  • w vector의 역할
    정규분포를 따르지 않는 intermediate vector w를 이용하면 visual attribute와 stochastic variation을 조절하기 훨씬 용이해진다.

intermediate vector w는 데이터 간 상관관계를 줄여 z vector보다 더 disentanglement한 latent vector를 만든다.

z, w vector disentanglement
출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

출처 : https://www.coursera.org/lecture/build-better-generative-adversarial-networks-gans/noise-mapping-network-Udixn

intermediate vector w는 synthesis network가 이미지를 생성하는 과정에서 style을 입히는데 사용된다.




mapping network code

def G_mapping(
    latents_in,                             # First input: Latent vectors (Z) [minibatch, latent_size].
    labels_in,                              # Second input: Conditioning labels [minibatch, label_size].
    latent_size             = 512,          # Latent vector (Z) dimensionality.
    label_size              = 0,            # Label dimensionality, 0 if no labels.
    dlatent_size            = 512,          # Disentangled latent (W) dimensionality.
    dlatent_broadcast       = None,         # Output disentangled latent (W) as [minibatch, dlatent_size] or [minibatch, dlatent_broadcast, dlatent_size].
    mapping_layers          = 8,            # Number of mapping layers.
    mapping_fmaps           = 512,          # Number of activations in the mapping layers.
    mapping_lrmul           = 0.01,         # Learning rate multiplier for the mapping layers.
    mapping_nonlinearity    = 'lrelu',      # Activation function: 'relu', 'lrelu'.
    use_wscale              = True,         # Enable equalized learning rate?
    normalize_latents       = True,         # Normalize latent vectors (Z) before feeding them to the mapping layers?
    dtype                   = 'float32',    # Data type to use for activations and outputs.
    **_kwargs):                             # Ignore unrecognized keyword args.

    act, gain = {'relu': (tf.nn.relu, np.sqrt(2)), 'lrelu': (leaky_relu, np.sqrt(2))}[mapping_nonlinearity]

    # Inputs.
    latents_in.set_shape([None, latent_size])
    labels_in.set_shape([None, label_size])
    latents_in = tf.cast(latents_in, dtype)
    labels_in = tf.cast(labels_in, dtype)
    x = latents_in

    # Embed labels and concatenate them with latents.
    if label_size:
        with tf.variable_scope('LabelConcat'):
            w = tf.get_variable('weight', shape=[label_size, latent_size], initializer=tf.initializers.random_normal())
            y = tf.matmul(labels_in, tf.cast(w, dtype))
            x = tf.concat([x, y], axis=1)

    # Normalize latents.
    if normalize_latents:
        x = pixel_norm(x)

    # Mapping layers.
    for layer_idx in range(mapping_layers):
        with tf.variable_scope('Dense%d' % layer_idx):
            fmaps = dlatent_size if layer_idx == mapping_layers - 1 else mapping_fmaps
            x = dense(x, fmaps=fmaps, gain=gain, use_wscale=use_wscale, lrmul=mapping_lrmul)
            x = apply_bias(x, lrmul=mapping_lrmul)
            x = act(x)

    # Broadcast.
    if dlatent_broadcast is not None:
        with tf.variable_scope('Broadcast'):
            x = tf.tile(x[:, np.newaxis], [1, dlatent_broadcast, 1])

    # Output.
    assert x.dtype == tf.as_dtype(dtype)
    return tf.identity(x, name='dlatents_out')
출처: https://github.com/NVlabs/stylegan/blob/master/training/networks_stylegan.py#L300

mapping_layer 보시면 8개이고 latent_size=512이다.
따라서 8개의 fully connected layer를 지난 정규화된 z vector는 1X512 size의 w mapping network를 만드는 것을 볼 수 있다.

3) synthesis network

  • ADAIN(Adaptive Instance Normalization)

출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

이제 synthesis network 부분을 살펴보자

synthesis nework를 보면 w vector(style을 변화시키는)가 들어가는 AdaIn이 있다.

AdaIn 활용
출처:https://m.blog.naver.com/PostView.nhn?blogId=tlqordl89&logNo=221536378926&proxyReferer=https:%2F%2Fwww.google.com%2F

사진을 보면 알듯이 AdaIn은 사진에 스타일을 입혀서 새로운 그림을 그리는 기능을한다

AdaIN 수식 출처: https://sensibilityit.tistory.com/510

w vector를 학습된 2개의 affine Transformation(벡터의 직선, 길이(거리)의 비, 평행성(parallelism)을 보존) FC를 통과 시켜 y_s, y_b를 얻는다 y_s는 style, y_b는 style bias이다.
여기서 X는 counvolution output이고 각 채널의 정규화를 통해 채널들에 원하는 스타일을 입힐 수 있다.

ADAIN을 통해 scale-specific control이 가능하게된다.

ADIN code

# Apply bias to the given activation tensor.

def apply_bias(x, lrmul=1):
    b = tf.get_variable('bias', shape=[x.shape[1]], initializer=tf.initializers.zeros()) * lrmul
    b = tf.cast(b, x.dtype)
    if len(x.shape) == 2:
        return x + b
    return x + tf.reshape(b, [1, -1, 1, 1])
# Instance normalization.

def instance_norm(x, epsilon=1e-8):
    assert len(x.shape) == 4 # NCHW
    with tf.variable_scope('InstanceNorm'):
        orig_dtype = x.dtype
        x = tf.cast(x, tf.float32)
        x -= tf.reduce_mean(x, axis=[2,3], keepdims=True)
        epsilon = tf.constant(epsilon, dtype=x.dtype, name='epsilon')
        x *= tf.rsqrt(tf.reduce_mean(tf.square(x), axis=[2,3], keepdims=True) + epsilon)
        x = tf.cast(x, orig_dtype)
        return x
# Style modulation.

def style_mod(x, dlatent, **kwargs):
    with tf.variable_scope('StyleMod'):
        style = apply_bias(dense(dlatent, fmaps=x.shape[1]*2, gain=1, **kwargs))
        style = tf.reshape(style, [-1, 2, x.shape[1]] + [1] * (len(x.shape) - 2))
        return x * (style[:,0] + 1) + style[:,1]
출처: https://github.com/NVlabs/stylegan/blob/master/training/networks_stylegan.py#L300

여기서 apply_bias는 w vector를 y_s, y_b 구하는 과정
instance_norm은 X를 정규화 시키는 코드
style modulation은 ADAIN을 보여준다.

AdaIN 설명: https://blog.naver.com/PostView.nhn?blogId=tlqordl89&logNo=221536378926&parentCategoryNo=&categoryNo=20&viewDate=&isShowPopularPosts=true&from=search
AdaIN 논문: https://arxiv.org/abs/1703.06868
AdaIN 코드: https://github.com/xunhuang1995/AdaIN-style
Affin Transformation: https://darkpgmr.tistory.com/79



  • style mixing

출처: https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431

4X4X512 크기의 초기 네트워크(constant tensor)에
AdaIN에 이용하여 레이어에 이미지와 style을 결합하고 progressive growing에 적용하여 1024X1024X3 이미지로 변환시킨다.

gan 모델의 다양성을 높이기 위하여 각기 다른 vector w를 혼합하여 이미지의 변화를 줄 수 있다. 그리고 다른 vector w를 혼합하여 모델을 만들면 인접한 layer간 style correlate 현상을 방지 할 수 있다.

다른 vector w를 혼합하여 이미지를 형성하는 것을 style mixing이라한다.

출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

이렇게 각 layer 마다 다른 style mixing 할 수 있다.
4X4/ 8X8 layer에서 style mixing하면 coarse style (pose, hair style, face shape 등)

16X16, 32X32 layer에서 style mixing하면 middle style (facial features, hair style, eyes open/closed 등)


64X64, 1024X1024 layer에서 style mixing하면 fine style (color scheme) 등을 나타내서 각부분에 다른 W를 넣어서 style 조절을 가능하게 한다.

2개 이상의 w vector를 사용한 style mixing을 통해
Dropout과 비슷한 작용을 하게되었다고 볼 수 있고
저해상도layer는 전체적인 이미지 스타일을 반영하고
고화질 layer로 갈수록 세부적인 구조를 담당하는 것을 볼 수 있다.

style mixing code

 # Things to do at the end of each layer.
    def layer_epilogue(x, layer_idx):
        if use_noise:
            x = apply_noise(x, noise_inputs[layer_idx], randomize_noise=randomize_noise)
        x = apply_bias(x)
        x = act(x)
        if use_pixel_norm:
            x = pixel_norm(x)
        if use_instance_norm:
            x = instance_norm(x)
        if use_styles:
            x = style_mod(x, dlatents_in[:, layer_idx], use_wscale=use_wscale)
        return x
출처: https://github.com/NVlabs/stylegan/blob/master/training/networks_stylegan.py#L300

apply_noise를 보면 노이즈를 넣어주고

ADAIN을 적용하는 것을 볼 수 있다.

  • stochastic variation

하지만 아무리 고화질 layer에 style을 적용해도


짧은 수염, 주근깨, 주름 등 세세한것들을 바꿀 수 없다.


출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

여기서 노이즈 부분이 주근깨, 짧은 수염, 머리카락 한올 등 세세한 것들을 바꾸는데 영향을 미친다.

정규분포에서 가져온 sample noise를 convolution layer에 더하여
이미지를 보다 세세하게 만든다.


AdaIN이 이미지의 큼직한 부분(style)을 바꾸는 방법이면 stochastic variation 세세한 부분을 바꾸는 방법이다.

stochastic variation code

# Noise input.

def apply_noise(x, noise_var=None, randomize_noise=True):
    assert len(x.shape) == 4 # NCHW
    with tf.variable_scope('Noise'):
        if noise_var is None or randomize_noise:
            noise = tf.random_normal([tf.shape(x)[0], 1, x.shape[2], x.shape[3]], dtype=x.dtype)
        else:
            noise = tf.cast(noise_var, x.dtype)
        weight = tf.get_variable('weight', shape=[x.shape[1].value], initializer=tf.initializers.zeros())
        return x + noise * tf.reshape(tf.cast(weight, x.dtype), [1, -1, 1, 1])

# Noise inputs.
    noise_inputs = []
    if use_noise:
        for layer_idx in range(num_layers):
            res = layer_idx // 2 + 2
            shape = [1, use_noise, 2**res, 2**res]
            noise_inputs.append(tf.get_variable('noise%d' % layer_idx, shape=shape, initializer=tf.initializers.random_normal(), trainable=False))
출처: https://github.com/NVlabs/stylegan/blob/master/training/networks_stylegan.py#L300

noise를 입히는 과정이다. append를 통해 노이즈를 더해 준것을 볼 수 있다.

출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

6. style gan이 제안한 latent space disentanglement 측정법

  • perceptual path length
    latent space로 부터 2개의 random한 입력간에 interpolation 하는 과정에서 얼마나 이미지가 급격하게 변하는지 측정한다.
    interpolation을 했을때 non-linear한 변화가 이미지에서 일어난다면 latent space가 entangled할 수 있다는 뜻이다.


출처: A Style-Based Generator Architecture for Generative Adversarial Networks 
<https://arxiv.org/abs/1812.04948>

각각 z와 w 일 경우의 distance를 구하는 공식이고, z는 spherical interpolation을 하고, w는 linear interpolation을 하는데, w를 linear interpolation하는 이유는 w 벡터들은 normalized 되어있지 않기 때문이다.

기존에 pretrained된 2개의 VGG-16 모델을 사용하여 위의 식에다 어떠한 latent vector z1값과 z2을 넣고 각각의 이미지를 VGG-16모델에 각각 embedding을 시켰을때 feature 값들의 distance를 구합니다.

따라서 E의 변화가 있었을 때, feature가 많이 변하면 distance도 커지고 interpolation이 제대로 안되는 entanglement라는 뜻이다.

  • linear separability
출처:물공's의 딥러닝<https://sensibilityit.tistory.com/510>

latent space가 충분히 disentangle되었다면 stochastic variation을 설명할 수 있는 latent vector z의 direction vector(ex, 성별, 머리카락 길이, 머리색 등)을 정확하게 찾아낸다.
입력값을 이진분류해서 분류가 잘 될 수록 disentangled는 뜻이다.

7. style gan 총 정리

출처: https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431

Style gan의 이미지 생성과 학습과정을 정리하면

1X512의 latent z vector를 mapping network에 넣어서 더 dis entanglement한 w vector를 만든다.

constant tensor 4X4X512의 이미지에
각기 다른 w vector를 AdaIn에 넣어서 style을 입힌다.

세세한 사항을 바꾸기 위해 noise를 더한다.

그렇게 해서 1024X1024의 이미지를 만든다.
이 synthesis network는 progressive growing 구조이다.


그리고 proGan discriminator로 Gan을 학습시킨다.



discriminator code

# Discriminator used in the StyleGAN paper.

def D_basic(
    images_in,                          # First input: Images [minibatch, channel, height, width].
    labels_in,                          # Second input: Labels [minibatch, label_size].
    num_channels        = 1,            # Number of input color channels. Overridden based on dataset.
    resolution          = 32,           # Input resolution. Overridden based on dataset.
    label_size          = 0,            # Dimensionality of the labels, 0 if no labels. Overridden based on dataset.
    fmap_base           = 8192,         # Overall multiplier for the number of feature maps.
    fmap_decay          = 1.0,          # log2 feature map reduction when doubling the resolution.
    fmap_max            = 512,          # Maximum number of feature maps in any layer.
    nonlinearity        = 'lrelu',      # Activation function: 'relu', 'lrelu',
    use_wscale          = True,         # Enable equalized learning rate?
    mbstd_group_size    = 4,            # Group size for the minibatch standard deviation layer, 0 = disable.
    mbstd_num_features  = 1,            # Number of features for the minibatch standard deviation layer.
    dtype               = 'float32',    # Data type to use for activations and outputs.
    fused_scale         = 'auto',       # True = fused convolution + scaling, False = separate ops, 'auto' = decide automatically.
    blur_filter         = [1,2,1],      # Low-pass filter to apply when resampling activations. None = no filtering.
    structure           = 'auto',       # 'fixed' = no progressive growing, 'linear' = human-readable, 'recursive' = efficient, 'auto' = select automatically.
    is_template_graph   = False,        # True = template graph constructed by the Network class, False = actual evaluation.
    **_kwargs):                         # Ignore unrecognized keyword args.

    resolution_log2 = int(np.log2(resolution))
    assert resolution == 2**resolution_log2 and resolution >= 4
    def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max)
    def blur(x): return blur2d(x, blur_filter) if blur_filter else x
    if structure == 'auto': structure = 'linear' if is_template_graph else 'recursive'
    act, gain = {'relu': (tf.nn.relu, np.sqrt(2)), 'lrelu': (leaky_relu, np.sqrt(2))}[nonlinearity]

    images_in.set_shape([None, num_channels, resolution, resolution])
    labels_in.set_shape([None, label_size])
    images_in = tf.cast(images_in, dtype)
    labels_in = tf.cast(labels_in, dtype)
    lod_in = tf.cast(tf.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype)
    scores_out = None

    # Building blocks.
    def fromrgb(x, res): # res = 2..resolution_log2
        with tf.variable_scope('FromRGB_lod%d' % (resolution_log2 - res)):
            return act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=1, gain=gain, use_wscale=use_wscale)))
    def block(x, res): # res = 2..resolution_log2
        with tf.variable_scope('%dx%d' % (2**res, 2**res)):
            if res >= 3: # 8x8 and up
                with tf.variable_scope('Conv0'):
                    x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, gain=gain, use_wscale=use_wscale)))
                with tf.variable_scope('Conv1_down'):
                    x = act(apply_bias(conv2d_downscale2d(blur(x), fmaps=nf(res-2), kernel=3, gain=gain, use_wscale=use_wscale, fused_scale=fused_scale)))
            else: # 4x4
                if mbstd_group_size > 1:
                    x = minibatch_stddev_layer(x, mbstd_group_size, mbstd_num_features)
                with tf.variable_scope('Conv'):
                    x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, gain=gain, use_wscale=use_wscale)))
                with tf.variable_scope('Dense0'):
                    x = act(apply_bias(dense(x, fmaps=nf(res-2), gain=gain, use_wscale=use_wscale)))
                with tf.variable_scope('Dense1'):
                    x = apply_bias(dense(x, fmaps=max(label_size, 1), gain=1, use_wscale=use_wscale))
            return x
출처: https://github.com/NVlabs/stylegan/blob/master/training/networks_stylegan.py#L300

discriminator는 upscale된 이미지를 downscale하는것을 볼 수 있다.

stlye gan의 의의

  • 기존 PGGAN의 구조 개선
    -> PGGAN의 feature들이 entanglement문제 해결

  • image 합성 과정에서 scale-spcific control 가능
    -> w vector를 사용한 ADIN으로 scale-spcific control 가능

  • 이미지를 합쳐보니 새로운 이미지를 잘 생성해내는것을 발견
    -> style mixing으로 새로운 이미지 생성

  • Latent space의 disentanglement 측정방법 제안
    (perseptual path length, linear separability)

  • 고화질이고 다양한 사람의 얼굴을 포함하는 FFHQ 데이터셋 공개
    -> 나이와 민족 시선, 밝기 그리고 이미지 배경이 다양한 FFHQ dataset 공개

8. style gan의 한계

출처: Analyzing and Improving the Image Quality of StyleGAN <https://arxiv.org/abs/1912.04958>

<water droplet artifacts 문제>

AdaIn으로 인해 feature map에 노이즈가 발생한다.
원래 feature type의 값이 작은데 AdaIn으로 정규화하여 인해 값이 커지고 이게 noise를 발생시킨다.




출처: Analyzing and Improving the Image Quality of StyleGAN <https://arxiv.org/abs/1912.04958>

<phase artifacts 문제>
다음은 일부 feature들이 얼굴의 움직임을 따르지 않는 문제이다.
얼굴이 움직임에도 이는 움직이지 않는 것을 볼 수 있다
이 문제는 progressive growing으로 인해 발생하는데
각각의 코드블록마다 독립적으로 이미지가 생성되기때문에 이러한 특징이 자주 나타난다.

9. style gan2

그래서 style gan의 water droplet artifacts 문제와 phase artifacts문제를 해결한 style gan2가 나왔다.
style gan2에서는
water droplet artifacts를 제거하기 위해 AdaIn 대신 CNN의 가중치를 정규화하였다.


<water droplet artifacts 개선>

출처: Analyzing and Improving the Image Quality of StyleGAN <https://arxiv.org/abs/1912.04958>

출처: https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2

출처: https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2

progressive growing을 제거하여 phase artifacts 문제를 개선하였다.

style gan2 논문: https://arxiv.org/abs/1912.04958
style gan2 코드: https://github.com/NVlabs/stylegan2
style gan2 설명: https://iamseungjun.tistory.com/6?category=881965

references

style gan 강의 https://www.coursera.org/lecture/build-better-generative-adversarial-networks-gans/welcome-to-week-3-oe097

style gan 관련
https://velog.io/@chy0428/StyleGAN-A-Style-Based-Generator-Architecture-for-Generative-Adversarial-Networks-%EB%85%BC%EB%AC%B8-%EC%A0%95%EB%A6%AC

https://sensibilityit.tistory.com/510
https://www.kakaobrain.com/blog/55
https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431
https://jayhey.github.io/deep%20learning/2019/01/14/style_based_GAN_1/
https://jayhey.github.io/deep%20learning/2019/01/16/style_based_GAN_2/
https://nuguziii.github.io/paper-review/PR-001/
https://blog.lunit.io/2019/02/25/a-style-based-generator-architecture-for-generative-adversarial-networks/

style gan 논문 : https://github.com/NVlabs/stylegan
style gan 코드 : https://github.com/NVlabs/ffhq-dataset

AdaIn관련: https://github.com/xunhuang1995/AdaIN-style

style gan2 관련: https://iamseungjun.tistory.com/6?category=881965
https://prowiseman.tistory.com/entry/StyleGAN-StyleGAN2

질문1. stochastic variation이 feature들을 조절하는 것인지?

These are single-channel images consisting of uncorrelated
Gaussian noise, and we feed a dedicated noise image to each layer of the synthesis network. The noise image is
broadcasted to all feature maps using learned per-feature
scaling factors and then added to the output of the corresponding convolution …

A Style-Based Generator Architecture for Generative Adversarial Networks, 2018.

를 보면 노이즈 이미지는 학습된 기능별 스케일링 요소를 사용하여 모든 feature map에 broadcasted 된 다음 해당 convolution의 출력에 추가된다고 말한다. 이는 stochastic variation가 지정된 세부 수준에서 feature 변형을 위해 사용한다 볼 수 있다.

질문 2. Entanglement latent vector z를 Fully connected layer부분에서 disentanglement로 바뀌는 것인지? AdaIn 부분에서 disentanglement로 바뀌는 것인지?

Style Modules (AdaIN)
The AdaIN (Adaptive Instance Normalization) module transfers the encoded information ⱳ, created by the Mapping Network, into the generated image. The module is added to each resolution level of the Synthesis Network and defines the visual expression of the features in that level:
1. Each channel of the convolution layer output is first normalized to make sure the scaling and shifting of step 3 have the expected effect.
2. The intermediate vector ⱳ is transformed using another fully-connected layer (marked as A) into a scale and bias for each channel.
3. The scale and bias vectors shift each channel of the convolution output, thereby defining the importance of each filter in the convolution. This tuning translates the information from ⱳ to a visual representation.

출처: https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431

Vector Z를 8개의 Fully connected layer에 통과 시킨 결과 disentanglement한 결과가 나오고 ADAIN layer는 style_scale, style_bias로 변환시키는 역할을 한다. 이때 style_scale, style_bias는 convolution layer를 통과하여 defining the importance of each filter의 역할을 한다.

profile
투빅스 생성모델 세미나입니다.

9개의 댓글

comment-user-thumbnail
2020년 11월 7일

투빅스 14기 한유진

  • GAN의 무수한 발전에도 불구하고 여전히 stability, capacity, diversity의 개선점이 존재합니다. 이를 개선한 모델인 styleGAN에 대해서 배웠습니다.
  • styleGAN의 구조중 progressing growing은 PGGAN을 base로 합니다. PGGAN은 G부분에서 44 저해상도 이미지를 점진적으로 늘려가면서 10241024의 고해상도까지 학습하고 D가 다시 10241024부터 44까지 학습하는 과정을 밟습니다. 하지만 PGGAN의 progressive growing구조는 feature들이 뭉쳐있게 만들어지므로 input이 조금이라도 조정되면 동시에 여러 feature가 영향을 받는다고 합니다.
  • styleGAN에 적용된 PGGAN의 progressing growing은 synthesis network부분에 있습니다. mapping network로 인해 만들어진 w vector가 들어가는 AdaIN이 사용됩니다. AdaIN으로 scale-specific control이 가능하다고 합니다. 여기서 w,z vector의 차이에 대해서 잘 설명해주셔서 이해하기 쉬웠습니다. GAN의 다양성을 높이기 위해 각기 다른 w vector를 혼합하여 이미지를 형성하는 것을 style mixing이라고 합니다. 이것은 이미지의 큰 부분의 style을 바꿔주는 것이라면 noise를 통해 내가 관심있는 feature말고 다른 부분을 적당하게 뽑아주는 stochastic variation방법도 존재합니다.
    styleGAN의 한계에는 AdaIN으로 정규화를 하여 값이 커져서 feature map에 noise를 발생시키고(주로 64*64 layer에서 발생), 일부 feature들이 얼굴의 움직임을 따르지 않는 문제가 발생합니다. 이를 해결하기 위해 AdaIN대신 CNN의 가중치를 정규화 시킨 styleGAN2가 등장했다고 합니다.

styleGAN의 구조와 한계점에 따른 해결방안들은 다양한 시각적 자료들로 쉽게 설명해주셔서 이해하기 좋았던 수업이었습니다. 좋은 강의 감사합니다!

답글 달기
comment-user-thumbnail
2020년 11월 9일

투빅스 14기 김상현
Style GAN에 관한 강의로 투빅스 14기 박준영님이 진행해주셨습니다.
Style GAN은 stability, capacity, diversity를 개선한 모델이다. 기존의 PGGAN의 구조를 개선했고, image합성 과정에서 scale-specific control가능하다.

  • Progressive growing: 처음부터 고해상도의 이미지를 학습하면 mode collapse 문제가 발생한다. 이를 막기 위해 4x4 저해상도 이미지부터 점진적으로 layer를 추가하며 1024x1024의 고해상도 이미지를 생성한다.
  • Mapping network: input vector z를 fully connected layers를 거쳐 비선형성을 갖는 w(intermediate vector)로 변환한다. 이렇게 변환된 w는 정규분포를 따를 필요가 없고 data를 훨씬 유동적인 공간에 mapping 할 수 있게 된다. w는 데이터 간의 상관관계를 줄여 z 보다 더 disentanglement한 latent vector를 만든다.
  • AdaIn: 사진에 스타일을 입혀서 새로운 그림을 그리는 기능을 한다. w vector를 학습된 affine transformation을 통과시켜 y_s, y_b를 얻는다. 여기서 y_s: style scale, y_b: style bias. x(upsample or conv를 통과한)를 instance normalize를 한 후 y_s를 곱하고, y_b를 더해서 AdaIn을 수행한다.
  • Style mixing: 다른 w vector를 혼합하여 이미지를 형성할 수 있다. 앞 부분 layer에서는 coarse style, 뒤 부분 layer에서는 fine style을 조절 가능하다
  • Stochastic variation: 노이즈를 이용해 주근깨, 머리카락 등의 세세한 부분을 바꿀 수 있다. 이때 노이즈는 정규분포에서 가져온 sample noise를 이용해 convolution layer를 더하여 세세한 이미지를 만든다.

Style GAN의 전체적인 구조뿐만 아니라 활용방안 및 의의와 한계점과 개선안에 대해 알 수 있었습니다.
좋은 강의 감사합니다!

답글 달기
comment-user-thumbnail
2020년 11월 10일

투빅스 14기 정재윤 :
이번 강의는 style GAN에 대한 강의로 투빅스 14기 박준영님이 진행해주셨습니다.

  • Style GAN은 stability, capacity, diversity를 개선한 모델입니다. 즉, 전반적인 GAN의 성능을 올림으로써 더 좋은 퀄리티의 이미지를 만들 수 있게 짜여진 모델입니다.

  • Style GAN의 경우, PGGAN을 발전시켜 만든 모델로, 저해상도 이미지부터 시작해서 쌓은 layer를 추가해 고해상도 이미지를 만들 수 있게 하는 것입니다. 게다가 여기에 더해 발전 시킨 점은 W vector를 만드는 것입니다. W vector는 z vector보다 더 disentanglement한 latent vector를 의미합니다. 즉, 상대적으로 덜 꼬여있는 vector를 만들어 내는 것인데요. Latent vector가 덜 꼬여있으면 이미지를 생성할 때, 좀 더 다양하고 자연스러운 이미지를 만들어 낼 수 있게 됩니다.

  • W vector를 AdaIn으로 통과시키면 이미지에 새롭게 스타일을 입히는 것이 가능해집니다. 여기서 스타일에 관한 scale과 스타일에 관한 bias를 통해 추출한 스타일과 유사하게끔 output feature map을 만들게 됩니다. 즉, AdaIn은 이미지에 대한 구체적인 control을 가능케 하는 것입니다.

  • 마지막으로 Noise를 통해 세세한 부분들을 조절합니다.

전반적으로 style GAN의 전반적인 흐름과 구조에 대해서 깔끔하게 정리할 수 있었고, 한계와 개선점을 집어주는 좋은 강의였습니다. 또한 GAN의 활용에 대해서 도입부에 알려주시므로써, 세미나에 더 흥미를 갖게 해주셨습니다. 감사합니다 😊

답글 달기
comment-user-thumbnail
2020년 11월 10일

투빅스 11기 이도연
StyleGAN이 나오게 된 배경과 활용, 의의부터 구조를 하나하나 뜯어보고 마지막 정리와 한계, 그 후의 개선까지 전반적인 내용을 다룬 강의였습니다. 좋은 강의 감사합니다!

  • GAN의 stability, capacity, diversity를 개선하기 위한 연구가 계속되고 있다.
  • StyleGAN은 Style Transfer에 기반해 Generator의 새로운 구조를 제안했다.
  • Synthesis Network에서의 progressive growing은 PGGAN을 base로 한다. PGGAN의 progressive growing에서는 4x4의 저해상도 이미지에서 1024x1024의 고해상도 이미지까지 점진적으로 학습을 시킨다.
  • Mapping Network는 latent vector z를 intermediate vector w로 변화시킨다. 8개의 fully connected layer로 구성된 mapping network를 통해 w는 더이상 고정된 distribution을 따를 필요가 없어져 보다 더 disentanglement하게 만들 수 있다.
  • 여기서 Disentanglement를 수치화하기 위해 Perceptual path length, Linear separability를 제시한다.
  • 앞서 생성된 w는 Synthesis Network에서 style을 입히는데 사용된다. AdaIN을 통해 style을 입혀지며 style vector는 w로부터 affine transformation을 통해 얻어진다.
  • style mixing을 통해 Synthesis Network에서 초반에는 w1으로 학습하다가 특정 layer 이후부터는 w2로 학습하는 등 style이 교체되는 layer를 매번 random으로 결정해 인접한 layer간의 style correlate 현상을 방지하고 각 layer가 담당하는 style이 구분되도록 한다.
  • 각 layer마다 추가된 Noise는 머리카락, 수염, 주름 등 조금 더 stochastic한 요소를 결정하도록 해서 더욱 사실적인 이미지를 생성함과 동시에 input latent vector w가 성별, 인종, 머리모양 등 이미지의 중요한 정보에 더 집중할 수 있도록 한다.
  • StyleGAN의 water droplet artifacts, phase artifacts 문제를 해결하기 위해 StyleGAN2가 나왔다.
답글 달기
comment-user-thumbnail
2020년 11월 10일

투빅스 14기 김민경

  • PGGAN은 progressive growing 구조를 이용해 44 저해상도 이미지에서부터 점진적으로 은닉층을 추가하면서 10241024의 고해상도 이미지를 생성하는 모델이다.
  • StyleGAN은 PGGAN의 generator 부분을 개선한 모델이며 1. Mapping Network 2. Synthesis Network 3. Noise로 구분해서 볼 수 있다.
  • 첫 번째로 Mapping Network 부분은 PGGAN에서 latent z를 그대로 input으로 넣은 것과 달리, FCN를 거쳐서 non-linear하게 mapping된 w를 얻는다. 이로 인해 특징들이 disentanglement하게 되어 특징들 간 분리가 가능하다.
  • 두 번째로 Synthesis Network 부분은 PGGAN의 progressive growing 구조를 base로 하지만 PGGAN처럼 직접적으로 모델에 넣지 않고 아핀 변환을 해서 세부적인 style을 모델의 각 layer에 넣어준다. 그리고 normalization 기법으로 AdaIN을 도입했는데, 매번 AdaIN으로 정규화할 때마다 한 style이 각 layer에서만 영향을 주기 때문에 특징들끼리 분리할 수 있는 효과도 준다. 또한 w를 그대로 가져오지 않고 style mixing을 통해 random한 w를 사용했기 떄문에 style이 상관관계를 가지지 않게 해주었다.
  • 세 번째로 처음 들어간 latent z 뿐만 아니라 추가적인 noise를 생성해 Synthesis Network의 각 layer에 더해줌으로써 더욱 진짜 같은 이미지를 생성하는 효과를 냈다.
  • discriminator는 PGGAN과 동일하다고 한다.
  • StyleGAN은 AdaIN으로 인해 water droplet artifacts 문제가 발생한다. 원래 feature map이 작은데 AdaIN으로 normalization하여 값이 커지면서 noise가 생기는 것이다. 이를 보완해 styleGAN2에서는 AdaIN 대신 CNN의 가중치를 normalization하는 방법을 제안했다.
  • styleGAN의 전후 모델도 같이 설명해주셔서 잘 이해가 되는 강의였습니다. 감사합니다:)
답글 달기
comment-user-thumbnail
2020년 11월 10일

투빅스 14기 박지은

  • GAN은 stability, capacity, diversity의 측면에서 개선할 필요가 있습니다. styleGAN은 이 중 stability를 개선하기 위해 expotential averaging과 progressive growing을 사용하는 방법입니다.
  • styleGAN은 기존 PGGAN의 구조를 개선하여 scale-specific control이 가능하고, input을 조정할 때 여러가지 특징에 영향을 주는 disentanglement를 측정하는 방법을 제안했습니다.
  • styleGAN의 progressive growing은 PGGAN을 이용하여 한 번에 전체 이미지를 학습시키는 것이 아니라 저해상도 이미지부터 레이어를 추가해가며 점점 고해상도 이미지를 만드는 방법입니다. 이는 latent vector z가 정규화 후 input으로 들어가는데, 여기서 latent space는 반드시 training data의 probability density를 따라야 하므로 entanglement하게 만들어집니다.
  • mapping network는 input vector가 fully connected layer로 구성된 mapping network를 통과하여 w vector로 변화되고, 이러한 w vector는 정규분포를 따를 필요가 없기 때문에 데이터셋을 더 유동적으로 mapping 할 수 있습니다. 따라서 z vector보다 더 disentanglement한 latent vector을 만들 수 있습니다. 이러한 intermediate vector w는 synthesis network가 이미지를 생성하는 과정에서 style을 입히는 데에 사용됩니다.
  • synthesis network 중 ADAIN은 채널들에 원하는 이미지의 큼직한 style을 입히는 방법이라면, stochastic variation은 더 세세한 부분을 바꿔줍니다.
  • styleGAN의 perceptual path length와 linear separability를 통해 latent space의 disentanglement를 측정할 수 있습니다.
    설명이 매우 친절하셔서 styleGAN의 특징에 대하여 공부할 때 내용 간의 연결이 더 용이했습니다. 좋은 강의 정말 감사드립니다.
답글 달기
comment-user-thumbnail
2020년 11월 10일

투빅스 13기 신민정

StyleGAN 강의는 박준영님께서 진행해주셨습니다.

  • progressive growing : PGGAN에서 제안한 구조입니다. 고해상도 일수록 fake를 구분하기 쉬워지고 작은 크기의 mini-batch를 사용할 수 없어 모드 붕괴에 빠진다는 단점이 있었습니다. PGGAN은 고해상도 이미지 생성 문제를 해결하기 위해 제안된 모델입니다. 4x4 -> 1028x1028으로 점진적으로 layer를 추가하며 고해상도 이미지를 만듭니다. StyleGAN Generator의 Synthesis Network(up-sampling)와 Discriminator(down-sampling)에서 progrssive growing를 가집니다.
  • mapping network : latent vector z가 FC를 거쳐 w(비선형)로 mapping됩니다.mapping network를 사용하여 입력 z vector를 각각의 요소가 다른 visual feature를 control하게 만드는 intermediate vector로 변환시킵니다. 결론적으로 z보다 disentangle이 보장된 w를 만들어줍니다.
  • Synthesis Network :
    w->AdaIn Network(AdaIN : 스타일을 입히는 역할을 합니다. affine transformation에서 나온 Style scale, Style bais로 계산됩니다.ADAIN을 통해 scale-specific control이 가능하게 됩니다.)
  • Noise : 생성되는 데이터의 다양성을 위해 Synthesis network에 noise를 추가합니다.
  • StyleGAN2 : AdaIn 대신 CNN가중치를 정규화하여 기존 모델의 water droplet artifacts문제를 해결하였고, progressive growing을 제거하여 phase arifacts문제를 해결하였다.

시각자료와 자세한 설명, 코드까지 첨부하여 하나하나 설명해주셔서 이해가 잘됐습니다. 유익한 강의 정말 감사드립니다!

답글 달기
comment-user-thumbnail
2020년 11월 12일

투빅스 12기 김태한 :

  • 이번 강의는 style GAN에 대한 강의였습니다.

  • Style GAN은 기존의 GAN의 문제점들을 개선한 모델로써 더 높은 퀄리티의 이미지를 만들 수 있다는 장점을 가지고 있습니다.

  • 기본적으로 Style GAN은 PGGAN의 방법으로 모델을 구성하며 이렇게 저해상도부터 고해상도를 학습하도록 layer를 쌓은후 AdaIN이라는 특정 네트워크 구조를 활용하여 Style과 Variation을 구분하여 반영하도록 하였습니다. AdaIN에 들어가는 w latent vector가 이미지의 전반적인 Style을 반영하며 noise를 통해 variation을 주어 다양한 이미지가 생성되도록 하고있습니다.

  • Style GAN은 기존 GAN의 문제점들을 해결한 중요 모델로써 흐름부터 원리와 과정까지 알 수 있는 좋은 강의였습니다.

좋은 강의 감사합니다 :)

답글 달기
comment-user-thumbnail
2020년 12월 20일

투빅스 13기 이예지:
이번 강의는 ‘Style GAN’으로, 박준영님이 진행하였습니다.

StyleGAN

  • GAN의 한계점 stability, capacity, diversity를 개선한 모델임.

StyleGAN의 applications

  • 단순히 훈련 데이터 분포를 학습해 새로운 데이터를 만드는 것 뿐만 아니라, 다양한 응용분야가 존재함.
  • 가상 모델, 가상의 공간 생성, AI 앵커

StyleGAN의 구조

  • mapping network
    w vector를 통해 disentanglement feature를 만들기 위함.
  • synthesis network

    Progressive growing의 확장

StyleGAN의 한계

  • Water droplet artifacts 문제
  • Phase artifacts 문제

=> StyleGAN2가 등장하게 됨.

StyleGAN2
- Water droplet artifacts 문제를 해결하기 위해 Adain 대신 CNN 가중치를 정규화하함.

StyleGAN1, 2의 전반적인 배경과 구조를 알 수 있어습니다.
좋은 강의 감사합니다 :)

답글 달기