|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | +from workflow.torch import module_eval |
| 4 | + |
| 5 | +from vae import architecture |
| 6 | + |
| 7 | + |
| 8 | +def log_examples(description, trainer, model): |
| 9 | + def log_examples_(engine, logger, event_name): |
| 10 | + n_examples = 5 |
| 11 | + indices = np.random.choice( |
| 12 | + len(engine.state.output['predictions']), |
| 13 | + n_examples, |
| 14 | + replace=False, |
| 15 | + ) |
| 16 | + |
| 17 | + logger.writer.add_images( |
| 18 | + f'{description}/predictions', |
| 19 | + np.stack([ |
| 20 | + np.concatenate([ |
| 21 | + np.array( |
| 22 | + engine.state.output['examples'][index] |
| 23 | + .representation() |
| 24 | + ), |
| 25 | + np.array( |
| 26 | + engine.state.output['predictions'][index] |
| 27 | + .representation() |
| 28 | + ), |
| 29 | + ], axis=0) / 255 |
| 30 | + for index in indices |
| 31 | + ]), |
| 32 | + trainer.state.epoch, |
| 33 | + dataformats='NHWC', |
| 34 | + ) |
| 35 | + |
| 36 | + with torch.no_grad(), module_eval(model) as eval_model: |
| 37 | + std_samples = [ |
| 38 | + eval_model.generated(16, prior_std) |
| 39 | + for prior_std in np.linspace(0.4, 1.1, num=8) |
| 40 | + ] |
| 41 | + |
| 42 | + logger.writer.add_images( |
| 43 | + f'{description}/samples', |
| 44 | + np.stack([np.concatenate([ |
| 45 | + np.concatenate([ |
| 46 | + np.array(sample.representation()) |
| 47 | + for sample in samples |
| 48 | + ], axis=1) |
| 49 | + for samples in std_samples |
| 50 | + ], axis=0)]) / 255, |
| 51 | + trainer.state.epoch, |
| 52 | + dataformats='NHWC', |
| 53 | + ) |
| 54 | + |
| 55 | + with torch.no_grad(), module_eval(model) as eval_model: |
| 56 | + partial_samples = [ |
| 57 | + eval_model.partially_generated( |
| 58 | + architecture.FeaturesBatch.from_examples( |
| 59 | + [ |
| 60 | + engine.state.output['examples'][index] |
| 61 | + for index in indices |
| 62 | + ] |
| 63 | + ).image_batch, |
| 64 | + sample=[ |
| 65 | + index == sample_index |
| 66 | + for index in range(model.levels) |
| 67 | + ], |
| 68 | + prior_std=0.7, |
| 69 | + ) |
| 70 | + for sample_index in range(model.levels) |
| 71 | + ] |
| 72 | + |
| 73 | + logger.writer.add_images( |
| 74 | + f'{description}/partially_sampled', |
| 75 | + np.concatenate([ |
| 76 | + np.stack([ |
| 77 | + np.array(sample.representation()) |
| 78 | + for sample in samples |
| 79 | + ]) |
| 80 | + for samples in partial_samples |
| 81 | + ], axis=1) / 255, |
| 82 | + trainer.state.epoch, |
| 83 | + dataformats='NHWC', |
| 84 | + ) |
| 85 | + |
| 86 | + return log_examples_ |
0 commit comments