hysts HF staff commited on
Commit
e909f79
1 Parent(s): bce4f39
Files changed (6) hide show
  1. .gitignore +1 -0
  2. .gitmodules +3 -0
  3. app.py +159 -0
  4. gan-control +1 -0
  5. patch +157 -0
  6. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ controller_age015id025exp02hai04ori02gam15
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "gan-control"]
2
+ path = gan-control
3
+ url = https://github.com/amazon-research/gan-control
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import functools
7
+ import os
8
+ import pathlib
9
+ import subprocess
10
+ import sys
11
+ import tarfile
12
+
13
+ import gradio as gr
14
+ import huggingface_hub
15
+ import numpy as np
16
+ import PIL.Image
17
+ import torch
18
+
19
+ if os.environ.get('SYSTEM') == 'spaces':
20
+ subprocess.call('git apply ../patch'.split(), cwd='gan-control')
21
+
22
+ sys.path.insert(0, 'gan-control/src')
23
+
24
+ from gan_control.inference.controller import Controller
25
+
26
+ TITLE = 'amazon-research/gan-control'
27
+ DESCRIPTION = 'This is a demo for https://github.com/amazon-research/gan-control.'
28
+ ARTICLE = None
29
+
30
+ TOKEN = os.environ['TOKEN']
31
+
32
+
33
+ def parse_args() -> argparse.Namespace:
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument('--device', type=str, default='cpu')
36
+ parser.add_argument('--theme', type=str)
37
+ parser.add_argument('--live', action='store_true')
38
+ parser.add_argument('--share', action='store_true')
39
+ parser.add_argument('--port', type=int)
40
+ parser.add_argument('--disable-queue',
41
+ dest='enable_queue',
42
+ action='store_false')
43
+ parser.add_argument('--allow-flagging', type=str, default='never')
44
+ parser.add_argument('--allow-screenshot', action='store_true')
45
+ return parser.parse_args()
46
+
47
+
48
+ def download_models() -> None:
49
+ model_dir = pathlib.Path('controller_age015id025exp02hai04ori02gam15')
50
+ if not model_dir.exists():
51
+ path = huggingface_hub.hf_hub_download(
52
+ 'hysts/gan-control',
53
+ 'controller_age015id025exp02hai04ori02gam15.tar.gz',
54
+ use_auth_token=TOKEN)
55
+ with tarfile.open(path) as f:
56
+ f.extractall()
57
+
58
+
59
+ @torch.inference_mode()
60
+ def run(
61
+ seed: int,
62
+ truncation: float,
63
+ yaw: int,
64
+ pitch: int,
65
+ age: int,
66
+ hair_color_r: float,
67
+ hair_color_g: float,
68
+ hair_color_b: float,
69
+ nrows: int,
70
+ ncols: int,
71
+ controller: Controller,
72
+ device: torch.device,
73
+ ) -> PIL.Image.Image:
74
+ seed = int(np.clip(seed, 0, np.iinfo(np.uint32).max))
75
+ batch_size = nrows * ncols
76
+ latent_size = controller.config.model_config['latent_size']
77
+ latent = torch.from_numpy(
78
+ np.random.RandomState(seed).randn(batch_size,
79
+ latent_size)).float().to(device)
80
+
81
+ initial_image_tensors, initial_latent_z, initial_latent_w = controller.gen_batch(
82
+ latent=latent, truncation=truncation)
83
+ res0 = controller.make_resized_grid_image(initial_image_tensors,
84
+ nrow=ncols)
85
+
86
+ pose_control = torch.tensor([[yaw, pitch, 0]], dtype=torch.float32)
87
+ image_tensors, _, modified_latent_w = controller.gen_batch_by_controls(
88
+ latent=initial_latent_w,
89
+ input_is_latent=True,
90
+ orientation=pose_control)
91
+ res1 = controller.make_resized_grid_image(image_tensors, nrow=ncols)
92
+
93
+ age_control = torch.tensor([[age]], dtype=torch.float32)
94
+ image_tensors, _, modified_latent_w = controller.gen_batch_by_controls(
95
+ latent=initial_latent_w, input_is_latent=True, age=age_control)
96
+ res2 = controller.make_resized_grid_image(image_tensors, nrow=ncols)
97
+
98
+ hair_color = torch.tensor([[hair_color_r, hair_color_g, hair_color_b]],
99
+ dtype=torch.float32) / 255
100
+ hair_color = torch.clamp(hair_color, 0, 1)
101
+ image_tensors, _, modified_latent_w = controller.gen_batch_by_controls(
102
+ latent=initial_latent_w, input_is_latent=True, hair=hair_color)
103
+ res3 = controller.make_resized_grid_image(image_tensors, nrow=ncols)
104
+
105
+ return res0, res1, res2, res3
106
+
107
+
108
+ def main():
109
+ args = parse_args()
110
+ device = torch.device(args.device)
111
+
112
+ download_models()
113
+
114
+ path = 'controller_age015id025exp02hai04ori02gam15/'
115
+ controller = Controller(path, device)
116
+
117
+ func = functools.partial(run, controller=controller, device=device)
118
+ func = functools.update_wrapper(func, run)
119
+
120
+ gr.Interface(
121
+ func,
122
+ [
123
+ gr.inputs.Number(default=0, label='Seed'),
124
+ gr.inputs.Slider(0, 1, step=0.1, default=0.7, label='Truncation'),
125
+ gr.inputs.Slider(-90, 90, step=1, default=30, label='Yaw'),
126
+ gr.inputs.Slider(-90, 90, step=1, default=0, label='Pitch'),
127
+ gr.inputs.Slider(15, 75, step=1, default=75, label='Age'),
128
+ gr.inputs.Slider(
129
+ 0, 255, step=1, default=186, label='Hair Color (R)'),
130
+ gr.inputs.Slider(
131
+ 0, 255, step=1, default=158, label='Hair Color (G)'),
132
+ gr.inputs.Slider(
133
+ 0, 255, step=1, default=92, label='Hair Color (B)'),
134
+ gr.inputs.Slider(1, 10, step=1, default=1, label='Number of Rows'),
135
+ gr.inputs.Slider(
136
+ 1, 10, step=1, default=5, label='Number of Columns'),
137
+ ],
138
+ [
139
+ gr.outputs.Image(type='pil', label='Generated Image'),
140
+ gr.outputs.Image(type='pil', label='Head Pose Controlled'),
141
+ gr.outputs.Image(type='pil', label='Age Controlled'),
142
+ gr.outputs.Image(type='pil', label='Hair Color Controlled'),
143
+ ],
144
+ title=TITLE,
145
+ description=DESCRIPTION,
146
+ article=ARTICLE,
147
+ theme=args.theme,
148
+ allow_screenshot=args.allow_screenshot,
149
+ allow_flagging=args.allow_flagging,
150
+ live=args.live,
151
+ ).launch(
152
+ enable_queue=args.enable_queue,
153
+ server_port=args.port,
154
+ share=args.share,
155
+ )
156
+
157
+
158
+ if __name__ == '__main__':
159
+ main()
gan-control ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 057805e4a33298716d323c3e4f0754e20ab4153d
patch ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/gan_control/inference/controller.py b/src/gan_control/inference/controller.py
2
+ index ee464ba..d1907dd 100644
3
+ --- a/src/gan_control/inference/controller.py
4
+ +++ b/src/gan_control/inference/controller.py
5
+ @@ -13,9 +13,9 @@ _log = get_logger(__name__)
6
+
7
+
8
+ class Controller(Inference):
9
+ - def __init__(self, controller_dir):
10
+ + def __init__(self, controller_dir, device):
11
+ _log.info('Init Controller class...')
12
+ - super(Controller, self).__init__(os.path.join(controller_dir, 'generator'))
13
+ + super(Controller, self).__init__(os.path.join(controller_dir, 'generator'), device)
14
+ self.fc_controls = {}
15
+ self.config_controls = {}
16
+ for sub_group_name in self.batch_utils.sub_group_names:
17
+ @@ -29,21 +29,21 @@ class Controller(Inference):
18
+ @torch.no_grad()
19
+ def gen_batch_by_controls(self, batch_size=1, latent=None, normalize=True, input_is_latent=False, static_noise=True, **kwargs):
20
+ if latent is None:
21
+ - latent = torch.randn(batch_size, self.config.model_config['latent_size'], device='cuda')
22
+ + latent = torch.randn(batch_size, self.config.model_config['latent_size'], device=self.device)
23
+ latent = latent.clone()
24
+ if input_is_latent:
25
+ latent_w = latent
26
+ else:
27
+ if isinstance(self.model, torch.nn.DataParallel):
28
+ - latent_w = self.model.module.style(latent.cuda())
29
+ + latent_w = self.model.module.style(latent.to(self.device))
30
+ else:
31
+ - latent_w = self.model.style(latent.cuda())
32
+ + latent_w = self.model.style(latent.to(self.device))
33
+ for group_key in kwargs.keys():
34
+ if self.check_if_group_has_control(group_key):
35
+ if group_key == 'expression' and kwargs[group_key].shape[1] == 8:
36
+ - group_w_latent = self.fc_controls['expression_q'](kwargs[group_key].cuda().float())
37
+ + group_w_latent = self.fc_controls['expression_q'](kwargs[group_key].to(self.device).float())
38
+ else:
39
+ - group_w_latent = self.fc_controls[group_key](kwargs[group_key].cuda().float())
40
+ + group_w_latent = self.fc_controls[group_key](kwargs[group_key].to(self.device).float())
41
+ latent_w = self.insert_group_w_latent(latent_w, group_w_latent, group_key)
42
+ injection_noise = None
43
+ if static_noise:
44
+ @@ -101,12 +101,12 @@ class Controller(Inference):
45
+ ckpt_path = ckpt_list[-1]
46
+ ckpt_iter = ckpt_path.split('.')[0]
47
+ config = read_json(config_path, return_obj=True)
48
+ - ckpt = torch.load(os.path.join(checkpoints_path, ckpt_path))
49
+ + ckpt = torch.load(os.path.join(checkpoints_path, ckpt_path), map_location=self.device)
50
+ group_chunk = self.batch_utils.place_in_latent_dict[sub_group_name if sub_group_name is not 'expression_q' else 'expression']
51
+ group_latent_size = group_chunk[1] - group_chunk[0]
52
+
53
+ _log.info('Init %s Controller...' % sub_group_name)
54
+ - controller = FcStack(config.model_config['lr_mlp'], config.model_config['n_mlp'], config.model_config['in_dim'], config.model_config['mid_dim'], group_latent_size).cuda()
55
+ + controller = FcStack(config.model_config['lr_mlp'], config.model_config['n_mlp'], config.model_config['in_dim'], config.model_config['mid_dim'], group_latent_size).to(self.device)
56
+ controller.print()
57
+
58
+ _log.info('Loading Controller: %s, ckpt iter %s' % (controller_dir_path, ckpt_iter))
59
+ diff --git a/src/gan_control/inference/inference.py b/src/gan_control/inference/inference.py
60
+ index e6ccedb..4393bb7 100644
61
+ --- a/src/gan_control/inference/inference.py
62
+ +++ b/src/gan_control/inference/inference.py
63
+ @@ -15,10 +15,11 @@ _log = get_logger(__name__)
64
+
65
+
66
+ class Inference():
67
+ - def __init__(self, model_dir):
68
+ + def __init__(self, model_dir, device):
69
+ _log.info('Init inference class...')
70
+ self.model_dir = model_dir
71
+ - self.model, self.batch_utils, self.config, self.ckpt_iter = self.retrieve_model(model_dir)
72
+ + self.device = device
73
+ + self.model, self.batch_utils, self.config, self.ckpt_iter = self.retrieve_model(model_dir, device)
74
+ self.noise = None
75
+ self.reset_noise()
76
+ self.mean_w_latent = None
77
+ @@ -28,7 +29,7 @@ class Inference():
78
+ _log.info('Calc mean_w_latents...')
79
+ mean_latent_w_list = []
80
+ for i in range(100):
81
+ - latent_z = torch.randn(1000, self.config.model_config['latent_size'], device='cuda')
82
+ + latent_z = torch.randn(1000, self.config.model_config['latent_size'], device=self.device)
83
+ if isinstance(self.model, torch.nn.DataParallel):
84
+ latent_w = self.model.module.style(latent_z).cpu()
85
+ else:
86
+ @@ -41,9 +42,9 @@ class Inference():
87
+
88
+ def reset_noise(self):
89
+ if isinstance(self.model, torch.nn.DataParallel):
90
+ - self.noise = self.model.module.make_noise(device='cuda')
91
+ + self.noise = self.model.module.make_noise(device=self.device)
92
+ else:
93
+ - self.noise = self.model.make_noise(device='cuda')
94
+ + self.noise = self.model.make_noise(device=self.device)
95
+
96
+ @staticmethod
97
+ def expend_noise(noise, batch_size):
98
+ @@ -56,14 +57,14 @@ class Inference():
99
+ self.calc_mean_w_latents()
100
+ injection_noise = None
101
+ if latent is None:
102
+ - latent = torch.randn(batch_size, self.config.model_config['latent_size'], device='cuda')
103
+ + latent = torch.randn(batch_size, self.config.model_config['latent_size'], device=self.device)
104
+ elif input_is_latent:
105
+ - latent = latent.cuda()
106
+ + latent = latent.to(self.device)
107
+ for group_key in kwargs.keys():
108
+ if group_key not in self.batch_utils.sub_group_names:
109
+ raise ValueError('group_key: %s not in sub_group_names %s' % (group_key, str(self.batch_utils.sub_group_names)))
110
+ if isinstance(kwargs[group_key], str) and kwargs[group_key] == 'random':
111
+ - group_latent_w = self.model.style(torch.randn(latent.shape[0], self.config.model_config['latent_size'], device='cuda'))
112
+ + group_latent_w = self.model.style(torch.randn(latent.shape[0], self.config.model_config['latent_size'], device=self.device))
113
+ group_latent_w = group_latent_w[:, self.batch_utils.place_in_latent_dict[group_key][0], self.batch_utils.place_in_latent_dict[group_key][0]]
114
+ latent[:, self.batch_utils.place_in_latent_dict[group_key][0], self.batch_utils.place_in_latent_dict[group_key][0]] = group_latent_w
115
+ if static_noise:
116
+ @@ -82,11 +83,11 @@ class Inference():
117
+ latent[:, place_in_latent[0]: place_in_latent[1]] = \
118
+ truncation * (latent[:, place_in_latent[0]: place_in_latent[1]] - torch.cat(
119
+ [self.mean_w_latents[key].clone().unsqueeze(0) for _ in range(latent.shape[0])], dim=0
120
+ - ).cuda()) + torch.cat(
121
+ + ).to(self.device)) + torch.cat(
122
+ [self.mean_w_latents[key].clone().unsqueeze(0) for _ in range(latent.shape[0])], dim=0
123
+ - ).cuda()
124
+ + ).to(self.device)
125
+
126
+ - tensor, latent_w = self.model([latent.cuda()], return_latents=True, input_is_latent=input_is_latent, noise=injection_noise)
127
+ + tensor, latent_w = self.model([latent.to(self.device)], return_latents=True, input_is_latent=input_is_latent, noise=injection_noise)
128
+ if normalize:
129
+ tensor = tensor.mul(0.5).add(0.5).clamp(min=0., max=1.).cpu()
130
+ return tensor, latent, latent_w
131
+ @@ -107,7 +108,7 @@ class Inference():
132
+ return grid_image
133
+
134
+ @staticmethod
135
+ - def retrieve_model(model_dir):
136
+ + def retrieve_model(model_dir, device):
137
+ config_path = os.path.join(model_dir, 'args.json')
138
+
139
+ _log.info('Retrieve config from %s' % config_path)
140
+ @@ -117,7 +118,7 @@ class Inference():
141
+ ckpt_path = ckpt_list[-1]
142
+ ckpt_iter = ckpt_path.split('.')[0]
143
+ config = read_json(config_path, return_obj=True)
144
+ - ckpt = torch.load(os.path.join(checkpoints_path, ckpt_path))
145
+ + ckpt = torch.load(os.path.join(checkpoints_path, ckpt_path), map_location=device)
146
+
147
+ batch_utils = None
148
+ if not config.model_config['vanilla']:
149
+ @@ -140,7 +141,7 @@ class Inference():
150
+ fc_config=None if config.model_config['vanilla'] else batch_utils.get_fc_config(),
151
+ conv_transpose=config.model_config['conv_transpose'],
152
+ noise_mode=config.model_config['g_noise_mode']
153
+ - ).cuda()
154
+ + ).to(device)
155
+ _log.info('Loading Model: %s, ckpt iter %s' % (model_dir, ckpt_iter))
156
+ model.load_state_dict(ckpt['g_ema'])
157
+ model = torch.nn.DataParallel(model)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ numpy==1.22.3
2
+ Pillow==9.1.0
3
+ torch==1.11.0
4
+ torchvision==0.12.0