Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change some code to Pythonic way. #277

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 101 additions & 94 deletions stylegan2_pytorch/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,25 @@

import numpy as np


def cast_list(el):
return el if isinstance(el, list) else [el]

def timestamped_filename(prefix = 'generated-'):

def timestamped_filename(prefix='generated-'):
now = datetime.now()
timestamp = now.strftime("%m-%d-%Y_%H-%M-%S")
return f'{prefix}{timestamp}'


def set_seed(seed):
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)


def run_training(rank, world_size, model_args, data, load_from, new, num_train_steps, name, seed):
is_main = rank == 0
is_ddp = world_size > 1
Expand All @@ -41,9 +45,9 @@ def run_training(rank, world_size, model_args, data, load_from, new, num_train_s
print(f"{rank + 1}/{world_size} process initialized.")

model_args.update(
is_ddp = is_ddp,
rank = rank,
world_size = world_size
is_ddp=is_ddp,
rank=rank,
world_size=world_size
)

model = Trainer(**model_args)
Expand All @@ -55,7 +59,7 @@ def run_training(rank, world_size, model_args, data, load_from, new, num_train_s

model.set_data_src(data)

progress_bar = tqdm(initial = model.steps, total = num_train_steps, mininterval=10., desc=f'{name}<{data}>')
progress_bar = tqdm(initial=model.steps, total=num_train_steps, mininterval=10., desc=f'{name}<{data}>')
while model.steps < num_train_steps:
retry_call(model.train, tries=3, exceptions=NanException)
progress_bar.n = model.steps
Expand All @@ -68,94 +72,95 @@ def run_training(rank, world_size, model_args, data, load_from, new, num_train_s
if is_ddp:
dist.destroy_process_group()


def train_from_folder(
data = './data',
results_dir = './results',
models_dir = './models',
name = 'default',
new = False,
load_from = -1,
image_size = 128,
network_capacity = 16,
fmap_max = 512,
transparent = False,
batch_size = 5,
gradient_accumulate_every = 6,
num_train_steps = 150000,
learning_rate = 2e-4,
lr_mlp = 0.1,
ttur_mult = 1.5,
rel_disc_loss = False,
num_workers = None,
save_every = 1000,
evaluate_every = 1000,
generate = False,
num_generate = 1,
generate_interpolation = False,
interpolation_num_steps = 100,
save_frames = False,
num_image_tiles = 8,
trunc_psi = 0.75,
mixed_prob = 0.9,
fp16 = False,
no_pl_reg = False,
cl_reg = False,
fq_layers = [],
fq_dict_size = 256,
attn_layers = [],
no_const = False,
aug_prob = 0.,
aug_types = ['translation', 'cutout'],
top_k_training = False,
generator_top_k_gamma = 0.99,
generator_top_k_frac = 0.5,
dual_contrast_loss = False,
dataset_aug_prob = 0.,
multi_gpus = False,
calculate_fid_every = None,
calculate_fid_num_images = 12800,
clear_fid_cache = False,
seed = 42,
log = False
data='./data',
results_dir='./results',
models_dir='./models',
name='default',
new=False,
load_from=-1,
image_size=128,
network_capacity=16,
fmap_max=512,
transparent=False,
batch_size=5,
gradient_accumulate_every=6,
num_train_steps=150000,
learning_rate=2e-4,
lr_mlp=0.1,
ttur_mult=1.5,
rel_disc_loss=False,
num_workers=None,
save_every=1000,
evaluate_every=1000,
generate=False,
num_generate=1,
generate_interpolation=False,
interpolation_num_steps=100,
save_frames=False,
num_image_tiles=8,
trunc_psi=0.75,
mixed_prob=0.9,
fp16=False,
no_pl_reg=False,
cl_reg=False,
fq_layers=[],
fq_dict_size=256,
attn_layers=[],
no_const=False,
aug_prob=0.,
aug_types=['translation', 'cutout'],
top_k_training=False,
generator_top_k_gamma=0.99,
generator_top_k_frac=0.5,
dual_contrast_loss=False,
dataset_aug_prob=0.,
multi_gpus=False,
calculate_fid_every=None,
calculate_fid_num_images=12800,
clear_fid_cache=False,
seed=42,
log=False
):
model_args = dict(
name = name,
results_dir = results_dir,
models_dir = models_dir,
batch_size = batch_size,
gradient_accumulate_every = gradient_accumulate_every,
image_size = image_size,
network_capacity = network_capacity,
fmap_max = fmap_max,
transparent = transparent,
lr = learning_rate,
lr_mlp = lr_mlp,
ttur_mult = ttur_mult,
rel_disc_loss = rel_disc_loss,
num_workers = num_workers,
save_every = save_every,
evaluate_every = evaluate_every,
num_image_tiles = num_image_tiles,
trunc_psi = trunc_psi,
fp16 = fp16,
no_pl_reg = no_pl_reg,
cl_reg = cl_reg,
fq_layers = fq_layers,
fq_dict_size = fq_dict_size,
attn_layers = attn_layers,
no_const = no_const,
aug_prob = aug_prob,
aug_types = cast_list(aug_types),
top_k_training = top_k_training,
generator_top_k_gamma = generator_top_k_gamma,
generator_top_k_frac = generator_top_k_frac,
dual_contrast_loss = dual_contrast_loss,
dataset_aug_prob = dataset_aug_prob,
calculate_fid_every = calculate_fid_every,
calculate_fid_num_images = calculate_fid_num_images,
clear_fid_cache = clear_fid_cache,
mixed_prob = mixed_prob,
log = log
name=name,
results_dir=results_dir,
models_dir=models_dir,
batch_size=batch_size,
gradient_accumulate_every=gradient_accumulate_every,
image_size=image_size,
network_capacity=network_capacity,
fmap_max=fmap_max,
transparent=transparent,
lr=learning_rate,
lr_mlp=lr_mlp,
ttur_mult=ttur_mult,
rel_disc_loss=rel_disc_loss,
num_workers=num_workers,
save_every=save_every,
evaluate_every=evaluate_every,
num_image_tiles=num_image_tiles,
trunc_psi=trunc_psi,
fp16=fp16,
no_pl_reg=no_pl_reg,
cl_reg=cl_reg,
fq_layers=fq_layers,
fq_dict_size=fq_dict_size,
attn_layers=attn_layers,
no_const=no_const,
aug_prob=aug_prob,
aug_types=cast_list(aug_types),
top_k_training=top_k_training,
generator_top_k_gamma=generator_top_k_gamma,
generator_top_k_frac=generator_top_k_frac,
dual_contrast_loss=dual_contrast_loss,
dataset_aug_prob=dataset_aug_prob,
calculate_fid_every=calculate_fid_every,
calculate_fid_num_images=calculate_fid_num_images,
clear_fid_cache=clear_fid_cache,
mixed_prob=mixed_prob,
log=log
)

if generate:
Expand All @@ -171,7 +176,8 @@ def train_from_folder(
model = Trainer(**model_args)
model.load(load_from)
samples_name = timestamped_filename()
model.generate_interpolation(samples_name, num_image_tiles, num_steps = interpolation_num_steps, save_frames = save_frames)
model.generate_interpolation(samples_name, num_image_tiles, num_steps=interpolation_num_steps,
save_frames=save_frames)
print(f'interpolation generated at {results_dir}/{name}/{samples_name}')
return

Expand All @@ -182,9 +188,10 @@ def train_from_folder(
return

mp.spawn(run_training,
args=(world_size, model_args, data, load_from, new, num_train_steps, name, seed),
nprocs=world_size,
join=True)
args=(world_size, model_args, data, load_from, new, num_train_steps, name, seed),
nprocs=world_size,
join=True)


def main():
fire.Fire(train_from_folder)
26 changes: 19 additions & 7 deletions stylegan2_pytorch/diff_augment.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,21 @@ def rand_brightness(x, scale):
x = x + (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * scale
return x


def rand_saturation(x, scale):
x_mean = x.mean(dim=1, keepdim=True)
x = (x - x_mean) * (((torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * 2.0 * scale) + 1.0) + x_mean
x = (x - x_mean) * (
((torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * 2.0 * scale) + 1.0) + x_mean
return x


def rand_contrast(x, scale):
x_mean = x.mean(dim=[1, 2, 3], keepdim=True)
x = (x - x_mean) * (((torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * 2.0 * scale) + 1.0) + x_mean
x = (x - x_mean) * (
((torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * 2.0 * scale) + 1.0) + x_mean
return x


def rand_translation(x, ratio=0.125):
shift_x, shift_y = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
translation_x = torch.randint(-shift_x, shift_x + 1, size=[x.size(0), 1, 1], device=x.device)
Expand All @@ -49,11 +54,12 @@ def rand_translation(x, ratio=0.125):
x = x_pad.permute(0, 2, 3, 1).contiguous()[grid_batch, grid_x, grid_y].permute(0, 3, 1, 2)
return x


def rand_offset(x, ratio=1, ratio_h=1, ratio_v=1):
w, h = x.size(2), x.size(3)

imgs = []
for img in x.unbind(dim = 0):
for img in x.unbind(dim=0):
max_h = int(w * ratio * ratio_h)
max_v = int(h * ratio * ratio_v)

Expand All @@ -70,12 +76,15 @@ def rand_offset(x, ratio=1, ratio_h=1, ratio_v=1):

return torch.stack(imgs)


def rand_offset_h(x, ratio=1):
return rand_offset(x, ratio=1, ratio_h=ratio, ratio_v=0)


def rand_offset_v(x, ratio=1):
return rand_offset(x, ratio=1, ratio_h=0, ratio_v=ratio)


def rand_cutout(x, ratio=0.5):
cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
offset_x = torch.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.device)
Expand All @@ -92,15 +101,18 @@ def rand_cutout(x, ratio=0.5):
x = x * mask.unsqueeze(1)
return x


AUGMENT_FNS = {
'brightness': [partial(rand_brightness, scale=1.)],
'lightbrightness': [partial(rand_brightness, scale=.65)],
'contrast': [partial(rand_contrast, scale=.5)],
'lightcontrast': [partial(rand_contrast, scale=.25)],
'contrast': [partial(rand_contrast, scale=.5)],
'lightcontrast': [partial(rand_contrast, scale=.25)],
'saturation': [partial(rand_saturation, scale=1.)],
'lightsaturation': [partial(rand_saturation, scale=.5)],
'color': [partial(rand_brightness, scale=1.), partial(rand_saturation, scale=1.), partial(rand_contrast, scale=0.5)],
'lightcolor': [partial(rand_brightness, scale=0.65), partial(rand_saturation, scale=.5), partial(rand_contrast, scale=0.5)],
'color': [partial(rand_brightness, scale=1.), partial(rand_saturation, scale=1.),
partial(rand_contrast, scale=0.5)],
'lightcolor': [partial(rand_brightness, scale=0.65), partial(rand_saturation, scale=.5),
partial(rand_contrast, scale=0.5)],
'offset': [rand_offset],
'offset_h': [rand_offset_h],
'offset_v': [rand_offset_v],
Expand Down
Loading