MCPcopy Create free account
hub / github.com/cientgu/VQ-Diffusion / sample

Method sample

image_synthesis/engine/solver.py:178–228  ·  view source on GitHub ↗
(self, batch, phase='train', step_type='iteration')

Source from the content-addressed store, hash-verified

176 return lrs
177
178 def sample(self, batch, phase='train', step_type='iteration'):
179 tic = time.time()
180 self.logger.log_info('Begin to sample...')
181 if self.ema is not None:
182 self.ema.modify_to_inference()
183 suffix = '_ema'
184 else:
185 suffix = ''
186
187 if isinstance(self.model, torch.nn.parallel.DistributedDataParallel):
188 model = self.model.module
189 else:
190 model = self.model
191
192 with torch.no_grad():
193 if self.debug == False:
194 if self.args.amp:
195 with autocast():
196 samples = model.sample(batch=batch, step=self.last_iter)
197 else:
198 samples = model.sample(batch=batch, step=self.last_iter)
199 else:
200 samples = model.sample(batch=batch[0].cuda(), step=self.last_iter)
201
202 step = self.last_iter if step_type == 'iteration' else self.last_epoch
203 for k, v in samples.items():
204 save_dir = os.path.join(self.image_dir, phase, k)
205 os.makedirs(save_dir, exist_ok=True)
206 save_path = os.path.join(save_dir, 'e{:010d}_itr{:010d}_rank{}{}'.format(self.last_epoch, self.last_iter%self.dataloader['train_iterations'], get_rank(), suffix))
207 if torch.is_tensor(v) and v.dim() == 4 and v.shape[1] in [1, 3]: # image
208 im = v
209 im = im.to(torch.uint8)
210 self.logger.add_images(tag='{}/{}e_{}itr/{}'.format(phase, self.last_epoch, self.last_iter%self.dataloader['train_iterations'], k), img_tensor=im, global_step=step, dataformats='NCHW')
211
212 # save images
213 im_grid = torchvision.utils.make_grid(im)
214 im_grid = im_grid.permute(1, 2, 0).to('cpu').numpy()
215 im_grid = Image.fromarray(im_grid)
216
217 im_grid.save(save_path + '.jpg')
218 self.logger.log_info('save {} to {}'.format(k, save_path+'.jpg'))
219 else: # may be other values, such as text caption
220 with open(save_path+'.txt', 'a') as f:
221 f.write(str(v)+'\n')
222 f.close()
223 self.logger.log_info('save {} to {}'.format(k, save_path+'txt'))
224
225 if self.ema is not None:
226 self.ema.modify_to_train()
227
228 self.logger.log_info('Sample done, time: {:.2f}'.format(time.time() - tic))
229
230 def step(self, batch, phase='train'):
231 loss = {}

Callers 1

train_epochMethod · 0.95

Calls 7

get_rankFunction · 0.90
log_infoMethod · 0.80
modify_to_inferenceMethod · 0.80
add_imagesMethod · 0.80
saveMethod · 0.80
closeMethod · 0.80
modify_to_trainMethod · 0.80

Tested by

no test coverage detected