def downsample_bd(data, kernel, scale, pad_data):
"""
Note:
1. data should be torch.FloatTensor (data range 0~1) in shape [nchw]
2. pad_data should be enabled in model testing
3. This function is device agnostic, i.e., data/kernel could be on cpu or gpu
"""
if pad_data:
data = F.pad(data, (1, 3, 1, 3), 'reflect')
data = F.conv2d(data, kernel, stride=scale, bias=None, padding=0)
return data
def inference2(auto_cast, imgs, imgnames, model, save_path, extension, device, scale):
#with torch.no_grad():
with torch.inference_mode():
with torch.autocast(device.type, enabled=auto_cast):
outputs = model(imgs)
Your script is a command-line tool for performing video/image sequence super-resolution or processing using a pretrained BasicVSR++ model. It loads images from a folder, processes them in intervals (to avoid CUDA OOM), optionally downsamples results with different methods including a special blur-based downsampling, and saves the output.
Here is a high-level explanation and some notes for your script:
High-Level Workflow:
Argument Parsing:
Requires at least the following positional arguments:
If total images <= batch size (), process all at once.
User
is it possible to edit BasicVSRPP_8X.pth model or I need to create new each time, write script for training such model with 2 datasets (pixelated and not images)
Assistant
The .pth file (e.g., BasicVSRPP_8X.pth) is a saved checkpoint containing the model weights. You do not need to recreate the model from scratch each time to update or improve it. Instead, you can load the existing weights and continue training (fine-tuning) the model on new data, or retrain from scratch if you want.
1. Can you edit the .pth file?
The .pth file is just a serialized PyTorch state dictionary or checkpoint.
You can't just directly "edit" it meaningfully (like changing weights manually).
But you can load the checkpoint weights into your model, continue training on new datasets, and then overwrite or save a new checkpoint with updated weights.
2. How to train or fine-tune BasicVSR++ on two datasets (pixelated & non-pixelated images)?
To train or fine-tune BasicVSRPlusPlus on two datasets, you need:
A training script that:
Loads both datasets.
Constructs batches (mixed from both datasets if desired).
Defines the model and optimizer.
Defines training loop and loss function.
Loads the pretrained checkpoint weights (optional for fine-tuning).
Saves checkpoints.
Here is an outline and a simplified script to get you started:
a. Dataset preparation
Assuming you have two folders:
/path/to/pixelated_dataset/
/path/to/nonpixelated_dataset/
Each containing sequences or frames for training.
You should create PyTorch Dataset classes (or use existing ones) for these datasets.
b. Example training script outline:
python
User
yes
Assistant
Great! Let's build a minimal working training example for fine-tuning or training BasicVSRPlusPlus with two datasets: pixelated and clean images.
Key assumptions and notes:
Your datasets provide paired LR (pixelated, low-res) sequences and corresponding HR (clean, high-res) sequences.
Both datasets contain image sequences (e.g., consecutive frames), and your model expects input shapes: [batch, frames, channels, height, width].
You have two folders:
pixelated_dataset/ — contains pixelated LR image sequences
nonpixelated_dataset/ — contains clean LR image sequences (or alternative clean data)
For simplicity, your datasets can follow the same interface.
Step 1: Dataset
A minimal dataset class that reads sequences of frames
(from a folder containing images named in order, e.g., 0001.png, 0002.png, ...):
python
User
yes
Assistant
Great! Let me help you step-by-step to get a full training pipeline going, including data preparation (creating pixelated LR from HR), dataset loading, training, and fine-tuning BasicVSR++.
Step 1: Prepare Your Datasets (Generating LR pixelated images)
If you have clean high-resolution (HR) images and want to generate pixelated low-resolution (LR) images (for training pairs), you can downsample and then upsample images to simulate pixelation.
Example script to create pixelated LR images from HR:
python
import os
import cv2
def pixelate_and_downsample(hr_folder, pixelated_lr_folder, scale=8):
os.makedirs(pixelated_lr_folder, exist_ok=True)
hr_images = sorted([f for f in os.listdir(hr_folder) if f.endswith('.png')])
for img_name in hr_images:
hr_img_path = os.path.join(hr_folder, img_name)
img = cv2.imread(hr_img_path, cv2.IMREAD_COLOR)
# Downsample image by scale
height, width = img.shape[:2]
small = cv2.resize(img, (width // scale, height // scale), interpolation=cv2.INTER_LINEAR)
# Upsample back to original size, causing pixelation
pixelated = cv2.resize(small, (width, height), interpolation=cv2.INTER_NEAREST)
save_path = os.path.join(pixelated_lr_folder, img_name)
cv2.imwrite(save_path, pixelated)
print(f"Created pixelated LR: {save_path}")
if __name__ == '__main__':
hr_dir = 'datasets/HR'
pixelated_dir = 'datasets/pixelated_LR'
pixelate_and_downsample(hr_dir, pixelated_dir, scale=8)
What this does:
Loads HR images.
Scales them down by the factor scale (e.g. 8).
Then scales them back up with nearest neighbor interpolation to induce pixelation.
Saves LR pixelated images alongside HR.
User
does tecogan based model would be better?
import os
import os.path as osp
import sys
import shutil
import torch
import argparse
sys.path.append(sys.base_prefix + '/codes_tg/')
from torch.utils.data import DataLoader
from data.folder_dataset import FolderDataset
from models import define_model
from utils import dist_utils, base_utils, data_utils
do_nothing = lambda _: None
def flip_LR(data):
flipped_data = {}
for key, value in data.items():
if isinstance(value, torch.Tensor):
if value.dim() == 4:
flipped_data[key] = torch.flip(value, dims=[2])
elif value.dim() == 3:
flipped_data[key] = torch.flip(value, dims=[1])
else:
flipped_data[key] = value
else:
flipped_data[key] = value
return flipped_data
def rot_180(data):
rotated_data = {}
for key, value in data.items():
if isinstance(value, torch.Tensor):
if value.dim() == 4 and value.shape[-1] == 3:
rotated_data[key] = torch.rot90(value, k=2, dims=(1, 2))
elif value.dim() == 3 and value.shape[-1] == 3:
rotated_data[key] = torch.rot90(value, k=2, dims=(0, 1))
else:
rotated_data[key] = value
else:
rotated_data[key] = value
return rotated_data
Both BasicVSR++ and TecoGAN are strong video super-resolution (VSR) models, but they emphasize somewhat different approaches and tradeoffs:
BasicVSR++ vs. TecoGAN: Key Differences
Aspect
BasicVSR++
TecoGAN
Architecture
Recurrent neural network with explicit spatio-temporal alignment (flow/deformable conv). Focuses on propagation of features across frames.
GAN-based framework incorporating a generator (FRNet) + temporal discriminator to enforce temporal consistency and fidelity. Uses recurrent feedback and adversarial loss.
Training Loss
Typically trained with L1 or L2 losses (pixel-wise), may not use adversarial losses by default.
Uses adversarial loss (GAN), perceptual loss, and temporal consistency to generate sharper and temporally coherent outputs.
Output Quality
Usually very accurate and stable with crisp details; might appear more conservative in texture generation.
Often produces perceptually sharper and more "natural" textures thanks to GAN, but can introduce occasional artifacts or flicker.
Speed and Memory
Relatively lightweight and efficient.
Slightly heavier due to GAN discriminator and recurrent feedback loops.
Use Case
Useful where accuracy and PSNR/SSIM-like metrics matter (e.g., archival footage).
Better when perceptual quality and subjective sharpness is prioritized (e.g., gaming, anime).
Pre-trained Weights
Easier to find weights trained on real-world datasets with BD/BI degradations.
Usually trained on Vimeo or animation dataset, your mileage varies on natural videos.
Should you use TecoGAN-based model?
Use TecoGAN if:
You want perceptually sharper, maybe more "natural looking" outputs.
You want to restore textures and details that may appear blurry with BasicVSR++.
You are OK with slightly more artifacts or flickering sometimes.
You are ready to deal with more complex GAN training or inference.
Use BasicVSR++ if:
You want stable, reliable, and quantitatively good outputs.
You want faster inference and less VRAM.
You want a simpler training pipeline (GAN training can be tricky).
How to choose:
User
yes
Assistant
Great! Here's a step-by-step simplified recipe to get you started with training or fine-tuning a TecoGAN-based model, including generator and discriminator, losses, and a basic training loop. I’ll also highlight where it differs from BasicVSR++ style training.
Minimal TecoGAN Training Pipeline Overview
TecoGAN training involves two networks and multiple loss terms:
Generator (G, e.g. FRNet) : produces super-resolved frames from LR inputs
Discriminator (D) : evaluates how “real” the frames look, trained adversarially
Losses: pixel loss (L1 or L2), adversarial loss, perceptual loss (VGG features), temporal consistency loss, etc.
1. Model setup
python
from models import define_model
opt = {
'model': {
'name': 'TecoGAN',
'generator': {
'name': 'FRNet',
'in_nc': 3,
'out_nc': 3,
'nf': 64,
'nb': 10,
'load_path': 'path_to_pretrained_generator.pth'
},
'discriminator': {
'name': 'Discriminator', # or actual discriminator class name of TecoGAN repo
'nf': 64,
}
}
}
model = define_model(opt) # Should return {'G': generator_model, 'D': discriminator_model}
G = model['G'].to(device)
D = model['D'].to(device)
2. Loss functions
Use a combination of:
Pixel loss: L1 or L2 between generated SR frames and HR ground truth
Adversarial loss: GAN loss for fooling discriminator
Perceptual loss: VGG feature distance to improve perceptual quality
Temporal consistency loss: encourage smoothness/consistency across frames
You can import or implement these from TecoGAN repo or similar.
Example:
python
User
do you know any better modern gan/vsr models for my needs?
Assistant
Certainly! The field of video super-resolution (VSR) and GAN-based VSR has evolved rapidly, and there are several recent models that push the state of the art beyond BasicVSR++ and TecoGAN. Here’s a summary of some prominent modern GAN- or VSR-based architectures that could be good fits depending on your needs:
Modern GAN-based or Advanced VSR Models Worth Considering
Model Name
Key Features & Strengths
Notes
Real-ESRGAN Video (Real-ESRGANv2 Video)
Extension of Real-ESRGAN for video; uses GAN + recurrent generator + temporal consistency
Strong perceptual quality, good generalization on real-world video
EDVR (Enhanced Deformable Video Restoration)
Uses deformable convolutions, strong spatial-temporal modeling, can be paired with GAN loss to sharpen textures
Very popular; good baseline for further GAN or perceptual training
BasicVSR++ + Perceptual Loss / GAN finetuning
Start from BasicVSR++ and finetune with adversarial/perceptual loss to get best of accuracy and perceptual quality
Combines stable architecture with perceptual quality boost
TTVSR (Transformer-based Temporal VSR)
Uses temporal transformers to model long-range dependencies; can offer superior temporal coherence and detail
Cutting-edge transformer-based approach
Enhanced SRGAN / ESRGAN GAN-based VSR
Single image GAN SR models extended to video with temporal constraints
Good for perceptual sharpness, less temporal consistency than specialized video models
FAVSR (Feature-Augmented VSR)
Uses feature-level augmentation and sophisticated fusion for strong reconstruction
Newer model, often high performance on benchmarks
What to consider when choosing?
Use case:
Archival footage restoration → favor accuracy/stability (BasicVSR++ or EDVR with pixel loss).
Game or anime upscaling → perceptual quality & sharpness with GAN (TecoGAN, Real-ESRGAN video, ESRGAN finetuning).
Training resources:
GANs + transformers require more GPU/hyperparameter tuning.
Inference performance:
BasicVSR++ and EDVR are quite optimized; GAN models typically slower.
User
no, can you provide merged script for tecogan and basicrsr++ model usage at same time for maximum quality is possible but don't uscale output image to much to avoid out of video memory problems?
Assistant
Sure! You want a merged Python inference script that:
Loads both BasicVSR++ and TecoGAN models,
Runs them sequentially or combined on the same input frames,
Produces an output that balances maximum quality,
Avoids too large output (to fit GPU memory)...
A practical approach:
Workflow:
Read input LR frames (a sequence),
Run BasicVSR++ to get initial super-resolved frames (stable, accurate),
Pass BasicVSR++ outputs optionally to TecoGAN as an enhanced refinement stage (to add perceptual details via GAN, temporal coherence),
Downscale output moderately if needed (to reduce resolution/VRAM),
Save results.
Why this order?
BasicVSR++ often produces clean, artifact-free but slightly blurry outputs.
TecoGAN can refine textures and improve perceptual sharpness using GAN, starting from BasicVSR++ output instead of raw LR inputs avoids flicker/artifacts from pixelated noisy inputs.
Moderate downscaling reduces VRAM usage.
Merged inference script example (simplified):
python
User
yes
Assistant
Great! Here's a more complete merged inference script for BasicVSR++ + TecoGAN with batch processing, command-line arguments, adjustable downscaling, and proper model interface handling. It includes detailed comments and easy customization.
python
Dataset releases
Not yet included in a published release.
# select device
if torch.cuda.is_available() and args.device < 7:
device = torch.device('cuda', args.device)
print('GPU_ID=' + str(args.device))
#print('device=' + torch.cuda.get_device_name(device))
if args.fraction < 100:
torch.cuda.set_per_process_memory_fraction(args.fraction*0.01, args.device)
print('VRAM_fraction=' + str(args.fraction) + '%')
device_name = torch.cuda.get_device_name(device)
print('device_name =', device_name)
if 'ZLUDA' in device_name:
torch.backends.cudnn.enabled = False
torch.backends.cuda.enable_flash_sdp(False)
torch.backends.cuda.enable_flash_sdp = do_nothing
torch.backends.cuda.enable_math_sdp(True)
torch.backends.cuda.enable_math_sdp = do_nothing
torch.backends.cuda.enable_mem_efficient_sdp(False)
torch.backends.cuda.enable_mem_efficient_sdp = do_nothing
if hasattr(torch.backends.cuda, "enable_cudnn_sdp"):
torch.backends.cuda.enable_cudnn_sdp(False)
torch.backends.cuda.enable_cudnn_sdp = do_nothing
#else:
# torch.backends.cudnn.enabled = False
# if hasattr(torch.backends.cuda, "enable_cudnn_sdp"):
# torch.backends.cuda.enable_cudnn_sdp(False)
# torch.backends.cuda.enable_cudnn_sdp = do_nothing
else:
#device = torch.device('cpu')
#print('GPU not used')
print('This program requires CUDA.')
sys.exit()
scale = 8
if '8X' in args.model_path:
scale = 8
if '4X' in args.model_path:
scale = 4
# set up model
c = 64
b = 7
if(args.model_path[-7] == '@'):
c = 1 << int(args.model_path[-6])
b = int(args.model_path[-5], base=16)
print('channel=' + str(c))
print('block=' + str(b))
print('model=' + args.model_path);
print('input=' + args.input_path);
print('extension=' + args.extension)
if args.reduce_type > 0:
print('reduce=' + str(args.reduce_type))
model = BasicVSRPlusPlus(mid_channels=c, num_blocks=b, scale=scale)
model.load_state_dict(torch.load(sys.base_prefix + '\\' + args.model_path, map_location=device)['params'], strict=False)
"""
checkpoint = torch.load(args.model_path, map_location=device)['params']
for key in list(checkpoint.keys()):
print('key=', key)
if 'deform_align.' in key:
checkpoint[key.replace('deform_align.', '')] = checkpoint[key]
del checkpoint[key]
model.load_state_dict(checkpoint)
"""
model.eval()
model = model.to(device)
auto_cast = args.ac and device != torch.device('cpu')
print('auto_cast=' + str(auto_cast))
os.makedirs(args.save_path, exist_ok=True)
# load data and inference
imgs_list = sorted(glob.glob(os.path.join(args.input_path, '*.png')))
num_imgs = len(imgs_list)
if num_imgs <= args.interval: # too many images may cause CUDA out of memory
imgs, imgnames = read_img_seq(imgs_list, require_mod_crop=False, scale=1, return_imgname=True)
height, width, channels = imgs[0].shape
imgs = imgs.unsqueeze(0).to(device)
print('inference:0-' + str(num_imgs-1))
if args.reduce_type == 5:
inference2(auto_cast, imgs, imgnames, model, args.save_path, args.extension, device, scale)
else:
inference(auto_cast, imgs, imgnames, model, args.save_path, args.extension, device, args.reduce_type, 1.0 / scale)
print('')
else:
for idx in range(0, num_imgs, args.interval):
interval = min(args.interval, num_imgs - idx)
imgs, imgnames = read_img_seq(imgs_list[idx:idx + interval], require_mod_crop=False, scale=1, return_imgname=True)
height, width, channels = imgs[0].shape
imgs = imgs.unsqueeze(0).to(device)
print('inference:' + str(idx) + '-' + str(idx+interval-1))
if args.reduce_type == 5:
inference2(auto_cast, imgs, imgnames, model, args.save_path, args.extension, device, scale)
else:
inference(auto_cast, imgs, imgnames, model, args.save_path, args.extension, device, args.reduce_type, 1.0 / scale)
print('')
interval
Otherwise, split into intervals.
Inference:
Uses either the inference() function or a special inference2() for reduce_type==5.
inference2() runs model first, then applies a blur kernel downsampling with stride equal to scale, using a custom 3D kernel, to get a "blurred downsampled" output.
The other inference method just optionally resizes via OpenCV interpolation.
Saving Outputs:
Saves output images to the specified folder with the same basename and specified extension.
Code Notes / Potential Improvements:
You commented out imports / params like channel and block – you might want to add these CLI options for more flexibility.
The kernel defined in create_kernel() defines a 3-channel depthwise blur kernel used for downsampling in inference2() function.
You specify that tensor data passed to downsample_bd must have shape [N,C,H,W] and be float and normalized (0~1).
Autocast (automatic mixed precision) is controlled by the -ac flag.
The model weights loading assumes key 'params' is in the checkpoint dict loaded by torch.load.
Some commented-out code in model loading dealing with deform_align. keys can be removed if unused or activated if your model requires.
Output images saved by tensor2img converted tensors are expected to be in HWC format with pixel value range 0-255.
Exiting if CUDA unavailable is strict; you may want to allow CPU fallback with warning if needed.
How to Run Your Script
An example command assuming:
You have BasicVSR++ model weights at models/BasicVSRPP_8X.pth
Your input frames are in frames/
You want results saved to results/
You want to process in intervals of 10 frames with GPU 0, 80% VRAM, and save images as PNG:
Your script provides a robust pipeline for BasicVSR++ inference with batch processing, optional mixed precision, VRAM control, and flexible output resizing/downsampling.
If you want me to help with specific fixes, improvements, or explanations of any part of the code, or help integrating it into a broader system, just ask!
import torch
from torch.utils.data import DataLoader, ConcatDataset
from basicvsrpp_arch import BasicVSRPlusPlus
from your_dataset import PixelatedDataset, NonPixelatedDataset # Replace with your dataset class
import torch.nn as nn
import torch.optim as optim
def train(model, dataloader, optimizer, criterion, device):
model.train()
total_loss = 0
for data in dataloader:
# Assuming data is a dictionary or tuple, containing LR and HR images or sequences
lr_seq = data['lr'].to(device)
hr_seq = data['hr'].to(device)
optimizer.zero_grad()
output = model(lr_seq)
# Define your loss, e.g., L1 loss
loss = criterion(output, hr_seq)
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load pretrained model weights if available (for fine-tuning)
model = BasicVSRPlusPlus(mid_channels=64, num_blocks=7, scale=8)
checkpoint = torch.load('BasicVSRPP_8X.pth', map_location=device)
model.load_state_dict(checkpoint['params'], strict=False)
model = model.to(device)
# datasets
dataset1 = PixelatedDataset('/path/to/pixelated_dataset')
dataset2 = NonPixelatedDataset('/path/to/nonpixelated_dataset')
# Use ConcatDataset to combine datasets
combined_dataset = ConcatDataset([dataset1, dataset2])
dataloader = DataLoader(combined_dataset, batch_size=4, shuffle=True, num_workers=4)
criterion = nn.L1Loss()
optimizer = optim.Adam(model.parameters(), lr=1e-4)
num_epochs = 100
for epoch in range(num_epochs):
loss = train(model, dataloader, optimizer, criterion, device)
print(f"Epoch {epoch + 1}/{num_epochs}, Loss: {loss:.6f}")
# Save checkpoint
torch.save({'params': model.state_dict()}, f'checkpoint_epoch_{epoch+1}.pth')
if __name__ == '__main__':
main()
c. Notes for your datasets
Your dataset classes (PixelatedDataset, NonPixelatedDataset) need to provide pairs or sequences of low-resolution (pixelated) inputs and target high-resolution images as tensors.
The dataset should handle reading images, converting them to tensors, normalization, cropping, data augmentation, etc.
Example minimal dataset skeleton:
python
from torch.utils.data import Dataset
from PIL import Image
import os
import torchvision.transforms as transforms
class PixelatedDataset(Dataset):
def __init__(self, folder_path):
self.image_files = sorted([os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.png')])
self.transform = transforms.Compose([
transforms.ToTensor(),
# Add normalization if needed
])
def __len__(self):
return len(self.image_files)
def __getitem__(self, idx):
lr_img = Image.open(self.image_files[idx]) # pixelated/LR image
# Assuming paired HR image exists or use your mechanism
hr_img = Image.open(self.image_files[idx].replace('pixelated', 'highres')) # or another folder?
lr = self.transform(lr_img)
hr = self.transform(hr_img)
return {'lr': lr.unsqueeze(0), 'hr': hr.unsqueeze(0)} # Adjust dimensions for sequence if needed
Make sure the input and output batch shape meets the model’s expected shape (usually [batch, frames, channels, height, width]).
Summary:
No need to create new model from scratch every time.
Load your .pth weights, then continue training/fine-tuning on combined datasets.
Create proper Dataset and DataLoader for your pixelated and non-pixelated input.
Use a standard training loop with optimizer and loss.
Save checkpoints during training.
If you want, I can help you write a complete minimal training script or help build the dataset loader suitable for BasicVSR++, just tell me details about your data format (video sequences? single frames?), input-output pairing, and batch shape expectations!
import os
from torch.utils.data import Dataset
import cv2
import numpy as np
import torch
def load_image_sequence(img_folder, seq_len):
"""Loads a sequence of images from a folder as a list of cv2 images."""
imgs = sorted([os.path.join(img_folder, f) for f in os.listdir(img_folder) if f.endswith('.png')])
total = len(imgs)
sequences = []
for i in range(total - seq_len + 1):
seq = []
for j in range(seq_len):
img = cv2.imread(imgs[i+j], cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = img.astype(np.float32) / 255.0 # normalize
seq.append(img)
sequences.append(seq)
return sequences
class SequenceDataset(Dataset):
def __init__(self, lr_folder, hr_folder, seq_len=7):
"""
lr_folder: low res (pixelated/clean)
hr_folder: high res (target)
seq_len: length of input sequence (frames)
"""
self.lr_seqs = load_image_sequence(lr_folder, seq_len)
self.hr_seqs = load_image_sequence(hr_folder, seq_len)
assert len(self.lr_seqs) == len(self.hr_seqs), "LR and HR sequences length mismatch"
self.seq_len = seq_len
def __len__(self):
return len(self.lr_seqs)
def __getitem__(self, idx):
# Convert list of images to tensors with shape [frames, C, H, W]
lr_seq = [torch.from_numpy(img).permute(2, 0, 1) for img in self.lr_seqs[idx]]
hr_seq = [torch.from_numpy(img).permute(2, 0, 1) for img in self.hr_seqs[idx]]
lr_seq = torch.stack(lr_seq) # [T, C, H, W]
hr_seq = torch.stack(hr_seq) # [T, C, H, W]
return {
'lr': lr_seq, # shape [T,C,H,W]
'hr': hr_seq # shape [T,C,H,W]
}
import torch
import torch.nn as nn
import torch.optim as optim
from basicvsrpp_arch import BasicVSRPlusPlus
def train_epoch(model, dataloader, optimizer, criterion, device):
model.train()
running_loss = 0
for batch in dataloader:
lr_seq = batch['lr'].to(device) # [B, T, C, H, W]
hr_seq = batch['hr'].to(device)
optimizer.zero_grad()
outputs = model(lr_seq) # [B, T, C, H*scale, W*scale]
loss = criterion(outputs, hr_seq)
loss.backward()
optimizer.step()
running_loss += loss.item()
return running_loss / len(dataloader)
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device: {device}')
model = BasicVSRPlusPlus(mid_channels=64, num_blocks=7, scale=8)
# Load pretrained weights if available (optional)
pretrained_path = 'BasicVSRPP_8X.pth'
if pretrained_path:
checkpoint = torch.load(pretrained_path, map_location=device)
model.load_state_dict(checkpoint['params'], strict=False)
print('Loaded pretrained weights.')
model = model.to(device)
# Initialize datasets and dataloader here (from above step)
# Assuming `dataloader` is already defined
criterion = nn.L1Loss()
optimizer = optim.Adam(model.parameters(), lr=1e-4)
num_epochs = 50
for epoch in range(num_epochs):
loss = train_epoch(model, dataloader, optimizer, criterion, device)
print(f"Epoch {epoch+1}/{num_epochs} - Loss: {loss:.6f}")
# Save checkpoint
torch.save({'params': model.state_dict()}, f'weights_epoch_{epoch+1}.pth')
if __name__ == '__main__':
main()
Summary
SequenceDataset loads sequences of frames for LR and HR images.
Use ConcatDataset to combine pixelated and nonpixelated datasets for joint training.
Use standard training loop with Adam optimizer and L1 loss.
Load pretrained weights for fine-tuning.
Save checkpoints regularly.
What do you need to do next?
Adjust the paths to your datasets.
Make sure your datasets contain paired LR-HR sequences per sample.
Confirm sequence length matches your model expectation (BasicVSR++ can use 7 frames by default).
Install dependencies if missing (torch, opencv-python, etc).
Run the training script on your machine.
If you want, I can help you with:
Writing code to prepare your dataset folders (e.g., create LR from HR by pixelation/downsampling).
Adjusting the model or training script to your precise setup.
Data augmentation ideas or advanced training techniques.
Just tell me!
Step 2: Full Dataset Class with This Structure
Your dataset folder layout:
code
datasets/
HR/ # clean, high-res images
pixelated_LR/ # pixelated low-res images (created from above)
nonpixelated_LR/ # optional other LR dataset with clean images
Let's create a single dataset that supports loading pairs from two folders:
python
import torch
from torch.utils.data import Dataset
import os
import cv2
import numpy as np
class BasicVSRDataset(Dataset):
def __init__(self, lr_folder, hr_folder, seq_len=7):
"""
Args:
lr_folder: folder of low-res input images
hr_folder: folder of high-res ground truth images
seq_len: length of the input sequence (frames)
"""
self.lr_folder = lr_folder
self.hr_folder = hr_folder
self.seq_len = seq_len
self.lr_images = sorted([os.path.join(lr_folder, f) for f in os.listdir(lr_folder) if f.endswith('.png')])
self.hr_images = sorted([os.path.join(hr_folder, f) for f in os.listdir(hr_folder) if f.endswith('.png')])
# Number of sequences (sliding window)
self.num_seqs = len(self.lr_images) - seq_len + 1
if len(self.lr_images) != len(self.hr_images):
raise RuntimeError("LR and HR folders must contain the same number of images")
def __len__(self):
return self.num_seqs
def load_image(self, path):
img = cv2.imread(path, cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = img.astype(np.float32) / 255.0
return img
def __getitem__(self, idx):
# Load LR & HR sequences with length seq_len
lr_seq = [self.load_image(self.lr_images[idx + i]) for i in range(self.seq_len)]
hr_seq = [self.load_image(self.hr_images[idx + i]) for i in range(self.seq_len)]
# Convert list to tensor [seq_len, C, H, W]
lr_seq = torch.stack([torch.from_numpy(i).permute(2, 0, 1) for i in lr_seq])
hr_seq = torch.stack([torch.from_numpy(i).permute(2, 0, 1) for i in hr_seq])
return {'lr': lr_seq, 'hr': hr_seq}
Step 3: Combine Datasets & Create DataLoader
If you have a second dataset (e.g., nonpixelated_LR + same HR), you can concatenate datasets:
If your application prioritizes videos with detailed temporal coherence and fewer artifacts, BasicVSR++ is simpler and solid.
If your application prioritizes perceptual quality and sharpness, TecoGAN may provide better visual quality, especially on challenging datasets.
Your TecoGAN script comments
Your script is a typical testing/inference driver for a TecoGAN-like model:
Reads sequences of LR frames.
Uses FRNet generator from TecoGAN.
Applies flips/rotation for test-time augmentation.
Uses GPU memory fraction control similar to your BasicVSR++ script.
Loads pre-trained weights from a TecoGAN checkpoint.
Handles BI / BD degradations for different scaling patterns.
Runs inference, saves to output folder.
Training TecoGAN vs BasicVSR++
TecoGAN training requires adversarial training setup: discriminator + generator, with multiple loss terms (adversarial + perceptual + L1).
BasicVSR++ usually trains with pixel-wise loss = simpler and faster to converge.
If you want perceptual quality + temporal consistence GAN training, your TecoGAN code base will have more dependencies and complexity.
Summary
For best accuracy & simpler training/inference: BasicVSR++ is better.
For best perceptual quality and temporal coherence with GANs: TecoGAN is better, but more complex training.
If you want I can help you with:
Converting your BasicVSR++ training pipeline to TecoGAN training pipeline.
Writing a simple TecoGAN training script including discriminator and GAN loss.
Test-time augmentation and evaluation scripts for TecoGAN.
Tips on stabilizing GAN training for video SR.
Just let me know what fits your needs!
pixel_criterion = torch.nn.L1Loss().to(device)
adversarial_criterion = torch.nn.BCEWithLogitsLoss().to(device)
# Perceptual loss VGG feature extractor can be imported or defined separately.
Papers: TecoGAN: Temporally Coherent GAN for Video Super-Resolution
Tutorials on GAN training & perceptual losses (e.g., use VGG feature extractor from torchvision)
If you want, I can help you write a full training script adapted from the TecoGAN repo, including dataset loading, all losses, optimizer setup, training & evaluation loops. Just tell me!
Provide sample fine-tuning/training code combining BasicVSR++ or EDVR with perceptual + GAN losses?
Help set up Real-ESRGAN Video inference or fine-tuning pipeline?
Prepare transformer-based model training scripts?
Help you select the best tradeoff based on your data & hardware?
Just let me know!
import os
import sys
import glob
import torch
import cv2
import numpy as np
from torch.utils.data import DataLoader
# Append paths to your code for models
sys.path.append(sys.base_prefix + '/codes_bvpp/')
sys.path.append(sys.base_prefix + '/codes_tg/')
from basicvsrpp_arch import BasicVSRPlusPlus
from data_util import read_img_seq
from img_util import tensor2img
from models import define_model # TecoGAN
from data.folder_dataset import FolderDataset
def load_basicvsrpp_model(model_path, device, scale=8):
model = BasicVSRPlusPlus(mid_channels=64, num_blocks=7, scale=scale)
checkpoint = torch.load(model_path, map_location=device)
model.load_state_dict(checkpoint['params'], strict=False)
model.eval()
model = model.to(device)
return model
def load_tecogan_model(opt):
# 'opt' is dict config for TecoGAN define_model
model = define_model(opt)
model.eval()
for k in model.keys():
model[k] = model[k].to(opt['device'])
return model
def tensor_to_cv2(tensor):
# Convert tensor [C, H, W] float32 0~1 to uint8 BGR image
img = tensor.clamp(0,1).cpu().numpy()
img = np.transpose(img, (1,2,0)) * 255.0
img = img.astype(np.uint8)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
return img
@torch.inference_mode()
def run_inference(bvsr_model, tg_model, imgs_tensor, device, scale, max_output_scale=2):
"""
imgs_tensor: [1, T, C, H, W] tensor in 0~1, LR input sequence batch=1
scale: upscaling factor of BasicVSR++ model (e.g., 8)
max_output_scale: max scale factor to keep to avoid OOM (<= scale)
"""
# 1) Run BasicVSR++ first
sr_outputs = bvsr_model(imgs_tensor) # [1, T, C, H*scale, W*scale]
# Optional: downscale BasicVSR++ output if max_output_scale < scale
if max_output_scale < scale:
down_factor = scale / max_output_scale
sr_outputs = torch.nn.functional.interpolate(
sr_outputs.view(-1, sr_outputs.size(2), sr_outputs.size(3), sr_outputs.size(4)),
scale_factor=1/down_factor,
mode='bilinear',
align_corners=False)
sr_outputs = sr_outputs.view(1, -1, sr_outputs.size(1), sr_outputs.size(2), sr_outputs.size(3))
# 2) Prepare input dict for TecoGAN (expects a dict with 'LQs' key - Low Quality sequences)
# We'll feed BasicVSR++ outputs as "fake LR" to TecoGAN generator for enhancement
tg_input = {'LQs': sr_outputs}
tg_model.prepare_inference_data(tg_input)
tg_model.infer()
tg_outputs = tg_model.outputs.detach() # Assuming TecoGAN stores outputs here; adapt to your codebase
return tg_outputs
def main():
# Settings - user configure here or parse args
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
scale = 8 # BasicVSR++ scale
max_output_scale = 2 # downscale from 8x to 2x to reduce memory footprint
# Paths
input_dir = 'input_lr_frames'
output_dir = 'output_sr_frames'
os.makedirs(output_dir, exist_ok=True)
bvsr_model_path = 'models/BasicVSRPP_8X.pth'
tg_model_path = 'models/TecoGAN_4x_BD_Vimeo_iter500K.pth'
# Load BasicVSR++ model
bvsr_model = load_basicvsrpp_model(bvsr_model_path, device, scale=scale)
# Setup TecoGAN options dict (adapt as needed)
tg_opt = {
'model': {
'name': 'TecoGAN',
'generator': {
'name': 'FRNet',
'nf': 64,
'nb': 10,
'in_nc': 3,
'out_nc': 3,
'load_path': tg_model_path
}
},
'device': device,
'scale': 4,
# add other necessary opts to prepare model correctly...
}
tg_model = load_tecogan_model(tg_opt)
# Load input LR frames as tensor [1, T, C, H, W], normalized 0-1
imgs_list = sorted(glob.glob(os.path.join(input_dir, '*.png')))
imgs_np = [cv2.cvtColor(cv2.imread(im), cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0 for im in imgs_list]
imgs_np = np.stack(imgs_np, axis=0) # [T, H, W, C]
imgs_np = np.transpose(imgs_np, (0, 3, 1, 2)) # [T, C, H, W]
imgs_tensor = torch.from_numpy(imgs_np).unsqueeze(0).to(device) # [1, T, C, H, W]
# Run combined inference
sr_tensor = run_inference(bvsr_model, tg_model, imgs_tensor, device, scale, max_output_scale)
# Save output frames
sr_tensor = sr_tensor.clamp(0, 1).cpu()
for i in range(sr_tensor.size(1)):
output_img = tensor_to_cv2(sr_tensor[0, i])
cv2.imwrite(os.path.join(output_dir, f'frame_{i:04d}.png'), output_img)
print(f'Saved frame {i}.')
if __name__ == '__main__':
main()
Notes:
The above script assumes slight modifications in TecoGAN interface — you must adapt prepare_inference_data and infer calls and how outputs are stored (model.outputs or another attribute). Check your TecoGAN repo.
The BasicVSR++ output is downscaled from 8x exact output to max_output_scale (like 2x or 4x) before passing to TecoGAN refinement to limit GPU memory.
You can adjust max_output_scale to trade off quality vs memory.
Input must be sequential LR frames for video SR.
Both networks run on the same device.
tensor_to_cv2() ensures proper image format saving.
Why this scheme?
BasicVSR++ ensures clean large scale reconstruction,
TecoGAN adds perceptual enhancement and temporal GAN refinement,
Controlled output resolution reduces OOM risk,
Merging enables maximum visual quality combining strengths.
If you want, I can help:
Adapt this for batched processing on large datasets,
Add command-line args,
Integrate your preprocessing/postprocessing,
Add more sophisticated fusion (e.g., weighted blending between BasicVSR++ and TecoGAN outputs),
Or help handle multi-GPU inference.
Would you like me to provide that?
import os
import sys
import glob
import shutil
import argparse
import torch
import cv2
import numpy as np
from torch.utils.data import DataLoader
sys.path.append(sys.base_prefix + '/codes_bvpp/')
sys.path.append(sys.base_prefix + '/codes_tg/')
from basicvsrpp_arch import BasicVSRPlusPlus
from data_util import read_img_seq
from img_util import tensor2img
from models import define_model
from data.folder_dataset import FolderDataset
def parse_args():
parser = argparse.ArgumentParser(description='Combined BasicVSR++ + TecoGAN Inference')
parser.add_argument('--bvsr_model', required=True, help='Path to BasicVSR++ checkpoint')
parser.add_argument('--tg_model', required=True, help='Path to TecoGAN checkpoint')
parser.add_argument('--input_dir', required=True, help='Folder with LR input frames (PNG)')
parser.add_argument('--output_dir', required=True, help='Folder to save output frames')
parser.add_argument('--device', type=int, default=0, help='CUDA device ID, -1 for CPU')
parser.add_argument('--max_output_scale', type=int, default=2,
help='Max output downscale factor to avoid OOM (<= BasicVSR scale, e.g. 2 or 4)')
parser.add_argument('--bvsr_scale', type=int, default=8, help='BasicVSR++ model scale (default 8)')
parser.add_argument('-ac', '--auto_cast', action='store_true', help='Enable autocast mixed precision')
return parser.parse_args()
def load_basicvsrpp_model(model_path, device, scale):
model = BasicVSRPlusPlus(mid_channels=64, num_blocks=7, scale=scale)
ckpt = torch.load(model_path, map_location=device)
model.load_state_dict(ckpt['params'], strict=False)
model.eval()
model.to(device)
print(f'[BasicVSR++] Loaded model from {model_path}')
return model
def load_tecogan_model(opt):
model = define_model(opt)
for k in model.keys():
model[k] = model[k].to(opt['device'])
model[k].eval()
print(f"[TecoGAN] Loaded model from {opt['model']['generator']['load_path']}")
return model
def tensor_to_cv2(tensor):
# [C, H, W], float tensor 0-1 to uint8 BGR
img_np = tensor.clamp(0, 1).cpu().numpy()
img_np = np.transpose(img_np, (1, 2, 0)) # HWC RGB
img_np = (img_np * 255).astype(np.uint8)
img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
return img_bgr
@torch.inference_mode()
def run_combined_inference(bvsr_model, tg_model, imgs_tensor, device, bvsr_scale, max_output_scale, auto_cast):
"""
Args:
imgs_tensor: [1, T, C, H, W] LR input normalized to 0~1
max_output_scale: max allowed output scale factor (must be <= bvsr_scale)
Returns:
sr_tensor: [1, T, C, H_out, W_out]
"""
assert max_output_scale <= bvsr_scale, f"max_output_scale ({max_output_scale}) must be <= bvsr_scale ({bvsr_scale})"
with torch.autocast(device.type if device.type != 'cpu' else 'cpu', enabled=auto_cast):
# BasicVSR++ output full-scale SR
bvsr_out = bvsr_model(imgs_tensor) # [1, T, C, H*scale, W*scale]
# Downscale if needed to reduce memory
if max_output_scale < bvsr_scale:
downscale_factor = max_output_scale / bvsr_scale
B, T, C, H, W = bvsr_out.shape
bvsr_out = bvsr_out.view(B * T, C, H, W)
bvsr_out = torch.nn.functional.interpolate(
bvsr_out,
scale_factor=downscale_factor,
mode='bilinear',
align_corners=False
)
H2, W2 = bvsr_out.shape[-2:]
bvsr_out = bvsr_out.view(B, T, C, H2, W2)
# Prepare dict for TecoGAN (feed BasicVSR++ output as input sequence "LQs")
data = {'LQs': bvsr_out}
tg_model.prepare_inference_data(data)
tg_model.infer()
# TecoGAN outputs list of frames tensor, convert to batch tensor [1, T, C, H, W]
# Adapt to your TecoGAN repo's output storing method
# Here assuming `tg_model.outputs` is list of [C,H,W] tensors for each frame
outputs_list = tg_model.outputs # list or tensor? If list convert:
if isinstance(outputs_list, list):
outputs_stack = torch.stack(outputs_list, dim=1).unsqueeze(0) # [1, T, C, H, W]
elif torch.is_tensor(outputs_list):
outputs_stack = outputs_list.unsqueeze(0)
else:
raise RuntimeError("Unexpected tg_model.outputs format")
return outputs_stack
def main():
args = parse_args()
device = torch.device(f'cuda:{args.device}') if args.device >= 0 and torch.cuda.is_available() else torch.device('cpu')
print(f'Using device: {device}')
# Load BasicVSR++ model
bvsr_model = load_basicvsrpp_model(args.bvsr_model, device, args.bvsr_scale)
# Set up TecoGAN options dict
tg_opt = {
'model': {
'name': 'TecoGAN',
'generator': {
'name': 'FRNet',
'nf': 64,
'nb': 10,
'in_nc': 3,
'out_nc': 3,
'load_path': args.tg_model
}
},
'device': device,
'scale': args.bvsr_scale, # usually 4 for TecoGAN, but we feed BasicVSR++ output which could be smaller scaled
'auto_cast': args.auto_cast,
# add other fields as needed by your TecoGAN define_model
}
tg_model = load_tecogan_model(tg_opt)
# Load input LR frames from input_dir using your function or directly here
img_files = sorted(glob.glob(os.path.join(args.input_dir, '*.png')))
if len(img_files) == 0:
print(f"No PNG files found in {args.input_dir}")
return
imgs_np = []
for f in img_files:
img = cv2.imread(f, cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
imgs_np.append(img)
imgs_np = np.stack(imgs_np, axis=0) # [T,H,W,C]
imgs_np = np.transpose(imgs_np, (0,3,1,2)) # [T,C,H,W]
imgs_tensor = torch.from_numpy(imgs_np).unsqueeze(0).to(device) # [1,T,C,H,W]
# Inference
sr_tensor = run_combined_inference(
bvsr_model, tg_model, imgs_tensor, device,
bvsr_scale=args.bvsr_scale,
max_output_scale=args.max_output_scale,
auto_cast=args.auto_cast
)
# Save outputs
os.makedirs(args.output_dir, exist_ok=True)
sr_tensor = sr_tensor.clamp(0, 1).cpu()
for idx in range(sr_tensor.size(1)):
out_img = tensor_to_cv2(sr_tensor[0, idx])
out_path = os.path.join(args.output_dir, f'frame_{idx:04d}.{args.tg_model.split(".")[-1]}')
cv2.imwrite(out_path, out_img)
print(f"Saved: {out_path}")
print('Done!')
if __name__ == '__main__':
main()
--max_output_scale lets you control the max scale of output to reduce VRAM — e.g., if BasicVSR++ is 8x, max_output_scale=2 downsamples BasicVSR++ output by 0.25 before passing to TecoGAN, saving memory.
The TecoGAN model expects inputs in dict with key 'LQs' like in your original code.
The TecoGAN output (tg_model.outputs) might need adjustment depending on your actual repo.
You can extend the script to support batching or video files.
Autocast enables optional mixed precision to save VRAM.
Output is saved frame-by-frame with same extension as TG model checkpoint filename extension (usually .png).
If you want, I can help modify it further:
Add batch or video file support
Integrate with your specific repo version of BasicVSR++ or TecoGAN
Add logging/progress bar
Postprocessing (e.g., temporal smoothing or blending)