Download code/train_regress.py from DeepLense/flowlensing: direct link, hf CLI and curl.
- Browser
- Download file 9.24 kB
-
https://huggingface.co/DeepLense/flowlensing/resolve/main/code/train_regress.py
- Command line
-
hf download hf://DeepLense/flowlensing/code/train_regress.py
-
curl -L -o train_regress.py https://huggingface.co/DeepLense/flowlensing/resolve/main/code/train_regress.py
9.24 kB
| """ | |
| Thanks to Gemini 2.5 for pairing here and there. | |
| **Modified to train a model conditioned on continuous variables.** | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| import torch.optim as optim | |
| from model import DiT | |
| from torch.utils.data import DataLoader | |
| from contextlib import nullcontext | |
| from tqdm import tqdm | |
| import torchvision | |
| import os | |
| import re | |
| from dataset import VariableDataset, diffusion_transforms | |
| # Assuming your new dataset loader is ready. | |
| # from dataset import YourNewDiffusionDataset, diffusion_transforms | |
| # For demonstration, we'll use a placeholder. | |
| from torch.utils.data import TensorDataset | |
| torch.set_float32_matmul_precision("high") | |
| # --- Hyperparameters --- | |
| COND_SIZE = 4 # MODIFIED: Dimension of the conditioning vector (4 float values) | |
| IMG_SIZE = 64 | |
| IMG_CHANNELS = 1 | |
| # DiT specific parameters | |
| LATENT_DIM = 512 | |
| PATCH_SIZE = 2 | |
| MODEL_DEPTH = 6 | |
| MODEL_HEADS = 8 | |
| # Diffusion process parameters | |
| NUM_ODE_STEPS = 100 | |
| # Training parameters | |
| LEARNING_RATE = 1e-5 | |
| BATCH_SIZE = 128 | |
| EPOCHS = 300 | |
| DEVICE = "cuda:7" if torch.cuda.is_available() else "cpu" | |
| COMPILE = True | |
| AMP_DTYPE = torch.float32 if torch.cuda.is_available() else torch.bfloat16 | |
| # Sampling parameters | |
| SAMPLE_INTERVAL = 3 # Sample every N epochs | |
| NUM_SAMPLES_PER_VECTOR = 4 # Number of images to sample for each conditioning vector | |
| CFG_SCALE = 2.0 | |
| # Others | |
| CHECKPOINT_SAVE_INTERVAL = 3 | |
| DATA_DIR = "/speech/advait/rooshil/nanoDiT/cdm_regress_multi_param_normalized" # MODIFIED: Update with your dataset path | |
| SAVE_DIR = "diffusion_training_variable_conditioned" | |
| os.makedirs(SAVE_DIR, exist_ok=True) | |
| # --- Helper functions for flow-matching math --- | |
| def flow_lerp(x): | |
| bsz = x.shape[0] | |
| t = torch.rand((bsz,)).to(x.device) | |
| t_broadcast = t.view(bsz, 1, 1, 1) | |
| z1 = torch.randn_like(x) | |
| # the flow-matching lerp | |
| zt = (1 - t_broadcast) * x + t_broadcast * z1 | |
| return zt, z1, t | |
| # --- Sampling function (Euler) --- | |
| def sample_conditional_cfg( | |
| model, conditioning_vectors, ode_steps=100, cfg_scale=5.0 | |
| ): | |
| """ | |
| Generate images for specified conditioning vectors using CFG. | |
| conditioning_vectors: A tensor of shape (N, cond_size) | |
| """ | |
| model.eval() | |
| num_samples = conditioning_vectors.shape[0] | |
| # Initial state | |
| z = torch.randn((num_samples, IMG_CHANNELS, IMG_SIZE, IMG_SIZE), device=DEVICE) | |
| # Prepare conditional vectors | |
| y = conditioning_vectors.to(DEVICE).float() | |
| # For CFG, create a batch of unconditional inputs (zeros) | |
| using_cfg = cfg_scale >= 1.0 | |
| if using_cfg: | |
| y_null = torch.zeros_like(y) | |
| y = torch.cat([y, y_null], 0) | |
| # ODE derivative term | |
| dt = 1.0 / ode_steps | |
| dt_tensor = torch.tensor([dt], device=z.device).view(1, *([1] * (z.dim() - 1))) | |
| # Flow-sampling | |
| for i in range(ode_steps, 0, -1): | |
| z_final = torch.cat([z, z], 0) if using_cfg else z | |
| t = torch.full((z_final.shape[0],), i / ode_steps, device=z_final.device, dtype=z_final.dtype) | |
| predicted_velocity = model(z_final, t, y) | |
| if using_cfg: | |
| pred_cond, pred_uncond = predicted_velocity.chunk(2, dim=0) | |
| predicted_velocity = pred_uncond + cfg_scale * (pred_cond - pred_uncond) | |
| # Euler step | |
| z = z - dt_tensor * predicted_velocity | |
| z = z.to(z.dtype) # | |
| images = (z + 1) / 2.0 # De-normalize from [-1, 1] to [0, 1] | |
| images = torch.clamp(images, 0.0, 1.0) | |
| model.train() | |
| return images | |
| def train(): | |
| # --- Model Instantiation --- | |
| model = NanoDiT( | |
| input_size=IMG_SIZE, | |
| patch_size=PATCH_SIZE, | |
| in_channels=IMG_CHANNELS, | |
| hidden_size=LATENT_DIM, | |
| depth=MODEL_DEPTH, | |
| num_heads=MODEL_HEADS, | |
| cond_size=COND_SIZE, | |
| timestep_freq_scale=1000, | |
| label_conditioning=False | |
| ).to(DEVICE) | |
| start_epoch = 0 | |
| checkpoint_files = [f for f in os.listdir(SAVE_DIR) if f.endswith('.pth')] | |
| if checkpoint_files: | |
| latest_checkpoint_file = max( | |
| checkpoint_files, | |
| key=lambda f: int(re.search(r'(\d+)', f).group()) | |
| ) | |
| latest_checkpoint_path = os.path.join(SAVE_DIR, latest_checkpoint_file) | |
| try: | |
| # Extract the epoch number from the filename to resume training | |
| start_epoch = int(re.search(r'(\d+)', latest_checkpoint_file).group()) | |
| print(f"Resuming training from checkpoint: {latest_checkpoint_path}") | |
| # Load the model's state dictionary | |
| model.load_state_dict(torch.load(latest_checkpoint_path, map_location=DEVICE)) | |
| print(f"✅ Successfully loaded checkpoint. Resuming from epoch {start_epoch + 1}.") | |
| except Exception as e: | |
| print(f"❌ Could not load checkpoint: {e}. Starting training from scratch.") | |
| start_epoch = 0 | |
| else: | |
| print("No checkpoints found. Starting training from scratch.") | |
| if COMPILE: | |
| print("`torch.compile()` enabled.") | |
| model = torch.compile(model) | |
| # --- Optimizer and loss --- | |
| optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE) | |
| scaler = torch.amp.GradScaler() if AMP_DTYPE is not None and DEVICE.startswith("cuda") else None | |
| criterion = nn.MSELoss() | |
| amp_context = ( | |
| torch.autocast(device_type=torch.device(DEVICE).type, dtype=AMP_DTYPE) | |
| if AMP_DTYPE is not None and scaler is not None | |
| else nullcontext() | |
| ) | |
| if AMP_DTYPE and scaler: | |
| print(f"Using automatic mixed-precision in {AMP_DTYPE}.") | |
| # train_dataset = YourNewDiffusionDataset(DATA_DIR, transform=diffusion_transforms) | |
| train_dataset = VariableDataset(DATA_DIR, transform=diffusion_transforms) | |
| train_dataloader = DataLoader( | |
| train_dataset, | |
| batch_size=BATCH_SIZE, | |
| shuffle=True, | |
| num_workers=4, | |
| pin_memory=True, | |
| drop_last=True, | |
| ) | |
| # --- Training Loop --- | |
| print(f"Training on {DEVICE}") | |
| print(f"Using custom model: {type(model).__name__}") | |
| print(f"Model Parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad)}") | |
| for epoch in range(start_epoch, EPOCHS): | |
| model.train() | |
| for step, (real_images, cond_vectors) in enumerate(tqdm(train_dataloader, desc=f"Epoch {epoch+1}/{EPOCHS}")): | |
| optimizer.zero_grad() | |
| real_images = real_images.to(DEVICE, non_blocking=True) | |
| cond_vectors = cond_vectors.to(DEVICE, non_blocking=True).float() # Ensure it's float | |
| # 1. Interpolate between clean data and noise | |
| zt, z1, t = flow_lerp(real_images) | |
| # 2. Target velocity: u_t = z1 - x0 | |
| target_velocity_field = z1 - real_images | |
| with amp_context: | |
| # 3. Predict velocity using the model with conditioning vectors | |
| predicted_velocity = model(zt, t, cond_vectors) | |
| # 4. Calculate loss | |
| loss = criterion(target_velocity_field, predicted_velocity) | |
| # 5. Backpropagate and update weights | |
| if scaler is not None: | |
| scaler.scale(loss).backward() | |
| scaler.step(optimizer) | |
| scaler.update() | |
| else: | |
| loss.backward() | |
| optimizer.step() | |
| # if step % 50 == 0: # Print less frequently | |
| print(f"Epoch [{epoch + 1}/{EPOCHS}], Step [{step + 1}/{len(train_dataloader)}], Loss: {loss.item():.4f}") | |
| # --- Perform Sampling and Save Images (Intermediate Evaluation) --- | |
| if (epoch + 1) % SAMPLE_INTERVAL == 0 or epoch == EPOCHS - 1: | |
| print(f"\nSampling images at epoch {epoch + 1}...") | |
| # MODIFIED: Create a list of conditioning vectors to sample. | |
| # You should replace these with meaningful values for your use case. | |
| sample_vectors = torch.tensor([ | |
| [1.2815, -0.1781, 0.2004, 1.5728], | |
| [1.2815, -0.1019, -0.2664, -0.4410], | |
| [1.2815, 0.0671, -0.3282, -1.4732], | |
| [1.2815, 0.3388, -0.2729, 1.4220], | |
| ], device=DEVICE).float() | |
| # Repeat each vector to get multiple samples per vector | |
| sample_vectors_repeated = sample_vectors.repeat_interleave(NUM_SAMPLES_PER_VECTOR, dim=0) | |
| generated_sample_images = sample_conditional_cfg( | |
| model, sample_vectors_repeated, ode_steps=NUM_ODE_STEPS, cfg_scale=CFG_SCALE | |
| ) | |
| # Save as a grid | |
| if generated_sample_images.nelement() > 0: | |
| grid = torchvision.utils.make_grid(generated_sample_images, nrow=NUM_SAMPLES_PER_VECTOR) | |
| torchvision.utils.save_image(grid, f"{SAVE_DIR}/sample_epoch_{epoch + 1}.png") | |
| print(f"Saved sample images to {SAVE_DIR}/sample_epoch_{epoch + 1}.png") | |
| print("-" * 30) | |
| # Optional: Save model checkpoint | |
| if (epoch + 1) % CHECKPOINT_SAVE_INTERVAL == 0: | |
| # Unwrap the compiled model before saving the state_dict | |
| model_to_save = model._orig_mod if COMPILE else model | |
| torch.save(model_to_save.state_dict(), f"{SAVE_DIR}/dit_variable_cond_epoch_{epoch + 1}.pth") | |
| print("Training finished.") | |
| if __name__ == "__main__": | |
| train() |