Okay, let's propose a novel approach called Guided Feature Alignment (GFA) for training GANs, especially on resource-constrained hardware.
The Core Problem:
Standard GANs operate in an adversarial (zero-sum) manner. The generator (G) tries to fool the discriminator (D), and D tries to catch fakes. This dynamic often leads to:
- Instability: Vanishing/exploding gradients, mode collapse.
- Oscillating Losses: Neither G nor D consistently improves; they might overpower each other cyclically.
- High Resource Needs: Often require large batch sizes and deep networks for stability and quality, which is challenging on commodity hardware.
The Novel Theory: Guided Feature Alignment (GFA)
GFA reframes the GAN training as a collaborative process focused on aligning feature representations learned by the discriminator.
- Collaboration: Instead of just classifying real vs. fake, the discriminator also acts as a feature extractor. It learns meaningful representations of the data distribution in its intermediate layers. G's goal is modified: not only to fool D's final classification but also to generate samples whose intermediate feature representations (as judged by D) match those of real data.
- Decreasing Loss: By explicitly minimizing the difference between the feature distributions of real and generated data (using D's internal representations), we provide a smoother, more direct learning signal to G. This signal helps G improve more consistently. As G gets better at matching features, it generates more realistic samples, which improves D's ability to classify correctly and refine its feature extraction. This shared progress leads to a more stable training dynamic where both losses tend to decrease more monotonically.
Mathematical Formulation:
Let:
x_real: Real data samples.
z: Noise vector.
G(z): Generated samples.
D: Discriminator network.
D_intermediate(x): The output of an intermediate layer in D (before the final classification layer).
L_adv: Standard adversarial loss (e.g., Binary Cross-Entropy).
L_feat: Feature matching loss (e.g., Mean Squared Error between feature distributions).
Standard GAN Losses:
L_D = E[log(D(x_real))] + E[log(1 - D(G(z)))] (or variants like WGAN loss)
L_G = E[log(1 - D(G(z)))] (or E[-log(D(G(z)))] for non-saturating)
GFA Losses:
-
Discriminator Loss (L_D_GFA):
- Standard adversarial classification loss.
- Optional: Add a loss term to encourage D to produce discriminative intermediate features (e.g., encourage variance or separation, though this adds complexity). For simplicity, we'll focus on the standard term.
L_D_GFA = E[-log(D(x_real))] - E[log(D(G(z)))] (Using standard BCE formulation for clarity)
-
Generator Loss (L_G_GFA):
- Standard adversarial loss (G wants D to classify its output as real).
- Feature Alignment Term: G aims to minimize the distance between the intermediate features of its generated samples and the intermediate features of real samples, using D as the feature extractor.
L_G_GFA = E[-log(D(G(z)))] + lambda * L_feat
- Where
L_feat could be:
MSE( mean(D_intermediate(G(z))), mean(D_intermediate(x_real)) ) - Matching the mean features.
- Or potentially matching higher-order moments or using distributions like MMD, but MSE on means is simpler and often effective.
lambda is a hyperparameter balancing the two terms.
Why it Works on Commodity Hardware:
- Smoother Gradients: The
L_feat term provides a more stable gradient for G, less prone to vanishing.
- Reduced Mode Collapse: By forcing G to match the feature distribution, it encourages G to cover more modes of the real data distribution.
- Potential for Smaller Batches: The improved stability might allow effective training with smaller batch sizes, which are often necessary on commodity hardware due to memory limitations. Gradient accumulation can further simulate larger batches if needed.
- Simpler Architectures: GFA can potentially work better with smaller, less complex generator and discriminator networks compared to standard GANs needing vast capacity to overcome instability.
PyTorch 1D Example: Generating Simple Sine Waves
Let's implement a simplified GFA GAN to generate basic 1D sine wave signals.
1. Setup and Imports
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np
# Configuration
batch_size = 32
signal_length = 128
latent_dim = 64
lr = 0.0002
epochs = 500 # Adjust as needed
lambda_feat = 10.0 # Weight for the feature matching loss
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# --- Data Generation ---
def generate_real_batch(batch_size, signal_length):
# Generate slightly varying sine waves
freq = torch.rand(batch_size, 1) * 2.0 + 0.5 # Frequency between 0.5 and 2.5
phase = torch.rand(batch_size, 1) * np.pi # Phase between 0 and pi
time = torch.linspace(0, 1, signal_length).unsqueeze(0).repeat(batch_size, 1)
amplitude = torch.rand(batch_size, 1) * 0.5 + 0.5 # Amplitude between 0.5 and 1.0
noise = torch.randn(batch_size, signal_length) * 0.05 # Small noise
real_signals = amplitude * torch.sin(2 * np.pi * freq * time + phase) + noise
return real_signals.unsqueeze(1) # Add channel dimension (batch, channels, length)
# --- Models ---
# Simple Generator: Maps latent vector to a signal
class Generator(nn.Module):
def __init__(self, latent_dim, signal_length):
super().__init__()
# Simple linear layers + reshaping approach
hidden_dim = 256
self.net = nn.Sequential(
nn.Linear(latent_dim, hidden_dim),
nn.ReLU(True),
nn.Linear(hidden_dim, hidden_dim * 2),
nn.ReLU(True),
nn.Linear(hidden_dim * 2, signal_length), # Output raw signal values
# Optional: Add a Tanh if you want to bound output, e.g., [-1, 1]
# nn.Tanh()
)
def forward(self, z):
signal = self.net(z)
return signal.unsqueeze(1) # Add channel dim: (batch, channels, length)
# Simple Discriminator with intermediate feature extraction
class Discriminator(nn.Module):
def __init__(self, signal_length):
super().__init__()
# Use Conv1d for sequence processing
self.conv_layers = nn.Sequential(
nn.Conv1d(1, 32, kernel_size=5, stride=2, padding=2), # Output: 32x64
nn.LeakyReLU(0.2, inplace=True),
nn.Conv1d(32, 64, kernel_size=5, stride=2, padding=2), # Output: 64x32
nn.LeakyReLU(0.2, inplace=True),
nn.Conv1d(64, 128, kernel_size=5, stride=2, padding=2), # Output: 128x16
nn.LeakyReLU(0.2, inplace=True),
nn.Conv1d(128, 256, kernel_size=5, stride=2, padding=2), # Output: 256x8
nn.LeakyReLU(0.2, inplace=True),
)
# Calculate flattened size dynamically or estimate
# With kernel=5, stride=2, padding=2:
# 128 -> 64 -> 32 -> 16 -> 8
flattened_size = 256 * 8
# Intermediate layer for feature extraction (e.g., after conv blocks)
self.intermediate_layer = nn.Linear(flattened_size, 128)
self.intermediate_activation = nn.LeakyReLU(0.2, inplace=True)
# Final classification layer
self.final_layer = nn.Linear(128, 1) # Single output for real/fake score
def forward(self, x):
features = self.conv_layers(x)
features_flat = features.view(features.size(0), -1) # Flatten
intermediate_features = self.intermediate_activation(self.intermediate_layer(features_flat))
validity_score = torch.sigmoid(self.final_layer(intermediate_features)) # Output score [0, 1]
# Return both the final classification score and intermediate features
return validity_score, intermediate_features
# --- GFA Training ---
# Initialize models, optimizers
generator = Generator(latent_dim, signal_length).to(device)
discriminator = Discriminator(signal_length).to(device)
optimizer_G = optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.999))
optimizer_D = optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.999))
# Loss functions
adversarial_loss = nn.BCELoss() # Standard BCE for D output score
feature_loss = nn.MSELoss() # MSE for matching intermediate features
# Store losses for plotting
g_losses = []
d_losses = []
# --- Training Loop ---
print("Starting Training...")
for epoch in range(epochs):
# Generate real data and noise
real_signals = generate_real_batch(batch_size, signal_length).to(device)
z = torch.randn(batch_size, latent_dim).to(device)
# --- Train Discriminator ---
optimizer_D.zero_grad()
# Real samples
real_validity, real_inter_features = discriminator(real_signals)
d_real_loss = adversarial_loss(real_validity, torch.ones_like(real_validity))
# Fake samples
fake_signals = generator(z)
fake_validity, fake_inter_features = discriminator(fake_signals.detach()) # Detach to avoid training G here
d_fake_loss = adversarial_loss(fake_validity, torch.zeros_like(fake_validity))
# Total Discriminator loss
d_loss = (d_real_loss + d_fake_loss) / 2
# Backpropagate Discriminator loss
d_loss.backward()
optimizer_D.step()
# --- Train Generator ---
optimizer_G.zero_grad()
# Generate fresh fake samples and get their discriminator outputs/features
z = torch.randn(batch_size, latent_dim).to(device)
fake_signals = generator(z)
validity, inter_features = discriminator(fake_signals) # Pass generated signal through D
# Generator adversarial loss (wants validity to be 1)
g_adv_loss = adversarial_loss(validity, torch.ones_like(validity))
# Generator feature matching loss (matches features of fake vs real)
# Note: We use the real features computed during D's update step
g_feat_loss = feature_loss(inter_features, real_inter_features.detach())
# Total Generator loss (GFA)
g_loss = g_adv_loss + lambda_feat * g_feat_loss
# Backpropagate Generator loss
g_loss.backward()
optimizer_G.step()
# Store losses
g_losses.append(g_loss.item())
d_losses.append(d_loss.item())
# Print progress
if (epoch + 1) % 100 == 0:
print(f"[Epoch {epoch+1}/{epochs}] [D loss: {d_loss.item():.4f}] [G loss: {g_loss.item():.4f}]")
# Optionally: Plot a generated sample
with torch.no_grad():
plt.figure(figsize=(12, 3))
sample_z = torch.randn(1, latent_dim).to(device)
generated_sample = generator(sample_z).cpu().squeeze().numpy()
real_sample = generate_real_batch(1, signal_length).cpu().squeeze().numpy()
plt.plot(generated_sample, label='Generated')
plt.plot(real_sample[0], label='Real (Example)', alpha=0.7) # Plot one real example for comparison
plt.title(f"Epoch {epoch+1} Sample")
plt.legend()
plt.show()
print("Training Finished.")
# --- Plotting Losses ---
plt.figure(figsize=(10, 5))
plt.plot(range(len(g_losses)), g_losses, label='Generator Loss')
plt.plot(range(len(d_losses)), d_losses, label='Discriminator Loss')
plt.title('GFA GAN Training Losses')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.show()
# --- Generate Final Samples ---
with torch.no_grad():
num_samples = 5
z_final = torch.randn(num_samples, latent_dim).to(device)
final_samples = generator(z_final).cpu().squeeze().numpy()
plt.figure(figsize=(12, 8))
for i in range(num_samples):
plt.subplot(num_samples, 1, i + 1)
plt.plot(final_samples[i])
plt.title(f"Final Generated Sample {i+1}")
plt.ylim(-1.5, 1.5) # Adjust ylim based on generator output activation
plt.tight_layout()
plt.show()
Explanation of the Code:
- Models: We define a simple
Generator using linear layers and a Discriminator using Conv1d layers, suitable for 1D sequences. Crucially, the Discriminator's forward method returns both the final validity_score (between 0 and 1) and the intermediate_features from a layer before the final output.
- Data: A function
generate_real_batch creates batches of noisy sine waves with varying frequencies, phases, and amplitudes.
- Losses: We use standard
BCELoss for the adversarial part and MSELoss for the feature matching part.
- Training Loop:
- D Update: Calculates the standard loss on real (target=1) and fake (target=0) samples and updates D's weights. We store the intermediate features from both real and fake passes (
real_inter_features, fake_inter_features). Note that fake_inter_features are computed from detached fake samples.
- G Update:
- Generates fake samples and passes them through D to get
validity and inter_features.
- Calculates the adversarial loss (
g_adv_loss) trying to make validity close to 1.
- Calculates the feature matching loss (
g_feat_loss) using MSE between the current fake features (inter_features) and the features from a real batch computed during D's update (real_inter_features.detach()). This is the core GFA step.
- Combines these losses (
g_loss = g_adv_loss + lambda_feat * g_feat_loss).
- Updates G's weights.
- Monitoring: Losses are tracked, and periodically, generated samples are plotted to visualize progress.
This GFA approach provides a more structured and potentially stable way to train GANs, making it more amenable to commodity hardware by leveraging the discriminator's learned representations as a collaborative guidance mechanism for the generator.