| 74 | |
| 75 | |
| 76 | class GANTrainer(TowerTrainer): |
| 77 | |
| 78 | def __init__(self, input, model, num_gpu=1): |
| 79 | """ |
| 80 | Args: |
| 81 | input (InputSource): |
| 82 | model (GANModelDesc): |
| 83 | """ |
| 84 | super(GANTrainer, self).__init__() |
| 85 | assert isinstance(model, GANModelDesc), model |
| 86 | |
| 87 | if num_gpu > 1: |
| 88 | input = StagingInput(input) |
| 89 | |
| 90 | # Setup input |
| 91 | cbs = input.setup(model.get_input_signature()) |
| 92 | self.register_callback(cbs) |
| 93 | |
| 94 | if num_gpu <= 1: |
| 95 | self._build_gan_trainer(input, model) |
| 96 | else: |
| 97 | self._build_multigpu_gan_trainer(input, model, num_gpu) |
| 98 | |
| 99 | def _build_gan_trainer(self, input, model): |
| 100 | """ |
| 101 | We need to set tower_func because it's a TowerTrainer, |
| 102 | and only TowerTrainer supports automatic graph creation for inference during training. |
| 103 | |
| 104 | If we don't care about inference during training, using tower_func is |
| 105 | not needed. Just calling model.build_graph directly is OK. |
| 106 | """ |
| 107 | # Build the graph |
| 108 | self.tower_func = TowerFunc(model.build_graph, model.inputs()) |
| 109 | with TowerContext('', is_training=True): |
| 110 | self.tower_func(*input.get_input_tensors()) |
| 111 | opt = model.get_optimizer() |
| 112 | |
| 113 | # Define the training iteration |
| 114 | # by default, run one d_min after one g_min |
| 115 | with tf.name_scope('optimize'): |
| 116 | g_min = opt.minimize(model.g_loss, var_list=model.g_vars, name='g_op') |
| 117 | with tf.control_dependencies([g_min]): |
| 118 | d_min = opt.minimize(model.d_loss, var_list=model.d_vars, name='d_op') |
| 119 | self.train_op = d_min |
| 120 | |
| 121 | def _build_multigpu_gan_trainer(self, input, model, num_gpu): |
| 122 | assert num_gpu > 1 |
| 123 | raw_devices = ['/gpu:{}'.format(k) for k in range(num_gpu)] |
| 124 | |
| 125 | # Build the graph with multi-gpu replication |
| 126 | def get_cost(*inputs): |
| 127 | model.build_graph(*inputs) |
| 128 | return [model.d_loss, model.g_loss] |
| 129 | |
| 130 | self.tower_func = TowerFunc(get_cost, model.get_input_signature()) |
| 131 | devices = [LeastLoadedDeviceSetter(d, raw_devices) for d in raw_devices] |
| 132 | cost_list = DataParallelBuilder.call_for_each_tower( |
| 133 | list(range(num_gpu)), |
no outgoing calls
no test coverage detected
searching dependent graphs…