Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Train a GAN using the techniques described in the paper
"Training Generative Adversarial Networks with Limited Data"."""
import os
import click
import re
import json
import tempfile
import torch
import dnnlib
from training import training_loop
from torch_utils import training_stats
from torch_utils import custom_ops
import warnings
warnings.filterwarnings("ignore")
from colorama import init
from colorama import Fore, Style
from icecream import ic
init(autoreset=True)
import shutil
@click.option('--fp32', help='Disable mixed-precision training', type=bool, metavar='BOOL')
@click.option('--nhwc', help='Use NHWC memory format with FP16', type=bool, metavar='BOOL')
@click.option('--nobench', help='Disable cuDNN benchmarking', type=bool, metavar='BOOL')
@click.option('--allow-tf32', help='Allow PyTorch to use TF32 internally', type=bool, metavar='BOOL')
@click.option('--workers', help='Override number of DataLoader workers', type=int, metavar='INT')
def main(ctx, outdir, dry_run, **config_kwargs):
"""Train a GAN using the techniques described in the paper
"Training Generative Adversarial Networks with Limited Data".
code
Examples:
\b
# Train with custom dataset using 1 GPU.
python train.py --outdir=~/training-runs --data=~/mydataset.zip --gpus=1
\b
Base configs (--cfg):
auto Automatically select reasonable defaults based on resolution
and GPU count. Good starting point for new datasets.
"""
dnnlib.util.Logger(should_flush=True)
# Setup training options.
try:
run_desc, args = setup_training_loop_kwargs(**config_kwargs)
except UserError as err:
ctx.fail(err)
# Pick output directory.
prev_run_dirs = []
if os.path.isdir(outdir):
prev_run_dirs = [x for x in os.listdir(outdir) if os.path.isdir(os.path.join(outdir, x))]
prev_run_ids = [re.match(r'^\d+', x) for x in prev_run_dirs]
prev_run_ids = [int(x.group()) for x in prev_run_ids if x is not None]
cur_run_id = max(prev_run_ids, default=-1) + 1
args.run_dir = os.path.join(outdir, f'{run_desc}')
# assert not os.path.exists(args.run_dir)
# Print options.
print()
print(Fore.CYAN + Style.BRIGHT + 'Training options:')
print(Fore.YELLOW + json.dumps(args, indent=2))
print()
print(Fore.GREEN + f'Output directory: {args.run_dir}')
print(Fore.GREEN + f'Training data: {args.training_set_kwargs.img_path}')
print(Fore.GREEN + f'Training duration: {args.total_kimg} kimg')
print(Fore.GREEN + f'Number of GPUs: {args.num_gpus}')
print(Fore.GREEN + f'Number of images: {args.training_set_kwargs.max_size}')
print(Fore.GREEN + f'Image resolution: {args.training_set_kwargs.resolution}')
print(Fore.GREEN + f'Dataset x-flips: {args.training_set_kwargs.xflip}')
print()
# Dry run?
if dry_run:
print('Dry run; exiting.')
return
# Create output directory.
print('Creating output directory...')
if os.path.exists(args.run_dir):
shutil.rmtree(args.run_dir)
if os.path.exists('training-runs-inp/losses'):
shutil.rmtree('training-runs-inp/losses')
if not os.path.exists(args.run_dir):
os.makedirs(args.run_dir)
with open(os.path.join(args.run_dir, 'training_options.json'), 'wt') as f:
json.dump(args, f, indent=2)
# Launch processes.
print('Launching processes...')
torch.multiprocessing.set_start_method('spawn')
with tempfile.TemporaryDirectory() as temp_dir:
if args.num_gpus == 1:
subprocess_fn(rank=0, args=args, temp_dir=temp_dir)
else:
torch.multiprocessing.spawn(fn=subprocess_fn, args=(args, temp_dir), nprocs=args.num_gpus)
if name == "main":
main() # pylint: disable=no-value-for-parameter
how to do cpu training
To train a GAN on a CPU using the provided script, you'll need to make a few modifications since the default configuration is set up for GPU usage. Below is a guide on how to run the script for CPU training:
Install or Ensure Dependencies: Make sure you have all the required Python libraries installed. This includes PyTorch configured for CPU use.
Modify the Script:
Since PyTorch will automatically fall back to CPU if a GPU is not available, you don't necessarily need to modify a lot of code to force CPU training. However, to explicitly ensure the script only uses the CPU, you may remove any GPU-specific configurations or set conditions to use CPU.
Run the Script:
Use the CLI to specify --gpus=0, which generally indicates that no GPUs should be used, though you might need to modify the script to support this input if it does not already handle such a case. In the original script above, it appears that there is an implicit assumption that at least one GPU will be used, which might need minor changes for CPU operation.
Here's a structured approach to modify the original script for CPU only:
Script Adjustments:
Adjustments in main and setup_training_loop_kwargs Functions:
For CPU training, you can modify setup_training_loop_kwargs to ensure that GPU indices and distributed training logic are not activated.
You will have to comment out or adjust any distributed training setup meant for GPU usage.
Skip GPU Initialization:
In the subprocess_fn, skip the Distributed GPU init section or adjust conditions based on the --gpus parameter.
Adjust Metrics:
Avoid using metrics or features that are GPU-specific unless you adjust them for CPU alternatives, where available.
Example Modification:
To force the training to use CPU, ensure you are not calling any GPU-specific functionalities. PyTorch typically defaults to the CPU if CUDA is not available or if you specify CPU as the device. You might adjust this section:
python
if args.num_gpus > 0:
sync_device = torch.device('cuda', rank) if args.num_gpus > 1 else None
else:
sync_device = torch.device('cpu')
training_stats.init_multiprocessing(rank=rank, sync_device=sync_device)
if rank != 0:
custom_ops.verbosity = 'none'
Set num_gpus to 0 or remove any conditionals executing GPU setup when num_gpus is 0.
Running the Script:
Command Line Execution:
Use the script with the --gpus=0 argument to explicitly indicate CPU usage.
Environment Adjustments:
Ensure your environment supports CPU execution optimally. You may also decrease batch sizes and other resource-intensive options to accommodate the CPU training constraints.
Validation:
Verify that the system utilizes the CPU by checking resource managers like htop or equivalent to confirm CPU load during execution.
By making these changes, you should be able to successfully run the GAN training process on a CPU. Remember, however, that training GANs on a CPU can be significantly slower than when using a GPU.