{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "SB93Ge748VQs" }, "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "cellView": "form", "execution": { "iopub.execute_input": "2025-06-26T11:07:04.263787Z", "iopub.status.busy": "2025-06-26T11:07:04.263187Z", "iopub.status.idle": "2025-06-26T11:07:04.267052Z", "shell.execute_reply": "2025-06-26T11:07:04.266472Z" }, "id": "0sK8X2O9bTlz" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "HEYuO5NFwDK9" }, "source": [ "# Migrating tf.summary usage to TF 2.x\n", "\n", "
\n",
" ![]() | \n",
" \n",
" ![]() | \n",
" \n",
" ![]() | \n",
" \n",
" ![]() | \n",
"
tf.compat.v1.summary
will automatically forward to their TF 2.x equivalents under the following conditions:\n",
"\n",
" - The outermost context is eager mode\n",
" - A default TF 2.x summary writer has been set\n",
" - A non-empty value for step has been set for the writer (using tf.summary.SummaryWriter.as_default
, tf.summary.experimental.set_step
, or alternatively tf.compat.v1.train.create_global_step
)\n",
"\n",
"Note that when TF 2.x summary implementation is invoked, the return value will be an empty bytestring tensor, to avoid duplicate summary writing. Additionally, the input argument forwarding is best-effort and not all arguments will be preserved (for instance `family` argument will be supported whereas `collections` will be removed).\n",
"\n",
"Example to invoke tf.summary.scalar
behaviors in tf.compat.v1.summary.scalar
:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"execution": {
"iopub.execute_input": "2025-06-26T11:07:10.963657Z",
"iopub.status.busy": "2025-06-26T11:07:10.963389Z",
"iopub.status.idle": "2025-06-26T11:07:10.972672Z",
"shell.execute_reply": "2025-06-26T11:07:10.972056Z"
},
"id": "6457297c0b9d"
},
"outputs": [],
"source": [
"# Enable eager execution.\n",
"tf.compat.v1.enable_v2_behavior()\n",
"\n",
"# A default TF 2.x summary writer is available.\n",
"writer = tf.summary.create_file_writer(\"/tmp/mylogs/enable_v2_in_v1\")\n",
"# A step is set for the writer.\n",
"with writer.as_default(step=0):\n",
" # Below invokes `tf.summary.scalar`, and the return value is an empty bytestring.\n",
" tf.compat.v1.summary.scalar('float', tf.constant(1.0), family=\"family\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Pq4Fy1bSUdrZ"
},
"source": [
"### Full Migration\n",
"\n",
"To fully migrate to TF 2.x, you'll need to adapt your code as follows:\n",
"\n",
"1. A default writer set via `.as_default()` must be present to use summary ops\n",
"\n",
" - This means executing ops eagerly or using ops in graph construction\n",
" - Without a default writer, summary ops become silent no-ops\n",
" - Default writers do not (yet) propagate across the `@tf.function` execution boundary - they are only detected when the function is traced - so best practice is to call `writer.as_default()` within the function body, and to ensure that the writer object continues to exist as long as the `@tf.function` is being used\n",
"\n",
"1. The \"step\" value must be passed into each op via a the `step` argument\n",
"\n",
" - TensorBoard requires a step value to render the data as a time series\n",
" - Explicit passing is necessary because the global step from TF 1.x has been removed, so each op must know the desired step variable to read\n",
" - To reduce boilerplate, experimental support for registering a default step value is available as `tf.summary.experimental.set_step()`, but this is provisional functionality that may be changed without notice\n",
"\n",
"1. Function signatures of individual summary ops have changed\n",
"\n",
" - Return value is now a boolean (indicating if a summary was actually written)\n",
" - The second parameter name (if used) has changed from `tensor` to `data`\n",
" - The `collections` parameter has been removed; collections are TF 1.x only\n",
" - The `family` parameter has been removed; just use `tf.name_scope()`\n",
"\n",
"1. [Only for legacy graph mode / session execution users]\n",
" - First initialize the writer with `v1.Session.run(writer.init())`\n",
"\n",
" - Use `v1.summary.all_v2_summary_ops()` to get all TF 2.x summary ops for the current graph, e.g. to execute them via `Session.run()`\n",
" - Flush the writer with `v1.Session.run(writer.flush())` and likewise for `close()`\n",
"\n",
"If your TF 1.x code was instead using `tf.contrib.summary` API, it's much more similar to the TF 2.x API, so `tf_upgrade_v2` script will automate most of the migration steps (and emit warnings or errors for any usage that cannot be fully migrated). For the most part it just rewrites the API calls to `tf.compat.v2.summary`; if you only need compatibility with TF 2.x you can drop the `compat.v2` and just reference it as `tf.summary`."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1GUZRWSkW3ZC"
},
"source": [
"## Additional tips\n",
"\n",
"In addition to the critical areas above, some auxiliary aspects have also changed:\n",
"\n",
"* Conditional recording (like \"log every 100 steps\") has a new look\n",
"\n",
" - To control ops and associated code, wrap them in a regular if statement (which works in eager mode and in [`@tf.function` via autograph](https://www.tensorflow.org/alpha/guide/autograph)) or a `tf.cond`\n",
" - To control just \tsummaries, use the new `tf.summary.record_if()` context manager, and pass it the boolean condition of your choosing\n",
" - These replace the TF 1.x pattern:\n",
" ```\n",
" if condition:\n",
" writer.add_summary()\n",
" ```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9VMYrKn4Uh52"
},
"source": [
"* No direct writing of `tf.compat.v1.Graph` - instead use trace functions\n",
"\n",
" - Graph execution in TF 2.x uses `@tf.function` instead of the explicit Graph\n",
" - In TF 2.x, use the new tracing-style APIs `tf.summary.trace_on()` and `tf.summary.trace_export()` to record executed function graphs\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UGItA6U0UkDx"
},
"source": [
"* No more global writer caching per logdir with `tf.summary.FileWriterCache`\n",
"\n",
" - Users should either implement their own caching/sharing of writer objects, or just use separate writers (TensorBoard support for the latter is [in progress](https://github.com/tensorflow/tensorboard/issues/1063))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d7BQJVcsUnMp"
},
"source": [
"* The event file binary representation has changed\n",
"\n",
" - TensorBoard 1.x already supports the new format; this difference only affects users who are manually parsing summary data from event files\n",
" - Summary data is now stored as tensor bytes; you can use `tf.make_ndarray(event.summary.value[0].tensor)` to convert it to numpy"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [],
"name": "migrate.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.23"
}
},
"nbformat": 4,
"nbformat_minor": 0
}