compat.py 6.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

M
Mark Daoust 已提交
17 18
See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
19 20 21 22 23 24 25
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
26
import os
27

28
from tensorflow.python.platform import tf_logging as logging
29
from tensorflow.python.util import tf_contextlib
30
from tensorflow.python.util.tf_export import tf_export
31

32

33 34 35
# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
36
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2020, 11, 1)
37
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
38 39 40 41 42 43
_FORWARD_COMPATIBILITY_DATE_NUMBER = None


def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

44

45 46
def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""
47

48 49 50 51
  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
52
  else:
53 54 55 56 57
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

58 59 60 61
  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
62 63 64 65 66
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)


_update_forward_compatibility_date_number()
67

68

69
@tf_export("compat.forward_compatible")
70 71 72
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

M
Mark Daoust 已提交
73 74
  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
K
Kazuaki Ishizaki 已提交
105
    # To maintain forward compatibility, use the old implementation.
106 107 108 109 110 111 112 113 114
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
115 116
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
117
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
118
      `int`.
119 120 121 122 123 124

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
125 126
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)
127 128


129
@tf_export("compat.forward_compatibility_horizon")
130 131 132 133
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

M
Mark Daoust 已提交
134 135
  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

159 160 161
  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
162
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
163
      `int`.
164 165 166 167 168

  Yields:
    Nothing.
  """
  try:
169
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
170 171
    yield
  finally:
172
    _update_forward_compatibility_date_number()