16.5  적대적 이미지 생성

16.1절 의 다층 퍼셉트론은 알아볼 수 있는 \(28 \times 28\) Fashion-MNIST 실루엣을 생성했지만 완전 연결 층이 공간 지역성을 무시하기 때문에 질감이 거칠었습니다. \(64 \times 64\) RGB 이미지를 생성하려면 100차원 잠재 벡터로부터 \(12{,}288\) 개의 픽셀 값을 만들어 내야 합니다. 여기서 두 가지 질문이 제기됩니다:

  1. 적대적 이미지 생성에서 안정적으로 훈련되는 합성곱 아키텍처는 무엇일까요?
  2. 가능도를 쓸 수 없을 때 이미지 생성자들을 어떻게 정량적으로 평가하고 비교할 수 있을까요?

합성곱 생성자와 합성곱 판별자는 Radford 기타 (2015년) 의 심층 합성곱 GAN(Deep Convolutional GAN, DCGAN)을 통해 처음으로 GAN을 자연 이미지로 확장했습니다. 이후 범용 이미지 합성에서는 확산 모델(17장)이 주류 기법으로 자리 잡았지만, 합성곱 판별자와 특성 공간 평가 지표들은 현대 이미지 토크나이저와 1스텝 증류 생성자에서 여전히 중심적인 역할을 맡고 있습니다(16.7절).

이 절에서는 \(64 \times 64\) 포켓몬 스프라이트 40,597장으로 이루어진 데이터셋 위에서 훈련합니다. 먼저 고전적인 2015년 DCGAN 아키텍처를 구현한 뒤, R3GAN (Huang 기타 2024년) 에서 영감을 받은 간결한 무정규화 합성곱 백본을 구축합니다. 이 무정규화 백본을 세 가지 목적 함수(무페널티 고전적 로지스틱 손실, \(R_1 + R_2\) 페널티를 결합한 고전적 로지스틱 손실, \(R_1 + R_2\) 페널티를 결합한 상대론적 페어링 손실) 아래 훈련함으로써 영중심 그레이디언트 페널티(16.4절)가 배치 정규화 및 기타 아키텍처 휴리스틱을 대체할 수 있는지 시험합니다. 이어서 표준 특성 공간 평가 지표인 Fréchet 거리(FID), 커널 Inception 거리(KID), \(k\)-NN 정밀도와 재현율을 구현하고 잠재 공간 보간과 판별자 과적합을 살펴봅니다.

# Deterministic GPU kernels; JAX reads XLA_FLAGS once, before the imports
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
                           ' --xla_gpu_deterministic_ops=true').strip()
import torchvision

16.5.1 DCGAN 아키텍처

DCGAN (Radford 기타 2015년) 은 16.1절 의 고전적 비포화 로지스틱 목적 함수를 그대로 유지하면서 일련의 아키텍처 규약을 통해 합성곱 훈련을 안정화합니다:

  • 생성자의 공간 업샘플링에는 전치 합성곱(transposed convolution, 분수 스트라이드 합성곱)을 쓰고, 판별자의 다운샘플링에는 풀링 층 대신 스트라이드 합성곱을 씁니다.
  • 생성자 출력층과 판별자 입력층을 제외한 모든 합성곱 뒤에 배치 정규화를 적용합니다.
  • 생성자는 ReLU 은닉 활성화 함수와 (\([-1, 1]\) 범위 픽셀 값에 맞춘) \(\tanh\) 출력 활성화 함수를 쓰는 반면, 판별자는 그레이디언트가 0이 되는 죽은 영역을 막기 위해 전 구간에서 Leaky ReLU(\(\text{slope} = 0.2\))를 씁니다.
  • 가중치는 \(\mathcal{N}(0, 0.02^2)\) 에서 초기화하며 Adam은 낮춘 모멘텀 \(\beta_1 = 0.5\) 를 사용합니다.

16.5.1.1 포켓몬 스프라이트 데이터셋

데이터셋은 pokemondb.net에서 가져온 포켓몬 721종의 RGB 스프라이트 40,597장으로 구성되며 \(64 \times 64\) 크기로 리사이즈하고 \([-1, 1]\) 범위로 스케일링합니다. 전체 데이터셋이 메모리에 들어가므로 load_pokemon이 단일 텐서로 디코딩합니다.

d2l.DATA_HUB['pokemon'] = (d2l.DATA_URL + 'pokemon.zip',
                           'c065c0e2593b8b161a2d7873e42418bf6a21106c')


def load_pokemon(resolution=64):
    """All Pokemon sprites as one (n, 3, h, w) tensor in [-1, 1]."""
    import warnings
    transform = torchvision.transforms.Compose([
        torchvision.transforms.Resize((resolution, resolution)),
        torchvision.transforms.PILToTensor()])
    dataset = torchvision.datasets.ImageFolder(
        d2l.download_extract('pokemon'), transform=transform)
    loader = torch.utils.data.DataLoader(
        dataset, batch_size=512, num_workers=d2l.get_dataloader_workers())
    with warnings.catch_warnings():  # palette sprites with transparency
        warnings.filterwarnings('ignore', message='Palette images')
        return torch.cat([X for X, _ in loader]).float() / 127.5 - 1

images = load_pokemon()
images.shape
torch.Size([40597, 3, 64, 64])

d2l.DATA_HUB['pokemon'] = (d2l.DATA_URL + 'pokemon.zip',
                           'c065c0e2593b8b161a2d7873e42418bf6a21106c')


def load_pokemon(resolution=64):
    """All Pokemon sprites as one (n, h, w, 3) array in [-1, 1]."""
    import warnings
    from PIL import Image
    data_dir = d2l.download_extract('pokemon')
    files = sorted(os.path.join(root, f)
                   for root, _, names in os.walk(data_dir) for f in names
                   if f.lower().endswith(('.png', '.jpg', '.jpeg')))
    def load(path):
        img = Image.open(path).convert('RGB')
        return np.asarray(img.resize((resolution, resolution), Image.BILINEAR),
                          dtype=np.float32)
    with warnings.catch_warnings():  # palette sprites with transparency
        warnings.filterwarnings('ignore', message='Palette images')
        return np.stack([load(f) for f in files]) / 127.5 - 1

images = load_pokemon()
images.shape
(40597, 64, 64, 3)

고정된 순열로 전체 이미지의 10분의 1을 따로 떼어 두며 이 이미지들은 훈련에 결코 쓰이지 않습니다. 이들은 생성 이미지들을 채점할 기준 실제 표본이 되며 크리틱이 미관측 이미지보다 훈련 이미지에 더 높은 점수를 주는지도 보여 줍니다. 종(species) 단위가 아니라 이미지 단위로 분할했으므로 한 종의 변형들이 양쪽에 나뉘어 들어갈 수 있으며 훈련 스프라이트를 그대로 베낀 생성자가 홀드아웃된 변형 이미지 근처에 안착할 수도 있습니다.

device = d2l.try_gpu()
perm = np.random.default_rng(12345).permutation(len(images))
n_holdout = len(images) // 10
train_imgs = images[perm[n_holdout:]].to(device)
holdout_imgs = images[perm[:n_holdout]].to(device)
print(f'{len(train_imgs)} training and {len(holdout_imgs)} held-out images')
d2l.show_images(train_imgs[:20].cpu().permute(0, 2, 3, 1) / 2 + 0.5,
                num_rows=4, num_cols=5);
36538 training and 4059 held-out images

perm = np.random.default_rng(12345).permutation(len(images))
n_holdout = len(images) // 10
train_imgs = jnp.asarray(images[perm[n_holdout:]])
holdout_imgs = jnp.asarray(images[perm[:n_holdout]])
print(f'{len(train_imgs)} training and {len(holdout_imgs)} held-out images')
d2l.show_images(np.asarray(train_imgs[:20]) / 2 + 0.5,
                num_rows=4, num_cols=5);
36538 training and 4059 held-out images

16.5.1.2 전치 합성곱과 배치 정규화

100채널짜리 \(1 \times 1\) 특성 맵을 \(64 \times 64\) 이미지로 업샘플링하기 위해 DCGAN은 전치 합성곱(20.10절 (영문판))을 사용합니다. 커널 크기 \(k\), 스트라이드 \(s\), 패딩 \(p\) 인 전치 합성곱은 \(n \times n\) 공간 격자를 다음 한 변 길이의 출력으로 사상합니다:

\[s(n - 1) + k - 2p. \tag{16.5.1}\]

\(k = 4, s = 2, p = 1\) 이면 각 층이 공간 해상도를 두 배로 키우며(\(n \to 2n\)), 첫 번째 층(\(k = 4, s = 1, p = 0\))에서는 \(1 \times 1\) 입력이 \(4 \times 4\) 로 확장됩니다. 역으로 \(k = 4, s = 2, p = 1\) 인 스트라이드 합성곱은 공간 해상도를 절반으로 줄입니다.

그림 16.5.1 에서 보듯이 DCGAN 생성자는 해상도 \(1 \to 4 \to 8 \to 16 \to 32 \to 64\) 에 걸쳐 다섯 개의 전치 합성곱을 연쇄적으로 연결하여 매 단계 채널 폭을 절반으로 줄인 뒤 최종적으로 3개의 RGB 채널을 출력합니다. 판별자는 스트라이드 합성곱으로 이 계층 구조를 거꾸로 뒤집어 단일 \(1 \times 1\) 로짓까지 내려갑니다.

그림 16.5.1: DCGAN 아키텍처 (Radford 기타 2015년) (기본 채널 폭 512 및 \(4 \times 4\) 커널 기준). 생성자는 전치 합성곱들을 통해 100차원 잠재 벡터를 \(64 \times 64\) RGB 이미지로 사상하고 크리틱은 스트라이드 합성곱들로 계층 구조를 역전시킵니다. 생성자 출력층과 크리틱 입력 블록을 제외한 모든 블록에 배치 정규화를 사용합니다.
def G_block(c_in, c_out, stride=2, padding=1):
    """Transposed convolution (kernel 4), batch norm, ReLU."""
    return nn.Sequential(
        nn.ConvTranspose2d(c_in, c_out, 4, stride, padding, bias=False),
        nn.BatchNorm2d(c_out), nn.ReLU())

def D_block(c_in, c_out, norm=True):
    """Strided convolution (kernel 4), batch norm, leaky ReLU."""
    return nn.Sequential(
        nn.Conv2d(c_in, c_out, 4, 2, 1, bias=False),
        nn.BatchNorm2d(c_out) if norm else nn.Identity(), nn.LeakyReLU(0.2))
conv_init = nnx.initializers.normal(0.02)  # DCGAN: kernels from N(0, 0.02^2)

def bn_scale_init(key, shape, dtype=jnp.float32):
    return 1 + 0.02 * jax.random.normal(key, shape, dtype)  # N(1, 0.02^2)

def batch_norm(c, rngs):
    # Running averages decay 0.9; the variance is computed in two passes
    return nnx.BatchNorm(c, momentum=0.9, use_fast_variance=False,
                         scale_init=bn_scale_init, rngs=rngs)

def G_block(c_in, c_out, rngs, stride=2, padding='SAME'):
    """Transposed convolution (kernel 4), batch norm, ReLU."""
    return nnx.Sequential(
        nnx.ConvTranspose(c_in, c_out, (4, 4), strides=(stride, stride),
                          padding=padding, use_bias=False,
                          kernel_init=conv_init, rngs=rngs),
        batch_norm(c_out, rngs), nnx.relu)

def D_block(c_in, c_out, rngs, norm=True):
    """Strided convolution (kernel 4), batch norm, leaky ReLU."""
    return nnx.Sequential(
        nnx.Conv(c_in, c_out, (4, 4), strides=(2, 2), padding='SAME',
                 use_bias=False, kernel_init=conv_init, rngs=rngs),
        batch_norm(c_out, rngs) if norm else (lambda x: x),
        lambda x: nnx.leaky_relu(x, 0.2))

네 개의 G_block 스테이지에 최종 전치 합성곱과 tanh를 쌓아 net_G를 구성하고, 네 개의 D_block 스테이지(첫 블록에서는 배치 정규화 생략)와 \(4 \times 4\) 합성곱으로 net_D를 구성합니다. 100차원 잠재 벡터 두 개에 대한 순전파 패스로 출력 형상을 확인합니다:

torch.manual_seed(0)
net_G = nn.Sequential(                                   # (100,)
    nn.Unflatten(1, (100, 1, 1)),                        # (100, 1, 1)
    G_block(100, 512, stride=1, padding=0),              # (512, 4, 4)
    G_block(512, 256), G_block(256, 128), G_block(128, 64),  # (64, 32, 32)
    nn.ConvTranspose2d(64, 3, 4, 2, 1, bias=False), nn.Tanh()).to(device)
net_D = nn.Sequential(                                   # (3, 64, 64)
    D_block(3, 64, norm=False),                          # (64, 32, 32)
    D_block(64, 128), D_block(128, 256), D_block(256, 512),  # (512, 4, 4)
    nn.Conv2d(512, 1, 4, bias=False)).to(device)         # (1, 1, 1)
X = net_G(torch.zeros(2, 100, device=device))
print(X.shape, net_D(X).shape)
torch.Size([2, 3, 64, 64]) torch.Size([2, 1, 1, 1])
rngs = nnx.Rngs(0)
net_G = nnx.Sequential(                                  # (100,)
    lambda z: z.reshape(-1, 1, 1, 100),                  # (1, 1, 100)
    G_block(100, 512, rngs, stride=1, padding='VALID'),  # (4, 4, 512)
    G_block(512, 256, rngs), G_block(256, 128, rngs),
    G_block(128, 64, rngs),                              # (32, 32, 64)
    nnx.ConvTranspose(64, 3, (4, 4), strides=(2, 2), padding='SAME',
                      use_bias=False, kernel_init=conv_init, rngs=rngs),
    nnx.tanh)                                            # (64, 64, 3)
net_D = nnx.Sequential(                                  # (64, 64, 3)
    D_block(3, 64, rngs, norm=False),                    # (32, 32, 64)
    D_block(64, 128, rngs), D_block(128, 256, rngs),
    D_block(256, 512, rngs),                             # (4, 4, 512)
    nnx.Conv(512, 1, (4, 4), padding='VALID', use_bias=False,
             kernel_init=conv_init, rngs=rngs))          # (1, 1, 1)
X = net_G(jnp.zeros((2, 100)))
print(X.shape, net_D(X).shape)
(2, 64, 64, 3) (2, 1, 1, 1)

16.5.1.3 고전적 손실로 훈련하기

크리틱의 로지스틱 회귀 스텝과 생성자의 비포화 스텝을 번갈아 밟는 16.1절 의 d2l.train_gan 루프는 이미지에도 수정 없이 그대로 적용됩니다. 원논문의 128장 대신 더 큰 256장 미니배치로 DCGAN 설정을 사용합니다. 학습률은 \(2 \cdot 10^{-4}\), \(\beta_1 = 0.5\) 이고 합성곱 커널은 \(\mathcal{N}(0, 0.02^2)\) 에서 추출합니다. 저자들이 공개한 코드와 마찬가지로 배치 정규화 스케일은 \(\mathcal{N}(1, 0.02^2)\) 에서, 오프셋은 0에서 시작합니다.

def dcgan_init(module):
    if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)):
        nn.init.normal_(module.weight, 0, 0.02)
    elif isinstance(module, nn.BatchNorm2d):
        nn.init.normal_(module.weight, 1, 0.02)
        nn.init.zeros_(module.bias)

for net in (net_D, net_G):
    net.apply(dcgan_init)
dataset = torch.utils.data.TensorDataset(train_imgs)
# Sample whole minibatches of indices, so that the GPU tensor is indexed
# once per minibatch rather than once per image
sampler = torch.utils.data.BatchSampler(
    torch.utils.data.RandomSampler(dataset), 256, drop_last=True)
data_iter = torch.utils.data.DataLoader(dataset, sampler=sampler,
                                        batch_size=None)
# The training images from the host array: the loader keeps them there
data_iter = d2l.ArrayLoader((images[perm[n_holdout:]],), 256, shuffle=True,
                            drop_last=True, key=jax.random.key(3))

생성자의 마지막 가중치 대신 최근 가중치들의 평균으로부터 샘플을 추출합니다. EMA는 매 스텝 직후 다음과 같이 갱신되는 매개변수 지수 이동 평균을 유지합니다:

\[\bar\theta \leftarrow \beta\, \bar\theta + (1 - \beta)\, \theta, \qquad \beta = 2^{-1/n_{1/2}}, \tag{16.5.2}\]

이에 따라 과거 스텝의 가중치는 반감기(half-life)인 \(n_{1/2}\) 스텝마다 절반으로 줄어듭니다. 게임의 반복점들은 평형 주위를 회전하므로(16.4절) 개별 반복점들보다 그 평균이 평형에 더 가까이 자리 잡습니다. 배치 정규화 통계량은 매개변수가 아니므로 평균 모델은 실시간 신경망으로부터 이를 복사해 옵니다. 복사된 값은 평균 가중치가 아니라 실시간 가중치에 맞춘 통계량이므로 훈련이 끝난 뒤 다시 추정합니다.

class EMA:
    """Exponential moving average of a model's parameters, given as a
    half-life in steps. Buffers such as batch-norm statistics are copied;
    the average is kept in evaluation mode."""
    def __init__(self, model, half_life):
        import copy  # the d2l library preamble does not import it
        self.model = copy.deepcopy(model).requires_grad_(False).eval()
        self.decay = 0.5 ** (1 / half_life)

    def update(self, model):
        with torch.no_grad():
            for avg, p in zip(self.model.parameters(), model.parameters()):
                avg.lerp_(p, 1 - self.decay)
            for avg, b in zip(self.model.buffers(), model.buffers()):
                avg.copy_(b)

class EMA:
    """Exponential moving average of a model's parameters, given as a
    half-life in steps. Other state such as batch-norm statistics is copied;
    the average is kept in evaluation mode."""
    def __init__(self, model, half_life):
        self.model = nnx.clone(model)
        self.model.eval()
        self.decay = 0.5 ** (1 / half_life)

    def update(self, model):
        self.average(self.model, model, self.decay)

    @staticmethod
    @nnx.jit
    def average(avg, model, decay):
        """Move the parameters of avg toward those of model, in place."""
        params = jax.tree.map(lambda a, p: decay * a + (1 - decay) * p,
                              nnx.state(avg, nnx.Param),
                              nnx.state(model, nnx.Param))
        nnx.update(avg, params, nnx.state(model, nnx.Not(nnx.Param)))

이 절 뒤쪽의 실행들은 이미지 32,000장, 즉 배치 크기 64 기준 반감기 500스텝에 걸쳐 평균을 냅니다. 배치 크기 256에서는 똑같은 이미지 32,000장이 125스텝에 해당하여 이 실행 전체 2,840스텝(142스텝씩 20에포크)의 20분의 1 미만입니다.

출력되는 크리틱 손실은 16.1절 의 두 배치 평균 합으로 평형에서 \(2 \log 2 \approx 1.39\) 와 같아지며 생성자 손실은 그곳에서 \(\log 2 \approx 0.69\) 와 같아집니다.

ema = EMA(net_G, half_life=125)  # 32,000 images, as in the later runs
history = d2l.train_gan(net_D, net_G, data_iter, num_epochs=20,
                        latent_dim=100, lr_D=0.0002, lr_G=0.0002, seed=1,
                        ema=ema)
loss_D, loss_G = history[-1]
print(f'last epoch: loss_D {loss_D:.3f}, loss_G {loss_G:.3f}')
last epoch: loss_D 0.252, loss_G 3.188
ema = EMA(net_G, half_life=125)  # 32,000 images, as in the later runs
history = d2l.train_gan(net_D, net_G, data_iter, num_epochs=20,
                        latent_dim=100, lr_D=0.0002, lr_G=0.0002, seed=1,
                        ema=ema)
loss_D, loss_G = history[-1]
print(f'last epoch: loss_D {loss_D:.3f}, loss_G {loss_G:.3f}')
last epoch: loss_D 0.427, loss_G 3.027

다음 셀은 새로 뽑은 잠재 코드 배치 100개 위에서 평균 생성자를 훈련 모드로 실행하여 평균 모델의 배치 정규화 통계량을 재추정합니다. 이동 평균이 배치당 비율 0.1로 이전 값을 잊으므로 복사해 왔던 값의 잔여 가중치는 \(0.9^{100} \approx 3 \cdot 10^{-5}\) 로 사실상 0이 됩니다.

ema.model.train()  # batch-norm statistics for the averaged weights
with torch.no_grad():  # 100 batches; running averages forget at rate 0.1
    for _ in range(100):
        ema.model(torch.randn(256, 100, device=device))
ema.model.eval();
ema.model.train()  # batch-norm statistics for the averaged weights
# 100 batches; running averages forget at rate 0.1
for key in jax.random.split(jax.random.key(4), 100):
    ema.model(jax.random.normal(key, (256, 100)))
ema.model.eval()

각 이미지가 오직 자기 잠재 코드에만 의존하도록 평가 모드에서 샘플링합니다.

with torch.no_grad():
    fake = ema.model(torch.randn(20, 100, device=device))
d2l.show_images(fake.cpu().permute(0, 2, 3, 1) / 2 + 0.5,
                num_rows=4, num_cols=5);

fake = ema.model(jax.random.normal(jax.random.key(2), (20, 100)))
d2l.show_images(np.asarray(fake) / 2 + 0.5, num_rows=4, num_cols=5);

생성된 스프라이트들은 흰 배경 위에 다채로운 실루엣과 색상 팔레트를 보여 주지만 질감에 다소 얼룩진 흔적이 있습니다. 판별자 손실(\(\sim 0.25\text{--}0.45\))이 \(2\log 2 \approx 1.39\) 보다 한참 아래에 머물러 있는데도 모드 붕괴를 일으키지 않는다는 점에 주목합시다.

16.5.2 무정규화 백본

DCGAN 이후 수년에 걸쳐 대규모 이미지 GAN에는 수많은 아키텍처 안정화 장치가 덧붙여졌습니다(StyleGAN2 (Karras, Laine, 기타 2020년) 는 열 가지 개별 기법을 결합했습니다). R3GAN (Huang 기타 2024년) 은 목적 함수를 \(R_1 + R_2\) 그레이디언트 페널티와 상대론적 페어링 손실로 제대로 정칙화하기만 하면 그러한 임시방편 아키텍처 장치들을 걷어낼 수 있음을 보여 주었습니다. 특히 배치 정규화는 미니배치 전반에 걸쳐 샘플들을 서로 묶어 샘플별 입력 그레이디언트 계산을 어그러뜨리므로 \(R_1\) 과 \(R_2\) 를 쓸 때 판별자에서 배치 정규화를 빼는 일은 필수적입니다.

16.5.2.1 아키텍처와 팬인 초기화

정규화 층이나 출력 \(\tanh\) 가 없는 간결한 합성곱 백본(그림 16.5.2)을 구축합니다:

  • 생성자는 학습된 \(4 \times 4 \times 128\) 상수 텐서를 \(z\) 의 선형 투영(\(4 \times 4 \times 100\) 및 16.6절 클래스 조건화에 쓰이는 선택적 추가 채널)과 이어 붙인 뒤, 양선형 보간에 이은 \(3 \times 3\) 합성곱과 Leaky ReLU(\(\text{slope} = 0.2\))로 네 차례(\(4 \to 8 \to 16 \to 32 \to 64\)) 업샘플링합니다. 양선형 업샘플링 뒤 \(3 \times 3\) 합성곱을 배치하면 불균등한 전치 합성곱 중첩(그림 16.5.3)이 유발하는 체커보드 아티팩트를 피할 수 있습니다 (Odena 기타 2016년).
  • 크리틱은 \(3 \times 3\) 합성곱, Leaky ReLU, 양선형 다운샘플링으로 이 구조를 거울처럼 뒤집어 \(4 \times 4\) 특성 맵 \(\phi(x)\) 에 이른 뒤 선형 헤드를 통과시킵니다.
  • 배치 정규화 없이 층 전반에 걸쳐 활성화값 분산을 보존하기 위해 모든 가중치는 기울기 \(0.2\) 인 Leaky ReLU에 맞춰 스케일링한 He 팬인 초기화 (He 기타 2015년), 즉 분산 \(2 / ((1 + 0.2^2)\,n_{\mathrm{in}})\) 을 사용합니다.
그림 16.5.2: 무정규화 합성곱 백본. 생성자는 학습된 \(4 \times 4 \times 128\) 상수를 투영된 잠재 벡터와 결합한 뒤 양선형 업샘플링, \(3 \times 3\) 합성곱, Leaky ReLU의 네 스테이지를 거칩니다. 크리틱은 선형 헤드까지 양선형 다운샘플링으로 이 계층 구조를 대칭되게 뒤집습니다.
그림 16.5.3: 스트라이드 2인 전치 합성곱의 중첩 횟수. 각 입력 픽셀은 출력 위에 커널 복사본 하나를 도장처럼 찍으며 각 숫자는 테두리에서 떨어진 내부에서 해당 출력 픽셀을 덮는 도장 개수를 셉니다. 이웃한 두 도장에 테두리를 둘렀습니다. \(3 \times 3\) 커널(왼쪽)에서는 횟수가 4, 2, 1 사이에서 번갈아 바뀌어 상수 가중치만으로도 체커보드 무늬가 그려집니다. 크기가 스트라이드의 배수인 \(4 \times 4\) 커널(오른쪽)에서는 모든 픽셀이 고르게 네 번씩 덮입니다.
def fan_in_init(module):
    """Fan-in normal weights with the leaky-ReLU gain, zero offsets."""
    if isinstance(module, (nn.Conv2d, nn.Linear)):
        nn.init.kaiming_normal_(module.weight, a=0.2)
        nn.init.zeros_(module.bias)


class Generator(nn.Module):
    """Learned 4x4 constant + projected latent (+ extra 4x4 input maps),
    bilinearly upsampled to resolution x resolution; no normalization."""
    def __init__(self, latent_dim, resolution, base_ch, *, extra_ch=0,
                 const_ch=128):
        super().__init__()
        self.latent_dim = latent_dim
        self.const = nn.Parameter(torch.randn(1, const_ch, 4, 4))
        self.z_proj = nn.Linear(latent_dim, 16 * latent_dim)
        self.mix = nn.Conv2d(const_ch + latent_dim + extra_ch, base_ch, 3,
                             padding=1)
        num_stages = int(np.log2(resolution / 4))       # 64: four doublings
        chans = [base_ch // 2 ** i for i in range(num_stages + 1)]
        self.stages = nn.ModuleList(
            [nn.Conv2d(c_in, c_out, 3, padding=1)
             for c_in, c_out in zip(chans[:-1], chans[1:])])
        self.to_rgb = nn.Conv2d(chans[-1], 3, 3, padding=1)
        self.act = nn.LeakyReLU(0.2)
        self.apply(fan_in_init)

    def forward(self, z, extra=None):
        zc = self.z_proj(z).reshape(-1, self.latent_dim, 4, 4)
        const = self.const.expand(z.shape[0], -1, -1, -1)
        maps = [const, zc] + ([] if extra is None else [extra])
        x = self.act(self.mix(torch.cat(maps, dim=1)))
        for conv in self.stages:                     # 4 -> 8 -> ... -> 64
            x = F.interpolate(x, scale_factor=2, mode='bilinear')
            x = self.act(conv(x))
        return self.to_rgb(x)                        # no tanh: raw output

# Fan-in initialization with the leaky-ReLU gain (normal, not truncated)
fan_in_init = nnx.initializers.variance_scaling(2 / (1 + 0.2 ** 2),
                                                'fan_in', 'normal')


class Generator(nnx.Module):
    """Learned 4x4 constant + projected latent (+ extra 4x4 input maps),
    bilinearly upsampled to resolution x resolution; no normalization."""
    def __init__(self, latent_dim, resolution, base_ch, *, extra_ch=0,
                 const_ch=128, rngs):
        self.latent_dim = latent_dim
        self.const = nnx.Param(
            jax.random.normal(rngs.params(), (1, 4, 4, const_ch)))
        self.z_proj = nnx.Linear(latent_dim, 16 * latent_dim,
                                 kernel_init=fan_in_init, rngs=rngs)
        self.mix = nnx.Conv(const_ch + latent_dim + extra_ch, base_ch,
                            (3, 3), padding='SAME', kernel_init=fan_in_init,
                            rngs=rngs)
        num_stages = int(np.log2(resolution / 4))       # 64: four doublings
        chans = [base_ch // 2 ** i for i in range(num_stages + 1)]
        self.stages = nnx.List(
            [nnx.Conv(c_in, c_out, (3, 3), padding='SAME',
                      kernel_init=fan_in_init, rngs=rngs)
             for c_in, c_out in zip(chans[:-1], chans[1:])])
        self.to_rgb = nnx.Conv(chans[-1], 3, (3, 3), padding='SAME',
                               kernel_init=fan_in_init, rngs=rngs)

    def __call__(self, z, extra=None):
        zc = self.z_proj(z).reshape(-1, 4, 4, self.latent_dim)
        const = jnp.broadcast_to(self.const[...],
                                 (z.shape[0],) + self.const.shape[1:])
        maps = [const, zc] + ([] if extra is None else [extra])
        x = nnx.leaky_relu(self.mix(jnp.concatenate(maps, axis=-1)), 0.2)
        for conv in self.stages:                     # 4 -> 8 -> ... -> 64
            b, h, w, c = x.shape
            x = jax.image.resize(x, (b, 2 * h, 2 * w, c), method='bilinear')
            x = nnx.leaky_relu(conv(x), 0.2)
        return self.to_rgb(x)                        # no tanh: raw output

크리틱은 생성자와 대칭을 이룹니다. 합성곱, Leaky ReLU, 양선형 다운샘플링의 네 스테이지가 \(64 \times 64\) 이미지를 \(4 \times 4\) 로 줄이고 혼합 합성곱과 선형 헤드가 단일 점수를 반환합니다.

class Discriminator(nn.Module):
    """Critic that mirrors the generator: conv + leaky ReLU + bilinear
    downsampling to a 4x4 feature map phi(x), then a linear head on the
    flattened map."""
    def __init__(self, resolution, base_ch):
        super().__init__()
        num_stages = int(np.log2(resolution / 4))
        chans = [3] + [base_ch * 2 ** i for i in range(num_stages)]
        self.stages = nn.ModuleList(
            [nn.Conv2d(c_in, c_out, 3, padding=1)
             for c_in, c_out in zip(chans[:-1], chans[1:])])
        self.mix = nn.Conv2d(chans[-1], 2 * chans[-1], 3, padding=1)
        self.head = nn.Linear(2 * chans[-1] * 4 * 4, 1)
        self.act = nn.LeakyReLU(0.2)
        self.apply(fan_in_init)

    def phi(self, x):
        for conv in self.stages:                     # 64 -> 32 -> ... -> 4
            x = F.interpolate(self.act(conv(x)), scale_factor=0.5,
                              mode='bilinear', antialias=True)
        return self.act(self.mix(x))

    def forward(self, x):
        return self.head(self.phi(x).flatten(1))

for net in (Generator(latent_dim=100, resolution=64, base_ch=512),
            Discriminator(resolution=64, base_ch=32)):
    print(f'{type(net).__name__}: {d2l.num_params(net)} parameters')
Generator: 2782851 parameters
Discriminator: 1576769 parameters

class Discriminator(nnx.Module):
    """Critic that mirrors the generator: conv + leaky ReLU + bilinear
    downsampling to a 4x4 feature map phi(x), then a linear head on the
    flattened map."""
    def __init__(self, resolution, base_ch, *, rngs):
        num_stages = int(np.log2(resolution / 4))
        chans = [3] + [base_ch * 2 ** i for i in range(num_stages)]
        self.stages = nnx.List(
            [nnx.Conv(c_in, c_out, (3, 3), padding='SAME',
                      kernel_init=fan_in_init, rngs=rngs)
             for c_in, c_out in zip(chans[:-1], chans[1:])])
        self.mix = nnx.Conv(chans[-1], 2 * chans[-1], (3, 3),
                            padding='SAME', kernel_init=fan_in_init,
                            rngs=rngs)
        self.head = nnx.Linear(2 * chans[-1] * 4 * 4, 1,
                               kernel_init=fan_in_init, rngs=rngs)

    def phi(self, x):
        for conv in self.stages:                     # 64 -> 32 -> ... -> 4
            x = nnx.leaky_relu(conv(x), 0.2)
            b, h, w, c = x.shape
            x = jax.image.resize(x, (b, h // 2, w // 2, c),
                                 method='bilinear')
        return nnx.leaky_relu(self.mix(x), 0.2)

    def __call__(self, x):
        return self.head(self.phi(x).reshape(x.shape[0], -1))

for net in (Generator(100, 64, 512, rngs=nnx.Rngs(0)),
            Discriminator(64, 32, rngs=nnx.Rngs(0))):
    print(f'{type(net).__name__}: {d2l.num_params(net)} parameters')
Generator: 2782851 parameters
Discriminator: 1576769 parameters

생성자는 약 \(\sim 2.8\text{M}\) 개, 크리틱은 약 \(\sim 1.6\text{M}\) 개의 매개변수를 갖습니다.

16.5.3 통제된 손실 비교

16.5.3.1 세 가지 실험군

동일한 초기 가중치에서 출발해 Adam(\(\beta_1 = 0, \beta_2 = 0.99, \text{lr} = 2 \times 10^{-4}\)), 배치 크기 64, 무작위 좌우 반전, EMA(\(\text{half-life} = 500\) 스텝)를 쓰고 오직 훈련 목적 함수만 달리하여 무정규화 백본을 세 차례 훈련합니다:

\[L(D) + \frac{\gamma}{2}\Big(\mathbb{E}_x\big[\|\nabla_x D(x)\|^2\big] + \mathbb{E}_{x'}\big[\|\nabla_{x'} D(x')\|^2\big]\Big), \tag{16.5.3}\]

여기서 \(L(D)\) 는 고전적 로지스틱 손실(d2l.gan_loss_D) 또는 상대론적 페어링 손실(d2l.rpgan_loss_D)이며 생성자는 각각에 대응하는 비포화 손실을 사용합니다:

실험군 크리틱 손실 그레이디언트 페널티 스텝
NS 고전적 로지스틱 \(\gamma = 0\) (없음) 6,000
NS + R1 + R2 고전적 로지스틱 \(\gamma = 10\) 12,000
RpGAN + R1 + R2 상대론적 페어링 \(\gamma = 10\) 12,000

처음 두 실험군을 비교하면 \(R_1 + R_2\) 그레이디언트 페널티의 효과가 분리되고(무페널티 실험군은 그보다 훨씬 일찍 붕괴하므로 6,000스텝에서 중단합니다), 두 번째와 세 번째 실험군을 비교하면 쌍별 순위 매김의 효과가 분리됩니다(1 에서 이미지 해상도에 따라 \(\gamma\) 가 어떻게 스케일링되는지 분석합니다). 저장된 보조 함수 두 개가 훈련 루프를 뒷받침합니다. sample_real은 좌우 반전을 적용해 무작위 미니배치를 뽑고, pair_stats는 쌍별 순위 정확도 \(\hat P(D(x) > D(x'))\) 와 평균 상대론적 순위 가중치 \(w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))]\) 를 계산합니다.

def sample_real(images, n, labels=None):
    """Draw a training batch with random horizontal flips; return it with
    its labels (None without labels)."""
    idx = torch.randint(0, len(images), (n,), device=images.device)
    batch = images[idx]
    flip = torch.rand(n, device=images.device) < 0.5
    batch = torch.where(flip.view(-1, 1, 1, 1), batch.flip(-1), batch)
    return batch, (None if labels is None else labels[idx])


def pair_stats(net_D, real, fake, y=None):
    """Ranking accuracy P(D(x) > D(x')) and mean rank weight
    E[sigma(D(x') - D(x))] over aligned (real, generated) pairs; given
    labels y, the critic is D(., y)."""
    critic = net_D if y is None else lambda x: net_D(x, y)
    with torch.no_grad():
        diff = critic(fake) - critic(real)
    return float((diff < 0).float().mean()), float(torch.sigmoid(diff).mean())

def sample_real(key, images, n, labels=None):
    """Draw a training batch with random horizontal flips; return it with
    its labels (None without labels)."""
    k1, k2 = jax.random.split(key)
    idx = jax.random.randint(k1, (n,), 0, len(images))
    batch = images[idx]
    flip = jax.random.bernoulli(k2, 0.5, (n,))
    batch = jnp.where(flip[:, None, None, None], batch[:, :, ::-1, :], batch)
    return batch, (None if labels is None else labels[idx])


def pair_stats(net_D, real, fake, y=None):
    """Ranking accuracy P(D(x) > D(x')) and mean rank weight
    E[sigma(D(x') - D(x))] over aligned (real, generated) pairs; given
    labels y, the critic is D(., y)."""
    critic = net_D if y is None else lambda x: net_D(x, y)
    diff = critic(fake) - critic(real)
    return float((diff < 0).mean()), float(jax.nn.sigmoid(diff).mean())

JAX에서는 먼저 매 훈련 반복마다 단일 JIT 호출로 d2l.critic_step과 d2l.generator_step을 함께 묶어 실행하도록 r3gan_step을 컴파일합니다:


@nnx.jit(static_argnums=(4, 5))
def r3gan_step(net_G, net_D, opt_G, opt_D, loss_D, loss_G, gamma,
               X, z, y, X2, z2, y2):
    """One critic step on X against G(z), one generator step on (X2, z2);
    generated images take the labels y, y2 (None: unconditional). Return
    the critic loss, R1, R2 and the generator loss."""
    fake = net_G(z) if y is None else net_G(z, y)
    loss_d, r1, r2 = d2l.critic_step(net_D, opt_D, loss_D, X, fake, gamma, y)
    loss_g = d2l.generator_step(net_G, opt_G, loss_G, net_D, X2, z2, y2)
    return loss_d, r1, r2, loss_g

저장된 루프 train_r3gan은 반전된 실제 배치 위에서 16.4절 의 d2l.critic_step과 d2l.generator_step을 번갈아 실행하며 매 스텝 뒤 EMA 생성자를 갱신합니다. 크리틱 스텝이 \(R_1\) 과 \(R_2\) 의 배치 평균을 반환하므로 모든 실험군에서 실제 이미지 위의 크리틱 가파르기 \(\mathbb{E}_x\|\nabla_x D(x)\|^2\) 가 기록됩니다(첫 실험군에서는 가중치 \(\gamma = 0\)). 또한 250스텝마다 새로 뽑은 256개 쌍에 pair_stats를 적용합니다:

def train_r3gan(net_G, net_D, loss_D, loss_G, gamma, num_steps, images,
                labels=None, *, eval_images=None, eval_labels=None,
                eval_size=256, batch_size=64, lr=2e-4, half_life=500,
                log_every=250, seed=None):
    """Train with Adam (beta_1 = 0), alternating critic_step and
    generator_step on flipped real batches; a generated batch takes the
    labels of its real batch, if any. Every log_every steps, log the losses,
    R1, R2 and pair_stats on fresh pairs from eval_images (default: images).
    Return the EMA of the generator and the history, a dict of arrays."""
    if seed is not None:
        torch.manual_seed(seed)
    if eval_images is None:
        eval_images, eval_labels = images, labels
    opt_G, opt_D = [torch.optim.Adam(net.parameters(), lr, betas=(0.0, 0.99))
                    for net in (net_G, net_D)]
    noise = lambda n: torch.randn(n, net_G.latent_dim, device=images.device)
    generate = lambda z, y: net_G(z) if y is None else net_G(z, y)
    ema = EMA(net_G, half_life)
    history = {k: [] for k in ('step', 'loss_D', 'loss_G', 'R1', 'R2',
                               'accuracy', 'rank_weight')}
    for step in range(1, num_steps + 1):
        X, y = sample_real(images, batch_size, labels)
        with torch.no_grad():
            fake = generate(noise(batch_size), y)
        loss_d, r1, r2 = d2l.critic_step(net_D, opt_D, loss_D, X, fake,
                                         gamma, y)
        X, y = sample_real(images, batch_size, labels)
        loss_g = d2l.generator_step(net_G, opt_G, loss_G, net_D, X,
                                    noise(batch_size), y)
        ema.update(net_G)
        if step % log_every == 0:  # fresh pairs of real and generated images
            X, y = sample_real(eval_images, eval_size, eval_labels)
            with torch.no_grad():
                fake = generate(noise(eval_size), y)
            acc, weight = pair_stats(net_D, X, fake, y)
            logs = (step, loss_d, loss_g, r1, r2, acc, weight)
            for k, v in zip(history, logs):
                history[k].append(float(v))
    return ema.model, {k: np.array(v) for k, v in history.items()}

def train_r3gan(net_G, net_D, loss_D, loss_G, gamma, num_steps, images,
                labels=None, *, eval_images=None, eval_labels=None,
                eval_size=256, batch_size=64, lr=2e-4, half_life=500,
                log_every=250, seed=None):
    """Train with Adam (beta_1 = 0), alternating critic_step and
    generator_step on flipped real batches; a generated batch takes the
    labels of its real batch, if any. Every log_every steps, log the losses,
    R1, R2 and pair_stats on fresh pairs from eval_images (default: images).
    Return the EMA of the generator and the history, a dict of arrays."""
    key = d2l.get_key() if seed is None else jax.random.key(seed)
    if eval_images is None:
        eval_images, eval_labels = images, labels
    opt_G, opt_D = [nnx.Optimizer(net, optax.adam(lr, b1=0.0, b2=0.99),
                                  wrt=nnx.Param) for net in (net_G, net_D)]
    noise = lambda key, n: jax.random.normal(key, (n, net_G.latent_dim))
    generate = lambda z, y: net_G(z) if y is None else net_G(z, y)
    ema = EMA(net_G, half_life)
    history = {k: [] for k in ('step', 'loss_D', 'loss_G', 'R1', 'R2',
                               'accuracy', 'rank_weight')}
    for step in range(1, num_steps + 1):
        key, kx, kz, kx2, kz2 = jax.random.split(key, 5)
        X, y = sample_real(kx, images, batch_size, labels)
        X2, y2 = sample_real(kx2, images, batch_size, labels)
        loss_d, r1, r2, loss_g = r3gan_step(
            net_G, net_D, opt_G, opt_D, loss_D, loss_G, gamma,
            X, noise(kz, batch_size), y, X2, noise(kz2, batch_size), y2)
        ema.update(net_G)
        if step % log_every == 0:  # fresh pairs of real and generated images
            key, kx, kz = jax.random.split(key, 3)
            X, y = sample_real(kx, eval_images, eval_size, eval_labels)
            fake = generate(noise(kz, eval_size), y)
            acc, weight = pair_stats(net_D, X, fake, y)
            logs = (step, loss_d, loss_g, r1, r2, acc, weight)
            for k, v in zip(history, logs):
                history[k].append(float(v))
    return ema.model, {k: np.array(v) for k, v in history.items()}

train_arm은 모든 실험군에서 동일한 시드로 두 신경망을 생성해 훈련하고, 훈련 이미지 1,024장 평균 점수와 홀드아웃 이미지 1,024장 평균 점수 차이인 크리틱 훈련–홀드아웃 격차를 반환합니다.

def train_arm(loss_D, loss_G, gamma, num_steps):
    torch.manual_seed(0)  # the same initialization in every arm
    net_G = Generator(100, 64, 512).to(device)
    net_D = Discriminator(64, 32).to(device)
    ema_G, history = train_r3gan(net_G, net_D, loss_D, loss_G, gamma,
                                 num_steps, train_imgs, seed=1)
    with torch.no_grad():
        gap = (net_D(train_imgs[:1024]).mean()
               - net_D(holdout_imgs[:1024]).mean())
    return ema_G, history, float(gap)
def train_arm(loss_D, loss_G, gamma, num_steps):
    rngs = nnx.Rngs(0)  # the same initialization in every arm
    net_G = Generator(100, 64, 512, rngs=rngs)
    net_D = Discriminator(64, 32, rngs=rngs)
    ema_G, history = train_r3gan(net_G, net_D, loss_D, loss_G, gamma,
                                 num_steps, train_imgs, seed=1)
    gap = (net_D(train_imgs[:1024]).mean()
           - net_D(holdout_imgs[:1024]).mean())
    return ema_G, history, float(gap)

페널티가 크리틱 입력 그레이디언트를 한 번 더 미분하므로 페널티 스텝은 무페널티 스텝보다 계산 비용이 더 듭니다. 각 실행이 끝난 뒤 마지막 2,000스텝의 여덟 번 점검에 걸쳐 평균 낸 크리틱 손실·페널티와 훈련–홀드아웃 격차를 출력합니다.

arms = {'NS': (d2l.gan_loss_D, d2l.gan_loss_G, 0, 6000),
        'NS + R1 + R2': (d2l.gan_loss_D, d2l.gan_loss_G, 10, 12000),
        'RpGAN + R1 + R2': (d2l.rpgan_loss_D, d2l.rpgan_loss_G, 10, 12000)}
runs = {}
for name, (loss_D, loss_G, gamma, num_steps) in arms.items():
    ema_G, hist, gap = train_arm(loss_D, loss_G, gamma, num_steps)
    runs[name] = (ema_G, hist)
    loss, r1, r2 = (hist[k][-2000 // 250:].mean()  # the last 2,000 steps
                    for k in ('loss_D', 'R1', 'R2'))
    print(f'{name:16s} critic loss {loss:.2f}, '
          f'penalty {gamma / 2 * (r1 + r2):.3f}, train-holdout gap {gap:+.2f}')
NS               critic loss 0.57, penalty 0.000, train-holdout gap +0.08
NS + R1 + R2     critic loss 1.04, penalty 0.127, train-holdout gap +0.05
RpGAN + R1 + R2  critic loss 0.51, penalty 0.077, train-holdout gap +0.02
arms = {'NS': (d2l.gan_loss_D, d2l.gan_loss_G, 0, 6000),
        'NS + R1 + R2': (d2l.gan_loss_D, d2l.gan_loss_G, 10, 12000),
        'RpGAN + R1 + R2': (d2l.rpgan_loss_D, d2l.rpgan_loss_G, 10, 12000)}
runs = {}
for name, (loss_D, loss_G, gamma, num_steps) in arms.items():
    ema_G, hist, gap = train_arm(loss_D, loss_G, gamma, num_steps)
    runs[name] = (ema_G, hist)
    loss, r1, r2 = (hist[k][-2000 // 250:].mean()  # the last 2,000 steps
                    for k in ('loss_D', 'R1', 'R2'))
    print(f'{name:16s} critic loss {loss:.2f}, '
          f'penalty {gamma / 2 * (r1 + r2):.3f}, train-holdout gap {gap:+.2f}')
NS               critic loss 0.58, penalty 0.000, train-holdout gap +0.29
NS + R1 + R2     critic loss 1.04, penalty 0.122, train-holdout gap +0.05
RpGAN + R1 + R2  critic loss 0.47, penalty 0.092, train-holdout gap +0.03

페널티가 적용된 두 크리틱 모두 평형값보다 적당히 낮은 수준에 안착하는 반면(고전적 로지스틱은 \(2\log 2 \approx 1.39\) 대 \(1.04\); 페어링은 \(\log 2 \approx 0.69\) 대 \(0.47\text{--}0.51\)), 무페널티 크리틱은 \(0.57\text{--}0.58\) 까지 떨어집니다.

16.5.3.2 훈련 궤적과 생성 샘플

250스텝마다 크리틱 제곱 입력 그레이디언트 \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\), 쌍별 순위 정확도 \(\hat P(D(x) > D(x'))\), 상대론적 순위 가중치 \(w_{\mathrm{Rp}} = \mathbb{E}[\sigma(D(x') - D(x))]\) 를 그리면 그레이디언트 페널티가 어떻게 훈련을 안정화하는지 드러납니다:

fig, axes = d2l.plt.subplots(1, 3, figsize=(12, 3.2))
hists = [hist for _, hist in runs.values()]
for ax, key, ylabel, yscale in zip(
        axes, ('R1', 'accuracy', 'rank_weight'),
        (r'$E\,\|\nabla_x D(x)\|^2$', 'ranking accuracy',
         r'rank weight $w_{\mathrm{Rp}}$'),
        ('log', 'linear', 'linear')):
    d2l.plot([h['step'] for h in hists], [h[key] for h in hists], 'step',
             ylabel, yscale=yscale, axes=ax)
axes[0].legend(list(runs), loc='center right')
fig.tight_layout()

fig, axes = d2l.plt.subplots(1, 3, figsize=(12, 3.2))
hists = [hist for _, hist in runs.values()]
for ax, key, ylabel, yscale in zip(
        axes, ('R1', 'accuracy', 'rank_weight'),
        (r'$E\,\|\nabla_x D(x)\|^2$', 'ranking accuracy',
         r'rank weight $w_{\mathrm{Rp}}$'),
        ('log', 'linear', 'linear')):
    d2l.plot([h['step'] for h in hists], [h[key] for h in hists], 'step',
             ylabel, yscale=yscale, axes=ax)
axes[0].legend(list(runs), loc='center right')
fig.tight_layout()

\(R_1 + R_2\) 가 없으면 크리틱 제곱 그레이디언트 노름이 두 자릿수 치솟습니다(페널티 크리틱의 \(\sim 0.01\) 대비 \(1\text{--}8\) 에 도달). 세 크리틱 모두 \(> 90\%\) 의 쌍 순서를 올바르게 매기지만 페널티 크리틱들은 작은 점수 마진(\(w_{\mathrm{Rp}} \in [0.25, 0.40]\), 로짓 차이 중앙값 약 \(0.7\) 에 해당)을 유지하는 반면 무페널티 크리틱은 \(w_{\mathrm{Rp}}\) 를 \(0.15\) 아래로 몰아붙입니다.

샘플 품질을 시각적으로 비교하기 위해 먼저 \([-1, 1]\) 범위 이미지 배치를 단일 \([0, 1]\) 격자로 배열하는 보조 함수 tile_images를 정의합니다:

def tile_images(imgs, num_rows):
    """Tile images (n, 3, h, w) in [-1, 1] into one (rows * h, cols * w, 3)
    array in [0, 1]."""
    n, c, h, w = imgs.shape
    grid = (imgs.clamp(-1, 1) + 1) / 2
    grid = grid.reshape(num_rows, n // num_rows, c, h, w)
    grid = grid.permute(0, 3, 1, 4, 2)  # (rows, h, cols, w, c)
    return grid.reshape(num_rows * h, -1, c).cpu().numpy()

def tile_images(imgs, num_rows):
    """Tile images (n, h, w, 3) in [-1, 1] into one (rows * h, cols * w, 3)
    array in [0, 1]."""
    n, h, w, c = imgs.shape
    grid = (jnp.clip(imgs, -1, 1) + 1) / 2
    grid = grid.reshape(num_rows, n // num_rows, h, w, c)
    grid = grid.transpose(0, 2, 1, 3, 4)  # (rows, h, cols, w, c)
    return np.asarray(grid.reshape(num_rows * h, -1, c))

이제 동일한 잠재 벡터 64개 z_show 위에서 DCGAN과 세 무정규화 실험군을 합친 네 EMA 생성자 모두를 평가하고 출력을 \(8 \times 8\) 격자로 배열합니다:

torch.manual_seed(42)
z_show = torch.randn(64, 100, device=device)
gens = {'DCGAN': ema.model,
        **{name: ema_G for name, (ema_G, _) in runs.items()}}
with torch.no_grad():
    grids = [tile_images(G(z_show), 8) for G in gens.values()]
d2l.show_images(grids, 1, 4, titles=list(gens), scale=3.4);

z_show = jax.random.normal(jax.random.key(42), (64, 100))
gens = {'DCGAN': ema.model,
        **{name: ema_G for name, (ema_G, _) in runs.items()}}
grids = [tile_images(G(z_show), 8) for G in gens.values()]
d2l.show_images(grids, 1, 4, titles=list(gens), scale=3.4);

배치 정규화도 그레이디언트 페널티도 없는 NS 실험군은 완전한 모드 붕괴를 겪어 64개 잠재 코드 전체에서 균일한 회색 질감만 내놓습니다(4 참조). \(R_1 + R_2\) 를 추가하면(NS + R1 + R2 및 RpGAN + R1 + R2) 붕괴가 방지되고 깨끗한 흰 배경 위에 중앙 정렬된 다양한 스프라이트 실루엣이 생성됩니다.

16.5.4 정량 평가 지표

육안 점검만으로도 파국적 붕괴는 쉽게 잡아낼 수 있지만 정상 작동하는 두 생성자를 비교하려면 정량 지표가 필요합니다. 표준 GAN 평가는 사전 학습된 특성 추출기 \(\phi(x) \in \mathbb{R}^d\) 에 실제 이미지 \(n\) 장과 생성 이미지 \(n\) 장을 통과시켜 임베딩하고 16.2절 의 닫힌 형태 거리들로 두 경험적 특성 분포 사이의 불일치를 측정합니다.

16.5.4.1 FID와 KID

  1. Fréchet Inception 거리(FID) (Heusel 기타 2017년) 는 실제 및 생성 특성 구름에 다변량 가우스 분포 \(\mathcal{N}(\mu_p, \Sigma_p)\) 와 \(\mathcal{N}(\mu_q, \Sigma_q)\) 를 적합하고 둘 사이의 제곱 Wasserstein-2 거리를 계산합니다 (Dowson 와/과 Landau 1982년; Givens 와/과 Shortt 1984년):

    \[ \begin{aligned} \mathrm{FID} &= \big\| \mu_p - \mu_q \big\|^2 \\ &\quad + \operatorname{tr}\!\Big( \Sigma_p + \Sigma_q - 2 \big( \Sigma_p^{1/2}\, \Sigma_q\, \Sigma_p^{1/2} \big)^{1/2} \Big). \end{aligned} \tag{16.5.4}\]

    FID는 특성 분포의 처음 두 모멘트에만 의존하며 플러그인 표본 공분산 추정량이 유한 표본 크기에서 양의 \(O(1/n)\) 편향을 갖습니다(3 참조).

  2. 커널 Inception 거리(KID) (Bińkowski 기타 2018년) 는 3차 모멘트까지 비교하는 삼차 다항 커널 \(k(u, v) = (u^\top v / d + 1)^3\) 을 사용하여 불편 제곱 최대 평균 불일치(d2l.mmd2_unbiased, 16.2절)를 계산합니다(5 참조):

    \[ \begin{aligned} \widehat{\mathrm{MMD}}^2 &= \frac{1}{n_p(n_p-1)} \sum_{i \neq i'} k\big(\phi(x_i), \phi(x_{i'})\big) \\ &\quad + \frac{1}{n_q(n_q-1)} \sum_{j \neq j'} k\big(\phi(x'_j), \phi(x'_{j'})\big) \\ &\quad - \frac{2}{n_p n_q} \sum_{i,j} k\big(\phi(x_i), \phi(x'_j)\big). \end{aligned} \tag{16.5.5}\]

def fid_score(feat_p, feat_q):
    """Frechet distance between Gaussians fitted to two feature sets."""
    feat_p = np.asarray(feat_p, np.float64)
    feat_q = np.asarray(feat_q, np.float64)
    mu_p, mu_q = feat_p.mean(0), feat_q.mean(0)
    C_p = np.cov(feat_p, rowvar=False)
    C_q = np.cov(feat_q, rowvar=False)
    lam, U = np.linalg.eigh(C_p)
    sqrt_C_p = (U * np.sqrt(np.maximum(lam, 0))) @ U.T
    M = sqrt_C_p @ C_q @ sqrt_C_p
    cross = np.linalg.eigvalsh((M + M.T) / 2)   # symmetric up to rounding
    return (((mu_p - mu_q) ** 2).sum() + np.trace(C_p) + np.trace(C_q)
            - 2 * np.sqrt(np.maximum(cross, 0)).sum())


def kid_score(feat_p, feat_q):
    """Unbiased MMD^2 between two feature sets, cubic polynomial kernel."""
    d = feat_p.shape[1]
    kernel = lambda a, b: (a @ b.T / d + 1) ** 3
    return d2l.mmd2_unbiased(kernel(feat_p, feat_p), kernel(feat_q, feat_q),
                             kernel(feat_p, feat_q))

def fid_score(feat_p, feat_q):
    """Frechet distance between Gaussians fitted to two feature sets."""
    feat_p = np.asarray(feat_p, np.float64)
    feat_q = np.asarray(feat_q, np.float64)
    mu_p, mu_q = feat_p.mean(0), feat_q.mean(0)
    C_p = np.cov(feat_p, rowvar=False)
    C_q = np.cov(feat_q, rowvar=False)
    lam, U = np.linalg.eigh(C_p)
    sqrt_C_p = (U * np.sqrt(np.maximum(lam, 0))) @ U.T
    M = sqrt_C_p @ C_q @ sqrt_C_p
    cross = np.linalg.eigvalsh((M + M.T) / 2)   # symmetric up to rounding
    return (((mu_p - mu_q) ** 2).sum() + np.trace(C_p) + np.trace(C_q)
            - 2 * np.sqrt(np.maximum(cross, 0)).sum())


def kid_score(feat_p, feat_q):
    """Unbiased MMD^2 between two feature sets, cubic polynomial kernel."""
    d = feat_p.shape[1]
    kernel = lambda a, b: (a @ b.T / d + 1) ** 3
    return d2l.mmd2_unbiased(kernel(feat_p, feat_p), kernel(feat_q, feat_q),
                             kernel(feat_p, feat_q))

16.5.4.2 특성 신경망

표준 벤치마크들은 ImageNet으로 사전 학습된 Inception-v3 신경망의 2,048차원 특성이나 자기지도 DINOv2 특성을 사용해 FID와 KID를 계산합니다 (Stein 기타 2023년; Oquab 기타 2024년). 이 주피터 노트북이 외부 의존성 없이 자체 완결되도록 여기서는 가벼운 3블록 CIFAR-10 분류기 d2l.FeatureCNN(27.9.4절)을 \(32 \times 32\) 해상도에서 15에포크 동안 훈련하고 마지막 직전 128차원 층을 \(\phi\) 로 사용합니다(\(64 \times 64\) 스프라이트는 \(2 \times 2\) 평균 풀링으로 \(32 \times 32\) 로 다운샘플링합니다).

def batched(f, X, batch_size=1000):
    """Apply f to X in batches, without gradients, and concatenate."""
    with torch.no_grad():
        return torch.cat([f(X_k) for X_k in X.split(batch_size)])

def batched(f, X, batch_size=1000):
    """Apply f to X in batches and concatenate."""
    return jnp.concatenate([f(X[i:i + batch_size])
                            for i in range(0, len(X), batch_size)])

메모리 안전한 평가를 위해 batched를 사용해 CIFAR-10을 불러오고 무작위 4픽셀 이동 증강과 함께 \(32 \times 32\) 해상도에서 d2l.FeatureCNN을 훈련한 뒤 테스트 세트 분류 정확도를 확인합니다:

cifar_X, cifar_y, test_X, test_y = d2l.load_cifar10_arrays()
torch.manual_seed(0)
cnn = d2l.FeatureCNN(resolution=32).to(device)
d2l.train_feature_cnn(cnn, cifar_X, cifar_y, shift=4)
pred = batched(cnn, test_X).argmax(1)
print(f'CIFAR-10 test accuracy: {float((pred == test_y).float().mean()):.3f}')
CIFAR-10 test accuracy: 0.778
cifar_X, cifar_y, test_X, test_y = d2l.load_cifar10_arrays()
cnn = d2l.FeatureCNN(resolution=32, rngs=nnx.Rngs(1))
d2l.train_feature_cnn(cnn, cifar_X, cifar_y, shift=4)
pred = batched(cnn, test_X).argmax(1)
print(f'CIFAR-10 test accuracy: {float((pred == test_y).mean()):.3f}')
CIFAR-10 test accuracy: 0.781

16.5.4.3 정밀도와 재현율

FID나 KID 같은 단일 거리는 두 가지 서로 다른 실패 양상, 즉 낮은 충실도(\(p\) 의 지지집합 바깥에 비현실적 이미지 생성)와 낮은 커버리지(모드 누락, \(p\) 의 일부를 덮지 못함)를 하나로 뭉뚱그립니다. Kynkäänniemi 기타 (2019년) 의 연구는 특성 공간의 \(K\)-최근접 이웃 공들로 둘을 분리합니다. 각 실제 특성 \(\phi(x_i)\) 주위로 \(K\) 번째 최근접 실제 이웃까지 닿는 유클리드 공 \(B(\phi(x_i), r_i)\) 를 두고 생성 특성들 사이에서도 유사하게 \(B(\phi(x'_j), r'_j)\) 를 정의합시다(여기서는 \(K = 3\) 사용). 그러면 다음과 같습니다:

\[ \begin{aligned} \mathrm{precision} &= \frac{1}{n_q} \sum_{j=1}^{n_q} \mathbb{1}\Big[\phi(x'_j) \in \textstyle\bigcup_i B\big(\phi(x_i), r_i\big)\Big], \\ \mathrm{recall} &= \frac{1}{n_p} \sum_{i=1}^{n_p} \mathbb{1}\Big[\phi(x_i) \in \textstyle\bigcup_j B\big(\phi(x'_j), r'_j\big)\Big]. \end{aligned} \]

정밀도(precision)는 추정된 실제 특성 지지집합 안에 들어오는 생성 샘플의 비율이고, 재현율(recall)은 추정된 생성 특성 지지집합에 덮이는 실제 샘플의 비율입니다. 생성자가 단일 출력으로 붕괴하면 \(K\)-NN 반지름 \(r'_j\) 가 0으로 수축하여 재현율이 \(0\) 으로 떨어집니다.

def precision_recall(feat_real, feat_gen, k=3, chunk=1000):
    """k-NN precision and recall of two feature sets: the fraction of each
    set inside the union of the other set's balls, each ball reaching to its
    center's k-th nearest neighbor; return (precision, recall)."""
    P = np.asarray(feat_real, np.float64)
    Q = np.asarray(feat_gen, np.float64)
    def dists(A, B):  # (len(A), len(B)) Euclidean distances
        sq = (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)
        return np.sqrt(np.maximum(sq, 0))
    def chunks(A):
        return (A[i:i + chunk] for i in range(0, len(A), chunk))
    def radii(A):  # sorted distances start with the point itself, at 0
        return np.concatenate([np.partition(dists(a, A), k, axis=1)[:, k]
                               for a in chunks(A)])
    def covered(A, B, r_B):  # is each row of A inside some ball of B?
        return np.concatenate([(dists(a, B) <= r_B).any(1)
                               for a in chunks(A)])
    return (float(covered(Q, P, radii(P)).mean()),
            float(covered(P, Q, radii(Q)).mean()))

def precision_recall(feat_real, feat_gen, k=3, chunk=1000):
    """k-NN precision and recall of two feature sets: the fraction of each
    set inside the union of the other set's balls, each ball reaching to its
    center's k-th nearest neighbor; return (precision, recall)."""
    P = np.asarray(feat_real, np.float64)
    Q = np.asarray(feat_gen, np.float64)
    def dists(A, B):  # (len(A), len(B)) Euclidean distances
        sq = (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)
        return np.sqrt(np.maximum(sq, 0))
    def chunks(A):
        return (A[i:i + chunk] for i in range(0, len(A), chunk))
    def radii(A):  # sorted distances start with the point itself, at 0
        return np.concatenate([np.partition(dists(a, A), k, axis=1)[:, k]
                               for a in chunks(A)])
    def covered(A, B, r_B):  # is each row of A inside some ball of B?
        return np.concatenate([(dists(a, B) <= r_B).any(1)
                               for a in chunks(A)])
    return (float(covered(Q, P, radii(P)).mean()),
            float(covered(P, Q, radii(Q)).mean()))

16.5.4.4 실행 결과 채점하기

홀드아웃된 스프라이트 4,059장 전체를 기준으로 각 생성자의 이동 평균 모델에서 뽑은 샘플 \(n = 4{,}059\) 장을 채점합니다. 각 생성자는 잠재 코드 추출 두 묶음 위에서 채점하므로 두 번째 행은 샘플만 바뀔 때 점수가 얼마나 흔들리는지 보여 줍니다. 바닥 기준선으로는 서로 겹치지 않는 훈련 이미지 4,059장짜리 두 집합을 서로 채점하는데, 둘 사이의 거리는 추정량 잡음과(FD의 경우) 유한 표본 편향뿐입니다. 자체 특성 신경망을 썼으므로 점수를 FID와 KID 대신 FD와 \(\mathrm{MMD}^2\) 라 부르며 표본 수도 열두 배 많이 쓰는 공개 논문 수치들과는 직접 비교할 수 없습니다. 백본에 tanh가 없으므로 채점 전에 출력을 클램핑하며 마지막 두 열은 \(+1\) 초과 및 \(-1\) 미만인 원시 픽셀 값 비율을 보고합니다.

features = lambda imgs: batched(  # 2 x 2 averages: 64 x 64 -> 32 x 32
    cnn.features, F.avg_pool2d(imgs, 2)).cpu().numpy()
n = len(holdout_imgs)
zs = []
for seed in (7, 8):  # a second latent draw gives the sampling range
    torch.manual_seed(seed)
    zs.append(torch.randn(n, 100, device=device))
z_score = zs[0]
feat_gen, out_of_range = {}, {}  # out_of_range: fractions above +1, below -1
for name, G in gens.items():
    for row, z in zip((name, '  second draw'), zs):
        x = batched(G, z)
        out_of_range[(name, row)] = (float((x > 1).float().mean()),
                                     float((x < -1).float().mean()))
        feat_gen[(name, row)] = features(x.clamp(-1, 1))
feat_real = features(holdout_imgs)
feat_a, feat_b = features(train_imgs[:n]), features(train_imgs[n:2 * n])
white = float((holdout_imgs == 1).float().mean())
features = lambda imgs: np.asarray(batched(  # 2 x 2 averages: 64 -> 32
    cnn.features, nnx.avg_pool(imgs, (2, 2), strides=(2, 2))))
n = len(holdout_imgs)
zs = [jax.random.normal(jax.random.key(seed), (n, 100))
      for seed in (7, 8)]  # a second latent draw gives the sampling range
z_score = zs[0]
feat_gen, out_of_range = {}, {}  # out_of_range: fractions above +1, below -1
for name, G in gens.items():
    for row, z in zip((name, '  second draw'), zs):
        x = batched(G, z)
        out_of_range[(name, row)] = (float((x > 1).mean()),
                                     float((x < -1).mean()))
        feat_gen[(name, row)] = features(jnp.clip(x, -1, 1))
feat_real = features(holdout_imgs)
feat_a, feat_b = features(train_imgs[:n]), features(train_imgs[n:2 * n])
white = float((holdout_imgs == 1).mean())

각 특성 집합을 홀드아웃 스프라이트 특성 집합과 비교하며 첫 번째 행이 바닥 기준선입니다.

print(f'{"run":17s}{"FD":>7s}{"MMD^2":>8s}{"precision":>11s}{"recall":>8s}'
      f'{"> +1":>7s}{"< -1":>7s}')
scored = {(None, 'real vs. real'): (feat_a, feat_b),
          **{key: (feat_real, feat) for key, feat in feat_gen.items()}}
for key, (ref, feat) in scored.items():
    precision, recall = precision_recall(ref, feat)
    oor = ''.join(f'{v:7.3f}' for v in out_of_range.get(key, ()))
    print(f'{key[1]:17s}{fid_score(ref, feat):7.2f}{kid_score(ref, feat):8.3f}'
          f'{precision:11.2f}{recall:8.2f}{oor}')
print(f'real pixel values equal to +1: {white:.0%}')
run                   FD   MMD^2  precision  recall   > +1   < -1
real vs. real       0.19   0.003       0.95    0.95
DCGAN               2.05   0.115       0.34    0.48  0.000  0.000
  second draw       2.01   0.108       0.36    0.47  0.000  0.000
NS                 64.44   7.626       0.07    0.00  0.009  0.000
  second draw      64.32   7.628       0.07    0.00  0.010  0.000
NS + R1 + R2        5.32   1.092       0.33    0.42  0.150  0.001
  second draw       5.38   1.116       0.34    0.43  0.148  0.001
RpGAN + R1 + R2     3.51   0.652       0.36    0.44  0.143  0.001
  second draw       3.69   0.710       0.36    0.44  0.139  0.001
real pixel values equal to +1: 45%
print(f'{"run":17s}{"FD":>7s}{"MMD^2":>8s}{"precision":>11s}{"recall":>8s}'
      f'{"> +1":>7s}{"< -1":>7s}')
scored = {(None, 'real vs. real'): (feat_a, feat_b),
          **{key: (feat_real, feat) for key, feat in feat_gen.items()}}
for key, (ref, feat) in scored.items():
    precision, recall = precision_recall(ref, feat)
    oor = ''.join(f'{v:7.3f}' for v in out_of_range.get(key, ()))
    print(f'{key[1]:17s}{fid_score(ref, feat):7.2f}{kid_score(ref, feat):8.3f}'
          f'{precision:11.2f}{recall:8.2f}{oor}')
print(f'real pixel values equal to +1: {white:.0%}')
run                   FD   MMD^2  precision  recall   > +1   < -1
real vs. real       0.17  -0.001       0.95    0.95
DCGAN               1.80   0.083       0.39    0.48  0.000  0.000
  second draw       1.84   0.090       0.37    0.50  0.000  0.000
NS                 71.97   7.502       0.00    0.00  0.001  0.000
  second draw      71.95   7.501       0.00    0.00  0.001  0.000
NS + R1 + R2        3.96   0.663       0.40    0.41  0.146  0.001
  second draw       4.06   0.687       0.41    0.42  0.144  0.001
RpGAN + R1 + R2     3.71   0.603       0.41    0.42  0.149  0.001
  second draw       3.78   0.608       0.41    0.43  0.149  0.001
real pixel values equal to +1: 45%

이 표는 몇 가지 핵심 교훈을 보여 줍니다:

  1. 실제 대 실제 바닥 기준선: 서로소인 실제 스프라이트 \(4{,}059\) 장짜리 두 집합은 유한 표본 공분산 편향 때문에 \(\text{FD} \approx 0.2\) 를 기록하고 \(\widehat{\mathrm{MMD}}^2 \approx 0.000\) 및 정밀도/재현율 \(0.95\) 를 기록합니다. 두 번째 잠재 코드 묶음을 평가해도 FD 변화는 \(\leq 0.2\) 이하입니다.
  2. 붕괴 대 페널티 훈련: 붕괴한 무페널티 NS 실험군은 \(\text{FD} \approx 64\text{--}72\), \(\text{recall} = 0.00\), \(\text{precision} \leq 0.07\) 을 기록합니다. \(R_1 + R_2\) 를 추가하면 FD가 한 자릿수 줄어들고(\(\sim 3.5\text{--}5.5\)) 정밀도가 \(\sim 0.35\text{--}0.4\), 재현율이 \(\sim 0.4\) 로 올라갑니다.
  3. 특성 공간 민감도(DCGAN 대 페널티 백본): \(64 \times 64\) 육안 품질에서는 페널티 백본이 더 깔끔한 외곽선과 흰 배경을 만들어 내는데도, \(2 \times 2\) 다운샘플링이 DCGAN의 고주파 얼룩을 매끄럽게 뭉개 주는 \(32 \times 32\) CIFAR-10 분류기 특성 공간에서는 2015년 DCGAN이 더 낮은 FD(\(\sim 2\))와 \(\widehat{\mathrm{MMD}}^2\) 를 달성합니다. 특성 공간 지표들은 언제나 기저 특성 신경망의 불변성과 해상도를 그대로 반영합니다.

16.5.5 잠재 공간 보간과 크리틱 과적합

16.5.5.1 잠재 공간 보간

생성자가 이산적인 템플릿들을 암기하는 대신 잠재 코드에서 이미지로 가는 매끄러운 사상을 학습했는지 점검하기 위해 \(t \in [0, 1]\) 에 대해 64쌍의 잠재 벡터 사이를 \(z_t = (1 - t)z_0 + t z_1\) 로 선형 보간하고 생성 이미지 \(G(z_t)\) 를 픽셀별 교차 페이드(cross-fade) \((1 - t)G(z_0) + t G(z_1)\) 과 비교합니다.

G = runs['RpGAN + R1 + R2'][0]
torch.manual_seed(0)
z0, z1 = torch.randn(2, 64, 1, 100, device=device)  # 64 pairs of codes
t = torch.linspace(0, 1, 8, device=device).view(1, 8, 1)
path = batched(G, ((1 - t) * z0 + t * z1).reshape(-1, 100)).clamp(-1, 1)
path = path.reshape(64, 8, 3, 64, 64)               # (pair, step, image)
t = t.view(1, 8, 1, 1, 1)
fade = (1 - t) * path[:, :1] + t * path[:, -1:]     # pixel cross-fades
inner = lambda x: features(x[:, 1:-1].flatten(0, 1))
print(f'precision of the inner steps: latent walk '
      f'{precision_recall(feat_real, inner(path))[0]:.2f}, '
      f'cross-fade {precision_recall(feat_real, inner(fade))[0]:.2f}')
d2l.show_images([tile_images(x[:8].flatten(0, 1), 8) for x in (path, fade)],
                1, 2, titles=['latent walk', 'pixel cross-fade'], scale=4.5);
precision of the inner steps: latent walk 0.35, cross-fade 0.21

G = runs['RpGAN + R1 + R2'][0]
z0, z1 = jax.random.normal(jax.random.key(0), (2, 64, 1, 100))  # 64 pairs
t = jnp.linspace(0, 1, 8).reshape(1, 8, 1)
path = jnp.clip(batched(G, ((1 - t) * z0 + t * z1).reshape(-1, 100)), -1, 1)
path = path.reshape(64, 8, 64, 64, 3)               # (pair, step, image)
t = t.reshape(1, 8, 1, 1, 1)
fade = (1 - t) * path[:, :1] + t * path[:, -1:]     # pixel cross-fades
inner = lambda x: features(x[:, 1:-1].reshape(-1, 64, 64, 3))
print(f'precision of the inner steps: latent walk '
      f'{precision_recall(feat_real, inner(path))[0]:.2f}, '
      f'cross-fade {precision_recall(feat_real, inner(fade))[0]:.2f}')
d2l.show_images([tile_images(x[:8].reshape(-1, 64, 64, 3), 8)
                 for x in (path, fade)],
                1, 2, titles=['latent walk', 'pixel cross-fade'], scale=4.5);
precision of the inner steps: latent walk 0.38, cross-fade 0.18

중간 잠재 보간 이미지들은 무작위 생성자 추출과 똑같은 특성 정밀도(\(\sim 0.35\text{--}0.38\))를 유지하며 형태와 색상이 매끄럽게 전이되는 반면, 픽셀별 교차 페이드는 정밀도가 절반(\(\sim 0.18\text{--}0.21\))으로 떨어지는 잔상 겹침 이중 노출 이미지를 만듭니다.

16.5.5.2 크리틱 과적합과 비누수 데이터 증강

\(1.6\text{M}\) 개의 매개변수와 \(36{,}538\) 장의 훈련 스프라이트에서 크리틱은 12,000스텝 동안 각 훈련 이미지를 대략 20번씩 봅니다. 페널티 크리틱들은 아주 작은 훈련–홀드아웃 점수 격차(실제 대 가짜 마진 \(\sim 0.7\) 대비 \(+0.02\)~\(+0.05\), 2 참조)를 보입니다. 그러나 데이터셋이 더 작거나 훈련이 길어지면 판별자 암기가 FID를 떨어뜨릴 수 있습니다 (Karras, Aittala, 기타 2020년). 표준 처방인 적응형 판별자 증강(ADA, Karras, Aittala, 기타 (2020년))과 DiffAugment (Zhao 기타 2020년) 는 그레이디언트 경로 내부에서 실제 이미지와 생성 이미지 양쪽 모두에 가역적이고 비누수적인(non-leaking) 증강을 적용합니다(반면 본문의 좌우 반전처럼 실제 이미지에만 증강을 가하면 생성자가 증강된 분포에 맞춰지도록 훈련됩니다, 6 참조).

16.5.6 요약

DCGAN은 전치 합성곱과 스트라이드 합성곱, 배치 정규화, 작은 가중치 초기화(\(\sigma = 0.02\)), \(\beta_1 = 0.5\) Adam을 통해 고전적 로지스틱 손실 아래 합성곱 적대적 훈련을 안정화합니다. 배치 정규화와 아키텍처 안정화 장치들을 걷어내면 무페널티 로지스틱 손실은 완전히 붕괴하는 반면, 영중심 그레이디언트 페널티(\(R_1 + R_2\))를 더하면 크리틱 그레이디언트가 두 자릿수 감쇠되어 간결한 양선형 리샘플링 백본이 안정적으로 훈련됩니다. 생성자 가중치의 지수 이동 평균은 미니맥스 진동을 한층 더 감쇠시켜 주며 배치 정규화가 있을 때는 이동 통계량을 재보정해야 합니다. 마지막으로 정량 이미지 평가는 언제나 실제 대 실제 유한 표본 바닥 기준선에 맞춰 보정된 Fréchet 거리(식 16.5.4), 커널 Inception 거리(식 16.5.5), \(K\)-NN 정밀도와 재현율로 실제 및 생성 특성 구름을 비교합니다.

16.5.7 연습 문제

  1. 그레이디언트 페널티 가중치와 이미지 해상도. \(\nabla_x D(x)\) 의 단위는 길이 역수이므로 페널티 가중치 \(\gamma\) 는 이미지 해상도와 픽셀 스케일링에 의존합니다.

    1. \(U\) 가 각 픽셀을 \(2 \times 2\) 블록으로 복제해 \(64 \times 64\) 이미지 \(x\) 를 \(128 \times 128\) 로 업샘플링하고 \(A\) 가 각 \(2 \times 2\) 블록을 평균 내어 \(D' = D \circ A\) 가 \(D'(Ux) = D(x)\) 를 만족한다고 합시다. \(\|\nabla D'(Ux)\|^2\) 을 \(\|\nabla D(x)\|^2\) 으로 표현하고 \(128 \times 128\) 페널티를 \(64 \times 64\) 페널티와 같게 만드는 페널티 가중치 \(\gamma'\) 를 구하십시오.
    2. 픽셀 값을 \([-1, 1]\) 대신 \([0, 1]\) 로 정규화하면 \(\gamma\) 를 어떻게 재스케일링해야 합니까?
    3. (a)번 결과를 StyleGAN2-ADA (Karras, Aittala, 기타 2020년) 에서 쓰는 휴리스틱 \(\gamma \propto r^2 / B\)(해상도 \(r\) 과 배치 크기 \(B\))와 연결해 설명하십시오.
  2. [code] 스케일 무관 크리틱 과적합 통계량. 점수 스케일이 서로 다른 목적 함수들에 걸쳐 크리틱 암기 정도를 비교하기 위해 Karras, Aittala, 기타 (2020년) 의 연구는 다음 통계량을 정의합니다:

    \[ \begin{aligned} r_v &= \frac{\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{holdout}}]}{\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{generated}}]}, \\ r_t &= \mathbb{E}\big[\operatorname{sign}(D_{\textrm{train}})\big]. \end{aligned} \]

    1. 원시 격차 \(\mathbb{E}[D_{\textrm{train}}] - \mathbb{E}[D_{\textrm{holdout}}]\) 는 \(a\) 에 비례해 스케일링되고 \(r_t\) 는 이동 \(c\) 에 의존하는 반면, \(r_v\) 는 양의 아핀 변환 \(D \mapsto aD + c\)(\(a > 0\))에 불변임을 보이십시오.
    2. 이동 불변 페어링 크리틱에 대해 \(\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})]\) 는 \(D\) 의 어떤 변환들에 불변이며 훈련 점수와 홀드아웃 점수가 동일한 분포를 가질 때 어떤 값을 취합니까?
    3. net_D도 함께 반환하도록 train_arm을 수정하고 세 실험군 각각에 대해 이미지 1,024장 위에서 \(r_v\) 와 \(\mathbb{E}[\operatorname{sign}(D_{\textrm{train}} - D_{\textrm{holdout}})]\) 를 계산하십시오.
  3. [code] FID 대 KID의 유한 표본 편향.

    1. 각각 다섯 번의 무작위 분할에 걸쳐 \(n \in \{250, 500, 1000, 2000, 4059\}\) 에 대해 서로소인 훈련 스프라이트 \(n\) 장짜리 두 집합 사이의 실제 대 실제 FD와 \(\widehat{\mathrm{MMD}}^2\) 를 계산하십시오.
    2. \(1/n\) 에 대해 FD의 선형 회귀를 적합하고 \(1/n \to 0\) 으로 외삽하십시오(Chong 와/과 Forsyth (2020년)). \(n = 500\) 과 \(n = 4{,}059\) 에서 유한 표본 편향은 얼마나 큽니까?
    3. 홀드아웃 스프라이트 대비 RpGAN + R1 + R2 생성자에 대해 \(1/n\) 선형 적합을 반복하십시오. \(1/n\) 기울기가 생성자의 특성 공분산에 의존하므로 작은 \(n\) 에서의 유한 표본 편향이 어떻게 두 생성자의 순위를 뒤집을 수 있는지 설명하십시오.
  4. [code] 가중치 초기화와 모드 붕괴. ● z_show 위 생성 이미지들의 평균 쌍별 특성 거리를 홀드아웃 스프라이트 64장의 평균 쌍별 특성 거리로 나눈 값을 샘플 다양성으로 정의합시다.

    1. He 팬인 초기화 및 \(\sigma \in \{0.01, 0.02, 0.05\}\) 인 \(\mathcal{N}(0, \sigma^2)\) 초기화 아래 무페널티 NS 실험군에 대해 5,000스텝 동안 500스텝마다 샘플 다양성과 \(\mathbb{E}_x[\|\nabla_x D(x)\|^2]\) 을 기록하십시오. 크리틱 그레이디언트 노름의 급증이 다양성 하락보다 먼저 일어납니까?
    2. 세 시드에 걸쳐 팬인 실행을 반복하고 시드마다 붕괴 시점 스텝이 얼마나 달라지는지 측정하십시오.
  5. FID와 KID가 포착하는 모멘트. ●

    1. 이항 정리를 이용해 삼차 KID 커널 \(k(u, v) = (u^\top v / d + 1)^3\) 을 전개하여 모집단 \(\mathrm{MMD}^2(p, q)\) 가 다음과 같음을 보이고,

      \[\sum_{j=1}^{3} \binom{3}{j} d^{-j}\, \big\| \mathbb{E}_p[u^{\otimes j}] - \mathbb{E}_q[u^{\otimes j}] \big\|_F^2, \tag{16.5.6}\]

      따라서 특성 분포의 처음 세 모멘트를 비교함을 확인하십시오.

    2. 1차원(\(d = 1\))에서 \(p = \mathcal{N}(0, 1)\) 과 (i) \(X \sim \textrm{Exp}(1)\) 인 이동된 지수 분포 \(X - 1\)(평균 \(0\), 분산 \(1\), 왜도 \(2\)), (ii) 대칭 혼합 분포 \(\tfrac12\mathcal{N}(-a, 1 - a^2) + \tfrac12\mathcal{N}(a, 1 - a^2)\)(\(0 < a < 1\)) 사이의 모집단 FID 및 삼차 커널 \(\mathrm{MMD}^2\) 를 계산하십시오.

  6. 비누수 데이터 증강. ● \(F\) 를 좌우 반전 연산자라 하고 \(T_\rho r = (1 - \rho)r + \rho\,F_\# r\) 를 확률 \(\rho\) 로 \(r\) 의 샘플을 반전시켜 얻은 분포라 합시다.

    1. (sample_real처럼) 실제 이미지만 \(\rho = \tfrac12\) 로 반전시킬 때 생성자는 \(T_{1/2} p\) 를 향해 훈련됩니다. 참 스프라이트 중 비율 \(\alpha\) 가 우향 대응물 없이 왼쪽만 본다면 최적 생성자 샘플 중 오른쪽을 보는 비율은 얼마입니까?
    2. 크리틱 내부에서 실제 이미지와 생성 이미지 양쪽 모두에 \(T_\rho\) 를 적용할 때, \(F^2 = I\) 를 이용해 \(\rho \neq \tfrac12\) 이면 언제나 \(T_\rho q = T_\rho p \implies q = p\) 가 성립하는(비누수, Karras, Aittala, 기타 (2020년)) 반면 \(\rho = \tfrac12\) 에서는 \(p\) 와 반전 대칭화 밀도를 공유하는 임의 분포가 \(p\) 와 구별 불가능함을 보이십시오.

토론