Conditional GANs, StyleGAN and the adversarial loss as a tool
Control generation and use the discriminator as a learned loss. Study conditional GANs and projection discriminators, pix2pix and CycleGAN image translation, style-based generation and truncation, and perceptual plus adversarial reconstruction losses.
After this lesson you can
- Derive the projection discriminator from conditional density ratios.
- Implement pix2pix with PatchGAN and compare L1, adversarial loss and their combination.
- Implement StyleGAN2 modulated and demodulated convolution and verify its normalization.
- Explain and measure truncation as a quality-diversity trade-off.
- Train an autoencoder with perceptual and adversarial losses for reuse in latent diffusion.
Before you start
Generating under a condition
In an unconditional GAN we choose a noise sample and observe what appears. Translating an edge map to an image or generating a particular class requires a condition . It can be provided to both generator and discriminator: the former learns to produce an image compatible with and the latter compares real and generated pairs.
Label sampling matters: if frequencies differ between real and fake examples, the discriminator can exploit that difference without looking at the image. Mirza and Osindero introduce a conditional formulation; Miyato and Koyama study a projection discriminator.
A density ratio separating image and label
Assume discrete classes and positive densities at the point considered. With equal real and fake class priors and equally likely real/fake classes, the optimal discriminator logit is
To understand projection, model both class probabilities with log-linear softmax over a representation : and . The difference of their logarithms contains plus a difference of log-normalizers depending on , not the chosen class. If the marginal image ratio can also be expressed as a function of , group terms independent of to obtain . Without that assumption, the class-independent term is generally a free function of .
This derivation motivates an architecture; it does not prove a finite network learns the exact ratio. If class priors differ, their ratio appears explicitly when factorizing via ; in the decomposition above it is already included in conditionals . Projection lets compatibility and realism share features but does not guarantee classwise fidelity or coverage.
Translation with and without pairs
The L1 term encourages fidelity to the observed pair; the adversary penalizes learned discrepancies between real and generated patches. If several plausible outputs correspond to an ambiguous input, the deterministic solution minimizing coordinatewise L1 error is a coordinatewise conditional median. This can remove texture variations or produce smooth images, but L1 does not inevitably blur every problem. Adversarial loss can add plausible details that do not correspond to the particular image: compare fidelity too, and do not interpret sharpness as truth.
To calculate a receptive field, start with size and jump . For a layer with kernel and stride , and . Padding affects position and what part of the field falls outside the image, not the theoretical size of that recurrence. A PatchGAN map evaluates multiple overlapping fields; one output is not an independent judgment of the whole image.
When pairs do not exist, CycleGAN learns and with adversarial losses per domain and consistency such as . Approximately returning to the starting point does not identify a unique semantic translation: many bijections and hidden encodings satisfy the cycle. Inspect correspondence, artifacts and robustness, not cycle loss alone.
Styles and scales
StyleGAN2 formulates weight modulation and demodulation. For kernel and style , first and then
If inputs to a receptive field have zero mean, unit variance and are uncorrelated, linear output variance for a channel is , where . It approaches one if . Correlations, padding, nonlinearities and added noise can change that conclusion; demodulation does not exactly normalize every activation in a real network.
Contraction reduces variation in the modified style space, but does not guarantee improved quality for every image or a monotonic decline in every metric for every model. Report truncated layers and the value of . It resembles other fidelity-diversity controls, such as some diffusion guidance, but operations and distributions differ: contraction in is not classifier-free guidance.
A loss that learns to look
Perceptual and adversarial loss combines terms answering different questions. L2 measures pixelwise differences; LPIPS compares features of a network with calibration learned from perceptual judgments, under the protocol of Zhang and colleagues. A PatchGAN learns to distinguish patches of reconstructions and data. Neither alone guarantees generated content is faithful to the input.
VQGAN combines perceptual and adversarial reconstruction with a quantized autoencoder. Convincing texture can be wrong for the original image, especially with excessive adversarial weight. For an autoencoder intended for latent diffusion, save its checkpoint and document architecture, input scaling, latent dimensions and selection criterion; the later stage must use that same contract. GANs also appear in super-resolution and systems reducing generation steps, but costs and guarantees depend on the method.
Lab: modulation and demodulation
Implement a valid convolution without bias or padding, with a different modulated kernel per example. Styles and weights are fixed, and each input patch is an independent standard normal sample. Compare empirical variance with prediction for each output channel. In real images, overlapping inputs and learned features may be correlated: this checks assumptions of a controlled case, not variance throughout StyleGAN.
import numpy as np
def modulated_conv_numpy(x, weight, style, demodulate=True, eps=1e-8):
batch, channels, height, width = x.shape
outputs, inputs, kh, kw = weight.shape
assert inputs == channels and style.shape == (batch, channels)
scaled = weight[None] * style[:, None, :, None, None]
if demodulate:
norm = np.sqrt(np.sum(scaled**2, axis=(2, 3, 4), keepdims=True) + eps)
scaled = scaled / norm
result = np.empty((batch, outputs, height-kh+1, width-kw+1))
for row in range(height-kh+1):
for col in range(width-kw+1):
patch = x[:, :, row:row+kh, col:col+kw]
result[:, :, row, col] = np.einsum('bijk,boijk->bo', patch, scaled)
return result
rng = np.random.default_rng(1010)
weight = rng.normal(size=(4, 3, 3, 3))
fixed_style = np.array([0.3, 1.4, 0.7])
batch = 4096
styles = np.broadcast_to(fixed_style, (batch, 3))
x = rng.normal(size=(batch, 3, 3, 3))
raw = modulated_conv_numpy(x, weight, styles, demodulate=False)[:, :, 0, 0]
normalized = modulated_conv_numpy(x, weight, styles, demodulate=True)[:, :, 0, 0]
energy = np.sum((weight * fixed_style[None, :, None, None])**2, axis=(1, 2, 3))
print('Varianza teórica sin demodulación:', np.round(energy, 3))
print('Varianza empírica sin demodulación:', np.round(raw.var(axis=0), 3))
print('Varianza teórica demodulada:', np.round(energy / (energy + 1e-8), 3))
print('Varianza empírica demodulada:', np.round(normalized.var(axis=0), 3))The difference between the last two rows is Monte Carlo error. It may increase with fewer patches; changing input correlation also changes theoretical variance.
Local lab: pix2pix for edges and images
Fashion-MNIST offers continuous-intensity images; classes are not used in training. Construct input by applying a Sobel filter and fixed threshold 0.75 to each image; the target is the original image. U-Net has skip connections and the discriminator receives the pair (bordes, imagen), edges and image, with a 7×7 logit map. The interior receptive field of each logit is 26×26 pixels, with padding at the edges.
Compare three variants: L1 alone, non-saturating adversarial loss alone, and their sum with L1 weight 10 and adversarial weight 1. All begin with the same initialization, data order and number of generator and discriminator updates. The discriminator is trained even in the L1-only variant, although its loss does not influence G updates; this maintains equal step counts for both networks. One seed cannot separate randomness sensitivity from objective differences. Training losses alone do not measure perceptual quality.
Evaluation uses only images from the official test split, separate from training. Per-pixel L1 is reported and the same four inputs and targets are shown for all three models; a pixel metric alone does not establish visual quality or semantic fidelity. Adversarial output can invent details and a short test proves no method superior.
Install PyTorch, torchvision and matplotlib. By default all training images, 2048 test images and 15 epochs per variant are used. ORYON_QUICK=1 uses 128 training images, 64 test images, one epoch and fewer channels to check the workflow. ORYON_FASHION_ROOT points to the directory containing FashionMNIST; if unset, ORYON_DATA_ROOT or ./data is used.
import os
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
quick = os.environ.get('ORYON_QUICK') == '1'
root = Path(os.environ.get('ORYON_FASHION_ROOT', os.environ.get('ORYON_DATA_ROOT', './data')))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
width = 12 if quick else 32
epochs = 1 if quick else 15
batch_size = 16 if quick else 64
seed = 1010
data_train = datasets.FashionMNIST(root, train=True, download=True, transform=transforms.ToTensor())
data_test = datasets.FashionMNIST(root, train=False, download=True, transform=transforms.ToTensor())
train = Subset(data_train, range(128)) if quick else data_train
test = Subset(data_test, range(64 if quick else 2048))
test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)
def edges(x):
# Sobel fijo sobre cada imagen, seguido de un umbral explícito.
kernel = x.new_tensor([[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]])
gx = F.conv2d(x, kernel[None, None], padding=1)
gy = F.conv2d(x, kernel.T[None, None], padding=1)
return (torch.sqrt(gx.square() + gy.square()) > 0.75).to(x.dtype)
assert torch.count_nonzero(edges(torch.zeros(2, 1, 28, 28))) == 0
class UNet(nn.Module):
def __init__(self):
super().__init__()
self.down1 = nn.Conv2d(1, width, 4, 2, 1)
self.down2 = nn.Conv2d(width, 2 * width, 4, 2, 1)
self.middle = nn.Conv2d(2 * width, 2 * width, 3, padding=1)
self.up1 = nn.ConvTranspose2d(2 * width, width, 4, 2, 1)
self.up2 = nn.ConvTranspose2d(2 * width, width, 4, 2, 1)
self.output = nn.Conv2d(width, 1, 3, padding=1)
def forward(self, x):
first = F.leaky_relu(self.down1(x), 0.2)
second = F.leaky_relu(self.down2(first), 0.2)
hidden = F.relu(self.middle(second))
up = F.relu(self.up1(hidden))
up = F.relu(self.up2(torch.cat((up, first), dim=1)))
return torch.sigmoid(self.output(up))
class PatchDiscriminator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(2, width, 4, 2, 1), nn.LeakyReLU(0.2),
nn.Conv2d(width, 2 * width, 4, 2, 1), nn.LeakyReLU(0.2),
nn.Conv2d(2 * width, 2 * width, 3, padding=1), nn.LeakyReLU(0.2),
nn.Conv2d(2 * width, 1, 3, padding=1))
def forward(self, condition, image):
return self.net(torch.cat((condition, image), dim=1))
@torch.no_grad()
def evaluate(model):
model.eval()
total_abs = count = 0
for x, _ in test_loader:
x = x.to(device)
prediction = model(edges(x))
total_abs += (prediction - x).abs().sum().item()
count += x.numel()
return total_abs / count
def run(mode):
torch.manual_seed(seed)
if device.type == 'cuda':
torch.cuda.manual_seed_all(seed)
generator = UNet().to(device)
discriminator = PatchDiscriminator().to(device)
g_optimizer = torch.optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))
d_optimizer = torch.optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))
order = torch.Generator().manual_seed(seed + 1)
loader = DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=0, generator=order)
recon_weight, adversarial_weight = {'l1': (10.0, 0.0), 'adversaria': (0.0, 1.0), 'combinada': (10.0, 1.0)}[mode]
for epoch in range(epochs):
generator.train(); discriminator.train()
seen = 0
total_l1 = total_adv = total_d = 0.0
for target, _ in loader:
target = target.to(device)
condition = edges(target)
fake = generator(condition)
assert fake.shape == target.shape
d_optimizer.zero_grad(set_to_none=True)
real_logits = discriminator(condition, target)
fake_logits = discriminator(condition, fake.detach())
d_loss = F.softplus(-real_logits).mean() + F.softplus(fake_logits).mean()
d_loss.backward()
d_optimizer.step()
for parameter in discriminator.parameters():
parameter.requires_grad_(False)
g_optimizer.zero_grad(set_to_none=True)
generated_logits = discriminator(condition, fake)
l1 = F.l1_loss(fake, target)
adversarial = F.softplus(-generated_logits).mean()
loss = recon_weight * l1 + adversarial_weight * adversarial
loss.backward()
g_optimizer.step()
for parameter in discriminator.parameters():
parameter.requires_grad_(True)
n = len(target)
total_l1 += l1.item() * n
total_adv += adversarial.item() * n
total_d += d_loss.item() * n
seen += n
heldout_l1 = evaluate(generator)
print(mode, 'época', epoch + 1, 'L1 train:', round(total_l1 / seen, 4),
'adversaria train:', round(total_adv / seen, 4),
'D train:', round(total_d / seen, 4), 'L1 test:', round(heldout_l1, 4), flush=True)
generator.eval()
with torch.no_grad():
reference = next(iter(test_loader))[0][:4].to(device)
condition = edges(reference)
examples = generator(condition).cpu()
reference, condition = reference.cpu(), condition.cpu()
del generator, discriminator, g_optimizer, d_optimizer
del target, fake, loss, d_loss, l1, adversarial, real_logits, fake_logits, generated_logits, parameter
if device.type == 'cuda':
torch.cuda.empty_cache()
return reference, condition, examples, heldout_l1
print('Dispositivo:', device, '| prueba corta:', quick, '| train/test:', len(train), len(test), flush=True)
results = {mode: run(mode) for mode in ('l1', 'adversaria', 'combinada')}
fig, axes = plt.subplots(5, 4, figsize=(8, 10))
names = ['Bordes', 'Objetivo', 'Solo L1', 'Solo adversaria', 'L1 + adversaria']
rows = [results['l1'][1], results['l1'][0], results['l1'][2], results['adversaria'][2], results['combinada'][2]]
for row, images in enumerate(rows):
for col, image in enumerate(images):
axes[row, col].imshow(image[0], cmap='gray', vmin=0, vmax=1)
axes[row, col].axis('off')
axes[row, 0].set_title(names[row])
fig.tight_layout()
plt.show()
plt.close(fig)
print('L1 reservada por píxel:', {mode: round(results[mode][3], 4) for mode in results}, flush=True)npm run lab and open the connection link.Local lab: perceptual and adversarial reconstruction
Install torch, torchvision and lpips==0.1.4. The first run downloads ImageNet SqueezeNet weights and uses calibrated weights included in LPIPS. This is real LPIPS distance with the squeeze network, not a random network. Use aligned CelebA images and its official list_eval_partition.txt: set ORYON_CELEBA_DIR to the flat img_align_celeba folder and ORYON_CELEBA_SPLITS to that file. The training split is respected and the first 1024 validation images are reserved for checkpoint selection. CelebA terms restrict use and redistribution; consult them when downloading.
Train three autoencoders with identical architecture and initialization: MSE, MSE + 0.1 LPIPS and MSE + 0.1 LPIPS + 0.01 adversarial loss. The PatchGAN discriminator is not conditioned on the original image. To prevent early dominance it activates after five epochs; the short trial activates it immediately to test that branch. Selection uses the same validation MSE + 0.1 LPIPS criterion for all variants and epochs; best_autoencoder.pt contains winning weights, architecture, normalization, variant and epoch. It is a deterministic autoencoder with continuous 8×8×8 latent, not a VQGAN or pretrained VAE. Diffusion must load and freeze it, measure latent scale on training, and apply that same scale when encoding and decoding; no universal scale is assumed.
By default train 20 epochs per variant. ORYON_QUICK=1 uses little data and a smaller network only to check functionality. If ORYON_DEBUG_CIFAR_PARQUET also points to a folder with CIFAR-10 train-*.parquet and test-*.parquet, the test uses 32 training and 16 test images resized to 64×64 instead of CelebA; this option works only with ORYON_QUICK=1 and produces no diffusion checkpoint. MSE, LPIPS and Laplacian variance are recorded alongside identical validation grids. Higher edge variance does not prove greater fidelity: it can indicate artifacts or invented texture. The selection score does not replace independent perceptual evaluation.
import csv
import io
import os
from pathlib import Path
import lpips
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from torchvision.utils import save_image
quick = os.environ.get('ORYON_QUICK') == '1'
debug_dir = os.environ.get('ORYON_DEBUG_CIFAR_PARQUET')
if debug_dir and not quick:
raise ValueError('ORYON_DEBUG_CIFAR_PARQUET solo se usa con ORYON_QUICK=1')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(2)
width = 8 if quick else 48
epochs = 1 if quick else 20
batch_size = 4 if quick else 32
warmup = 0 if quick else 5
latent_channels = 8
output = Path(os.environ.get('ORYON_OUTPUT_DIR', './perceptual-autoencoder'))
output.mkdir(parents=True, exist_ok=True)
transform = transforms.Compose([
transforms.Resize((64, 64)), transforms.ToTensor(),
transforms.Normalize((0.5,) * 3, (0.5,) * 3),
])
class CelebAImages(Dataset):
def __init__(self, directory, partition_file, split, limit=None):
folder = Path(directory)
rows = Path(partition_file).read_text(encoding='utf-8').splitlines()
files = [folder / name for name, part in (row.split() for row in rows) if part == str(split)]
self.files = files[:limit] if limit else files
if not self.files or not all(path.is_file() for path in self.files):
raise FileNotFoundError('Faltan imágenes de la partición oficial de CelebA')
self.crop = transforms.CenterCrop(178)
def __len__(self):
return len(self.files)
def __getitem__(self, index):
with Image.open(self.files[index]) as image:
return transform(self.crop(image.convert('RGB')))
class DebugCIFAR(Dataset):
def __init__(self, folder, split, limit):
import pyarrow.parquet as pq
files = sorted(Path(folder).glob(f'{split}-*.parquet'))
if not files:
raise FileNotFoundError(f'No se encontró el parquet {split}')
self.rows = []
for file in files:
for batch in pq.ParquetFile(file).iter_batches(batch_size=limit, columns=['img']):
self.rows.extend(batch.slice(0, limit - len(self.rows)).to_pylist())
if len(self.rows) >= limit:
break
if len(self.rows) >= limit:
break
def __len__(self):
return len(self.rows)
def __getitem__(self, index):
with Image.open(io.BytesIO(self.rows[index]['img']['bytes'])) as image:
return transform(image.convert('RGB'))
if debug_dir:
train_data = DebugCIFAR(debug_dir, 'train', 32)
val_data = DebugCIFAR(debug_dir, 'test', 16)
else:
folder = os.environ.get('ORYON_CELEBA_DIR')
splits = os.environ.get('ORYON_CELEBA_SPLITS')
if not folder or not splits:
raise ValueError('Define ORYON_CELEBA_DIR y ORYON_CELEBA_SPLITS')
train_data = CelebAImages(folder, splits, 0, 32 if quick else None)
val_data = CelebAImages(folder, splits, 1, 16 if quick else 1024)
if len(train_data) < batch_size or not len(val_data):
raise ValueError('No hay suficientes imágenes para entrenar y validar')
val_loader = DataLoader(val_data, batch_size=batch_size, shuffle=False, num_workers=0)
class Autoencoder(nn.Module):
def __init__(self, base=width, z_channels=latent_channels):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, base, 4, 2, 1), nn.GroupNorm(8, base), nn.SiLU(),
nn.Conv2d(base, base * 2, 4, 2, 1), nn.GroupNorm(8, base * 2), nn.SiLU(),
nn.Conv2d(base * 2, base * 4, 4, 2, 1), nn.GroupNorm(8, base * 4), nn.SiLU(),
nn.Conv2d(base * 4, z_channels, 3, 1, 1),
)
self.decoder = nn.Sequential(
nn.Conv2d(z_channels, base * 4, 3, 1, 1), nn.GroupNorm(8, base * 4), nn.SiLU(),
nn.ConvTranspose2d(base * 4, base * 2, 4, 2, 1), nn.GroupNorm(8, base * 2), nn.SiLU(),
nn.ConvTranspose2d(base * 2, base, 4, 2, 1), nn.GroupNorm(8, base), nn.SiLU(),
nn.ConvTranspose2d(base, 3, 4, 2, 1), nn.Tanh(),
)
def forward(self, x):
return self.decoder(self.encoder(x))
class PatchDiscriminator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(3, width, 4, 2, 1), nn.LeakyReLU(0.2),
nn.Conv2d(width, width * 2, 4, 2, 1), nn.LeakyReLU(0.2),
nn.Conv2d(width * 2, width * 4, 4, 2, 1), nn.LeakyReLU(0.2),
nn.Conv2d(width * 4, 1, 4, 1, 1),
)
def forward(self, x):
return self.net(x)
def sharpness(x):
# Varianza espacial de la respuesta al laplaciano, media de canales e imágenes.
kernel = x.new_tensor([[0, 1, 0], [1, -4, 1], [0, 1, 0]]).reshape(1, 1, 3, 3)
kernel = kernel.expand(x.shape[1], 1, 3, 3)
edges = F.conv2d(x, kernel, padding=1, groups=x.shape[1])
return edges.flatten(2).var(dim=2, unbiased=False).mean()
perceptual = lpips.LPIPS(net='squeeze', verbose=False).to(device).eval()
for parameter in perceptual.parameters():
parameter.requires_grad_(False)
del parameter
best = float('inf')
history = []
for mode in ('mse', 'mse_lpips', 'mse_lpips_patch'):
torch.manual_seed(91)
if device.type == 'cuda':
torch.cuda.manual_seed_all(91)
model, disc = Autoencoder().to(device), PatchDiscriminator().to(device)
opt_model = torch.optim.Adam(model.parameters(), lr=0.0002, betas=(0.5, 0.999))
opt_disc = torch.optim.Adam(disc.parameters(), lr=0.0002, betas=(0.5, 0.999))
loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, drop_last=True,
num_workers=0, generator=torch.Generator().manual_seed(92))
mode_dir = output / mode
mode_dir.mkdir(parents=True, exist_ok=True)
for epoch in range(1, epochs + 1):
model.train()
disc.train()
adversarial = mode == 'mse_lpips_patch' and epoch > warmup
for real in loader:
real = real.to(device)
reconstruction = model(real)
if adversarial:
opt_disc.zero_grad(set_to_none=True)
d_loss = (F.softplus(-disc(real)).mean() +
F.softplus(disc(reconstruction.detach())).mean())
d_loss.backward()
opt_disc.step()
opt_model.zero_grad(set_to_none=True)
loss = F.mse_loss(reconstruction, real)
if mode != 'mse':
loss = loss + 0.1 * perceptual(reconstruction, real).mean()
if adversarial:
for parameter in disc.parameters():
parameter.requires_grad_(False)
loss = loss + 0.01 * F.softplus(-disc(reconstruction)).mean()
loss.backward()
opt_model.step()
if adversarial:
for parameter in disc.parameters():
parameter.requires_grad_(True)
model.eval()
totals = torch.zeros(4, device=device)
count = 0
with torch.no_grad():
for batch_index, real in enumerate(val_loader):
real = real.to(device)
reconstruction = model(real)
n = real.shape[0]
totals += n * torch.stack((F.mse_loss(reconstruction, real),
perceptual(reconstruction, real).mean(), sharpness(real), sharpness(reconstruction)))
count += n
if batch_index == 0:
pairs = torch.cat((real, reconstruction), dim=0)
save_image(((pairs + 1) / 2).clamp(0, 1),
mode_dir / f'validacion-{epoch:03d}.png', nrow=n)
mse, distance, sharp_real, sharp_rec = (totals / count).cpu().tolist()
score = mse + 0.1 * distance
history.append([mode, epoch, mse, distance, sharp_real, sharp_rec, score])
print(f'{mode} época {epoch:02d}: MSE={mse:.5f} LPIPS={distance:.5f} '
f'laplaciano real={sharp_real:.5f} reconstrucción={sharp_rec:.5f} score={score:.5f}')
if score < best:
best = score
torch.save({'state_dict': model.state_dict(), 'base': width,
'latent_channels': latent_channels, 'image_size': 64,
'input_range': [-1, 1], 'mode': mode, 'epoch': epoch,
'selection_score': score, 'debug': quick,
'selection': 'validation MSE + 0.1 LPIPS squeeze'},
output / ('debug_autoencoder.pt' if quick else 'best_autoencoder.pt'))
del real, reconstruction, totals, pairs, loss, model, disc, opt_model, opt_disc
if mode == 'mse_lpips_patch' and adversarial:
del d_loss, parameter
if device.type == 'cuda':
torch.cuda.empty_cache()
with (output / 'metricas.csv').open('w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['variante', 'epoca', 'mse_val', 'lpips_val', 'lap_real', 'lap_reconstruccion', 'score'])
writer.writerows(history)
print('Resultados:', output.resolve())
del perceptual
if device.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. How does the joint ratio separate?
import torch
import torch.nn.functional as F
def modulated_conv2d(x, weight, style, demodulate=True, eps=1e-8):
passConditioning a GAN changes the distributions being compared. Styles control a specific architecture, truncation changes its input distribution, and perceptual or adversarial loss must be evaluated alongside fidelity to data.