chinmayjs's picture
Upload 7 files
c2ca908 verified
Raw History Blame Contribute Delete
41.3 kB
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
from diffusers import AutoencoderKL, UNet2DConditionModel
from diffusers.schedulers import DDPMScheduler # Keep scheduler for noise addition
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
import os
import random
from transformers import CLIPTextModel, CLIPTokenizer
from accelerate import Accelerator, InitProcessGroupKwargs, DistributedDataParallelKwargs
from accelerate.utils import DistributedType, broadcast_object_list
import torch.distributed as dist
import pickle
import glob
from datetime import timedelta
import traceback
import sys
import math # Added for PSNR
import matplotlib # Added for plotting
matplotlib.use('Agg') # Use Agg backend for non-interactive plotting
import matplotlib.pyplot as plt # Added for plotting
# --- Configuration ---
# Core Model & Data Paths (MUST BE UPDATED BY USER)
SD_MODEL_ID = "runwayml/stable-diffusion-v1-5" # Base model for UNet/VAE arch
CLIP_MODEL_NAME = "openai/clip-vit-large-patch14" # For action conditioning
VAE_PATH = "./models/vae_full_finetuned_stage2_v10_api_fix_corrected.pth" # Optional: Path to fine-tuned VAE weights
DATA_DIR = "./dataset/" # <<< UPDATE PATH to dataset generated by your script
EPISODE_FILE_PREFIX = "" # <<< UPDATE if filenames differ
CHECKPOINT_DIR = "./training_diffusion/" # <<< UPDATE PATH (use new dir)
# Image & Latent Dimensions
IMAGE_RESOLUTION = 512 # Set to 512x512
VAE_SCALE_FACTOR = 0.18215
LATENT_CHANNELS = 4 # Standard for SD VAE (UNet input/output channels)
EXPECTED_FRAME_SHAPE = (3, IMAGE_RESOLUTION, IMAGE_RESOLUTION) # CHW format
# Training Hyperparameters (ADJUST AS NEEDED)
BATCH_SIZE = 8 # Per GPU
LEARNING_RATE = 1e-5
TOTAL_EPOCHS = 10
FREEZE_CLIP_BACKBONE = False # Train only ActionConditioner projection layers
# PREDICTION_TYPE = "sample" # Set prediction type for scheduler if used beyond add_noise
# Scheduler & Clipping
SCHEDULER_PATIENCE = 5
SCHEDULER_FACTOR = 0.2
GRADIENT_CLIP_MAX_NORM = 1.0
# Timesteps for Diffusion Noise Addition
# Needs to match scheduler config during init if different from default (1000)
NUM_TRAIN_TIMESTEPS = 1000 # Default for DDPMScheduler from SD v1.5
# Max noise step to sample from (can be less than NUM_TRAIN_TIMESTEPS)
# This matches `max_noise_steps` from the Bible script's config
MAX_NOISE_STEP_SAMPLE = 200
# Loss Weights
MSE_WEIGHT = 1.0 # Direct MSE between predicted and actual next latent
# Logging/Saving/Workers
SAVE_CHECKPOINT_EVERY_N_EPOCHS = 2
DATALOADER_NUM_WORKERS = 12
# Optimization Config
USE_BF16 = False
GRADIENT_ACCUMULATION_STEPS = 1
# Debugging Config
DEBUG_FIRST_N_BATCHES = 5
# PSNR Config
# Data range for PSNR calculation on latents.
# Since latents are scaled and don't have a fixed 0-255 range,
# we use 1.0 as a reference maximum value for the normalized space.
# Adjust if your VAE scaling leads to significantly different latent ranges.
PSNR_DATA_RANGE = 1.0
# -------------------------------------------------------------------
# 1. Model Definitions (ActionConditioner only)
# -------------------------------------------------------------------
class ActionConditioningModule(nn.Module):
""" Encodes action strings using CLIP and projects to target dimension. """
def __init__(
self,
clip_model_name: str = CLIP_MODEL_NAME,
max_clip_length: int = 16,
target_token_dim: int = 768,
freeze_clip: bool = True
):
super().__init__()
self.target_token_dim = target_token_dim
self.max_clip_length = max_clip_length
self.freeze_clip = freeze_clip
print(f"[ActionConditioner] Initializing with CLIP: {clip_model_name}")
self.clip_tokenizer = CLIPTokenizer.from_pretrained(clip_model_name)
self.clip_text_model = CLIPTextModel.from_pretrained(clip_model_name)
clip_output_dim = self.clip_text_model.config.hidden_size
print(f"[ActionConditioner] CLIP output dim: {clip_output_dim}")
if freeze_clip:
print("[ActionConditioner] Freezing CLIP text model parameters.")
for param in self.clip_text_model.parameters(): param.requires_grad = False
self.clip_text_model.eval()
else: print("[ActionConditioner] CLIP text model parameters are TRAINABLE.")
self.action_projection1 = nn.Linear(clip_output_dim, clip_output_dim)
self.action_projection2 = nn.Linear(clip_output_dim, target_token_dim)
print(f"[ActionConditioner] Added projection layers: {clip_output_dim}->{clip_output_dim}, {clip_output_dim}->{target_token_dim}")
def forward(self, action_strings, device):
b = len(action_strings)
clip_inputs = self.clip_tokenizer(action_strings, padding="max_length", truncation=True, max_length=self.max_clip_length, return_tensors="pt").to(device)
context_manager = torch.no_grad() if self.freeze_clip else torch.enable_grad()
with context_manager:
if self.freeze_clip: self.clip_text_model.eval()
outputs = self.clip_text_model(**clip_inputs)
last_hidden = outputs.last_hidden_state
eos_token_id = self.clip_tokenizer.eos_token_id
input_ids = clip_inputs["input_ids"]
batch_size, seq_len = last_hidden.shape[0], last_hidden.shape[1]
eos_mask = (input_ids == eos_token_id)
eos_indices = torch.where(eos_mask.any(dim=1), eos_mask.max(dim=1).indices, torch.tensor(seq_len - 1, device=device))
eos_indices = eos_indices.clamp(0, seq_len - 1)
pooled = last_hidden[torch.arange(batch_size, device=device), eos_indices]
x = F.silu(self.action_projection1(pooled))
x = self.action_projection2(x)
return x.unsqueeze(1)
# -------------------------------------------------------------------
# 2. Dataset Loader (Handles HWC -> CHW permutation)
# -------------------------------------------------------------------
class ConsolidatedTripletDataset(Dataset):
"""
Loads (previous_frame, action, target_frame) triplets.
Expects HWC input, permutes to CHW, outputs CHW [-1, 1].
"""
def __init__(self, data_dir, episode_prefix="", expected_chw_shape=(3, 512, 512), accelerator=None):
if accelerator is None: raise ValueError("Accelerator instance must be provided.")
self.accelerator = accelerator; self.data_dir = data_dir; self.episode_prefix = episode_prefix
self.target_chw_shape = expected_chw_shape # CHW
self.source_hwc_shape = (expected_chw_shape[1], expected_chw_shape[2], expected_chw_shape[0]) # HWC
self.accelerator.print(f"[Dataset] Init: '{data_dir}', Prefix: '{episode_prefix}', Output CHW: {self.target_chw_shape}")
self.index_map, self.total_transitions = [], 0; object_to_broadcast = [([], 0)]
if self.accelerator.is_main_process:
try:
self.index_map, self.total_transitions = self._build_index_map()
object_to_broadcast = [(self.index_map, self.total_transitions)]
self.accelerator.print(f"[Dataset] Main found {self.total_transitions} transitions across {len(self.index_map)} files.")
if self.total_transitions == 0: self._print_critical_warning()
except Exception as e: self.accelerator.print(f"[Dataset] FATAL build map: {e}"); traceback.print_exc(); object_to_broadcast = [([], 0)]
self.accelerator.wait_for_everyone(); broadcast_object_list(object_to_broadcast, 0); self.accelerator.wait_for_everyone()
self.index_map, self.total_transitions = object_to_broadcast[0]
self.accelerator.print(f"[Dataset] Proc {accelerator.process_index} received map. Total: {self.total_transitions}")
if self.total_transitions == 0 and self.accelerator.is_main_process: self._print_critical_warning()
self.cached_file_path, self.cached_data = None, None
def _print_critical_warning(self): self.accelerator.print(f"!!!!!!!!!! [CRIT DATASET WARN] 0 transitions found. Check DATA_DIR/EPISODE_FILE_PREFIX/shapes !!!!!!!!!!!!")
def _build_index_map(self):
idx_map, total_trans, cum_trans = [], 0, 0
pattern = os.path.join(self.data_dir, f"{self.episode_prefix}*.pth")
files = sorted(glob.glob(pattern))
if not files: self.accelerator.print(f"[Dataset] Warn: No files: {pattern}"); return [], 0
iterator = tqdm(files, "[Dataset] Scan", disable=not self.accelerator.is_main_process, leave=False)
for fpath in iterator:
try:
if not os.path.exists(fpath) or os.path.getsize(fpath)<100: continue
data = torch.load(fpath, 'cpu')
if not isinstance(data, dict) or not all(k in data for k in ['p','a','t']): data={'p':data.get('previous_frames'),'a':data.get('actions'),'t':data.get('target_frames')} # Alias check
if not isinstance(data['p'], torch.Tensor) or not isinstance(data['t'], torch.Tensor) or not isinstance(data['a'], list): continue
n = data['p'].shape[0]; fshape = data['p'].shape[1:]
if n==0 or len(data['a'])!=n or data['t'].shape[0]!=n or data['p'].ndim!=4 or data['t'].ndim!=4: continue
perm = False;
if fshape == self.source_hwc_shape: perm = True
elif fshape == self.target_chw_shape: perm = False
else: continue
if not all(isinstance(act, str) and act for act in data['a']): continue
idx_map.append((cum_trans, n, fpath, perm)); cum_trans+=n; total_trans+=n
except Exception as e: pass # Ignore individual file errors during scan
return idx_map, total_trans
def __len__(self): return self.total_transitions
def _find_episode(self, idx):
for start, num, path, permute in self.index_map:
if start <= idx < start + num: return path, idx - start, permute
raise IndexError(f"[Dataset ERROR] Index {idx} OoB ({self.total_transitions})")
def __getitem__(self, idx):
if not (0 <= idx < self.total_transitions): return torch.zeros(self.target_chw_shape), "<err_idx>", torch.zeros(self.target_chw_shape)
fpath, idx_in_file, needs_permute = "Unk", -1, False
try:
fpath, idx_in_file, needs_permute = self._find_episode(idx)
if fpath != self.cached_file_path or self.cached_data is None:
try: self.cached_data = torch.load(fpath,'cpu'); self.cached_file_path=fpath;
except Exception: self.cached_file_path,self.cached_data=None,None; return torch.zeros(self.target_chw_shape), f"<err_load_{os.path.basename(fpath)}>", torch.zeros(self.target_chw_shape)
prev_f = self.cached_data['previous_frames'][idx_in_file]; target_f = self.cached_data['target_frames'][idx_in_file]; act_s = self.cached_data['actions'][idx_in_file]
if needs_permute: prev_f=prev_f.permute(2,0,1).contiguous(); target_f=target_f.permute(2,0,1).contiguous()
if prev_f.shape!=self.target_chw_shape or target_f.shape!=self.target_chw_shape: raise ValueError(f"Shape mismatch {prev_f.shape}")
prev_f=torch.clamp(prev_f.float(),-1.,1.); target_f=torch.clamp(target_f.float(),-1.,1.)
if not isinstance(act_s, str) or not act_s: act_s = "<err_act>"
return prev_f, act_s, target_f
except Exception as e: self.cached_file_path,self.cached_data=None,None; return torch.zeros(self.target_chw_shape), "<err_getitem>", torch.zeros(self.target_chw_shape)
# -------------------------------
# 3. Checkpoint Utilities
# -------------------------------
def save_checkpoint(accelerator, epoch, checkpoint_dir, **models_to_save):
if accelerator.is_main_process:
abs_checkpoint_dir = os.path.abspath(checkpoint_dir)
accelerator.print(f"[Checkpoint] Saving epoch {epoch} to '{abs_checkpoint_dir}'...")
try:
os.makedirs(abs_checkpoint_dir, exist_ok=True)
accelerator.save_state(abs_checkpoint_dir)
accelerator.print(f"[Checkpoint] Accelerator state saved.")
accelerator.print(f"[Checkpoint] Saving individual unwrapped models...")
for name, model in models_to_save.items():
if model is not None:
try:
model_path = os.path.join(abs_checkpoint_dir, f"{name}_epoch_{epoch}.pth")
accelerator.save(accelerator.unwrap_model(model).state_dict(), model_path)
accelerator.print(f"[Checkpoint] Saved '{name}'.")
except Exception as err: accelerator.print(f"[Checkpoint] Warn: Save '{name}' failed: {err}.")
save_epoch_metadata(epoch, abs_checkpoint_dir)
accelerator.print(f"[Checkpoint] Checkpoint saving complete for epoch {epoch}.")
except Exception as e: accelerator.print(f"!!!!!!!!!! [CRITICAL CHECKPOINT ERROR] Epoch {epoch} Save Failed !!!!!!!!!!\n{e}\n{traceback.format_exc()}")
def load_checkpoint(accelerator, checkpoint_dir):
start_epoch = 0
abs_checkpoint_dir = os.path.abspath(checkpoint_dir)
accelerator.print(f"[Checkpoint] Proc {accelerator.process_index} loading from '{abs_checkpoint_dir}'...")
if os.path.isdir(abs_checkpoint_dir):
try:
accelerator.load_state(abs_checkpoint_dir)
accelerator.print(f"[Checkpoint] State loaded on proc {accelerator.process_index}.")
if accelerator.is_main_process:
metadata_path = os.path.join(abs_checkpoint_dir, "metadata_epoch.pt")
if os.path.exists(metadata_path):
try: start_epoch = torch.load(metadata_path, map_location='cpu').get('epoch', 0)
except Exception: start_epoch = 0
accelerator.print(f"[Checkpoint] Loaded metadata. Last epoch: {start_epoch}.")
else: accelerator.print(f"[Checkpoint] Warn: metadata_epoch.pt not found. Assuming epoch 0.")
start_epoch_list = [start_epoch]; broadcast_object_list(start_epoch_list, 0); start_epoch = start_epoch_list[0]
accelerator.print(f"[Checkpoint] Proc {accelerator.process_index} received start_epoch: {start_epoch}")
except Exception as e:
accelerator.print(f"!!!!!!!!!! [CHECKPOINT LOAD ERROR] !!!!!!!!!!!!\n{type(e).__name__}: {e}\nStarting from scratch.")
start_epoch = 0; start_epoch_list = [0]; broadcast_object_list(start_epoch_list, 0); start_epoch = 0
else: accelerator.print(f"[Checkpoint] Directory not found. Starting scratch.")
accelerator.wait_for_everyone()
accelerator.print(f"[Checkpoint] Proc {accelerator.process_index} starts after epoch {start_epoch}.")
return start_epoch
def save_epoch_metadata(epoch, checkpoint_dir):
if (dist.is_initialized() and dist.get_rank() == 0) or not dist.is_initialized():
try: torch.save({'epoch': epoch}, os.path.join(checkpoint_dir, "metadata_epoch.pt"))
except Exception as e: print(f"[Metadata Save Warn] {e}")
# -------------------------------------------------------------------
# 4. VAE Encoding Helper
# -------------------------------------------------------------------
@torch.no_grad()
def encode_images_vae(vae, image_tensors, vae_scale_factor):
vae.eval()
latents = vae.encode(image_tensors.to(dtype=vae.dtype)).latent_dist.mean
latents = latents * vae_scale_factor
return latents
# -------------------------------------------------------------------
# 5. PSNR Calculation Helper
# -------------------------------------------------------------------
def calculate_psnr(mse, data_range=1.0):
"""
Calculates PSNR from MSE.
Args:
mse (float): Mean Squared Error.
data_range (float): The maximum possible pixel value (or data range).
Defaults to 1.0 for normalized latent space.
Returns:
float: PSNR value in dB, or a high value (e.g., 100.0) for zero MSE.
"""
if mse <= 1e-10: # Handle near-zero MSE to avoid log10(inf)
return 100.0
elif mse < 0: # Should not happen with F.mse_loss, but as safeguard
return 0.0
return 10.0 * math.log10((data_range**2) / mse)
# -------------------------------------------------------------------
# 6. Plotting Helper
# -------------------------------------------------------------------
def save_plots(epochs, losses, psnrs, save_dir):
"""Saves plots of loss and PSNR vs epochs."""
if not epochs: # No data to plot
print("[Plotting] No epoch data found, skipping plot generation.")
return
try:
plt.figure(figsize=(10, 5))
plt.plot(epochs, losses, marker='o', linestyle='-')
plt.title('Average Training Loss per Epoch')
plt.xlabel('Epoch')
plt.ylabel('Average MSE Loss')
plt.grid(True)
plt.xticks(epochs) # Ensure epoch numbers are integers on the x-axis
loss_plot_path = os.path.join(save_dir, 'training_loss_plot.png')
plt.savefig(loss_plot_path)
plt.close() # Close the figure to free memory
print(f"[Plotting] Loss plot saved to: {loss_plot_path}")
plt.figure(figsize=(10, 5))
plt.plot(epochs, psnrs, marker='o', linestyle='-', color='r')
plt.title('Average Training PSNR per Epoch')
plt.xlabel('Epoch')
plt.ylabel('Average PSNR (dB)')
plt.grid(True)
plt.xticks(epochs)
psnr_plot_path = os.path.join(save_dir, 'training_psnr_plot.png')
plt.savefig(psnr_plot_path)
plt.close()
print(f"[Plotting] PSNR plot saved to: {psnr_plot_path}")
except Exception as e:
print(f"[Plotting Error] Failed to generate or save plots: {e}")
traceback.print_exc()
# -------------------------------------------------------------------
# 7. Main Training Script Execution
# -------------------------------------------------------------------
if __name__ == '__main__':
# --- Accelerator Initialization ---
init_handler = InitProcessGroupKwargs(timeout=timedelta(seconds=7200))
ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=False)
accelerator = Accelerator(
mixed_precision="fp16" if not USE_BF16 else "bf16",
log_with="tensorboard",
project_dir=os.path.join(CHECKPOINT_DIR, "logs"),
kwargs_handlers=[init_handler, ddp_kwargs],
gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS
)
DEVICE = accelerator.device
TARGET_DTYPE = torch.bfloat16 if USE_BF16 and accelerator.mixed_precision == 'bf16' else torch.float16
# --- Print Setup Info ---
accelerator.print(f"--- Process {accelerator.process_index}/{accelerator.num_processes} Initialized ---")
accelerator.print(f" Device: {DEVICE}, Dist Type: {accelerator.distributed_type}, Mixed Precision: {accelerator.mixed_precision}")
effective_batch_size = BATCH_SIZE * accelerator.num_processes * GRADIENT_ACCUMULATION_STEPS
accelerator.print(f" Per-GPU BS: {BATCH_SIZE}, Grad Accum: {GRADIENT_ACCUMULATION_STEPS}, Effective BS: {effective_batch_size}")
accelerator.print(f" LOGIC: Bible Diffusion Logic (Noise Current -> Predict Next)")
for k, v in {"Checkpoints": CHECKPOINT_DIR, "Dataset": DATA_DIR, "Image Size": IMAGE_RESOLUTION, "Freeze CLIP": FREEZE_CLIP_BACKBONE, "LR": LEARNING_RATE}.items():
accelerator.print(f" {k}: {v}")
# --- Create Dirs ---
if accelerator.is_main_process:
try:
os.makedirs(CHECKPOINT_DIR, exist_ok=True)
os.makedirs(os.path.join(CHECKPOINT_DIR, "logs"), exist_ok=True)
except OSError as e: accelerator.print(f"[Setup FATAL] Cannot create dirs: {e}"); sys.exit(1)
# --- Init Log Trackers ---
if accelerator.is_main_process:
accelerator.print("[Setup] Initializing trackers...")
try:
run_name = f"bible_diff_{SD_MODEL_ID.split('/')[-1]}_effBS{effective_batch_size}"
config_to_log = {k: v for k, v in globals().items() if isinstance(v, (str, int, float, bool)) and k.isupper()}
accelerator.init_trackers(run_name, config=config_to_log)
accelerator.print("[Setup] Trackers initialized.")
except Exception as e: accelerator.print(f"[Setup Warning] Tracker init failed: {e}.")
# --- Initialize Models ---
accelerator.print("[Setup] Initializing models on CPU...")
try:
vae = AutoencoderKL.from_pretrained(SD_MODEL_ID, subfolder="vae")
if VAE_PATH and os.path.exists(VAE_PATH):
accelerator.print(f"[Setup] Loading custom VAE: {VAE_PATH}")
vae.load_state_dict(torch.load(VAE_PATH, map_location='cpu'), strict=False)
vae.requires_grad_(False)
accelerator.print("[Setup] VAE Initialized.")
unet = UNet2DConditionModel.from_pretrained(SD_MODEL_ID, subfolder="unet")
unet_in_channels = unet.config.in_channels
unet_cross_attention_dim = unet.config.cross_attention_dim
if unet_in_channels != LATENT_CHANNELS:
accelerator.print(f"[Setup FATAL] UNet input channels {unet_in_channels} != expected {LATENT_CHANNELS}. Model {SD_MODEL_ID} might be incompatible.")
sys.exit(1)
accelerator.print(f"[Setup] UNet Initialized (Input Channels: {unet_in_channels}).")
action_conditioner = ActionConditioningModule(
target_token_dim=unet_cross_attention_dim,
freeze_clip=FREEZE_CLIP_BACKBONE
)
accelerator.print("[Setup] ActionConditioner Initialized.")
# Initialize DDPMScheduler (used only for add_noise)
try:
scheduler_config = DDPMScheduler.load_config(os.path.join(SD_MODEL_ID, "scheduler/scheduler_config.json"))
train_scheduler = DDPMScheduler.from_config(scheduler_config)
if train_scheduler.config.num_train_timesteps != NUM_TRAIN_TIMESTEPS:
accelerator.print(f"[Setup Warn] Scheduler config timesteps ({train_scheduler.config.num_train_timesteps}) != NUM_TRAIN_TIMESTEPS ({NUM_TRAIN_TIMESTEPS}). Using {train_scheduler.config.num_train_timesteps}.")
NUM_TRAIN_TIMESTEPS = train_scheduler.config.num_train_timesteps # Use actual value
accelerator.print(f"[Setup] DDPMScheduler loaded (Timesteps: {NUM_TRAIN_TIMESTEPS}).")
except Exception as e:
accelerator.print(f"[Setup Warn] Loading scheduler config failed: {e}. Using default DDPM.")
train_scheduler = DDPMScheduler(num_train_timesteps=NUM_TRAIN_TIMESTEPS)
except Exception as e:
accelerator.print(f"[Setup FATAL] Model initialization failed: {e}"); traceback.print_exc(); sys.exit(1)
# --- Parameters, Optimizer, Scheduler ---
params_to_optimize = list(unet.parameters())
if hasattr(action_conditioner, 'action_projection1'): params_to_optimize.extend(action_conditioner.action_projection1.parameters())
if hasattr(action_conditioner, 'action_projection2'): params_to_optimize.extend(action_conditioner.action_projection2.parameters())
if not FREEZE_CLIP_BACKBONE and hasattr(action_conditioner, 'clip_text_model'): params_to_optimize.extend(p for p in action_conditioner.clip_text_model.parameters() if p.requires_grad)
num_trainable_params = sum(p.numel() for p in params_to_optimize if p.requires_grad)
accelerator.print(f"[Setup] Total trainable parameters: {num_trainable_params:,}")
optimizer = optim.AdamW(params_to_optimize, lr=LEARNING_RATE, fused=(DEVICE.type == "cuda"))
lr_scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=SCHEDULER_FACTOR, patience=SCHEDULER_PATIENCE)
accelerator.print("[Setup] Optimizer and LR Scheduler initialized.")
# --- Dataset and Dataloader ---
accelerator.print("[Setup] Initializing Dataset and Dataloader...")
try:
dataset = ConsolidatedTripletDataset(
data_dir=DATA_DIR, episode_prefix=EPISODE_FILE_PREFIX,
expected_chw_shape=EXPECTED_FRAME_SHAPE, accelerator=accelerator,
)
if len(dataset) == 0: raise ValueError("Dataset empty after init.")
accelerator.print(f"[Setup] Dataset initialized: {len(dataset)} transitions.")
dataloader = DataLoader(
dataset, batch_size=BATCH_SIZE, shuffle=True,
num_workers=DATALOADER_NUM_WORKERS, pin_memory=True, drop_last=True,
persistent_workers=(DATALOADER_NUM_WORKERS > 0), prefetch_factor=4
)
accelerator.print("[Setup] DataLoader created.")
except Exception as e:
accelerator.print(f"[Setup FATAL] Dataset/Dataloader error: {e}."); traceback.print_exc()
if accelerator.distributed_type != DistributedType.NO: dist.barrier(); sys.exit(1)
# --- Prepare with Accelerator ---
accelerator.print("[Setup] Preparing components with Accelerator...")
components_to_prepare = [unet, action_conditioner, optimizer, dataloader, lr_scheduler, vae]
unet, action_conditioner, optimizer, dataloader, lr_scheduler, vae = accelerator.prepare(*components_to_prepare)
accelerator.print("[Setup] Components prepared.")
# --- Load Checkpoint AFTER prepare() ---
accelerator.print(f"[Setup] Loading checkpoint...")
start_epoch = load_checkpoint(accelerator, CHECKPOINT_DIR)
try: steps_per_epoch = len(dataloader) // accelerator.gradient_accumulation_steps
except TypeError: steps_per_epoch = 1000 # Fallback if dataloader length isn't available early
global_step = start_epoch * steps_per_epoch
accelerator.print(f"[Setup] Resuming after epoch {start_epoch}. Global step ~{global_step}")
# --- Plotting Data Storage (Main Process Only) ---
epoch_losses_history = []
epoch_psnrs_history = []
epochs_plotted_history = []
# --- Training Loop ---
accelerator.print(f"\n{'='*20} Starting Training {'='*20}")
vae.eval() # Keep VAE in eval mode
for epoch in range(start_epoch, TOTAL_EPOCHS):
epoch_num = epoch + 1
current_lr = optimizer.param_groups[0]['lr']
accelerator.print(f"\n--- Starting Epoch {epoch_num}/{TOTAL_EPOCHS} | LR: {current_lr:.2e} ---")
unet.train(); action_conditioner.train()
if not FREEZE_CLIP_BACKBONE and hasattr(action_conditioner, 'clip_text_model'): action_conditioner.clip_text_model.train()
epoch_total_loss_sum, epoch_mse_loss_sum, epoch_psnr_sum = 0.0, 0.0, 0.0 # Added psnr sum
num_batches_processed, epoch_skipped_batches = 0, 0
progress_bar = tqdm(dataloader, desc=f"E{epoch_num} P{accelerator.process_index}", disable=not accelerator.is_local_main_process, total=len(dataloader))
for step, batch in enumerate(progress_bar):
is_debug_step = (epoch == start_epoch and step < DEBUG_FIRST_N_BATCHES)
if is_debug_step: accelerator.print(f"\n[DEBUG E1S<{DEBUG_FIRST_N_BATCHES}] Batch {step+1} Start (Global Step ~{global_step})")
with accelerator.accumulate(unet):
try:
# 1. Unpack & Validate (Data is CHW [-1, 1])
prev_img_chw, actions, target_img_chw = batch
bsz = prev_img_chw.shape[0]
if bsz == 0 or any(a.startswith("<err") for a in actions): # Check for placeholder error actions too
epoch_skipped_batches += 1; continue
if is_debug_step:
accelerator.print(f"[DEBUG] Batch Validated: Size={bsz}, First Action='{actions[0]}'")
accelerator.print(f"[DEBUG] prev_img shape={prev_img_chw.shape}") # CHW
# 2. VAE Encode current (prev) and target (next) frames
prev_img_chw, target_img_chw = prev_img_chw.to(DEVICE), target_img_chw.to(DEVICE)
current_latent = encode_images_vae(vae, prev_img_chw, VAE_SCALE_FACTOR).to(dtype=TARGET_DTYPE)
actual_next_latent = encode_images_vae(vae, target_img_chw, VAE_SCALE_FACTOR).to(dtype=TARGET_DTYPE)
# NaN/Inf Check
if torch.isnan(current_latent).any() or torch.isinf(current_latent).any() or \
torch.isnan(actual_next_latent).any() or torch.isinf(actual_next_latent).any():
accelerator.print(f"[CRIT WARN E{epoch_num} S{step+1}] NaN/Inf in VAE latents! Clamping.")
current_latent, actual_next_latent = torch.nan_to_num(current_latent), torch.nan_to_num(actual_next_latent)
if is_debug_step:
accelerator.print(f"[DEBUG] VAE Encoded:")
accelerator.print(f"[DEBUG] current_latent shape={current_latent.shape}, dtype={current_latent.dtype}, range=({current_latent.min():.3f},{current_latent.max():.3f})")
accelerator.print(f"[DEBUG] actual_next_latent shape={actual_next_latent.shape}, dtype={actual_next_latent.dtype}, range=({actual_next_latent.min():.3f},{actual_next_latent.max():.3f})")
# 3. Action Embedding
action_emb = action_conditioner(list(actions), device=DEVICE).to(dtype=TARGET_DTYPE)
if is_debug_step: accelerator.print(f"[DEBUG] Action Embedding: shape={action_emb.shape}")
# 4. Add Noise to CURRENT latent (Bible Logic Step)
diff_noise = torch.randn_like(current_latent)
# Sample timesteps, but only up to MAX_NOISE_STEP_SAMPLE
timesteps = torch.randint(0, MAX_NOISE_STEP_SAMPLE, (bsz,), device=DEVICE).long()
noisy_current_latent = train_scheduler.add_noise(current_latent, diff_noise, timesteps).to(dtype=TARGET_DTYPE)
# NaN/Inf Check
if torch.isnan(noisy_current_latent).any() or torch.isinf(noisy_current_latent).any():
accelerator.print(f"[CRIT WARN E{epoch_num} S{step+1}] NaN/Inf after adding noise! T avg: {timesteps.float().mean().item():.1f}. Clamping.")
noisy_current_latent = torch.nan_to_num(noisy_current_latent)
if is_debug_step:
accelerator.print(f"[DEBUG] Noise Added to Current Latent:")
accelerator.print(f"[DEBUG] noisy_current_latent shape={noisy_current_latent.shape}, range=({noisy_current_latent.min():.3f},{noisy_current_latent.max():.3f})")
accelerator.print(f"[DEBUG] Timesteps sampled (0-{MAX_NOISE_STEP_SAMPLE-1}): avg={timesteps.float().mean().item():.1f}")
# 5. UNet Prediction (Input: noisy current latent, Condition: action)
predicted_next_latent = unet(
sample=noisy_current_latent, # Noisy current state
timestep=timesteps, # Timestep corresponding to noise level
encoder_hidden_states=action_emb # Action conditioning
).sample
if torch.isnan(predicted_next_latent).any() or torch.isinf(predicted_next_latent).any():
accelerator.print(f"[CRIT WARN E{epoch_num} S{step+1}] NaN/Inf in UNet output! Clamping.")
predicted_next_latent = torch.nan_to_num(predicted_next_latent)
if is_debug_step:
accelerator.print(f"[DEBUG] UNet Prediction (Predicted Next Latent): shape={predicted_next_latent.shape}, range=({predicted_next_latent.min():.3f},{predicted_next_latent.max():.3f})")
# 6. Loss & Metric Calculation
mse_loss = F.mse_loss(predicted_next_latent.float(), actual_next_latent.float(), reduction="mean")
step_psnr_val = 0.0 # Default PSNR if loss is invalid
total_loss = None
if torch.isnan(mse_loss).any() or torch.isinf(mse_loss).any():
accelerator.print(f"[CRIT WARN E{epoch_num} S{step+1}] NaN/Inf in MSE loss! Skipping backward.")
else:
total_loss = mse_loss * MSE_WEIGHT
# Calculate PSNR only if loss is valid
step_psnr_val = calculate_psnr(mse_loss.item(), data_range=PSNR_DATA_RANGE)
if is_debug_step: accelerator.print(f"[DEBUG] Loss = {mse_loss.item() if total_loss is not None else 'NaN/Inf'}, PSNR = {step_psnr_val:.2f} dB")
# 7. Backward & Optimize
if total_loss is not None:
accelerator.backward(total_loss)
if accelerator.sync_gradients:
if GRADIENT_CLIP_MAX_NORM: accelerator.clip_grad_norm_(params_to_optimize, GRADIENT_CLIP_MAX_NORM)
optimizer.step()
optimizer.zero_grad(set_to_none=True)
global_step += 1
if is_debug_step: accelerator.print(f"[DEBUG] Optimizer Step Taken. Global Step -> {global_step}")
elif is_debug_step: accelerator.print(f"[DEBUG] Accumulating Gradients...")
# --- Gather Metrics ---
metrics_to_gather = {
"mse": mse_loss.detach(),
"total": total_loss.detach(),
"psnr": torch.tensor(step_psnr_val, device=DEVICE) # Gather PSNR too
}
gathered_metrics = accelerator.gather_for_metrics(metrics_to_gather)
# Calculate mean of gathered metrics for this step
step_mse = gathered_metrics["mse"].mean().item()
step_total = gathered_metrics["total"].mean().item()
step_psnr = gathered_metrics["psnr"].mean().item()
# Accumulate for epoch averages
epoch_mse_loss_sum += step_mse
epoch_total_loss_sum += step_total
epoch_psnr_sum += step_psnr
num_batches_processed += 1
else:
# Handle case where loss was NaN/Inf
epoch_skipped_batches += 1
# Ensure gradients are zeroed even if step wasn't taken due to invalid loss,
# especially relevant when gradient accumulation is used.
if not accelerator.sync_gradients:
optimizer.zero_grad(set_to_none=True)
# --- Batch Exception Handling ---
except torch.cuda.OutOfMemoryError as e:
accelerator.print("\n" + "="*30 + f"\n[FATAL OOM ERROR] Proc {accelerator.process_index} E{epoch_num} S{step+1}\n{e}\n" + "="*30)
try: accelerator.print(torch.cuda.memory_summary(device=DEVICE, abbreviated=True))
except: pass
if accelerator.distributed_type != DistributedType.NO: dist.barrier()
sys.exit(1)
except Exception as e:
accelerator.print("\n" + "="*30 + f"\n[UNEXPECTED BATCH ERROR] Proc {accelerator.process_index} E{epoch_num} S{step+1}\n{type(e).__name__}: {e}\nTraceback:\n{traceback.format_exc(limit=5)}\nSkipping Batch...\n" + "="*30 + "\n")
optimizer.zero_grad(set_to_none=True) # Zero grads on error
epoch_skipped_batches += 1
continue
# --- Step Logging ---
if accelerator.sync_gradients and accelerator.is_main_process and total_loss is not None: # Only log if step was successful
log_data = {
"train/mse_loss_step": step_mse,
"train/total_loss_step": step_total,
"train/psnr_step": step_psnr, # Log step PSNR
"train/learning_rate": current_lr
}
try: accelerator.log(log_data, step=global_step)
except Exception as log_e: accelerator.print(f"[Log Warn S{global_step}] {log_e}")
if accelerator.is_local_main_process:
postfix = {
"MSE": f"{step_mse:.4f}",
"PSNR": f"{step_psnr:.2f}", # Add PSNR to progress bar
"LR": f"{current_lr:.1e}",
"Step": global_step
}
progress_bar.set_postfix(postfix)
if is_debug_step: accelerator.print(f"[DEBUG E1S<{DEBUG_FIRST_N_BATCHES}] --- Batch {step+1} End ---")
# --- End Epoch ---
if accelerator.is_local_main_process: progress_bar.close()
accelerator.wait_for_everyone()
accelerator.print(f"\n--- Epoch {epoch_num} Finished ---")
accelerator.print(f" Batches Processed: {num_batches_processed} (per proc), Skipped: {epoch_skipped_batches} (per proc)")
# --- Epoch Aggregation & Logging ---
avg_epoch_total_loss = epoch_total_loss_sum / num_batches_processed if num_batches_processed > 0 else 0.0
avg_epoch_mse_loss = epoch_mse_loss_sum / num_batches_processed if num_batches_processed > 0 else 0.0
avg_epoch_psnr = epoch_psnr_sum / num_batches_processed if num_batches_processed > 0 else 0.0 # Calculate average PSNR
# Gather epoch averages across all processes
metrics_to_gather = {'total': torch.tensor(avg_epoch_total_loss, device=DEVICE),
'mse': torch.tensor(avg_epoch_mse_loss, device=DEVICE),
'psnr': torch.tensor(avg_epoch_psnr, device=DEVICE), # Gather avg PSNR
'batches': torch.tensor(num_batches_processed, device=DEVICE)}
try: gathered = accelerator.gather_for_metrics(metrics_to_gather)
except Exception as gather_err:
accelerator.print(f"[WARN] Gather metrics failed: {gather_err}")
gathered = metrics_to_gather # Use local values if gather fails
gathered['batches'] = gathered['batches'].unsqueeze(0) # Ensure batches is iterable
if accelerator.is_main_process:
total_batches = gathered['batches'].sum().item()
global_avg_total = gathered['total'].mean().item() if total_batches > 0 else 0.0
global_avg_mse = gathered['mse'].mean().item() if total_batches > 0 else 0.0
global_avg_psnr = gathered['psnr'].mean().item() if total_batches > 0 else 0.0 # Get global average PSNR
accelerator.print(f" Epoch {epoch_num} Average Summary (Global):")
accelerator.print(f" Total Batches Globally: {int(total_batches)}")
accelerator.print(f" Avg Loss: Total={global_avg_total:.4f}, MSE={global_avg_mse:.4f}")
accelerator.print(f" Avg PSNR: {global_avg_psnr:.2f} dB") # Print PSNR
# Log epoch metrics to TensorBoard
if hasattr(accelerator, "log"):
log_epoch = {
"train/total_loss_epoch": global_avg_total,
"train/mse_loss_epoch": global_avg_mse,
"train/psnr_epoch": global_avg_psnr, # Log epoch PSNR
"epoch": epoch_num
}
try: accelerator.log(log_epoch, step=global_step) # Log against global_step for consistency
except Exception as e: accelerator.print(f"[Log Warn E{epoch_num}] {e}")
# Store for plotting later
if total_batches > 0: # Only store if the epoch had successful batches
epoch_losses_history.append(global_avg_mse) # Use MSE for loss plot
epoch_psnrs_history.append(global_avg_psnr)
epochs_plotted_history.append(epoch_num)
# LR Scheduler Step
if isinstance(lr_scheduler, ReduceLROnPlateau):
if total_batches > 0: lr_scheduler.step(global_avg_total) # Step based on total loss
else: accelerator.print(" LR Scheduler: Skipped step (0 batches).")
# --- Checkpoint Saving ---
accelerator.wait_for_everyone()
if (epoch_num % SAVE_CHECKPOINT_EVERY_N_EPOCHS == 0) or (epoch_num == TOTAL_EPOCHS):
accelerator.print(f"[Epoch End] Saving checkpoint for epoch {epoch_num}...")
models_to_save = {"unet": unet, "action_conditioner": action_conditioner}
save_checkpoint(accelerator, epoch_num, CHECKPOINT_DIR, **models_to_save)
# --- End Training ---
accelerator.print(f"\n{'='*15} Training Finished After {TOTAL_EPOCHS} Epochs {'='*15}")
# --- Save Plots (Main Process Only) ---
if accelerator.is_main_process:
accelerator.print("\n[Plotting] Generating and saving training plots...")
save_plots(epochs_plotted_history, epoch_losses_history, epoch_psnrs_history, CHECKPOINT_DIR)
# --- Clean Up ---
try: accelerator.end_training()
except Exception as e: accelerator.print(f"[Warning] Error end_training(): {e}")
accelerator.print(f"--- Process {accelerator.process_index} Finished ---")