MCPcopy Create free account
hub / github.com/Turing-Project/WriteGPT / construct_scalar_host_call

Function construct_scalar_host_call

LanguageNetwork/GPT2/train/utils.py:184–234  ·  view source on GitHub ↗

Construct a host call to log scalars when training on TPU. Args: metric_dict: A dict of the tensors to be logged. model_dir: The location to write the summary. prefix: The prefix (if any) to prepend to the metric names. Returns: A tuple of (function, args_to_be_pass

(metric_dict, model_dir, prefix="")

Source from the content-addressed store, hash-verified

182
183
184def construct_scalar_host_call(metric_dict, model_dir, prefix=""):
185 """Construct a host call to log scalars when training on TPU.
186
187 Args:
188 metric_dict: A dict of the tensors to be logged.
189 model_dir: The location to write the summary.
190 prefix: The prefix (if any) to prepend to the metric names.
191
192 Returns:
193 A tuple of (function, args_to_be_passed_to_said_function)
194 """
195 metric_names = list(metric_dict.keys())
196
197 def host_call_fn(global_step, *args):
198 """Training host call. Creates scalar summaries for training metrics.
199
200 This function is executed on the CPU and should not directly reference
201 any Tensors in the rest of the `model_fn`. To pass Tensors from the
202 model to the `metric_fn`, provide as part of the `host_call`. See
203 https://www.tensorflow.org/api_docs/python/tf/contrib/tpu/TPUEstimatorSpec
204 for more information.
205
206 Arguments should match the list of `Tensor` objects passed as the second
207 element in the tuple passed to `host_call`.
208
209 Args:
210 global_step: `Tensor with shape `[batch]` for the global_step
211 *args: Remaining tensors to log.
212
213 Returns:
214 List of summary ops to run on the CPU host.
215 """
216 step = global_step[0]
217 with tf.contrib.summary.create_file_writer(
218 logdir=model_dir, filename_suffix=".host_call").as_default():
219 with tf.contrib.summary.always_record_summaries():
220 for i, name in enumerate(metric_names):
221 tf.contrib.summary.scalar(prefix + name, args[i][0], step=step)
222
223 return tf.contrib.summary.all_summary_ops()
224
225 # To log the current learning rate, and gradient norm for Tensorboard, the
226 # summary op needs to be run on the host CPU via host_call. host_call
227 # expects [batch_size, ...] Tensors, thus reshape to introduce a batch
228 # dimension. These Tensors are implicitly concatenated to
229 # [params['batch_size']].
230 global_step_tensor = tf.reshape(
231 tf.compat.v1.train.get_or_create_global_step(), [1])
232 other_tensors = [tf.reshape(metric_dict[key], [1]) for key in metric_names]
233
234 return host_call_fn, [global_step_tensor] + other_tensors

Callers 1

model_fnFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected