From 2c858368c8c4b7e82c8d134786026a62a72d2676 Mon Sep 17 00:00:00 2001
From: Randy West
Date: Mon, 18 Dec 2017 18:22:03 -0500
Subject: [PATCH 0001/1193] Compute test accuracy in batches to avoid OOM on
GPUs. Reported here: https://github.com/tensorflow/tensorflow/issues/136
Alternative to this for mnist_deep.py:
https://github.com/tensorflow/tensorflow/pull/157
---
tensorflow/examples/tutorials/mnist/mnist_deep.py | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/tensorflow/examples/tutorials/mnist/mnist_deep.py b/tensorflow/examples/tutorials/mnist/mnist_deep.py
index 1e0294db27..2699738735 100644
--- a/tensorflow/examples/tutorials/mnist/mnist_deep.py
+++ b/tensorflow/examples/tutorials/mnist/mnist_deep.py
@@ -34,6 +34,8 @@ from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
+import numpy
+
FLAGS = None
@@ -164,8 +166,13 @@ def main(_):
print('step %d, training accuracy %g' % (i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
- print('test accuracy %g' % accuracy.eval(feed_dict={
- x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
+ # compute in batches to avoid OOM on GPUs
+ accuracy_l = []
+ for i in range(50):
+ batch = mnist.test.next_batch(500, shuffle=False)
+ accuracy_l.append(accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}))
+ print('test accuracy %g' % numpy.mean(accuracy_l))
+
if __name__ == '__main__':
parser = argparse.ArgumentParser()
--
GitLab
From 3f18817317940253e6ec0e6b412492c5add5927b Mon Sep 17 00:00:00 2001
From: Randy West
Date: Mon, 18 Dec 2017 23:18:30 -0500
Subject: [PATCH 0002/1193] Fix basic arithmetic fail + make loop pythonic
---
tensorflow/examples/tutorials/mnist/mnist_deep.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tensorflow/examples/tutorials/mnist/mnist_deep.py b/tensorflow/examples/tutorials/mnist/mnist_deep.py
index 2699738735..47d2777813 100644
--- a/tensorflow/examples/tutorials/mnist/mnist_deep.py
+++ b/tensorflow/examples/tutorials/mnist/mnist_deep.py
@@ -168,7 +168,7 @@ def main(_):
# compute in batches to avoid OOM on GPUs
accuracy_l = []
- for i in range(50):
+ for _ in range(20):
batch = mnist.test.next_batch(500, shuffle=False)
accuracy_l.append(accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}))
print('test accuracy %g' % numpy.mean(accuracy_l))
--
GitLab
From 5eb246cb79e37b6a7006b6dead99219ffd25de31 Mon Sep 17 00:00:00 2001
From: DavidNorman
Date: Wed, 16 May 2018 17:05:24 +0100
Subject: [PATCH 0003/1193] Don't do int64 tests for devices which do not
support int64
---
tensorflow/compiler/tests/binary_ops_test.py | 11 ++++++-----
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/tensorflow/compiler/tests/binary_ops_test.py b/tensorflow/compiler/tests/binary_ops_test.py
index 1e4dd32916..64eeed8312 100644
--- a/tensorflow/compiler/tests/binary_ops_test.py
+++ b/tensorflow/compiler/tests/binary_ops_test.py
@@ -686,11 +686,12 @@ class BinaryOpsTest(XLATestCase):
np.array([[10], [7], [2]], dtype=np.float32),
np.float32(7),
expected=np.array([[False], [False], [True]], dtype=np.bool))
- self._testBinary(
- less_op,
- np.array([[10], [7], [2], [-1]], dtype=np.int64),
- np.int64(7),
- expected=np.array([[False], [False], [True], [True]], dtype=np.bool))
+ if np.int64 in self.numeric_types:
+ self._testBinary(
+ less_op,
+ np.array([[10], [7], [2], [-1]], dtype=np.int64),
+ np.int64(7),
+ expected=np.array([[False], [False], [True], [True]], dtype=np.bool))
for less_equal_op in [math_ops.less_equal, (lambda x, y: x <= y)]:
self._testBinary(
--
GitLab
From 8f3635d15438af7c8f6f047a5999352d14901db7 Mon Sep 17 00:00:00 2001
From: Yong Tang
Date: Thu, 17 May 2018 17:50:20 +0000
Subject: [PATCH 0004/1193] Improve fast_tensor_util for bfloat16
In 19180, improvement has been done to speed up the
fast_tensor_util for `float16`. As both `float16`
and `bfloat16` uses the same size, `bfloat16`
could be improved as well. This fix speeds up `bfloat16`
in a similiar fashion as `float16`.
This fix is related to 19180.
Signed-off-by: Yong Tang
---
tensorflow/python/framework/fast_tensor_util.pyx | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/tensorflow/python/framework/fast_tensor_util.pyx b/tensorflow/python/framework/fast_tensor_util.pyx
index 17d112a1ec..2e3e15f53a 100644
--- a/tensorflow/python/framework/fast_tensor_util.pyx
+++ b/tensorflow/python/framework/fast_tensor_util.pyx
@@ -6,6 +6,13 @@ cimport numpy as np
from tensorflow.python.util import compat
+def AppendBFloat16ArrayToTensorProto(
+ tensor_proto, np.ndarray[np.uint16_t, ndim=1] nparray):
+ cdef long i, n
+ n = nparray.size
+ for i in range(n):
+ tensor_proto.half_val.append(nparray[i])
+
def AppendFloat16ArrayToTensorProto(
# For numpy, npy_half is a typedef for npy_uint16,
--
GitLab
From 6d5f5efadc6047828e79e0bdb4af133e0269faa7 Mon Sep 17 00:00:00 2001
From: Yong Tang
Date: Thu, 17 May 2018 17:53:07 +0000
Subject: [PATCH 0005/1193] Update tensorflow/python/framework/tensor_util.py
Signed-off-by: Yong Tang
---
tensorflow/python/framework/tensor_util.py | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/tensorflow/python/framework/tensor_util.py b/tensorflow/python/framework/tensor_util.py
index ca63efbc84..ebb1db534c 100644
--- a/tensorflow/python/framework/tensor_util.py
+++ b/tensorflow/python/framework/tensor_util.py
@@ -67,10 +67,14 @@ def SlowAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values):
[ExtractBitsFromBFloat16(x) for x in proto_values])
+def FastAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values):
+ fast_tensor_util.AppendBFloat16ArrayToTensorProto(tensor_proto, np.asarray(proto_values, dtype=dtypes.bfloat16.as_numpy_dtype).view(np.uint16))
+
+
if _FAST_TENSOR_UTIL_AVAILABLE:
_NP_TO_APPEND_FN = {
dtypes.bfloat16.as_numpy_dtype:
- SlowAppendBFloat16ArrayToTensorProto,
+ FastAppendBFloat16ArrayToTensorProto,
np.float16:
_MediumAppendFloat16ArrayToTensorProto,
np.float32:
--
GitLab
From 535fa4919c9e247e2df673d8af874c3a39a38976 Mon Sep 17 00:00:00 2001
From: Yong Tang
Date: Thu, 17 May 2018 17:55:10 +0000
Subject: [PATCH 0006/1193] Pylint fix.
Signed-off-by: Yong Tang
---
tensorflow/python/framework/tensor_util.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/tensorflow/python/framework/tensor_util.py b/tensorflow/python/framework/tensor_util.py
index ebb1db534c..e229d6105e 100644
--- a/tensorflow/python/framework/tensor_util.py
+++ b/tensorflow/python/framework/tensor_util.py
@@ -68,7 +68,9 @@ def SlowAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values):
def FastAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values):
- fast_tensor_util.AppendBFloat16ArrayToTensorProto(tensor_proto, np.asarray(proto_values, dtype=dtypes.bfloat16.as_numpy_dtype).view(np.uint16))
+ fast_tensor_util.AppendBFloat16ArrayToTensorProto(
+ tensor_proto, np.asarray(
+ proto_values, dtype=dtypes.bfloat16.as_numpy_dtype).view(np.uint16))
if _FAST_TENSOR_UTIL_AVAILABLE:
--
GitLab
From f2e22502fd58e8d81c9e080b9242375fbf2bc772 Mon Sep 17 00:00:00 2001
From: Jesse
Date: Tue, 5 Jun 2018 14:35:38 +0200
Subject: [PATCH 0007/1193] Updated line for creating global step + grammar
tf.train.get_global_step() returns None if there is no global step, preventing the pruning from working. Therefore, tf.train.get_or_create_global_step() is a safer option.
---
tensorflow/contrib/model_pruning/README.md | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/tensorflow/contrib/model_pruning/README.md b/tensorflow/contrib/model_pruning/README.md
index 86f4fd6adf..50e7e5d7cd 100644
--- a/tensorflow/contrib/model_pruning/README.md
+++ b/tensorflow/contrib/model_pruning/README.md
@@ -66,10 +66,10 @@ is the sparsity_function_begin_step. In this equation, the
sparsity_function_exponent is set to 3.
### Adding pruning ops to the training graph
-The final step involves adding ops to the training graph that monitors the
-distribution of the layer's weight magnitudes and determines the layer threshold
-such masking all the weights below this threshold achieves the sparsity level
-desired for the current training step. This can be achieved as follows:
+The final step involves adding ops to the training graph that monitor the
+distribution of the layer's weight magnitudes and determine the layer threshold,
+such that masking all the weights below this threshold achieves the sparsity
+level desired for the current training step. This can be achieved as follows:
```python
tf.app.flags.DEFINE_string(
@@ -79,7 +79,7 @@ tf.app.flags.DEFINE_string(
with tf.graph.as_default():
# Create global step variable
- global_step = tf.train.get_global_step()
+ global_step = tf.train.get_or_create_global_step()
# Parse pruning hyperparameters
pruning_hparams = pruning.get_pruning_hparams().parse(FLAGS.pruning_hparams)
--
GitLab
From f9c7fe82cb930ee26d281e4bf21211ed352d176e Mon Sep 17 00:00:00 2001
From: Jesse
Date: Tue, 5 Jun 2018 14:49:04 +0200
Subject: [PATCH 0008/1193] Put some emphasis on incrementing global step
Pruning will not work if the global step is not incremented
---
tensorflow/contrib/model_pruning/README.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/tensorflow/contrib/model_pruning/README.md b/tensorflow/contrib/model_pruning/README.md
index 50e7e5d7cd..9143d082bf 100644
--- a/tensorflow/contrib/model_pruning/README.md
+++ b/tensorflow/contrib/model_pruning/README.md
@@ -103,6 +103,7 @@ with tf.graph.as_default():
mon_sess.run(mask_update_op)
```
+Ensure that `global_step` is being [incremented](https://www.tensorflow.org/api_docs/python/tf/train/Optimizer#minimize), otherwise pruning will not work!
## Example: Pruning and training deep CNNs on the cifar10 dataset
--
GitLab
From e106a458dd26db58c7d5abbd4afef60f8ce33252 Mon Sep 17 00:00:00 2001
From: Jesse
Date: Tue, 5 Jun 2018 15:22:07 +0200
Subject: [PATCH 0009/1193] Prevent redundant ":0" in summary names
Take identical approach as is done with thresholds: using tf.Variable.op.name instead of tf.Variable.name, to prevent TensorFlow saying summary names are illegal (due to ":")
---
tensorflow/contrib/model_pruning/python/pruning.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tensorflow/contrib/model_pruning/python/pruning.py b/tensorflow/contrib/model_pruning/python/pruning.py
index 4b7af18b33..e6f9acc139 100644
--- a/tensorflow/contrib/model_pruning/python/pruning.py
+++ b/tensorflow/contrib/model_pruning/python/pruning.py
@@ -520,7 +520,7 @@ class Pruning(object):
thresholds = get_thresholds()
for index, mask in enumerate(masks):
if not self._exists_in_do_not_prune_list(mask.name):
- summary.scalar(mask.name + '/sparsity', nn_impl.zero_fraction(mask))
+ summary.scalar(mask.op.name + '/sparsity', nn_impl.zero_fraction(mask))
summary.scalar(thresholds[index].op.name + '/threshold',
thresholds[index])
--
GitLab
From 90b28b7316edb644b71b01edaaa8553d5913fc19 Mon Sep 17 00:00:00 2001
From: Jesse
Date: Wed, 6 Jun 2018 16:07:20 +0200
Subject: [PATCH 0010/1193] Removed redundant use of enumeration
Since every mask has an accompanying threshold, zip(masks, thresholds) can be used instead of enumerate(masks) and calling thresholds by index.
---
tensorflow/contrib/model_pruning/python/pruning.py | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/tensorflow/contrib/model_pruning/python/pruning.py b/tensorflow/contrib/model_pruning/python/pruning.py
index e6f9acc139..d843fa26d5 100644
--- a/tensorflow/contrib/model_pruning/python/pruning.py
+++ b/tensorflow/contrib/model_pruning/python/pruning.py
@@ -518,11 +518,10 @@ class Pruning(object):
summary.scalar('last_mask_update_step', self._last_update_step)
masks = get_masks()
thresholds = get_thresholds()
- for index, mask in enumerate(masks):
+ for mask, threshold in zip(masks, thresholds):
if not self._exists_in_do_not_prune_list(mask.name):
summary.scalar(mask.op.name + '/sparsity', nn_impl.zero_fraction(mask))
- summary.scalar(thresholds[index].op.name + '/threshold',
- thresholds[index])
+ summary.scalar(threshold.op.name + '/threshold', threshold)
def print_hparams(self):
logging.info(self._spec.to_json())
--
GitLab
From 02b7fa3dfe3e82ca61581bf3365788c8acaa2b19 Mon Sep 17 00:00:00 2001
From: Amit Patankar
Date: Wed, 6 Jun 2018 14:04:40 -0700
Subject: [PATCH 0011/1193] Adding a constraint for the setuptools version.
---
tensorflow/tools/pip_package/setup.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/tensorflow/tools/pip_package/setup.py b/tensorflow/tools/pip_package/setup.py
index 78d955c637..97f625e7e9 100644
--- a/tensorflow/tools/pip_package/setup.py
+++ b/tensorflow/tools/pip_package/setup.py
@@ -54,6 +54,7 @@ REQUIRED_PACKAGES = [
'numpy >= 1.13.3',
'six >= 1.10.0',
'protobuf >= 3.4.0',
+ 'setuptools <= 39.1.0',
'tensorboard >= 1.8.0, < 1.9.0',
'termcolor >= 1.1.0',
]
--
GitLab
From da3f4f86267a42f1a7780222143d79b167a75eb1 Mon Sep 17 00:00:00 2001
From: Amit Patankar
Date: Wed, 6 Jun 2018 14:27:59 -0700
Subject: [PATCH 0012/1193] Removing the force downgrade install.
---
tensorflow/tools/ci_build/builds/pip.sh | 4 ----
1 file changed, 4 deletions(-)
diff --git a/tensorflow/tools/ci_build/builds/pip.sh b/tensorflow/tools/ci_build/builds/pip.sh
index 883bb93647..5fa75e1d61 100755
--- a/tensorflow/tools/ci_build/builds/pip.sh
+++ b/tensorflow/tools/ci_build/builds/pip.sh
@@ -322,10 +322,6 @@ create_activate_virtualenv_and_install_tensorflow() {
pip install -v ${PIP_FLAGS} ${WHL_PATH} || \
die "pip install (forcing to reinstall tensorflow) FAILED"
echo "Successfully installed pip package ${TF_WHEEL_PATH}"
-
- # Force downgrade setuptools.
- pip install --upgrade setuptools==39.1.0
-
}
################################################################################
--
GitLab
From 60cb7f88afda606df2b700ce0bb662f22e1a7709 Mon Sep 17 00:00:00 2001
From: Derek Murray
Date: Thu, 7 Jun 2018 12:53:11 -0700
Subject: [PATCH 0013/1193] Consolidate `tf.data` release notes.
---
RELEASE.md | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/RELEASE.md b/RELEASE.md
index c1ed69bd45..8f76e7efb4 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -14,8 +14,13 @@
## Bug Fixes and Other Changes
* `tf.data`:
- * The `DatasetBase::DebugString()` method is now `const`.
- * Added the `tf.contrib.data.sample_from_datasets()` API for randomly sampling from multiple datasets.
+ * `Dataset.from_generator()` now accepts an `args` list, in order to create nested generators.
+ * `Dataset.list_files()` now produces determinstic results when `shuffle=False` or a `seed` is passed.
+ * `tf.contrib.data.sample_from_datasets()` and `tf.contrib.data.choose_from_datasets()` make it easier to sample or deterministically choose elements from multiple datasets.
+ * `tf.contrib.data.make_csv_dataset()` now supports line breaks in quoted strings, and two infrequently used arguments removed.
+ * (C++) `DatasetBase::DebugString()` is now `const`.
+ * (C++) `DatasetBase::MakeIterator()` has been renamed to `DatasetBase::MakeIteratorInternal()`.
+ * (C++) `IteratorBase::Initialize()` method was added to support raising errors during iterator construction.
* Eager Execution:
* `tf.keras`:
* Move Keras code out of _impl folder and remove API files.
@@ -24,8 +29,6 @@
* Accelerated Linear Algebra (XLA):
* TensorFlow Debugger (tfdbg) CLI:
* `tf.contrib`:
- * Add `tf.contrib.data.choose_from_datasets()`.
- * `tf.contrib.data.make_csv_dataset()` now supports line breaks in quoted strings. Two arguments were removed from `make_csv_dataset`.
* `tf.contrib.framework.zero_initializer` supports ResourceVariable.
* Adding "constrained_optimization" to tensorflow/contrib.
* Other:
@@ -35,7 +38,6 @@
* More consistent GcsFileSystem behavior for certain reads past EOF.
* Update benchmark for tf.scan to match ranges across eager and graph modes.
* Fixed bug in `tf.reduce_prod gradient` for complex dtypes.
- * Add optional `args` argument to `Dataset.from_generator()`.
* Allow the use of '.' in variables (e.g. "hparams.parse('a.b=1.0')"), which would previously raise an error. This will correspond to an attribute name with an embedded '.' symbol (e.g. 'a.b'), which can only be accessed indirectly (e.g. through getattr and setattr). To set this up the user will first need to explicitly add the variable to the hparam object (e.g. "hparams.add_hparam(name='a.b', value=0.0)").
* Benchmark for tf.scan in graph and eager modes.
* Added complex128 support to FFT, FFT2D, FFT3D, IFFT, IFFT2D, and IFFT3D.
@@ -45,7 +47,6 @@
* LinearOperator[1D,2D,3D]Circulant added to `tensorflow.linalg`.
* Conv3D, Conv3DBackpropInput, Conv3DBackpropFilter now supports arbitrary.
* Added `tf.train.Checkpoint` for reading/writing object-based checkpoints.
- * `Dataset.list_files()` now produces determinstic results when `shuffle=False` or a `seed` is passed.
* Added LinearOperatorKronecker, a dense-free implementation of the Kronecker Product.
* Allow LinearOperator to broadcast.
* SavedModelBuilder will now deduplicate asset names that point to files with the same basename and the same contents. Note that this may result in new asset files included in SavedModels in cases where assets with the same name but different contents were previously overwriting each other.
--
GitLab
From d3b482dadfa1b59ec04ee668ebd899e6bcb4b7b8 Mon Sep 17 00:00:00 2001
From: Shanqing Cai
Date: Fri, 8 Jun 2018 14:55:26 -0400
Subject: [PATCH 0014/1193] Update RELEASE.md (r1.9) for tfdbg and XLA
---
RELEASE.md | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/RELEASE.md b/RELEASE.md
index 8f76e7efb4..879ce6e440 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -26,8 +26,7 @@
* Move Keras code out of _impl folder and remove API files.
* `tf.keras.Model.save_weights` now saves in TensorFlow format by default.
* Enable dataset iterators to be passed to `tf.keras.Model` training/eval methods.
-* Accelerated Linear Algebra (XLA):
-* TensorFlow Debugger (tfdbg) CLI:
+* TensorFlow Debugger (tfdbg) CLI: fix an issue in which the TensorBoard Debugger Plugin could not handle total source file size exceeding gRPC message size limit (4 MB).
* `tf.contrib`:
* `tf.contrib.framework.zero_initializer` supports ResourceVariable.
* Adding "constrained_optimization" to tensorflow/contrib.
--
GitLab
From a08c8a79f3d0ea5a7fac74d8f5e9da5def89170b Mon Sep 17 00:00:00 2001
From: Mark Daoust
Date: Mon, 4 Jun 2018 11:11:06 -0700
Subject: [PATCH 0015/1193] Fix visibility for tf.keras.__version__
PiperOrigin-RevId: 199161696
---
tensorflow/python/keras/__init__.py | 4 ++++
tensorflow/python/keras/integration_test.py | 3 +++
2 files changed, 7 insertions(+)
diff --git a/tensorflow/python/keras/__init__.py b/tensorflow/python/keras/__init__.py
index 197f306097..3493069a5b 100644
--- a/tensorflow/python/keras/__init__.py
+++ b/tensorflow/python/keras/__init__.py
@@ -41,8 +41,12 @@ from tensorflow.python.keras.layers import Input
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.models import Sequential
+from tensorflow.python.util.tf_export import tf_export
+
__version__ = '2.1.6-tf'
+tf_export('keras.__version__').export_constant(__name__, '__version__')
+
del absolute_import
del division
del print_function
diff --git a/tensorflow/python/keras/integration_test.py b/tensorflow/python/keras/integration_test.py
index 2e83544d97..2a05699407 100644
--- a/tensorflow/python/keras/integration_test.py
+++ b/tensorflow/python/keras/integration_test.py
@@ -29,6 +29,9 @@ from tensorflow.python.platform import test
class KerasIntegrationTest(test.TestCase):
+ def test_version(self):
+ self.assertTrue(keras.__version__.endswith('-tf'))
+
def test_vector_classification_sequential(self):
with self.test_session():
np.random.seed(1337)
--
GitLab
From 0eac1ebafc1e16e6440658d6b431998f3e682bbc Mon Sep 17 00:00:00 2001
From: Francois Chollet
Date: Mon, 4 Jun 2018 14:46:38 -0700
Subject: [PATCH 0016/1193] Add various missing aliases for symbols in tf.keras
submodules.
PiperOrigin-RevId: 199198086
---
tensorflow/python/keras/losses.py | 35 ++++++++++++---
tensorflow/python/ops/init_ops.py | 21 +++++----
...nsorflow.keras.initializers.constant.pbtxt | 18 ++++++++
...nsorflow.keras.initializers.identity.pbtxt | 18 ++++++++
...tensorflow.keras.initializers.normal.pbtxt | 18 ++++++++
.../tensorflow.keras.initializers.ones.pbtxt | 18 ++++++++
...orflow.keras.initializers.orthogonal.pbtxt | 18 ++++++++
.../tensorflow.keras.initializers.pbtxt | 40 +++++++++++++++++
...low.keras.initializers.random_normal.pbtxt | 18 ++++++++
...ow.keras.initializers.random_uniform.pbtxt | 18 ++++++++
....keras.initializers.truncated_normal.pbtxt | 18 ++++++++
...ensorflow.keras.initializers.uniform.pbtxt | 18 ++++++++
.../tensorflow.keras.initializers.zeros.pbtxt | 18 ++++++++
.../api/golden/tensorflow.keras.losses.pbtxt | 44 +++++++++++++++++++
.../api/golden/tensorflow.keras.metrics.pbtxt | 44 +++++++++++++++++++
15 files changed, 350 insertions(+), 14 deletions(-)
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.constant.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.identity.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.normal.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.ones.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.orthogonal.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.random_normal.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.random_uniform.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.truncated_normal.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.uniform.pbtxt
create mode 100644 tensorflow/tools/api/golden/tensorflow.keras.initializers.zeros.pbtxt
diff --git a/tensorflow/python/keras/losses.py b/tensorflow/python/keras/losses.py
index d82ebd9c31..9f548bfe04 100644
--- a/tensorflow/python/keras/losses.py
+++ b/tensorflow/python/keras/losses.py
@@ -30,19 +30,31 @@ from tensorflow.python.util.tf_export import tf_export
@tf_export('keras.metrics.mean_squared_error',
- 'keras.losses.mean_squared_error')
+ 'keras.metrics.mse',
+ 'keras.metrics.MSE',
+ 'keras.losses.mean_squared_error',
+ 'keras.losses.mse',
+ 'keras.losses.MSE')
def mean_squared_error(y_true, y_pred):
return K.mean(math_ops.square(y_pred - y_true), axis=-1)
@tf_export('keras.metrics.mean_absolute_error',
- 'keras.losses.mean_absolute_error')
+ 'keras.metrics.mae',
+ 'keras.metrics.MAE',
+ 'keras.losses.mean_absolute_error',
+ 'keras.losses.mae',
+ 'keras.losses.MAE')
def mean_absolute_error(y_true, y_pred):
return K.mean(math_ops.abs(y_pred - y_true), axis=-1)
@tf_export('keras.metrics.mean_absolute_percentage_error',
- 'keras.losses.mean_absolute_percentage_error')
+ 'keras.metrics.mape',
+ 'keras.metrics.MAPE',
+ 'keras.losses.mean_absolute_percentage_error',
+ 'keras.losses.mape',
+ 'keras.losses.MAPE')
def mean_absolute_percentage_error(y_true, y_pred):
diff = math_ops.abs(
(y_true - y_pred) / K.clip(math_ops.abs(y_true), K.epsilon(), None))
@@ -50,7 +62,11 @@ def mean_absolute_percentage_error(y_true, y_pred):
@tf_export('keras.metrics.mean_squared_logarithmic_error',
- 'keras.losses.mean_squared_logarithmic_error')
+ 'keras.metrics.msle',
+ 'keras.metrics.MSLE',
+ 'keras.losses.mean_squared_logarithmic_error',
+ 'keras.losses.msle',
+ 'keras.losses.MSLE')
def mean_squared_logarithmic_error(y_true, y_pred):
first_log = math_ops.log(K.clip(y_pred, K.epsilon(), None) + 1.)
second_log = math_ops.log(K.clip(y_true, K.epsilon(), None) + 1.)
@@ -117,7 +133,11 @@ def binary_crossentropy(y_true, y_pred):
@tf_export('keras.metrics.kullback_leibler_divergence',
- 'keras.losses.kullback_leibler_divergence')
+ 'keras.metrics.kld',
+ 'keras.metrics.KLD',
+ 'keras.losses.kullback_leibler_divergence',
+ 'keras.losses.kld',
+ 'keras.losses.KLD')
def kullback_leibler_divergence(y_true, y_pred):
y_true = K.clip(y_true, K.epsilon(), 1)
y_pred = K.clip(y_pred, K.epsilon(), 1)
@@ -129,7 +149,10 @@ def poisson(y_true, y_pred):
return K.mean(y_pred - y_true * math_ops.log(y_pred + K.epsilon()), axis=-1)
-@tf_export('keras.metrics.cosine_proximity', 'keras.losses.cosine_proximity')
+@tf_export('keras.metrics.cosine_proximity',
+ 'keras.metrics.cosine',
+ 'keras.losses.cosine_proximity',
+ 'keras.losses.cosine')
def cosine_proximity(y_true, y_pred):
y_true = nn.l2_normalize(y_true, axis=-1)
y_pred = nn.l2_normalize(y_pred, axis=-1)
diff --git a/tensorflow/python/ops/init_ops.py b/tensorflow/python/ops/init_ops.py
index 1f8d8dc4f3..2df230d470 100644
--- a/tensorflow/python/ops/init_ops.py
+++ b/tensorflow/python/ops/init_ops.py
@@ -86,7 +86,7 @@ class Initializer(object):
@tf_export("keras.initializers.Zeros", "initializers.zeros",
- "zeros_initializer")
+ "zeros_initializer", "keras.initializers.zeros")
class Zeros(Initializer):
"""Initializer that generates tensors initialized to 0."""
@@ -102,7 +102,8 @@ class Zeros(Initializer):
return {"dtype": self.dtype.name}
-@tf_export("keras.initializers.Ones", "initializers.ones", "ones_initializer")
+@tf_export("keras.initializers.Ones", "initializers.ones", "ones_initializer",
+ "keras.initializers.ones")
class Ones(Initializer):
"""Initializer that generates tensors initialized to 1."""
@@ -119,7 +120,7 @@ class Ones(Initializer):
@tf_export("keras.initializers.Constant", "initializers.constant",
- "constant_initializer")
+ "constant_initializer", "keras.initializers.constant")
class Constant(Initializer):
"""Initializer that generates tensors with constant values.
@@ -225,7 +226,8 @@ class Constant(Initializer):
@tf_export("keras.initializers.RandomUniform", "initializers.random_uniform",
- "random_uniform_initializer")
+ "random_uniform_initializer", "keras.initializers.uniform",
+ "keras.initializers.random_uniform")
class RandomUniform(Initializer):
"""Initializer that generates tensors with a uniform distribution.
@@ -262,7 +264,8 @@ class RandomUniform(Initializer):
@tf_export("keras.initializers.RandomNormal", "initializers.random_normal",
- "random_normal_initializer")
+ "random_normal_initializer", "keras.initializers.normal",
+ "keras.initializers.random_normal")
class RandomNormal(Initializer):
"""Initializer that generates tensors with a normal distribution.
@@ -299,7 +302,8 @@ class RandomNormal(Initializer):
@tf_export("keras.initializers.TruncatedNormal",
- "initializers.truncated_normal", "truncated_normal_initializer")
+ "initializers.truncated_normal", "truncated_normal_initializer",
+ "keras.initializers.truncated_normal")
class TruncatedNormal(Initializer):
"""Initializer that generates a truncated normal distribution.
@@ -482,7 +486,7 @@ class VarianceScaling(Initializer):
@tf_export("keras.initializers.Orthogonal", "initializers.orthogonal",
- "orthogonal_initializer")
+ "orthogonal_initializer", "keras.initializers.orthogonal")
class Orthogonal(Initializer):
"""Initializer that generates an orthogonal matrix.
@@ -1062,7 +1066,8 @@ class ConvolutionOrthogonal3D(ConvolutionOrthogonal):
return self._dict_to_tensor(p, ksize, ksize, ksize)
-@tf_export("keras.initializers.Identity", "initializers.identity")
+@tf_export("keras.initializers.Identity", "initializers.identity",
+ "keras.initializers.identity")
class Identity(Initializer):
"""Initializer that generates the identity matrix.
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.constant.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.constant.pbtxt
new file mode 100644
index 0000000000..bddc37b907
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.constant.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.constant"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'value\', \'dtype\', \'verify_shape\'], varargs=None, keywords=None, defaults=[\'0\', \"\", \'False\'], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.identity.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.identity.pbtxt
new file mode 100644
index 0000000000..a4c5a61490
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.identity.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.identity"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'gain\', \'dtype\'], varargs=None, keywords=None, defaults=[\'1.0\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.normal.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.normal.pbtxt
new file mode 100644
index 0000000000..7485772784
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.normal.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.normal"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'mean\', \'stddev\', \'seed\', \'dtype\'], varargs=None, keywords=None, defaults=[\'0.0\', \'1.0\', \'None\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.ones.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.ones.pbtxt
new file mode 100644
index 0000000000..a89f78d1e1
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.ones.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.ones"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'dtype\'], varargs=None, keywords=None, defaults=[\"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.orthogonal.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.orthogonal.pbtxt
new file mode 100644
index 0000000000..ee1e9bbae2
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.orthogonal.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.orthogonal"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'gain\', \'seed\', \'dtype\'], varargs=None, keywords=None, defaults=[\'1.0\', \'None\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.pbtxt
index 093c56595b..14a667870d 100644
--- a/tensorflow/tools/api/golden/tensorflow.keras.initializers.pbtxt
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.pbtxt
@@ -40,6 +40,46 @@ tf_module {
name: "Zeros"
mtype: ""
}
+ member {
+ name: "constant"
+ mtype: ""
+ }
+ member {
+ name: "identity"
+ mtype: ""
+ }
+ member {
+ name: "normal"
+ mtype: ""
+ }
+ member {
+ name: "ones"
+ mtype: ""
+ }
+ member {
+ name: "orthogonal"
+ mtype: ""
+ }
+ member {
+ name: "random_normal"
+ mtype: ""
+ }
+ member {
+ name: "random_uniform"
+ mtype: ""
+ }
+ member {
+ name: "truncated_normal"
+ mtype: ""
+ }
+ member {
+ name: "uniform"
+ mtype: ""
+ }
+ member {
+ name: "zeros"
+ mtype: ""
+ }
member_method {
name: "deserialize"
argspec: "args=[\'config\', \'custom_objects\'], varargs=None, keywords=None, defaults=[\'None\'], "
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.random_normal.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.random_normal.pbtxt
new file mode 100644
index 0000000000..a6df1e87a3
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.random_normal.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.random_normal"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'mean\', \'stddev\', \'seed\', \'dtype\'], varargs=None, keywords=None, defaults=[\'0.0\', \'1.0\', \'None\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.random_uniform.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.random_uniform.pbtxt
new file mode 100644
index 0000000000..37a0fa0d55
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.random_uniform.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.random_uniform"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'minval\', \'maxval\', \'seed\', \'dtype\'], varargs=None, keywords=None, defaults=[\'0\', \'None\', \'None\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.truncated_normal.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.truncated_normal.pbtxt
new file mode 100644
index 0000000000..f97e93f0b7
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.truncated_normal.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.truncated_normal"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'mean\', \'stddev\', \'seed\', \'dtype\'], varargs=None, keywords=None, defaults=[\'0.0\', \'1.0\', \'None\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.uniform.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.uniform.pbtxt
new file mode 100644
index 0000000000..58186b1383
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.uniform.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.uniform"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'minval\', \'maxval\', \'seed\', \'dtype\'], varargs=None, keywords=None, defaults=[\'0\', \'None\', \'None\', \"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.initializers.zeros.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.initializers.zeros.pbtxt
new file mode 100644
index 0000000000..a262390687
--- /dev/null
+++ b/tensorflow/tools/api/golden/tensorflow.keras.initializers.zeros.pbtxt
@@ -0,0 +1,18 @@
+path: "tensorflow.keras.initializers.zeros"
+tf_class {
+ is_instance: ""
+ is_instance: ""
+ is_instance: ""
+ member_method {
+ name: "__init__"
+ argspec: "args=[\'self\', \'dtype\'], varargs=None, keywords=None, defaults=[\"\"], "
+ }
+ member_method {
+ name: "from_config"
+ argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "get_config"
+ argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
+ }
+}
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.losses.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.losses.pbtxt
index ae5f6305b7..eca6b91538 100644
--- a/tensorflow/tools/api/golden/tensorflow.keras.losses.pbtxt
+++ b/tensorflow/tools/api/golden/tensorflow.keras.losses.pbtxt
@@ -1,5 +1,25 @@
path: "tensorflow.keras.losses"
tf_module {
+ member_method {
+ name: "KLD"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MAE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MAPE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MSE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MSLE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "binary_crossentropy"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -12,6 +32,10 @@ tf_module {
name: "categorical_hinge"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "cosine"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "cosine_proximity"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -28,6 +52,10 @@ tf_module {
name: "hinge"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "kld"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "kullback_leibler_divergence"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -36,6 +64,14 @@ tf_module {
name: "logcosh"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "mae"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "mape"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "mean_absolute_error"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -52,6 +88,14 @@ tf_module {
name: "mean_squared_logarithmic_error"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "mse"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "msle"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "poisson"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
diff --git a/tensorflow/tools/api/golden/tensorflow.keras.metrics.pbtxt b/tensorflow/tools/api/golden/tensorflow.keras.metrics.pbtxt
index 42729e4237..a97a9b5758 100644
--- a/tensorflow/tools/api/golden/tensorflow.keras.metrics.pbtxt
+++ b/tensorflow/tools/api/golden/tensorflow.keras.metrics.pbtxt
@@ -1,5 +1,25 @@
path: "tensorflow.keras.metrics"
tf_module {
+ member_method {
+ name: "KLD"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MAE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MAPE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MSE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "MSLE"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "binary_accuracy"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -16,6 +36,10 @@ tf_module {
name: "categorical_crossentropy"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "cosine"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "cosine_proximity"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -32,10 +56,22 @@ tf_module {
name: "hinge"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "kld"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "kullback_leibler_divergence"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "mae"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "mape"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "mean_absolute_error"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
@@ -52,6 +88,14 @@ tf_module {
name: "mean_squared_logarithmic_error"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
}
+ member_method {
+ name: "mse"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
+ member_method {
+ name: "msle"
+ argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
+ }
member_method {
name: "poisson"
argspec: "args=[\'y_true\', \'y_pred\'], varargs=None, keywords=None, defaults=None"
--
GitLab
From 7c33a7751d77cfd70a5c441da369440f4f6b633a Mon Sep 17 00:00:00 2001
From: Pavithra Vijay
Date: Thu, 7 Jun 2018 09:20:57 -0700
Subject: [PATCH 0017/1193] Fix bug due to incorrect nesting of return
statement in eager iterator evaluation.
PiperOrigin-RevId: 199645638
---
.../python/keras/engine/training_eager.py | 10 ++--
.../keras/engine/training_eager_test.py | 54 +++++++++++++++++++
2 files changed, 59 insertions(+), 5 deletions(-)
diff --git a/tensorflow/python/keras/engine/training_eager.py b/tensorflow/python/keras/engine/training_eager.py
index 081e46aa66..a70b488f25 100644
--- a/tensorflow/python/keras/engine/training_eager.py
+++ b/tensorflow/python/keras/engine/training_eager.py
@@ -501,11 +501,11 @@ def iterator_test_loop(model, inputs, steps, verbose=0):
if verbose == 1:
progbar.update(step_index + 1)
- for i in range(len(outs)):
- outs[i] /= num_samples
- if len(outs) == 1:
- return outs[0]
- return outs
+ for i in range(len(outs)):
+ outs[i] /= num_samples
+ if len(outs) == 1:
+ return outs[0]
+ return outs
def batch_test_loop(model,
diff --git a/tensorflow/python/keras/engine/training_eager_test.py b/tensorflow/python/keras/engine/training_eager_test.py
index d9446fd437..7906d208eb 100644
--- a/tensorflow/python/keras/engine/training_eager_test.py
+++ b/tensorflow/python/keras/engine/training_eager_test.py
@@ -20,6 +20,7 @@ from __future__ import print_function
import numpy as np
+from tensorflow.python.data.ops import dataset_ops
from tensorflow.python import keras
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util as tf_test_util
@@ -670,6 +671,59 @@ class CorrectnessTest(test.TestCase):
outs = model.evaluate(x, y)
self.assertEqual(outs[1], 0.)
+ @tf_test_util.run_in_graph_and_eager_modes()
+ def test_loss_correctness_with_iterator(self):
+ # Test that training loss is the same in eager and graph
+ # (by comparing it to a reference value in a deterministic case)
+ model = keras.Sequential()
+ model.add(
+ keras.layers.Dense(
+ 3, activation='relu', input_dim=4, kernel_initializer='ones'))
+ model.add(
+ keras.layers.Dense(2, activation='softmax', kernel_initializer='ones'))
+ model.compile(
+ loss='sparse_categorical_crossentropy',
+ optimizer=RMSPropOptimizer(learning_rate=0.001))
+ x = np.ones((100, 4), dtype=np.float32)
+ np.random.seed(123)
+ y = np.random.randint(0, 1, size=(100, 1))
+ dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
+ dataset = dataset.repeat(100)
+ dataset = dataset.batch(10)
+ iterator = dataset.make_one_shot_iterator()
+ history = model.fit(iterator, epochs=1, steps_per_epoch=10)
+ self.assertEqual(np.around(history.history['loss'][-1], decimals=4), 0.6173)
+
+ @tf_test_util.run_in_graph_and_eager_modes()
+ def test_metrics_correctness_with_iterator(self):
+ model = keras.Sequential()
+ model.add(
+ keras.layers.Dense(
+ 8, activation='relu', input_dim=4, kernel_initializer='ones'))
+ model.add(
+ keras.layers.Dense(1, activation='sigmoid', kernel_initializer='ones'))
+ model.compile(
+ loss='binary_crossentropy',
+ metrics=['accuracy'],
+ optimizer=RMSPropOptimizer(learning_rate=0.001))
+ np.random.seed(123)
+ x = np.random.randint(10, size=(100, 4)).astype(np.float32)
+ y = np.random.randint(2, size=(100, 1)).astype(np.float32)
+ dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
+ dataset = dataset.batch(10)
+ iterator = dataset.make_one_shot_iterator()
+ outs = model.evaluate(iterator, steps=10)
+ self.assertEqual(np.around(outs[1], decimals=1), 0.5)
+
+ y = np.zeros((100, 1), dtype=np.float32)
+ dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
+ dataset = dataset.repeat(100)
+ dataset = dataset.batch(10)
+ iterator = dataset.make_one_shot_iterator()
+ outs = model.evaluate(iterator, steps=10)
+ self.assertEqual(outs[1], 0.)
+
+
if __name__ == '__main__':
ops.enable_eager_execution()
test.main()
--
GitLab
From 5177fd2f9acb9b46b9182ad782bb8b7b9386baeb Mon Sep 17 00:00:00 2001
From: "A. Unique TensorFlower"
Date: Tue, 5 Jun 2018 15:59:21 -0700
Subject: [PATCH 0018/1193] Only calls compare function if values were read
from event file
PiperOrigin-RevId: 199373169
---
tensorflow/python/estimator/exporter.py | 7 ++--
tensorflow/python/estimator/exporter_test.py | 34 ++++++++++++++++++++
2 files changed, 38 insertions(+), 3 deletions(-)
diff --git a/tensorflow/python/estimator/exporter.py b/tensorflow/python/estimator/exporter.py
index a7212bb83e..766ea23f2a 100644
--- a/tensorflow/python/estimator/exporter.py
+++ b/tensorflow/python/estimator/exporter.py
@@ -360,9 +360,10 @@ class BestExporter(Exporter):
for value in event.summary.value:
if value.HasField('simple_value'):
event_eval_result[value.tag] = value.simple_value
- if best_eval_result is None or self._compare_fn(
- best_eval_result, event_eval_result):
- best_eval_result = event_eval_result
+ if event_eval_result:
+ if best_eval_result is None or self._compare_fn(
+ best_eval_result, event_eval_result):
+ best_eval_result = event_eval_result
return best_eval_result
diff --git a/tensorflow/python/estimator/exporter_test.py b/tensorflow/python/estimator/exporter_test.py
index 4cb4bffc8d..c4b006955c 100644
--- a/tensorflow/python/estimator/exporter_test.py
+++ b/tensorflow/python/estimator/exporter_test.py
@@ -148,6 +148,40 @@ class BestExporterTest(test.TestCase):
"checkpoint_path", {"loss": 20}, False)
self.assertEqual(None, export_result)
+ def test_best_exporter_with_empty_event(self):
+
+ def _serving_input_receiver_fn():
+ pass
+
+ export_dir_base = tempfile.mkdtemp()
+ gfile.MkDir(export_dir_base)
+ gfile.MkDir(export_dir_base + "/export")
+ gfile.MkDir(export_dir_base + "/eval")
+
+ eval_dir_base = os.path.join(export_dir_base, "eval_continuous")
+ estimator_lib._write_dict_to_summary(eval_dir_base, {}, 1)
+ estimator_lib._write_dict_to_summary(eval_dir_base, {"loss": 60}, 2)
+
+ exporter = exporter_lib.BestExporter(
+ name="best_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ event_file_pattern="eval_continuous/*.tfevents.*",
+ assets_extra={"from/path": "to/path"},
+ as_text=False,
+ exports_to_keep=1)
+
+ estimator = test.mock.Mock(spec=estimator_lib.Estimator)
+ estimator.model_dir = export_dir_base
+ estimator.export_savedmodel.return_value = "export_result_path"
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"loss": 100}, False)
+ self.assertEqual(None, export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"loss": 10}, False)
+ self.assertEqual("export_result_path", export_result)
+
def test_garbage_collect_exports(self):
export_dir_base = tempfile.mkdtemp()
gfile.MkDir(export_dir_base)
--
GitLab
From 4fe8d4a14936dc38558a858283574993909c9895 Mon Sep 17 00:00:00 2001
From: "A. Unique TensorFlower"
Date: Sun, 27 May 2018 10:49:12 -0700
Subject: [PATCH 0019/1193] TPUEstimator.export_savedmodel() saves a SavedModel
with both TPU and CPU graphs.
PiperOrigin-RevId: 198229550
---
tensorflow/contrib/tpu/python/tpu/tpu_estimator.py | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
diff --git a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
index 4465833f88..c8c08a5a63 100644
--- a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
+++ b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
@@ -1807,7 +1807,7 @@ class TPUEstimator(estimator_lib.Estimator):
export_outputs['classes'] =
export_output_lib.ClassificationOutput(classes=classes)
- tpu.outside_compilation(host_call, logits)
+ tpu.outside_compilation(host_call, [logits])
...
```
@@ -1969,7 +1969,7 @@ class TPUEstimator(estimator_lib.Estimator):
input_receiver_fn_map[mode]}
export_tags = [tag_constants.SERVING, tag_constants.TPU]
mode = _REWRITE_FOR_INFERENCE_MODE
- try:
+ if self._export_to_tpu:
(super(TPUEstimator, self).
_add_meta_graph_for_mode(builder,
input_receiver_fn_map,
@@ -1978,9 +1978,6 @@ class TPUEstimator(estimator_lib.Estimator):
save_variables=False,
mode=mode,
export_tags=export_tags))
- except Exception as error: # pylint: disable=broad-except
- logging.warning('Saving meta graph for TPU failed: {}.'
- .format(str(error)))
def _call_model_fn(self, features, labels, mode, config):
if mode == _REWRITE_FOR_INFERENCE_MODE:
--
GitLab
From 51ad43efe5d918e7c57bd6c612fc1d0efd0b0664 Mon Sep 17 00:00:00 2001
From: "A. Unique TensorFlower"
Date: Tue, 29 May 2018 14:28:59 -0700
Subject: [PATCH 0020/1193] In TPUEstimator.export_savedmodel(), if saving TPU
metegraph fails, issue a warning instead so that user can still use the CPU
metagraph.
PiperOrigin-RevId: 198458571
--
GitLab
From 982f3e3038f8d07964b2c58843a51bd9745a8990 Mon Sep 17 00:00:00 2001
From: "A. Unique TensorFlower"
Date: Fri, 1 Jun 2018 16:32:20 -0700
Subject: [PATCH 0021/1193] Allow user to opt out of saving metagraph for TPU
with TPUEstimator.export_output().
PiperOrigin-RevId: 198944144
---
tensorflow/contrib/tpu/python/tpu/tpu_estimator.py | 13 +++++++++----
1 file changed, 9 insertions(+), 4 deletions(-)
diff --git a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
index c8c08a5a63..7c770912b4 100644
--- a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
+++ b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
@@ -1830,6 +1830,7 @@ class TPUEstimator(estimator_lib.Estimator):
predict_batch_size=None,
batch_axis=None,
eval_on_tpu=True,
+ export_to_tpu=True,
warm_start_from=None):
"""Constructs an `TPUEstimator` instance.
@@ -1872,6 +1873,8 @@ class TPUEstimator(estimator_lib.Estimator):
False or `PER_HOST_V2`, batch_axis is ignored.
eval_on_tpu: If False, evaluation runs on CPU or GPU. In this case, the
model_fn must return `EstimatorSpec` when called with `mode` as `EVAL`.
+ export_to_tpu: If True, `export_savedmodel()` exports a metagraph for
+ serving on TPU besides the one on CPU.
warm_start_from: Optional string filepath to a checkpoint or SavedModel to
warm-start from, or a `tf.estimator.WarmStartSettings`
object to fully configure warm-starting. If the string
@@ -1943,6 +1946,8 @@ class TPUEstimator(estimator_lib.Estimator):
use_tpu,
eval_on_tpu)
+ self._export_to_tpu = export_to_tpu
+
self._is_input_fn_invoked = None
def _add_meta_graph_for_mode(self,
@@ -1965,11 +1970,11 @@ class TPUEstimator(estimator_lib.Estimator):
save_variables,
mode=mode)
- input_receiver_fn_map = {_REWRITE_FOR_INFERENCE_MODE:
- input_receiver_fn_map[mode]}
- export_tags = [tag_constants.SERVING, tag_constants.TPU]
- mode = _REWRITE_FOR_INFERENCE_MODE
if self._export_to_tpu:
+ input_receiver_fn_map = {_REWRITE_FOR_INFERENCE_MODE:
+ input_receiver_fn_map[mode]}
+ export_tags = [tag_constants.SERVING, tag_constants.TPU]
+ mode = _REWRITE_FOR_INFERENCE_MODE
(super(TPUEstimator, self).
_add_meta_graph_for_mode(builder,
input_receiver_fn_map,
--
GitLab
From 6cc2741eb1c9b19742b32b8edda39090afbf5abf Mon Sep 17 00:00:00 2001
From: DavidNorman
Date: Tue, 12 Jun 2018 09:32:53 +0100
Subject: [PATCH 0022/1193] Fix python lint errors
---
tensorflow/compiler/tests/binary_ops_test.py | 11 ++++++-----
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/tensorflow/compiler/tests/binary_ops_test.py b/tensorflow/compiler/tests/binary_ops_test.py
index 64eeed8312..823afbbbdc 100644
--- a/tensorflow/compiler/tests/binary_ops_test.py
+++ b/tensorflow/compiler/tests/binary_ops_test.py
@@ -687,11 +687,12 @@ class BinaryOpsTest(XLATestCase):
np.float32(7),
expected=np.array([[False], [False], [True]], dtype=np.bool))
if np.int64 in self.numeric_types:
- self._testBinary(
- less_op,
- np.array([[10], [7], [2], [-1]], dtype=np.int64),
- np.int64(7),
- expected=np.array([[False], [False], [True], [True]], dtype=np.bool))
+ self._testBinary(
+ less_op,
+ np.array([[10], [7], [2], [-1]], dtype=np.int64),
+ np.int64(7),
+ expected=np.array(
+ [[False], [False], [True], [True]], dtype=np.bool))
for less_equal_op in [math_ops.less_equal, (lambda x, y: x <= y)]:
self._testBinary(
--
GitLab
From fd44596bc4b3ea8c67838b728b450a44e35c1b89 Mon Sep 17 00:00:00 2001
From: Anna R
Date: Mon, 11 Jun 2018 17:21:06 -0700
Subject: [PATCH 0023/1193] Merging
---
tensorflow/tools/api/generator/BUILD | 24 ++++++
.../tools/api/generator/create_python_api.py | 54 +++++++++++--
tensorflow/tools/api/generator/doc_srcs.py | 65 +++++++++++++++
.../tools/api/generator/doc_srcs_test.py | 80 +++++++++++++++++++
4 files changed, 217 insertions(+), 6 deletions(-)
create mode 100644 tensorflow/tools/api/generator/doc_srcs.py
create mode 100644 tensorflow/tools/api/generator/doc_srcs_test.py
diff --git a/tensorflow/tools/api/generator/BUILD b/tensorflow/tools/api/generator/BUILD
index f0c5877a90..3a28153e52 100644
--- a/tensorflow/tools/api/generator/BUILD
+++ b/tensorflow/tools/api/generator/BUILD
@@ -5,12 +5,21 @@ licenses(["notice"]) # Apache 2.0
exports_files(["LICENSE"])
+load("//tensorflow/tools/api/generator:api_gen.bzl", "TENSORFLOW_API_INIT_FILES")
+
+py_library(
+ name = "doc_srcs",
+ srcs = ["doc_srcs.py"],
+ srcs_version = "PY2AND3",
+)
+
py_binary(
name = "create_python_api",
srcs = ["create_python_api.py"],
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
deps = [
+ ":doc_srcs",
"//tensorflow/python:no_contrib",
],
)
@@ -24,3 +33,18 @@ py_test(
"//tensorflow/python:client_testlib",
],
)
+
+py_test(
+ name = "tensorflow_doc_srcs_test",
+ srcs = ["doc_srcs_test.py"],
+ args = [
+ "--package=tensorflow.python",
+ ] + TENSORFLOW_API_INIT_FILES,
+ main = "doc_srcs_test.py",
+ srcs_version = "PY2AND3",
+ deps = [
+ ":doc_srcs",
+ "//tensorflow/python:client_testlib",
+ "//tensorflow/python:no_contrib",
+ ],
+)
diff --git a/tensorflow/tools/api/generator/create_python_api.py b/tensorflow/tools/api/generator/create_python_api.py
index 9f210ad42b..31f287b7fe 100644
--- a/tensorflow/tools/api/generator/create_python_api.py
+++ b/tensorflow/tools/api/generator/create_python_api.py
@@ -25,6 +25,8 @@ import os
import sys
from tensorflow.python.util import tf_decorator
+from tensorflow.python.util import tf_export
+from tensorflow.tools.api.generator import doc_srcs
_API_CONSTANTS_ATTR = '_tf_api_constants'
@@ -36,10 +38,9 @@ _SYMBOLS_TO_SKIP_EXPLICITLY = {
# would have side effects.
'tensorflow.python.platform.flags.FLAGS'
}
-_GENERATED_FILE_HEADER = """\"\"\"Imports for Python API.
-
-This file is MACHINE GENERATED! Do not edit.
-Generated by: tensorflow/tools/api/generator/create_python_api.py script.
+_GENERATED_FILE_HEADER = """# This file is MACHINE GENERATED! Do not edit.
+# Generated by: tensorflow/tools/api/generator/create_python_api.py script.
+\"\"\"%s
\"\"\"
from __future__ import print_function
@@ -254,6 +255,44 @@ def get_module(dir_path, relative_to_dir):
return dir_path.replace('/', '.').strip('.')
+def get_module_docstring(module_name, package):
+ """Get docstring for the given module.
+
+ This method looks for docstring in the following order:
+ 1. Checks if module has a docstring specified in doc_srcs.
+ 2. Checks if module has a docstring source module specified
+ in doc_srcs. If it does, gets docstring from that module.
+ 3. Checks if module with module_name exists under base package.
+ If it does, gets docstring from that module.
+ 4. Returns a default docstring.
+
+ Args:
+ module_name: module name relative to tensorflow
+ (excluding 'tensorflow.' prefix) to get a docstring for.
+ package: Base python package containing python with target tf_export
+ decorators.
+
+ Returns:
+ One-line docstring to describe the module.
+ """
+ # Module under base package to get a docstring from.
+ docstring_module_name = module_name
+
+ if module_name in doc_srcs.TENSORFLOW_DOC_SOURCES:
+ docsrc = doc_srcs.TENSORFLOW_DOC_SOURCES[module_name]
+ if docsrc.docstring:
+ return docsrc.docstring
+ if docsrc.docstring_module_name:
+ docstring_module_name = docsrc.docstring_module_name
+
+ docstring_module_name = package + '.' + docstring_module_name
+ if (docstring_module_name in sys.modules and
+ sys.modules[docstring_module_name].__doc__):
+ return sys.modules[docstring_module_name].__doc__
+
+ return 'Public API for tf.%s namespace.' % module_name
+
+
def create_api_files(
output_files, package, root_init_template, output_dir):
"""Creates __init__.py files for the Python API.
@@ -296,7 +335,10 @@ def create_api_files(
continue
contents = ''
if module or not root_init_template:
- contents = _GENERATED_FILE_HEADER + text + _GENERATED_FILE_FOOTER
+ contents = (
+ _GENERATED_FILE_HEADER %
+ get_module_docstring(module, package) + text +
+ _GENERATED_FILE_FOOTER)
else:
# Read base init file
with open(root_init_template, 'r') as root_init_template_file:
@@ -309,7 +351,7 @@ def create_api_files(
raise ValueError(
'Missing outputs for python_api_gen genrule:\n%s.'
'Make sure all required outputs are in the '
- 'tensorflow/tools/api/generator/BUILD file.' %
+ 'tensorflow/tools/api/generator/api_gen.bzl file.' %
',\n'.join(sorted(missing_output_files)))
diff --git a/tensorflow/tools/api/generator/doc_srcs.py b/tensorflow/tools/api/generator/doc_srcs.py
new file mode 100644
index 0000000000..74f6db98fd
--- /dev/null
+++ b/tensorflow/tools/api/generator/doc_srcs.py
@@ -0,0 +1,65 @@
+# 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.
+# ==============================================================================
+"""Specifies sources of doc strings for API modules."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import collections
+
+
+# Specifies docstring source for a module.
+# Only one of docstring or docstring_module_name should be set.
+# * If docstring is set, then we will use this docstring when
+# for the module.
+# * If docstring_module_name is set, then we will copy the docstring
+# from docstring source module.
+DocSource = collections.namedtuple(
+ 'DocSource', ['docstring', 'docstring_module_name'])
+# Each attribute of DocSource is optional.
+DocSource.__new__.__defaults__ = (None,) * len(DocSource._fields)
+
+TENSORFLOW_DOC_SOURCES = {
+ 'app': DocSource(docstring_module_name='platform.app'),
+ 'compat': DocSource(docstring_module_name='util.compat'),
+ 'distributions': DocSource(
+ docstring_module_name='ops.distributions.distributions'),
+ 'bitwise': DocSource(docstring_module_name='ops.bitwise_ops'),
+ 'errors': DocSource(docstring_module_name='framework.errors'),
+ 'gfile': DocSource(docstring_module_name='platform.gfile'),
+ 'graph_util': DocSource(docstring_module_name='framework.graph_util'),
+ 'image': DocSource(docstring_module_name='ops.image_ops'),
+ 'keras.estimator': DocSource(docstring_module_name='estimator.keras'),
+ 'linalg': DocSource(docstring_module_name='ops.linalg_ops'),
+ 'logging': DocSource(docstring_module_name='ops.logging_ops'),
+ 'losses': DocSource(docstring_module_name='ops.losses.losses'),
+ 'manip': DocSource(docstring_module_name='ops.manip_ops'),
+ 'math': DocSource(docstring_module_name='ops.math_ops'),
+ 'metrics': DocSource(docstring_module_name='ops.metrics'),
+ 'nn': DocSource(docstring_module_name='ops.nn_ops'),
+ 'nn.rnn_cell': DocSource(docstring_module_name='ops.rnn_cell'),
+ 'python_io': DocSource(docstring_module_name='lib.io.python_io'),
+ 'resource_loader': DocSource(
+ docstring_module_name='platform.resource_loader'),
+ 'sets': DocSource(docstring_module_name='ops.sets'),
+ 'sparse': DocSource(docstring_module_name='ops.sparse_ops'),
+ 'spectral': DocSource(docstring_module_name='ops.spectral_ops'),
+ 'strings': DocSource(docstring_module_name='ops.string_ops'),
+ 'sysconfig': DocSource(docstring_module_name='platform.sysconfig'),
+ 'test': DocSource(docstring_module_name='platform.test'),
+ 'train': DocSource(docstring_module_name='training.training'),
+ 'train.queue_runner': DocSource(
+ docstring_module_name='training.queue_runner'),
+}
diff --git a/tensorflow/tools/api/generator/doc_srcs_test.py b/tensorflow/tools/api/generator/doc_srcs_test.py
new file mode 100644
index 0000000000..9ba95a3439
--- /dev/null
+++ b/tensorflow/tools/api/generator/doc_srcs_test.py
@@ -0,0 +1,80 @@
+# 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.
+# =============================================================================
+"""Tests for tensorflow.tools.api.generator.doc_srcs."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import argparse
+import importlib
+import sys
+
+from tensorflow.python.platform import test
+from tensorflow.tools.api.generator import doc_srcs
+
+
+FLAGS = None
+
+
+class DocSrcsTest(test.TestCase):
+
+ def testModulesAreValidAPIModules(self):
+ for module_name in doc_srcs.TENSORFLOW_DOC_SOURCES:
+ # Convert module_name to corresponding __init__.py file path.
+ file_path = module_name.replace('.', '/')
+ if file_path:
+ file_path += '/'
+ file_path += '__init__.py'
+
+ if file_path not in FLAGS.outputs:
+ self.assertFalse('%s is not a valid API module' % module_name)
+
+ def testHaveDocstringOrDocstringModule(self):
+ for module_name, docsrc in doc_srcs.TENSORFLOW_DOC_SOURCES.items():
+ if docsrc.docstring and docsrc.docstring_module_name:
+ self.assertFalse(
+ '%s contains DocSource has both a docstring and a '
+ 'docstring_module_name. '
+ 'Only one of "docstring" or "docstring_module_name" should be set.'
+ % (module_name))
+
+ def testDocstringModulesAreValidModules(self):
+ for _, docsrc in doc_srcs.TENSORFLOW_DOC_SOURCES.items():
+ if docsrc.docstring_module_name:
+ doc_module_name = '.'.join([
+ FLAGS.package, docsrc.docstring_module_name])
+ if doc_module_name not in sys.modules:
+ sys.assertFalse(
+ 'docsources_module %s is not a valid module under %s.' %
+ (docsrc.docstring_module_name, FLAGS.package))
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ 'outputs', metavar='O', type=str, nargs='+',
+ help='create_python_api output files.')
+ parser.add_argument(
+ '--package', type=str,
+ help='Base package that imports modules containing the target tf_export '
+ 'decorators.')
+ FLAGS, unparsed = parser.parse_known_args()
+
+ importlib.import_module(FLAGS.package)
+
+ # Now update argv, so that unittest library does not get confused.
+ sys.argv = [sys.argv[0]] + unparsed
+ test.main()
--
GitLab
From e042e3e051d3bd6bfb63dfd4ad407a82f7d1dacc Mon Sep 17 00:00:00 2001
From: Anna R
Date: Tue, 12 Jun 2018 17:47:58 -0700
Subject: [PATCH 0024/1193] Remove unused tf_export import
---
tensorflow/tools/api/generator/create_python_api.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/tensorflow/tools/api/generator/create_python_api.py b/tensorflow/tools/api/generator/create_python_api.py
index 31f287b7fe..e3ab056efc 100644
--- a/tensorflow/tools/api/generator/create_python_api.py
+++ b/tensorflow/tools/api/generator/create_python_api.py
@@ -25,7 +25,6 @@ import os
import sys
from tensorflow.python.util import tf_decorator
-from tensorflow.python.util import tf_export
from tensorflow.tools.api.generator import doc_srcs
--
GitLab
From f055a9f2f21154140785b9da7c3b2eae88e65623 Mon Sep 17 00:00:00 2001
From: Brennan Saeta
Date: Tue, 12 Jun 2018 18:09:35 -0700
Subject: [PATCH 0025/1193] Check to ensure the Cloud TPU is ready before
resolving.
Cherry picking this into the TF 1.9 release.
PiperOrigin-RevId: 200095692
Previous commit: 32c8013f0ab3feb139648ae759e2d0168fb5dc95
---
.../python/training/tpu_cluster_resolver.py | 3 ++
.../training/tpu_cluster_resolver_test.py | 44 +++++++++++++++++++
2 files changed, 47 insertions(+)
diff --git a/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver.py b/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver.py
index 880fca4ea6..935ad5ff37 100644
--- a/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver.py
+++ b/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver.py
@@ -255,6 +255,9 @@ class TPUClusterResolver(ClusterResolver):
request = self._service.projects().locations().nodes().get(name=full_name)
response = request.execute()
+ if 'state' in response and response['state'] != 'READY':
+ raise RuntimeError('TPU "%s" is not yet ready; state: "%s"' %
+ (self._tpu, response['state']))
if 'health' in response and response['health'] != 'HEALTHY':
raise RuntimeError('TPU "%s" is unhealthy: "%s"' % (self._tpu,
response['health']))
diff --git a/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver_test.py b/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver_test.py
index 5fac55fd02..7e002cc72f 100644
--- a/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver_test.py
+++ b/tensorflow/contrib/cluster_resolver/python/training/tpu_cluster_resolver_test.py
@@ -157,6 +157,50 @@ class TPUClusterResolverTest(test.TestCase):
job { name: 'worker' tasks { key: 0 value: '10.1.2.3:8470' } }
"""
self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)
+
+ @mock.patch.object(TPUClusterResolver, '_requestComputeMetadata',
+ mock_request_compute_metadata)
+ def testUnhealthyCloudTpu(self):
+ tpu_map = {
+ 'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
+ 'ipAddress': '10.1.2.3',
+ 'port': '8470',
+ 'health': 'UNHEALTHY'
+ }
+ }
+
+ tpu_cluster_resolver = TPUClusterResolver(
+ project=None,
+ zone=None,
+ tpu='test-tpu-1',
+ coordinator_name=None,
+ credentials=None,
+ service=self.mock_service_client(tpu_map=tpu_map))
+
+ with self.assertRaises(RuntimeError):
+ tpu_cluster_resolver.cluster_spec()
+
+ @mock.patch.object(TPUClusterResolver, '_requestComputeMetadata',
+ mock_request_compute_metadata)
+ def testNotReadyCloudTpu(self):
+ tpu_map = {
+ 'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
+ 'ipAddress': '10.1.2.3',
+ 'port': '8470',
+ 'state': 'CREATING'
+ }
+ }
+
+ tpu_cluster_resolver = TPUClusterResolver(
+ project=None,
+ zone=None,
+ tpu='test-tpu-1',
+ coordinator_name=None,
+ credentials=None,
+ service=self.mock_service_client(tpu_map=tpu_map))
+
+ with self.assertRaises(RuntimeError):
+ tpu_cluster_resolver.cluster_spec()
def testSimpleSuccessfulRetrieval(self):
tpu_map = {
--
GitLab
From 9a087a42293be8342570039d2c6d329a0589b773 Mon Sep 17 00:00:00 2001
From: Nick Felt
Date: Wed, 13 Jun 2018 00:30:09 -0700
Subject: [PATCH 0026/1193] Update tensorboard dependency to 1.9.x
---
tensorflow/tools/pip_package/setup.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tensorflow/tools/pip_package/setup.py b/tensorflow/tools/pip_package/setup.py
index 97f625e7e9..92a1465cea 100644
--- a/tensorflow/tools/pip_package/setup.py
+++ b/tensorflow/tools/pip_package/setup.py
@@ -55,7 +55,7 @@ REQUIRED_PACKAGES = [
'six >= 1.10.0',
'protobuf >= 3.4.0',
'setuptools <= 39.1.0',
- 'tensorboard >= 1.8.0, < 1.9.0',
+ 'tensorboard >= 1.9.0, < 1.10.0',
'termcolor >= 1.1.0',
]
--
GitLab
From b1d0048f2be83d6c6f7e1be996ef9c8358922aa6 Mon Sep 17 00:00:00 2001
From: Pete Warden
Date: Wed, 13 Jun 2018 01:06:50 -0700
Subject: [PATCH 0027/1193] Documentation for Raspberry Pi installation
---
tensorflow/docs_src/install/index.md | 2 +
.../docs_src/install/install_raspbian.md | 317 ++++++++++++++++++
2 files changed, 319 insertions(+)
create mode 100644 tensorflow/docs_src/install/install_raspbian.md
diff --git a/tensorflow/docs_src/install/index.md b/tensorflow/docs_src/install/index.md
index 4f85383925..c2e5a991d4 100644
--- a/tensorflow/docs_src/install/index.md
+++ b/tensorflow/docs_src/install/index.md
@@ -6,6 +6,7 @@ operating systems:
* macOS 10.12.6 (Sierra) or later.
* Ubuntu 16.04 or later
* Windows 7 or later.
+ * Raspbian 9.0 or later.
Although you might be able to install TensorFlow on other laptop or desktop
systems, we only support (and only fix issues in) the preceding configurations.
@@ -16,6 +17,7 @@ that enables you to write applications in Python:
* @{$install_linux$Installing TensorFlow on Ubuntu}
* @{$install_mac$Installing TensorFlow on macOS}
* @{$install_windows$Installing TensorFlow on Windows}
+ * @{$install_raspbian$Installing TensorFlow on a Raspberry Pi}
* @{$install_sources$Installing TensorFlow from Sources}
Many aspects of the Python TensorFlow API changed from version 0.n to 1.0.
diff --git a/tensorflow/docs_src/install/install_raspbian.md b/tensorflow/docs_src/install/install_raspbian.md
new file mode 100644
index 0000000000..2f425162a1
--- /dev/null
+++ b/tensorflow/docs_src/install/install_raspbian.md
@@ -0,0 +1,317 @@
+# Installing TensorFlow on Raspbian
+
+This guide explains how to install TensorFlow on a Raspberry Pi running
+Raspbian. Although these instructions might also work on other Pi variants, we
+have only tested (and we only support) these instructions on machines meeting
+the following requirements:
+
+* Raspberry Pi devices running Raspbian 9.0 or higher
+
+## Determine how to install TensorFlow
+
+You must pick the mechanism by which you install TensorFlow. The supported
+choices are as follows:
+
+* "Native" pip.
+* Cross-compiling from sources.
+
+**We recommend pip installation.**
+
+## Installing with native pip
+
+We have uploaded the TensorFlow binaries to piwheels.org. Therefore, you can
+install TensorFlow through pip.
+
+The [REQUIRED_PACKAGES section of
+setup.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/pip_package/setup.py)
+lists the packages that pip will install or upgrade.
+
+### Prerequisite: Python
+
+In order to install TensorFlow, your system must contain one of the following
+Python versions:
+
+* Python 2.7
+* Python 3.4+
+
+If your system does not already have one of the preceding Python versions,
+[install](https://wiki.python.org/moin/BeginnersGuide/Download) it now. It
+should already be included when Raspbian was installed though, so no extra steps
+should be needed.
+
+### Prerequisite: pip
+
+[Pip](https://en.wikipedia.org/wiki/Pip_\(package_manager\)) installs and
+manages software packages written in Python. If you intend to install with
+native pip, then one of the following flavors of pip must be installed on your
+system:
+
+* `pip3`, for Python 3.n (preferred).
+* `pip`, for Python 2.7.
+
+`pip` or `pip3` was probably installed on your system when you installed Python.
+To determine whether pip or pip3 is actually installed on your system, issue one
+of the following commands:
+
+$ pip3 -V # for Python 3.n
+$ pip -V # for Python 2.7
+
+If it gives the error "Command not found", then the package has not been
+installed yet. To install if for the first time, run:
+
+$ sudo apt-get install python3-pip # for Python 3.n
+sudo apt-get install python-pip # for Python 2.7
+
+You can find more help on installing and upgrading pip in
+[the Raspberry Pi documentation](https://www.raspberrypi.org/documentation/linux/software/python.md).
+
+### Prerequisite: Atlas
+
+[Atlas](http://math-atlas.sourceforge.net/) is a linear algebra library that
+numpy depends on, and so needs to be installed before TensorFlow. To add it to
+your system, run the following command:
+
+$ sudo apt install libatlas-base-dev
+
+### Install TensorFlow
+
+Assuming the prerequisite software is installed on your Pi, install TensorFlow
+by invoking **one** of the following commands:
+
+ $ pip3 install tensorflow # Python 3.n
+ $ pip install tensorflow # Python 2.7
+
+This can take some time on certain platforms like the Pi Zero, where some Python
+packages like scipy that TensorFlow depends on need to be compiled before the
+installation can complete. The Python 3 version will typically be faster to
+install because piwheels.org has pre-built versions of the dependencies
+available, so this is our recommended option.
+
+### Next Steps
+
+After installing TensorFlow, [validate your
+installation](#ValidateYourInstallation) to confirm that the installation worked
+properly.
+
+### Uninstalling TensorFlow
+
+To uninstall TensorFlow, issue one of following commands:
+
+$ pip uninstall tensorflow
+$ pip3 uninstall tensorflow
+
+## Cross-compiling from sources
+
+Cross-compilation means building on a different machine than than you'll be
+deploying on. Since Raspberry Pi's only have limited RAM and comparatively slow
+processors, and TensorFlow has a large amount of source code to compile, it's
+easier to use a MacOS or Linux desktop or laptop to handle the build process.
+Because it can take over 24 hours to build on a Pi, and requires external swap
+space to cope with the memory shortage, we recommend using cross-compilation if
+you do need to compile TensorFlow from source. To make the dependency management
+process easier, we also recommend using Docker to help simplify building.
+
+Note that we provide well-tested, pre-built TensorFlow binaries for Raspbian
+systems. So, don't build a TensorFlow binary yourself unless you are very
+comfortable building complex packages from source and dealing with the
+inevitable aftermath should things not go exactly as documented
+
+### Prerequisite: Docker
+
+Install Docker on your machine as described in the [Docker
+documentation](https://docs.docker.com/engine/installation/#/on-macos-and-windows).
+
+### Clone the TensorFlow repository
+
+Start the process of building TensorFlow by cloning a TensorFlow repository.
+
+To clone **the latest** TensorFlow repository, issue the following command:
+
+$ git clone https://github.com/tensorflow/tensorflow
+
+The preceding git clone command creates a subdirectory named
+`tensorflow`. After cloning, you may optionally build a **specific branch**
+(such as a release branch) by invoking the following commands:
+
+
+$ cd tensorflow
+$ git checkout Branch # where Branch is the desired branch
+
+
+For example, to work with the `r1.0` release instead of the master release,
+issue the following command:
+
+$ git checkout r1.0
+
+### Build from source
+
+To compile TensorFlow and produce a binary pip can install, do the following:
+
+1. Start a terminal.
+2. Navigate to the directory containing the tensorflow source code.
+3. Run a command to cross-compile the library, for example:
+
+$ CI_DOCKER_EXTRA_PARAMS="-e CI_BUILD_PYTHON=python3 -e CROSSTOOL_PYTHON_INCLUDE_PATH=/usr/include/python3.4" \
+tensorflow/tools/ci_build/ci_build.sh PI-PYTHON3 tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
+
+
+This will build a pip .whl file for Python 3.4, with Arm v7 instructions that
+will only work on the Pi models 2 or 3. These NEON instructions are required for
+the fastest operation on those devices, but you can build a library that will
+run across all Pi devices by passing `PI_ONE` at the end of the command line.
+You can also target Python 2.7 by omitting the initial docker parameters. Here's
+an example of building for Python 2.7 and Raspberry Pi model Zero or One
+devices:
+
+$ tensorflow/tools/ci_build/ci_build.sh PI tensorflow/tools/ci_build/pi/build_raspberry_pi.sh PI_ONE
+
+This will take some time to complete, typically twenty or thirty minutes, and
+should produce a .whl file in an output-artifacts sub-folder inside your source
+tree at the end. This wheel file can be installed through pip or pip3 (depending
+on your Python version) by copying it to a Raspberry Pi and running a terminal
+command like this (with the name of your actual file substituted):
+
+$ pip3 install tensorflow-1.9.0-cp34-none-linux_armv7l.whl
+
+### Troubleshooting the build
+
+The build script uses Docker internally to create a Linux virtual machine to
+handle the compilation. If you do have problems running the script, first check
+that you're able to run Docker tests like `docker run hello-world` on your
+system.
+
+If you're building from the latest development branch, try syncing to an older
+version that's known to work, for example release 1.9, with a command like this:
+
+$ git checkout r1.0
+
+
+
+## Validate your installation
+
+To validate your TensorFlow installation, do the following:
+
+1. Ensure that your environment is prepared to run TensorFlow programs.
+2. Run a short TensorFlow program.
+
+### Prepare your environment
+
+If you installed on native pip, Virtualenv, or Anaconda, then do the following:
+
+1. Start a terminal.
+2. If you installed TensorFlow source code, navigate to any directory *except*
+ one containing TensorFlow source code.
+
+### Run a short TensorFlow program
+
+Invoke python from your shell as follows:
+
+$ python
+
+Enter the following short program inside the python interactive shell:
+
+```python
+# Python
+import tensorflow as tf
+hello = tf.constant('Hello, TensorFlow!')
+sess = tf.Session()
+print(sess.run(hello))
+```
+
+If the system outputs the following, then you are ready to begin writing
+TensorFlow programs:
+
+Hello, TensorFlow!
+
+If you're running with Python 3.5, you may see a warning when you first import
+TensorFlow. This is not an error, and TensorFlow should continue to run with no
+problems, despite the log message.
+
+If the system outputs an error message instead of a greeting, see [Common
+installation problems](#common_installation_problems).
+
+If you are new to machine learning, we recommend the [Machine Learning Crash
+Course](https://developers.google.com/machine-learning/crash-course).
+
+If you are experienced with machine learning but new to TensorFlow, see
+@{$get_started/eager}.
+
+## Common installation problems
+
+We are relying on Stack Overflow to document TensorFlow installation problems
+and their remedies. The following table contains links to Stack Overflow answers
+for some common installation problems. If you encounter an error message or
+other installation problem not listed in the following table, search for it on
+Stack Overflow. If Stack Overflow doesn't show the error message, ask a new
+question about it on Stack Overflow and specify the `tensorflow` tag.
+
+
+ | Stack Overflow Link | Error Message |
+
+
+
+ | 42006320 |
+ ImportError: Traceback (most recent call last):
+File ".../tensorflow/core/framework/graph_pb2.py", line 6, in
+from google.protobuf import descriptor as _descriptor
+ImportError: cannot import name 'descriptor'
+ |
+
+
+
+ | 33623453 |
+ IOError: [Errno 2] No such file or directory:
+ '/tmp/pip-o6Tpui-build/setup.py'
+ |
+
+
+ | 35190574 |
+ SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
+ failed |
+
+
+
+ | 42009190 |
+
+ Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
+ Found existing installation: setuptools 1.1.6
+ Uninstalling setuptools-1.1.6:
+ Exception:
+ ...
+ [Errno 1] Operation not permitted:
+ '/tmp/pip-a1DXRT-uninstall/.../lib/python/_markerlib' |
+
+
+
+ | 33622019 |
+ ImportError: No module named copyreg |
+
+
+
+ | 37810228 |
+ During a pip install operation, the system returns:
+ OSError: [Errno 1] Operation not permitted
+ |
+
+
+
+ | 33622842 |
+ An import tensorflow statement triggers an error such as the
+ following:Traceback (most recent call last):
+ File "", line 1, in
+ File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py",
+ line 4, in
+ from tensorflow.python import *
+ ...
+ File "/usr/local/lib/python2.7/site-packages/tensorflow/core/framework/tensor_shape_pb2.py",
+ line 22, in
+ serialized_pb=_b('\n,tensorflow/core/framework/tensor_shape.proto\x12\ntensorflow\"d\n\x10TensorShapeProto\x12-\n\x03\x64im\x18\x02
+ \x03(\x0b\x32
+ .tensorflow.TensorShapeProto.Dim\x1a!\n\x03\x44im\x12\x0c\n\x04size\x18\x01
+ \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3')
+ TypeError: __init__() got an unexpected keyword argument 'syntax'
+ |
+
+
+
+
--
GitLab
From 76b8b01740233ff289d70a0d516c6e0ac0e6b042 Mon Sep 17 00:00:00 2001
From: Allen Lavoie
Date: Mon, 11 Jun 2018 11:55:34 -0700
Subject: [PATCH 0028/1193] Use the Keras session for saving/loading in
TensorFlow format
Fixes issues when there's no default session
PiperOrigin-RevId: 200088574
---
tensorflow/python/keras/engine/network.py | 10 +++-
tensorflow/python/keras/engine/saving_test.py | 52 +++++++++++++------
2 files changed, 44 insertions(+), 18 deletions(-)
diff --git a/tensorflow/python/keras/engine/network.py b/tensorflow/python/keras/engine/network.py
index 9dbf94a276..3d567b8378 100644
--- a/tensorflow/python/keras/engine/network.py
+++ b/tensorflow/python/keras/engine/network.py
@@ -20,6 +20,7 @@ from __future__ import division
from __future__ import print_function
import copy
+import functools
import json
import os
import weakref
@@ -1264,7 +1265,11 @@ class Network(base_layer.Layer):
with h5py.File(filepath, 'w') as f:
saving.save_weights_to_hdf5_group(f, self.layers)
else:
- self._checkpointable_saver.save(filepath)
+ if context.executing_eagerly():
+ session = None
+ else:
+ session = backend.get_session()
+ self._checkpointable_saver.save(filepath, session=session)
def load_weights(self, filepath, by_name=False):
"""Loads all layer weights, either from a TensorFlow or an HDF5 weight file.
@@ -1324,7 +1329,8 @@ class Network(base_layer.Layer):
'loading TensorFlow-formatted weights (got by_name=True to '
'load_weights).')
if not context.executing_eagerly():
- finalizer = status.run_restore_ops
+ session = backend.get_session()
+ finalizer = functools.partial(status.run_restore_ops, session=session)
if self.built:
finalizer()
else:
diff --git a/tensorflow/python/keras/engine/saving_test.py b/tensorflow/python/keras/engine/saving_test.py
index 30bcd3d185..b5448a9be1 100644
--- a/tensorflow/python/keras/engine/saving_test.py
+++ b/tensorflow/python/keras/engine/saving_test.py
@@ -404,26 +404,27 @@ class TestWholeModelSaving(test.TestCase):
os.remove(fname)
def test_saving_lambda_numpy_array_arguments(self):
- if h5py is None:
- self.skipTest('h5py required to run this test')
+ with self.test_session():
+ if h5py is None:
+ self.skipTest('h5py required to run this test')
- mean = np.random.random((4, 2, 3))
- std = np.abs(np.random.random((4, 2, 3))) + 1e-5
- inputs = keras.layers.Input(shape=(4, 2, 3))
- output = keras.layers.Lambda(lambda image, mu, std: (image - mu) / std,
- arguments={'mu': mean, 'std': std})(inputs)
- model = keras.models.Model(inputs, output)
- model.compile(loss='mse', optimizer='sgd', metrics=['acc'])
+ mean = np.random.random((4, 2, 3))
+ std = np.abs(np.random.random((4, 2, 3))) + 1e-5
+ inputs = keras.layers.Input(shape=(4, 2, 3))
+ output = keras.layers.Lambda(lambda image, mu, std: (image - mu) / std,
+ arguments={'mu': mean, 'std': std})(inputs)
+ model = keras.models.Model(inputs, output)
+ model.compile(loss='mse', optimizer='sgd', metrics=['acc'])
- fd, fname = tempfile.mkstemp('.h5')
- keras.models.save_model(model, fname)
+ fd, fname = tempfile.mkstemp('.h5')
+ keras.models.save_model(model, fname)
- model = keras.models.load_model(fname)
- os.close(fd)
- os.remove(fname)
+ model = keras.models.load_model(fname)
+ os.close(fd)
+ os.remove(fname)
- self.assertAllClose(mean, model.layers[1].arguments['mu'])
- self.assertAllClose(std, model.layers[1].arguments['std'])
+ self.assertAllClose(mean, model.layers[1].arguments['mu'])
+ self.assertAllClose(std, model.layers[1].arguments['std'])
def test_saving_model_with_long_layer_names(self):
if h5py is None:
@@ -580,6 +581,25 @@ class TestWeightSavingAndLoadingTFFormat(test.TestCase):
# Indirectly tests that the user is prompted
model.save_weights(prefix, save_format='tensorflow', overwrite=False)
+ def test_no_default_session(self):
+ with ops.Graph().as_default():
+ self.assertFalse(ops.get_default_session())
+ data = np.random.random((1000, 32)).astype(np.float32)
+ labels = np.random.random((1000, 10)).astype(np.float32)
+
+ model = keras.models.Sequential([
+ keras.layers.Dense(10, activation='softmax'),
+ keras.layers.Dense(10, activation='softmax')])
+
+ model.compile(optimizer=training_module.RMSPropOptimizer(0.001),
+ loss='categorical_crossentropy',
+ metrics=['accuracy'])
+
+ model.fit(data, labels)
+ fname = os.path.join(self.get_temp_dir(), 'weights', 'ckpt')
+ model.save_weights(fname)
+ model.load_weights(fname)
+
def test_no_graph_pollution(self):
with context.graph_mode():
graph = ops.Graph()
--
GitLab
From 50ba6dd3a182c9578bc10cb2a21d7914a1e7bac1 Mon Sep 17 00:00:00 2001
From: Akshay Modi
Date: Mon, 11 Jun 2018 10:42:15 -0700
Subject: [PATCH 0029/1193] Don't call back into python during insert (which
will leave the set in a broken condition if the runtime decides to let
another thread run).
Thank you for finding the bug. The watched_variables_ set should not really require a lock since all our functions hold the GIL (verified by looking at the generated SWIG). The reason that there was a concurrent access to the set is that the insert was calling back into python (which might release the GIL and let another thread run, which will also attempt to insert a variable and break the set).
I included the lock to be safe though, since its non-trivial to verify without looking at the generated swig wrappers that the GIL is held.
PiperOrigin-RevId: 200074843
---
tensorflow/python/eager/pywrap_tfe_src.cc | 82 ++++++++++++-----------
1 file changed, 43 insertions(+), 39 deletions(-)
diff --git a/tensorflow/python/eager/pywrap_tfe_src.cc b/tensorflow/python/eager/pywrap_tfe_src.cc
index e3ce0ef9d0..52b3268903 100644
--- a/tensorflow/python/eager/pywrap_tfe_src.cc
+++ b/tensorflow/python/eager/pywrap_tfe_src.cc
@@ -873,22 +873,6 @@ static tensorflow::DataType FastTensorDtype(PyObject* tensor) {
return static_cast(id);
}
-static tensorflow::int64 FastHandleId(PyObject* variable) {
- PyObject* handle = PyObject_GetAttrString(variable, "handle");
- if (handle == nullptr) {
- return -1;
- }
- tensorflow::int64 id = FastTensorId(handle);
- Py_DECREF(handle);
- return id;
-}
-
-struct CompareByHandleId {
- bool operator()(PyObject* lhs, PyObject* rhs) {
- return FastHandleId(lhs) < FastHandleId(rhs);
- }
-};
-
class GradientTape
: public tensorflow::eager::GradientTape {
public:
@@ -897,35 +881,63 @@ class GradientTape
persistent) {}
virtual ~GradientTape() {
- for (PyObject* v : watched_variables_) {
- Py_DECREF(v);
+ for (const IdAndVariable& v : watched_variables_) {
+ Py_DECREF(v.variable);
}
}
void WatchVariable(PyObject* v) {
- auto insert_result = watched_variables_.insert(v);
- if (insert_result.second) {
- // Only increment the reference count if we aren't already watching this
- // variable.
- Py_INCREF(v);
- }
- PyObject* handle = PyObject_GetAttrString(v, "handle");
+ tensorflow::Safe_PyObjectPtr handle(PyObject_GetAttrString(v, "handle"));
if (handle == nullptr) {
return;
}
- tensorflow::int64 id = FastTensorId(handle);
- Py_DECREF(handle);
+ tensorflow::int64 id = FastTensorId(handle.get());
+
if (!PyErr_Occurred()) {
this->Watch(id);
}
+
+ tensorflow::mutex_lock l(watched_variables_mu_);
+ auto insert_result = watched_variables_.emplace(id, v);
+
+ if (insert_result.second) {
+ // Only increment the reference count if we aren't already watching this
+ // variable.
+ Py_INCREF(v);
+ }
}
- const std::set WatchedVariables() {
- return watched_variables_;
+ PyObject* GetVariablesAsPyTuple() {
+ tensorflow::mutex_lock l(watched_variables_mu_);
+ PyObject* result = PyTuple_New(watched_variables_.size());
+ Py_ssize_t pos = 0;
+ for (const IdAndVariable& id_and_variable : watched_variables_) {
+ PyTuple_SET_ITEM(result, pos++, id_and_variable.variable);
+ Py_INCREF(id_and_variable.variable);
+ }
+ return result;
}
private:
- std::set watched_variables_;
+ // We store an IdAndVariable in the map since the map needs to be locked
+ // during insert, but should not call back into python during insert to avoid
+ // deadlocking with the GIL.
+ struct IdAndVariable {
+ tensorflow::int64 id;
+ PyObject* variable;
+
+ IdAndVariable(tensorflow::int64 id, PyObject* variable)
+ : id(id), variable(variable) {}
+ };
+ struct CompareById {
+ bool operator()(const IdAndVariable& lhs, const IdAndVariable& rhs) {
+ return lhs.id < rhs.id;
+ }
+ };
+
+ tensorflow::mutex watched_variables_mu_;
+ std::set watched_variables_
+ GUARDED_BY(watched_variables_mu_);
};
typedef struct {
@@ -1217,15 +1229,7 @@ void TFE_Py_TapeSetWatchVariable(PyObject* variable) {
}
PyObject* TFE_Py_TapeWatchedVariables(PyObject* tape) {
- const auto& watched_variables =
- reinterpret_cast(tape)->tape->WatchedVariables();
- PyObject* result = PyTuple_New(watched_variables.size());
- Py_ssize_t pos = 0;
- for (PyObject* variable : watched_variables) {
- PyTuple_SET_ITEM(result, pos++, variable);
- Py_INCREF(variable);
- }
- return result;
+ return reinterpret_cast(tape)->tape->GetVariablesAsPyTuple();
}
namespace {
--
GitLab
From ec769c7ec368adf90aaa0b6d2a97525da14e1a37 Mon Sep 17 00:00:00 2001
From: Akshay Modi
Date: Mon, 11 Jun 2018 16:27:12 -0700
Subject: [PATCH 0030/1193] Remove memory leak in read variable call, and
record gradient call.
Fix #19385
PiperOrigin-RevId: 200132949
---
tensorflow/python/eager/pywrap_tfe_src.cc | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/tensorflow/python/eager/pywrap_tfe_src.cc b/tensorflow/python/eager/pywrap_tfe_src.cc
index 52b3268903..6c9481c3af 100644
--- a/tensorflow/python/eager/pywrap_tfe_src.cc
+++ b/tensorflow/python/eager/pywrap_tfe_src.cc
@@ -1873,6 +1873,8 @@ PyObject* RecordGradient(PyObject* op_name, PyObject* inputs, PyObject* attrs,
delete backward_function;
});
+ Py_DECREF(num_inputs);
+
Py_RETURN_NONE;
}
@@ -1931,8 +1933,10 @@ bool ReadVariableOp(const FastPathOpExecInfo& parent_op_exec_info,
Py_INCREF(output->get()); // stay alive after since tuple steals.
PyTuple_SET_ITEM(outputs.get(), 0, output->get());
- if (!RecordGradient(GetPythonObjectFromString("ReadVariableOp"),
- inputs.get(), Py_None, outputs.get(), Py_None)) {
+ tensorflow::Safe_PyObjectPtr op_string(
+ GetPythonObjectFromString("ReadVariableOp"));
+ if (!RecordGradient(op_string.get(), inputs.get(), Py_None, outputs.get(),
+ Py_None)) {
return false;
}
}
--
GitLab
From c77fead531bc3756d765ba90e2e549abd7adf320 Mon Sep 17 00:00:00 2001
From: Brennan Saeta
Date: Wed, 13 Jun 2018 15:46:12 -0700
Subject: [PATCH 0031/1193] Make GCS ops work in open source
---
tensorflow/contrib/cloud/__init__.py | 5 +++--
tensorflow/contrib/cloud/kernels/BUILD | 1 +
tensorflow/core/platform/cloud/gcs_file_system.cc | 4 +++-
tensorflow/core/platform/default/build_config.bzl | 2 ++
4 files changed, 9 insertions(+), 3 deletions(-)
diff --git a/tensorflow/contrib/cloud/__init__.py b/tensorflow/contrib/cloud/__init__.py
index a6e13ea3ae..ef7aa7624c 100644
--- a/tensorflow/contrib/cloud/__init__.py
+++ b/tensorflow/contrib/cloud/__init__.py
@@ -27,8 +27,9 @@ from tensorflow.python.util.all_util import remove_undocumented
_allowed_symbols = [
'BigQueryReader',
- 'ConfigureColabSession',
- 'ConfigureGcs',
+ 'BlockCacheParams',
+ 'configure_colab_session',
+ 'configure_gcs',
'ConfigureGcsHook',
]
remove_undocumented(__name__, _allowed_symbols)
diff --git a/tensorflow/contrib/cloud/kernels/BUILD b/tensorflow/contrib/cloud/kernels/BUILD
index 40160706f7..1311063ec0 100644
--- a/tensorflow/contrib/cloud/kernels/BUILD
+++ b/tensorflow/contrib/cloud/kernels/BUILD
@@ -79,6 +79,7 @@ tf_kernel_library(
srcs = ["gcs_config_ops.cc"],
visibility = ["//tensorflow:internal"],
deps = [
+ "//tensorflow/contrib/cloud:gcs_config_ops_op_lib",
"//tensorflow/core:framework",
"//tensorflow/core:lib",
"//tensorflow/core/platform/cloud:curl_http_request",
diff --git a/tensorflow/core/platform/cloud/gcs_file_system.cc b/tensorflow/core/platform/cloud/gcs_file_system.cc
index 22ae6121e0..803b08f1a3 100644
--- a/tensorflow/core/platform/cloud/gcs_file_system.cc
+++ b/tensorflow/core/platform/cloud/gcs_file_system.cc
@@ -804,7 +804,9 @@ void GcsFileSystem::ResetFileBlockCache(size_t block_size_bytes,
mutex_lock l(block_cache_lock_);
file_block_cache_ =
MakeFileBlockCache(block_size_bytes, max_bytes, max_staleness_secs);
- stats_->Configure(this, &throttle_, file_block_cache_.get());
+ if (stats_) {
+ stats_->Configure(this, &throttle_, file_block_cache_.get());
+ }
}
// A helper function to build a FileBlockCache for GcsFileSystem.
diff --git a/tensorflow/core/platform/default/build_config.bzl b/tensorflow/core/platform/default/build_config.bzl
index 9e52ba344a..f12732b434 100644
--- a/tensorflow/core/platform/default/build_config.bzl
+++ b/tensorflow/core/platform/default/build_config.bzl
@@ -633,6 +633,7 @@ def tf_additional_cloud_op_deps():
"//tensorflow:with_gcp_support_ios_override": [],
"//tensorflow:with_gcp_support": [
"//tensorflow/contrib/cloud:bigquery_reader_ops_op_lib",
+ "//tensorflow/contrib/cloud:gcs_config_ops_op_lib",
],
"//conditions:default": [],
})
@@ -645,6 +646,7 @@ def tf_additional_cloud_kernel_deps():
"//tensorflow:with_gcp_support_ios_override": [],
"//tensorflow:with_gcp_support": [
"//tensorflow/contrib/cloud/kernels:bigquery_reader_ops",
+ "//tensorflow/contrib/cloud/kernels:gcs_config_ops",
],
"//conditions:default": [],
})
--
GitLab
From f9a44a69c35dcf7f1c0f42e1ae9971bae0148099 Mon Sep 17 00:00:00 2001
From: Brennan Saeta
Date: Wed, 13 Jun 2018 18:05:39 -0700
Subject: [PATCH 0032/1193] Update the docs and api_def.
---
.../contrib/cloud/ops/gcs_config_ops.cc | 42 +------------------
.../api_def_GcsConfigureBlockCache.pbtxt | 9 ++++
.../api_def_GcsConfigureCredentials.pbtxt | 33 +++++++++++++++
3 files changed, 44 insertions(+), 40 deletions(-)
create mode 100644 tensorflow/core/api_def/base_api/api_def_GcsConfigureBlockCache.pbtxt
create mode 100644 tensorflow/core/api_def/base_api/api_def_GcsConfigureCredentials.pbtxt
diff --git a/tensorflow/contrib/cloud/ops/gcs_config_ops.cc b/tensorflow/contrib/cloud/ops/gcs_config_ops.cc
index 9cf85f5f18..5e31a15498 100644
--- a/tensorflow/contrib/cloud/ops/gcs_config_ops.cc
+++ b/tensorflow/contrib/cloud/ops/gcs_config_ops.cc
@@ -21,50 +21,12 @@ namespace tensorflow {
REGISTER_OP("GcsConfigureCredentials")
.Input("json: string")
- .SetShapeFn(shape_inference::NoOutputs)
- .Doc(R"doc(
-Configures the credentials used by the GCS client of the local TF runtime.
-
-The json input can be of the format:
-
-1. Refresh Token:
-{
- "client_id": "",
- "client_secret": "",
- "refresh_token: "",
- "type": "authorized_user",
-}
-
-2. Service Account:
-{
- "type": "service_account",
- "project_id": "",
- "private_key_id": "",
- "private_key": "------BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY------\n",
- "client_email": "@.iam.gserviceaccount.com",
- "client_id": "",
- # Some additional fields elided
-}
-
-Note the credentials established through this method are shared across all
-sessions run on this runtime.
-
-Note be sure to feed the inputs to this op to ensure the credentials are not
-stored in a constant op within the graph that might accidentally be checkpointed
-or in other ways be persisted or exfiltrated.
-)doc");
+ .SetShapeFn(shape_inference::NoOutputs);
REGISTER_OP("GcsConfigureBlockCache")
.Input("max_cache_size: uint64")
.Input("block_size: uint64")
.Input("max_staleness: uint64")
- .SetShapeFn(shape_inference::NoOutputs)
- .Doc(R"doc(
-Re-configures the GCS block cache with the new configuration values.
-
-If the values are the same as already configured values, this op is a no-op. If
-they are different, the current contents of the block cache is dropped, and a
-new block cache is created fresh.
-)doc");
+ .SetShapeFn(shape_inference::NoOutputs);
} // namespace tensorflow
diff --git a/tensorflow/core/api_def/base_api/api_def_GcsConfigureBlockCache.pbtxt b/tensorflow/core/api_def/base_api/api_def_GcsConfigureBlockCache.pbtxt
new file mode 100644
index 0000000000..9d32940c64
--- /dev/null
+++ b/tensorflow/core/api_def/base_api/api_def_GcsConfigureBlockCache.pbtxt
@@ -0,0 +1,9 @@
+op {
+ graph_op_name: "GcsConfigureBlockCache"
+ summary: "Re-configures the GCS block cache with the new configuration values."
+ description: <",
+ "client_secret": "",
+ "refresh_token: "",
+ "type": "authorized_user",
+}
+
+2. Service Account:
+{
+ "type": "service_account",
+ "project_id": "",
+ "private_key_id": "",
+ "private_key": "------BEGIN PRIVATE KEY-----\n\n-----END PRIVATE KEY------\n",
+ "client_email": "@.iam.gserviceaccount.com",
+ "client_id": "",
+ # Some additional fields elided
+}
+
+Note the credentials established through this method are shared across all
+sessions run on this runtime.
+
+Note be sure to feed the inputs to this op to ensure the credentials are not
+stored in a constant op within the graph that might accidentally be checkpointed
+or in other ways be persisted or exfiltrated.
+END0
+}
--
GitLab
From ea3bdbc7ea72e488566326aeb446681a557f4334 Mon Sep 17 00:00:00 2001
From: Michael Case
Date: Thu, 14 Jun 2018 06:17:00 -0700
Subject: [PATCH 0033/1193] Update version strings for 1.9.0-rc1.
---
tensorflow/core/public/version.h | 2 +-
tensorflow/docs_src/install/install_c.md | 2 +-
tensorflow/docs_src/install/install_go.md | 2 +-
tensorflow/docs_src/install/install_java.md | 22 +++++++++----------
tensorflow/docs_src/install/install_linux.md | 18 +++++++--------
tensorflow/docs_src/install/install_mac.md | 10 ++++-----
.../docs_src/install/install_sources.md | 4 ++--
tensorflow/tools/pip_package/setup.py | 2 +-
8 files changed, 31 insertions(+), 31 deletions(-)
diff --git a/tensorflow/core/public/version.h b/tensorflow/core/public/version.h
index cb1fd09dbb..9e5e747557 100644
--- a/tensorflow/core/public/version.h
+++ b/tensorflow/core/public/version.h
@@ -24,7 +24,7 @@ limitations under the License.
// TF_VERSION_SUFFIX is non-empty for pre-releases (e.g. "-alpha", "-alpha.1",
// "-beta", "-rc", "-rc.1")
-#define TF_VERSION_SUFFIX "-rc0"
+#define TF_VERSION_SUFFIX "-rc1"
#define TF_STR_HELPER(x) #x
#define TF_STR(x) TF_STR_HELPER(x)
diff --git a/tensorflow/docs_src/install/install_c.md b/tensorflow/docs_src/install/install_c.md
index 2901848745..2f81ae0c40 100644
--- a/tensorflow/docs_src/install/install_c.md
+++ b/tensorflow/docs_src/install/install_c.md
@@ -38,7 +38,7 @@ enable TensorFlow for C:
OS="linux" # Change to "darwin" for macOS
TARGET_DIRECTORY="/usr/local"
curl -L \
- "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-${OS}-x86_64-1.9.0-rc0.tar.gz" |
+ "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-${OS}-x86_64-1.9.0-rc1.tar.gz" |
sudo tar -C $TARGET_DIRECTORY -xz
The `tar` command extracts the TensorFlow C library into the `lib`
diff --git a/tensorflow/docs_src/install/install_go.md b/tensorflow/docs_src/install/install_go.md
index 55bc0f64e7..1c03dd223e 100644
--- a/tensorflow/docs_src/install/install_go.md
+++ b/tensorflow/docs_src/install/install_go.md
@@ -38,7 +38,7 @@ steps to install this library and enable TensorFlow for Go:
TF_TYPE="cpu" # Change to "gpu" for GPU support
TARGET_DIRECTORY='/usr/local'
curl -L \
- "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-$(go env GOOS)-x86_64-1.9.0-rc0.tar.gz" |
+ "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-$(go env GOOS)-x86_64-1.9.0-rc1.tar.gz" |
sudo tar -C $TARGET_DIRECTORY -xz
The `tar` command extracts the TensorFlow C library into the `lib`
diff --git a/tensorflow/docs_src/install/install_java.md b/tensorflow/docs_src/install/install_java.md
index b3b739212e..c73e2f4281 100644
--- a/tensorflow/docs_src/install/install_java.md
+++ b/tensorflow/docs_src/install/install_java.md
@@ -36,7 +36,7 @@ following to the project's `pom.xml` to use the TensorFlow Java APIs:
org.tensorflow
tensorflow
- 1.9.0-rc0
+ 1.9.0-rc1
```
@@ -65,7 +65,7 @@ As an example, these steps will create a Maven project that uses TensorFlow:
org.tensorflow
tensorflow
- 1.9.0-rc0
+ 1.9.0-rc1
@@ -124,12 +124,12 @@ instead:
org.tensorflow
libtensorflow
- 1.9.0-rc0
+ 1.9.0-rc1
org.tensorflow
libtensorflow_jni_gpu
- 1.9.0-rc0
+ 1.9.0-rc1
```
@@ -148,7 +148,7 @@ refer to the simpler instructions above instead.
Take the following steps to install TensorFlow for Java on Linux or macOS:
1. Download
- [libtensorflow.jar](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.9.0-rc0.jar),
+ [libtensorflow.jar](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.9.0-rc1.jar),
which is the TensorFlow Java Archive (JAR).
2. Decide whether you will run TensorFlow for Java on CPU(s) only or with
@@ -167,7 +167,7 @@ Take the following steps to install TensorFlow for Java on Linux or macOS:
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
mkdir -p ./jni
curl -L \
- "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-${TF_TYPE}-${OS}-x86_64-1.9.0-rc0.tar.gz" |
+ "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-${TF_TYPE}-${OS}-x86_64-1.9.0-rc1.tar.gz" |
tar -xz -C ./jni
### Install on Windows
@@ -175,10 +175,10 @@ Take the following steps to install TensorFlow for Java on Linux or macOS:
Take the following steps to install TensorFlow for Java on Windows:
1. Download
- [libtensorflow.jar](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.9.0-rc0.jar),
+ [libtensorflow.jar](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.9.0-rc1.jar),
which is the TensorFlow Java Archive (JAR).
2. Download the following Java Native Interface (JNI) file appropriate for
- [TensorFlow for Java on Windows](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-cpu-windows-x86_64-1.9.0-rc0.zip).
+ [TensorFlow for Java on Windows](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-cpu-windows-x86_64-1.9.0-rc1.zip).
3. Extract this .zip file.
@@ -227,7 +227,7 @@ must be part of your `classpath`. For example, you can include the
downloaded `.jar` in your `classpath` by using the `-cp` compilation flag
as follows:
-javac -cp libtensorflow-1.9.0-rc0.jar HelloTF.java
+javac -cp libtensorflow-1.9.0-rc1.jar HelloTF.java
### Running
@@ -241,11 +241,11 @@ two files are available to the JVM:
For example, the following command line executes the `HelloTF` program on Linux
and macOS X:
-java -cp libtensorflow-1.9.0-rc0.jar:. -Djava.library.path=./jni HelloTF
+java -cp libtensorflow-1.9.0-rc1.jar:. -Djava.library.path=./jni HelloTF
And the following command line executes the `HelloTF` program on Windows:
-java -cp libtensorflow-1.9.0-rc0.jar;. -Djava.library.path=jni HelloTF
+java -cp libtensorflow-1.9.0-rc1.jar;. -Djava.library.path=jni HelloTF
If the program prints Hello from version, you've successfully
installed TensorFlow for Java and are ready to use the API. If the program
diff --git a/tensorflow/docs_src/install/install_linux.md b/tensorflow/docs_src/install/install_linux.md
index 2ecab808c4..9baf6870be 100644
--- a/tensorflow/docs_src/install/install_linux.md
+++ b/tensorflow/docs_src/install/install_linux.md
@@ -438,7 +438,7 @@ Take the following steps to install TensorFlow in an Anaconda environment:
(tensorflow)$ pip install --ignore-installed --upgrade \
- https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc0-cp34-cp34m-linux_x86_64.whl
+ https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc1-cp34-cp34m-linux_x86_64.whl
## Validate your installation
@@ -684,14 +684,14 @@ This section documents the relevant values for Linux installations.
CPU only:
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc0-cp27-none-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc1-cp27-none-linux_x86_64.whl
GPU support:
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc0-cp27-none-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc1-cp27-none-linux_x86_64.whl
Note that GPU support requires the NVIDIA hardware and software described in
@@ -703,14 +703,14 @@ Note that GPU support requires the NVIDIA hardware and software described in
CPU only:
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc0-cp34-cp34m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc1-cp34-cp34m-linux_x86_64.whl
GPU support:
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc0-cp34-cp34m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc1-cp34-cp34m-linux_x86_64.whl
Note that GPU support requires the NVIDIA hardware and software described in
@@ -722,14 +722,14 @@ Note that GPU support requires the NVIDIA hardware and software described in
CPU only:
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc0-cp35-cp35m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc1-cp35-cp35m-linux_x86_64.whl
GPU support:
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc0-cp35-cp35m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc1-cp35-cp35m-linux_x86_64.whl
@@ -741,14 +741,14 @@ Note that GPU support requires the NVIDIA hardware and software described in
CPU only:
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc0-cp36-cp36m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.9.0rc1-cp36-cp36m-linux_x86_64.whl
GPU support:
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc0-cp36-cp36m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.9.0rc1-cp36-cp36m-linux_x86_64.whl
diff --git a/tensorflow/docs_src/install/install_mac.md b/tensorflow/docs_src/install/install_mac.md
index 9d01271c5a..693254f876 100644
--- a/tensorflow/docs_src/install/install_mac.md
+++ b/tensorflow/docs_src/install/install_mac.md
@@ -119,7 +119,7 @@ Take the following steps to install TensorFlow with Virtualenv:
TensorFlow in the active Virtualenv is as follows:
$ pip3 install --upgrade \
- https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc0-py3-none-any.whl
+ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc1-py3-none-any.whl
If you encounter installation problems, see
[Common Installation Problems](#common-installation-problems).
@@ -242,7 +242,7 @@ take the following steps:
issue the following command:
$ sudo pip3 install --upgrade \
- https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc0-py3-none-any.whl
+ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc1-py3-none-any.whl
If the preceding command fails, see
[installation problems](#common-installation-problems).
@@ -350,7 +350,7 @@ Take the following steps to install TensorFlow in an Anaconda environment:
TensorFlow for Python 2.7:
(targetDirectory)$ pip install --ignore-installed --upgrade \
- https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc0-py2-none-any.whl
+ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc1-py2-none-any.whl
@@ -522,7 +522,7 @@ The value you specify depends on your Python version.
-https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc0-py2-none-any.whl
+https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc1-py2-none-any.whl
@@ -530,5 +530,5 @@ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc0-py2-none-a
-https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc0-py3-none-any.whl
+https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0rc1-py3-none-any.whl
diff --git a/tensorflow/docs_src/install/install_sources.md b/tensorflow/docs_src/install/install_sources.md
index d25e641cee..70e97cf556 100644
--- a/tensorflow/docs_src/install/install_sources.md
+++ b/tensorflow/docs_src/install/install_sources.md
@@ -328,10 +328,10 @@ Invoke `pip install` to install that pip package.
The filename of the `.whl` file depends on your platform.
For example, the following command will install the pip package
-for TensorFlow 1.9.0rc0 on Linux:
+for TensorFlow 1.9.0rc1 on Linux:
-$ sudo pip install /tmp/tensorflow_pkg/tensorflow-1.9.0rc0-py2-none-any.whl
+$ sudo pip install /tmp/tensorflow_pkg/tensorflow-1.9.0rc1-py2-none-any.whl
## Validate your installation
diff --git a/tensorflow/tools/pip_package/setup.py b/tensorflow/tools/pip_package/setup.py
index 92a1465cea..eb2e359ee5 100644
--- a/tensorflow/tools/pip_package/setup.py
+++ b/tensorflow/tools/pip_package/setup.py
@@ -45,7 +45,7 @@ DOCLINES = __doc__.split('\n')
# This version string is semver compatible, but incompatible with pip.
# For pip, we will remove all '-' characters from this string, and use the
# result for pip.
-_VERSION = '1.9.0-rc0'
+_VERSION = '1.9.0-rc1'
REQUIRED_PACKAGES = [
'absl-py >= 0.1.6',
--
GitLab
From f5ee4df50af4041dc0063d0adc31c7a6eebdbcd3 Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Fri, 8 Jun 2018 15:47:19 -0700
Subject: [PATCH 0034/1193] Copy edits to Keras guide, formatting, moving some
things around. Make the right TOC nav more useful.
PiperOrigin-RevId: 199863216
---
.../docs_src/programmers_guide/keras.md | 870 ++++++++----------
1 file changed, 389 insertions(+), 481 deletions(-)
diff --git a/tensorflow/docs_src/programmers_guide/keras.md b/tensorflow/docs_src/programmers_guide/keras.md
index 6a9df12a25..c6aca7ebf4 100644
--- a/tensorflow/docs_src/programmers_guide/keras.md
+++ b/tensorflow/docs_src/programmers_guide/keras.md
@@ -1,334 +1,304 @@
# Keras
-## What's Keras?
-
-Keras is a high-level API specification for building and training deep learning
-models, suitable for fast prototyping, advanced research, and production.
-It offers three key advantages:
-
-- **User friendliness.** Keras follows best practices for reducing
- cognitive load: it offers consistent & simple interfaces,
- it minimizes the number of user actions required for common use cases,
- and it provides clear and actionable feedback upon user error.
-- **Modularity and composability.** A Keras model is composed of
- fully-configurable building blocks that can be plugged together
- with as few restrictions as possible -- like Lego bricks.
-- **Easy extensibility.** You can easily write your own building blocks
- (such as new layers, new loss functions, new models where you write
- the forward pass from scratch). This allows for total expressiveness,
- making Keras suitable for advanced research.
-
-
-## What's tf.keras?
-
-`tf.keras` is TensorFlow's implementation of the Keras API specification, that
-serves as the TensorFlow high-level API: it's how you build models in TensorFlow.
-`tf.keras` seamlessly integrates with the rest of the TensorFlow API
-(such as `tf.data` input pipelines), bringing you the full power and flexibility
-of TensorFlow through an easy-to-use interface.
-
-You can import `tf.keras` via:
+Keras is a high-level API to build and train deep learning models. It's used for
+fast prototyping, advanced research, and production, with three key advantages:
+
+- *User friendly*
+ Keras has a simple, consistent interface optimized for common use cases. It
+ provides clear and actionable feedback for user errors.
+- *Modular and composable*
+ Keras models are made by connecting configurable building blocks together,
+ with few restrictions.
+- *Easy to extend*
Write custom building blocks to express new ideas for
+ research. Create new layers, loss functions, and develop state-of-the-art
+ models.
+
+## Import tf.keras
+
+`tf.keras` is TensorFlow's implementation of the
+[Keras API specification](https://keras.io){:.external}. This is a high-level
+API to build and train models that includes first-class support for
+TensorFlow-specific functionality, such as [eager execution](#eager_execution),
+`tf.data` pipelines, and [Estimators](/programmers_guide/estimators).
+`tf.keras` makes TensorFlow easier to use without sacrificing flexibility and
+performance.
+
+To get started, import `tf.keras` as part of your TensorFlow program setup:
```python
+import tensorflow as tf
from tensorflow import keras
```
-What follows is a quick introduction to the basics of `tf.keras`.
+`tf.keras` can run any Keras-compatible code, but keep in mind:
+* The `tf.keras` version in the latest TensorFlow release might not be the same
+ as the latest `keras` version from PyPI. Check `tf.keras.__version__`.
+* When [saving a model's weights](#weights_only), `tf.keras` defaults to the
+ [checkpoint format](/get_started/checkpoints). Pass `save_format='h5'` to use
+ HDF5.
-## Table of contents
+## Build a simple model
-- [Getting started: the Sequential model](#getting-started-the-sequential-model)
-- [Configuring layers](#configuring-layers)
-- [Configuring training](#configuring-training)
-- [Training and evaluation](#training-and-evaluation)
-- [Building advanced models: the functional API](#building-advanced-models-the-functional-api)
-- [Building fully-customizable research models: the Model subclassing API](#building-fully-customizable-research-models-the-model-subclassing-api)
-- [Callbacks](#callbacks)
-- [Saving and serialization](#saving-and-serialization)
-- [Developing custom layers](#developing-custom-layers)
-- [Eager execution](#eager-execution)
-- [Further reading](#further-reading)
-- [FAQ](#faq)
+### Sequential model
+In Keras, you assemble *layers* to build *models*. A model is (usually) a graph
+of layers. The most common type of model is a stack of layers: the
+`tf.keras.Sequential` model.
----
-
-## Getting started: the Sequential model
-
-In `tf.keras`, you're assembling together **layers** to build **models**.
-A model is generally a graph of layers.
-The most common type of model is just a stack of layers: the `Sequential` class.
-
-Here's how to build a simple fully-connected network (multi-layer perceptron):
+To build a simple, fully-connected network (i.e. multi-layer perceptron):
```python
-from tensorflow import keras
-from tensorflow.keras import layers
-
model = keras.Sequential()
-# This adds to the model a densely-connected layer with 64 units:
-model.add(Dense(64, activation='relu'))
-# Another one:
-model.add(Dense(64, activation='relu'))
-# This adds a softmax layer with 10 output units:
-model.add(Dense(10, activation='softmax'))
+# Adds a densely-connected layer with 64 units to the model:
+model.add(keras.layers.Dense(64, activation='relu'))
+# Add another:
+model.add(keras.layers.Dense(64, activation='relu'))
+# Add a softmax layer with 10 output units:
+model.add(keras.layers.Dense(10, activation='softmax'))
```
----
-
-## Configuring layers
-
-Each layer may have unique constructor arguments, but some common arguments include:
+### Configure the layers
-- `activation`: the activation function to be used.
- It could be specified by name, as a string (for built-in functions)
- or as a callable object. By default, no activation is applied.
-- `kernel_initializer` and `bias_initializer`: the initialization schemes to use
- to create the layer's weights (kernel and bias).
- Likewise, they may be passed either by name or by specifying a callable.
- By default, the "Glorot uniform" initializer is used.
-- `kernel_regularizer` and `bias_regularizer`: the regularization schemes to
- apply to the layer's weights (kernel and bias), such as L1
- or L2 regularization. By default, no regularization is applied.
+There are many `tf.keras.layers` available with some common constructor
+parameters:
+* `activation`: Set the activation function for the layer. This parameter is
+ specified by the name of a built-in function or as a callable object. By
+ default, no activation is applied.
+* `kernel_initializer` and `bias_initializer`: The initialization schemes
+ that create the layer's weights (kernel and bias). This parameter is a name or
+ a callable object. This defaults to the `"Glorot uniform"` initializer.
+* `kernel_regularizer` and `bias_regularizer`: The regularization schemes
+ that apply the layer's weights (kernel and bias), such as L1 or L2
+ regularization. By default, no regularization is applied.
-### Examples
+The following instantiates `tf.keras.layers.Dense` layers using constructor
+arguments:
```python
-import tensorflow as tf
-from tensorflow.keras.layers import Dense
-from tensorflow.keras import regularizers
-from tensorflow.keras import initializers
-
-# A sigmoid layer:
-Dense(64, activation='sigmoid')
-# Another way to define the same sigmoid layer:
-Dense(64, activation=tf.sigmoid)
-
-# A linear layer with L1 regularization of factor 0.01
-# applied to the kernel matrix:
-Dense(64, kernel_regularizer=regularizers.l1(0.01))
-# A linear layer with L2 regularization of factor 0.01
-# applied to the bias vector:
-Dense(64, bias_regularizer=regularizers.l2(0.01))
+# Create a sigmoid layer:
+layers.Dense(64, activation='sigmoid')
+# Or:
+layers.Dense(64, activation=tf.sigmoid)
+
+# A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix:
+layers.Dense(64, kernel_regularizer=keras.regularizers.l1(0.01))
+# A linear layer with L2 regularization of factor 0.01 applied to the bias vector:
+layers.Dense(64, bias_regularizer=keras.regularizers.l2(0.01))
# A linear layer with a kernel initialized to a random orthogonal matrix:
-Dense(64, kernel_initializer='orthogonal')
+layers.Dense(64, kernel_initializer='orthogonal')
# A linear layer with a bias vector initialized to 2.0s:
-Dense(64, bias_initializer=initializers.constant(2.0))
+layers.Dense(64, bias_initializer=keras.initializers.constant(2.0))
```
----
+## Train and evaluate
-## Configuring training
+### Set up training
-Once your model looks good, configure its learning process by calling `compile`:
+After the model is constructed, configure its learning process by calling the
+`compile` method:
```python
-import tensorflow as tf
-
model.compile(optimizer=tf.train.AdamOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
```
-There are three key arguments that you need to specify:
+`tf.keras.Model.compile` takes three important arguments:
-- An `optimizer`: this object specifies the training procedure.
- We recommend that you pass instances of optimizers from the `tf.train` module
- (such as [`AdamOptimizer`](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer),
- [`RMSPropOptimizer`](https://www.tensorflow.org/api_docs/python/tf/train/RMSPropOptimizer),
- or [`GradientDescentOptimizer`](https://www.tensorflow.org/api_docs/python/tf/train/GradientDescentOptimizer)).
-- A `loss` function to minimize: this specifies the optimization objective.
- Common choices include mean square error (`mse`), `categorical_crossentropy`
- and `binary_crossentropy`. Loss functions may be specified by name
- or by passing a callable (e.g. from the `tf.keras.losses` module).
-- Some `metrics` to monitor during training: again, you can pass these as either
- string names or callables (e.g. from the `tf.keras.metrics` module).
+* `optimizer`: This object specifies the training procedure. Pass it optimizer
+ instances from the `tf.train` module, such as
+ [`AdamOptimizer`](/api_docs/python/tf/train/AdamOptimizer),
+ [`RMSPropOptimizer`](/api_docs/python/tf/train/RMSPropOptimizer), or
+ [`GradientDescentOptimizer`](/api_docs/python/tf/train/GradientDescentOptimizer).
+* `loss`: The function to minimize during optimization. Common choices include
+ mean square error (`mse`), `categorical_crossentropy`, and
+ `binary_crossentropy`. Loss functions are specified by name or by
+ passing a callable object from the `tf.keras.losses` module.
+* `metrics`: Used to monitor training. These are string names or callables from
+ the `tf.keras.metrics` module.
-
-### Examples
+The following shows a few examples of configuring a model for training:
```python
-# Configures a model to do mean-squared error regression.
+# Configure a model for mean-squared error regression.
model.compile(optimizer=tf.train.AdamOptimizer(0.01),
- loss='mse', # mean squared error
+ loss='mse', # mean squared error
metrics=['mae']) # mean absolute error
-```
-```python
-# Configures a model to do categorical classification.
+
+# Configure a model for categorical classification.
model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),
- loss=tf.keras.losses.categorical_crossentropy,
- metrics=[tf.keras.metrics.categorical_accuracy])
+ loss=keras.losses.categorical_crossentropy,
+ metrics=[keras.metrics.categorical_accuracy])
```
----
-
-## Training and evaluation
+### Input NumPy data
-### From Numpy data
-
-When running locally on small datasets, the easiest way to do training and
-evaluation is to pass data to your model as Numpy arrays of inputs and targets.
-You can "fit" your model to some training data using the `model.fit()` method:
+For small datasets, use in-memory [NumPy](https://www.numpy.org/){:.external}
+arrays to train and evaluate a model. The model is "fit" to the training data
+using the `fit` method:
```python
import numpy as np
-data = np.random.random(shape=(1000, 32))
-targets = np.random.random(shape=(1000, 10))
+data = np.random.random((1000, 32))
+labels = np.random.random((1000, 10))
-model.fit(data, targets, epochs=10, batch_size=32)
+model.fit(data, labels, epochs=10, batch_size=32)
```
-Here are some key arguments you can pass to the `fit` method:
-
-- `epochs`: Training is structured into **epochs**. An epoch is one iteration
- over the entire input data (which is done in smaller batches).
-- `batch_size`: when passing Numpy data, the model will slice the data into
- smaller batches and iterate over these batches during training.
- This integer specifies the size of each batch
- (the last batch may be smaller if the total number of samples is not
- divisible by the batch size).
-- `validation_data`: when prototyping a model, you want to be able to quickly
- monitor its performance on some validation data.
- When you pass this argument (it expects a tuple of inputs and targets),
- the model will display the loss and metrics in inference mode on the data
- you passed, at the end of each epoch.
+`tf.keras.Model.fit` takes three important arguments:
+
+* `epochs`: Training is structured into *epochs*. An epoch is one iteration over
+ the entire input data (this is done in smaller batches).
+* `batch_size`: When passed NumPy data, the model slices the data into smaller
+ batches and iterates over these batches during training. This integer
+ specifies the size of each batch. Be aware that the last batch may be smaller
+ if the total number of samples is not divisible by the batch size.
+* `validation_data`: When prototyping a model, you want to easily monitor its
+ performance on some validation data. Passing this argument—a tuple of inputs
+ and labels—allows the model to display the loss and metrics in inference mode
+ for the passed data, at the end of each epoch.
Here's an example using `validation_data`:
```python
import numpy as np
-data = np.random.random(shape=(1000, 32))
-targets = np.random.random(shape=(1000, 10))
+data = np.random.random((1000, 32))
+labels = np.random.random((1000, 10))
-val_data = np.random.random(shape=(100, 32))
-val_targets = np.random.random(shape=(100, 10))
+val_data = np.random.random((100, 32))
+val_labels = np.random.random((100, 10))
-model.fit(data, targets, epochs=10, batch_size=32,
- validation_data=(val_data, val_targets))
+model.fit(data, labels, epochs=10, batch_size=32,
+ validation_data=(val_data, val_labels))
```
-### From tf.data datasets
+### Input tf.data datasets
-When you need to scale to large datasets or multi-device training,
-training from Numpy arrays in memory will not be ideal.
-In such cases, you should use [the `tf.data` API](https://www.tensorflow.org/programmers_guide/datasets).
-You can pass a `tf.data.Dataset` instance to the `fit` method:
+Use the [Datasets API](/programmers_guide/datasets) to scale to large datasets
+or multi-device training. Pass a `tf.data.Dataset` instance to the `fit`
+method:
```python
-import tensorflow as tf
-
# Instantiates a toy dataset instance:
-dataset = tf.data.Dataset.from_tensor_slices((data, targets)).batch(32)
+dataset = tf.data.Dataset.from_tensor_slices((data, labels))
+dataset = dataset.batch(32)
+dataset = dataset.repeat()
# Don't forget to specify `steps_per_epoch` when calling `fit` on a dataset.
model.fit(dataset, epochs=10, steps_per_epoch=30)
```
-When doing so, the dataset itself will yield batches of data,
-so the model does not need to be passed `batch_size` information.
-Instead, the model needs to know for how many steps (or batches of data)
-it should run at each epoch.
-You specify this with the `steps_per_epoch` argument: it's the number of
-training steps the model will run before moving on the next epoch.
+Here, the `fit` method uses the `steps_per_epoch` argument—this is the number of
+training steps the model runs before it moves to the next epoch. Since the
+`Dataset` yields batches of data, this snippet does not require a `batch_size`.
-You can also pass datasets for validation:
+Datasets can also be used for validation:
```python
-dataset = tf.data.Dataset.from_tensor_slices((data, targets)).batch(32)
-val_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_targets)).batch(32)
+dataset = tf.data.Dataset.from_tensor_slices((data, labels))
+dataset = dataset.batch(32).repeat()
-model.fit(dataset, epochs=10, steps_per_epoch=30, validation_data=val_dataset, validation_steps=3)
+val_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_labels))
+val_dataset = val_dataset.batch(32).repeat()
+
+model.fit(dataset, epochs=10, steps_per_epoch=30,
+ validation_data=val_dataset,
+ validation_steps=3)
```
### Evaluate and predict
-In addition, you get access to the following methods
-(both with Numpy data and dataset instances):
+The `tf.keras.Model.evaluate` and `tf.keras.Model.predict` methods can use NumPy
+data and a `tf.data.Dataset`.
-- `model.evaluate(x, y, batch_size=32)` or `model.evaluate(dataset, steps=30)`
- will return the inference-mode loss and metrics for the data provided.
-- `model.predict(x, y, batch_size=32)` or `model.predict(dataset, steps=30)`
- will return the output(s) of the last layer(s) in inference on the data
- provided, as Numpy array(s).
+To *evaluate* the inference-mode loss and metrics for the data provided:
----
+```python
+model.evaluate(x, y, batch_size=32)
-## Building advanced models: the functional API
+model.evaluate(dataset, steps=30
+```
-The `Sequential` model cannot represent arbitrary models -- only simple stacks
-of layers. If you need to use more complex model topologies,
-such as multi-input models, multi-output models,
-models with a same layer called several times (shared layers),
-or models with non-sequential data flows (e.g. residual connections),
-you can use the 'functional API'.
+And to *predict* the output of the last layer in inference for the data provided,
+as a NumPy array:
-Here's how it works:
+```
+model.predict(x, batch_size=32)
-- A layer instance is callable (on a tensor), and it returns a tensor.
-- Input tensor(s) and output tensor(s) can then be used to define a `Model` instance.
-- Such a model can be trained just like the `Sequential` model.
+model.predict(dataset, steps=30)
+```
-Here's a basic example showing the same model we previously defined,
-built using the functional API:
+## Build advanced models
-```python
-from tensorflow import keras
-from tensorflow.keras import layers
+### Functional API
-# This returns a placeholder tensor:
-inputs = keras.Input(shape=(784,))
+The `tf.keras.Sequential` model is a simple stack of layers that cannot
+represent arbitrary models. Use the
+[Keras functional API](https://keras.io/getting-started/functional-api-guide/){:.external}
+to build complex model topologies such as:
+
+* Multi-input models,
+* Multi-output models,
+* Models with shared layers (the same layer called several times),
+* Models with non-sequential data flows (e.g. residual connections).
+
+Building a model with the functional API works like this:
+
+1. A layer instance is callable and returns a tensor.
+2. Input tensors and output tensors are used to define a `tf.keras.Model`
+ instance.
+3. This model is trained just like the `Sequential` model.
+
+The following example uses the functional API to build a simple, fully-connected
+network:
+
+```python
+inputs = keras.Input(shape=(32,)) # Returns a placeholder tensor
# A layer instance is callable on a tensor, and returns a tensor.
-x = layers.Dense(64, activation='relu')(inputs)
-x = layers.Dense(64, activation='relu')(x)
-predictions = layers.Dense(10, activation='softmax')(x)
+x = keras.layers.Dense(64, activation='relu')(inputs)
+x = keras.layers.Dense(64, activation='relu')(x)
+predictions = keras.layers.Dense(10, activation='softmax')(x)
-# Instantiates the model given inputs and outputs.
+# Instantiate the model given inputs and outputs.
model = keras.Model(inputs=inputs, outputs=predictions)
-# The "compile" step specifies the training configuration.
-model.compile(optimizer='rmsprop',
+# The compile step specifies the training configuration.
+model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
-# Trains for 5 epochs.
+# Trains for 5 epochs
model.fit(data, labels, batch_size=32, epochs=5)
```
-This API enables you to create models with multiple inputs and outputs,
-and to "share" layers across different inputs
-(i.e. to reuse a same instance multiple times).
-For examples of these use cases,
-please see [this guide to the functional API in Keras](https://keras.io/getting-started/functional-api-guide/).
+### Model subclassing
----
+Build a fully-customizable model by subclassing `tf.keras.Model` and defining
+your own forward pass. Create layers in the `__init__` method and set them as
+attributes of the class instance. Define the forward pass in the `call` method.
-## Building fully-customizable research models: the Model subclassing API
+Model subclassing is particularly useful when
+[eager execution](/programmers_guide/eager) is enabled since the forward pass
+can be written imperatively.
-Besides `Sequential` and the functional API, one last, more flexible way to
-define models is to directly subclass the `Model` class and define your own
-forward pass manually.
+Key Point: Use the right API for the job. While model subclassing offers
+flexibility, it comes at a cost of greater complexity and more opportunities for
+user errors. If possible, prefer the functional API.
-In this API, you instante layers in `__init__` and set them as attribute of the
-class instance. Then you specify the forward pass in `call`.
-This API is particularly valuable when using TensorFlow with [eager execution](https://www.tensorflow.org/programmers_guide/eager),
-since eager execution allows you to write your forward pass in an
-imperative fashion (as if you were writing Numpy code, for instance).
+The following example shows a subclassed `tf.keras.Model` using a custom forward
+pass:
```python
-import tensorflow as tf
-from tensorflow import keras
-
-
class MyModel(keras.Model):
- def __init__(self, num_classes=2):
+ def __init__(self, num_classes=10):
super(MyModel, self).__init__(name='my_model')
self.num_classes = num_classes
# Define your layers here.
@@ -351,10 +321,10 @@ class MyModel(keras.Model):
# Instantiates the subclassed model.
-model = MyModel(num_classes=2)
+model = MyModel(num_classes=10)
-# The "compile" step specifies the training configuration.
-model.compile(optimizer='rmsprop',
+# The compile step specifies the training configuration.
+model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])
@@ -362,353 +332,291 @@ model.compile(optimizer='rmsprop',
model.fit(data, labels, batch_size=32, epochs=5)
```
-**Remember:** use the right API for the right job.
-Using the `Model` subclassing API offers more flexibility,
-but at the cost of greater complexity and a larger potential user error surface.
-Prefer using the functional API when possible.
----
+### Custom layers
-## Callbacks
+Create a custom layer by subclassing `tf.keras.layers.Layer` and implementing
+the following methods:
-Callbacks are objects that you can pass to your model that customize and extend
-its behavior during training.
-There are callbacks for saving checkpoints of your model at regular intervals
-(`tf.keras.callbacks.ModelCheckpoint`),
-to dynamically change the learning rate (`tf.keras.callbacks.LearningRateScheduler`)
-or to interrupt training when validation performance has stopped improving
-(`tf.keras.callbacks.EarlyStopping`).
-You can also use a callback to monitor your model's behavior using
-[TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard)
-(`tf.keras.callbacks.TensorBoard`).
-You can also write your own custom callbacks.
-
-Different built-in callback are found in `tf.keras.callbacks`.
-You use them by passing a `Callback` instance to `fit`:
+* `build`: Create the weights of the layer. Add weights with the `add_weight`
+ method.
+* `call`: Define the forward pass.
+* `compute_output_shape`: Specify how to compute the output shape of the layer
+ given the input shape.
+* Optionally, a layer can be serialized by implementing the `get_config` method
+ and the `from_config` class method.
+
+Here's an example of a custom layer that implements a `matmul` of an input with
+a kernel matrix:
```python
-from tensorflow import keras
+class MyLayer(keras.layers.Layer):
+
+ def __init__(self, output_dim, **kwargs):
+ self.output_dim = output_dim
+ super(MyLayer, self).__init__(**kwargs)
+
+ def build(self, input_shape):
+ shape = tf.TensorShape((input_shape[1], self.output_dim))
+ # Create a trainable weight variable for this layer.
+ self.kernel = self.add_weight(name='kernel',
+ shape=shape,
+ initializer='uniform',
+ trainable=True)
+ # Be sure to call this at the end
+ super(MyLayer, self).build(input_shape)
-callbacks = [
- # Interrupt training if `val_loss` stops improving for over 2 epochs
- keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
- # Write TensorBoard logs to `./logs` directory
- keras.callbacks.TensorBoard(log_dir='./logs')
-]
-model.fit(data, labels, batch_size=32, epochs=5, callbacks=callbacks)
-```
+ def call(self, inputs):
+ return tf.matmul(inputs, self.kernel)
----
+ def compute_output_shape(self, input_shape):
+ shape = tf.TensorShape(input_shape).as_list()
+ shape[-1] = self.output_dim
+ return tf.TensorShape(shape)
-## Saving and serialization
+ def get_config(self):
+ base_config = super(MyLayer, self).get_config()
+ base_config['output_dim'] = self.output_dim
-### Weights-only saving
+ @classmethod
+ def from_config(cls, config):
+ return cls(**config)
-You can save the weight values of a model via `model.save_weights(filepath)`:
-```python
-# Saves weights to a SavedModel file.
-model.save_weights('my_model')
+# Create a model using the custom layer
+model = keras.Sequential([MyLayer(10),
+ keras.layers.Activation('softmax')])
-# Restores the model's state
-# (this requires a model that has the same architecture).
-model.load_weights('my_model')
+# The compile step specifies the training configuration
+model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
+ loss='categorical_crossentropy',
+ metrics=['accuracy'])
+
+# Trains for 5 epochs.
+model.fit(data, targets, batch_size=32, epochs=5)
```
-By default, this saves the weight in the TensorFlow
-[`SavedModel`](https://www.tensorflow.org/programmers_guide/saved_model) format.
-You could also save them in the Keras HDF5 format
-(which is the default in the multi-backend implementation of Keras):
-```python
-# Saves weights to a HDF5 file.
-model.save_weights('my_model.h5', format='h5')
+## Callbacks
-# Restores the model's state.
-model.load_weights('my_model.h5')
-```
+A callback is an object passed to a model to customize and extend its behavior
+during training. You can write your own custom callback, or use the built-in
+`tf.keras.callbacks` that include:
-### Configuration-only saving (serialization)
+* `tf.keras.callbacks.ModelCheckpoint`: Save checkpoints of your model at
+ regular intervals.
+* `tf.keras.callbacks.LearningRateScheduler`: Dynamically change the learning
+ rate.
+* `tf.keras.callbacks.EarlyStopping`: Interrupt training when validation
+ performance has stopped improving.
+* `tf.keras.callbacks.TensorBoard`: Monitor the model's behavior using
+ [TensorBoard](/programmers_guide/summaries_and_tensorboard).
-You can also save the model's configuration
-(its architecture, without any weight values),
-which allows you to recreate the same model later (freshly initialized) even if
-you don't have the code that defined it anymore.
-Two possible serialization formats are JSON and YAML:
+To use a `tf.keras.callbacks.Callback`, pass it to the model's `fit` method:
```python
-from tensorflow.keras import models
-
-# Serializes a model to JSON.
-json_string = model.to_json()
-# Recreates the model (freshly initialized).
-fresh_model = models.from_json(json_string)
-
-# Serializes a model to YAML.
-yaml_string = model.to_yaml()
-# Recreates the model.
-fresh_model = models.from_yaml(yaml_string)
+callbacks = [
+ # Interrupt training if `val_loss` stops improving for over 2 epochs
+ keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
+ # Write TensorBoard logs to `./logs` directory
+ keras.callbacks.TensorBoard(log_dir='./logs')
+]
+model.fit(data, labels, batch_size=32, epochs=5, callbacks=callbacks,
+ validation_data=(val_data, val_targets))
```
-Note that this feature is not available with subclassed models,
-because they are simply not serializable:
-their architecture is defined as Python code
-(the body of the `call` method of the model).
-### Whole-model saving
+## Save and restore
-Finally, you can also save a model wholesale, to a file that will contain both
-the weight values, the model's configuration,
-and even the optimizer's configuration.
-The allows you to checkpoint a model and resume training later --
-from the exact same state -- even if you don't have access to the original code.
+### Weights only
-```python
-from tensorflow.keras import models
+Save and load the weights of a model using `tf.keras.Model.save_weights`:
-model.save('my_model.h5')
+```python
+# Save weights to a TensorFlow Checkpoint file
+model.save_weights('./my_model')
-# Recreates the exact same model, complete with weights and optimizer.
-model = models.load_model('my_model.h5')
+# Restore the model's state,
+# this requires a model with the same architecture.
+model.load_weights('my_model')
```
----
-
-## Developing custom layers
-
-You can write your own custom layers by subclassing the class
-`tf.keras.layers.Layer`. You will need to implement the following three methods:
-
-- `build`: Creates the weights of the layer.
- Weights should be added via the `add_weight` method.
-- `call`: Specifies the forward pass.
-- `compute_output_shape`: Specifies how to compute the output shape of the layer
- given the input shape.
-
-Optionally, you may also implement the method `get_config()` and the
-class method `from_config()` if you want your layer to be serializable.
-
-Here's a simple example of a custom layer that implements a `matmul`
-of an input with a kernel matrix:
+By default, this saves the model's weights in the
+[TensorFlow checkpoint](/get_started/checkpoints) file format. Weights can also
+be saved to the Keras HDF5 format (the default for the multi-backend
+implementation of Keras):
```python
-import tensorflow as tf
-from tensorflow.keras import layers
-
-class MyLayer(layers.Layer):
-
- def __init__(self, output_dim, **kwargs):
- self.output_dim = output_dim
- super(MyLayer, self).__init__(**kwargs)
-
- def build(self, input_shape):
- # Create a trainable weight variable for this layer.
- self.kernel = self.add_weight(name='kernel',
- shape=(input_shape[1], self.output_dim),
- initializer='uniform',
- trainable=True)
- # Be sure to call this at the end
- super(MyLayer, self).build(input_shape)
-
- def call(self, inputs):
- return tf.matmul(inputs, self.kernel)
-
- def compute_output_shape(self, input_shape):
- shape = tf.TensorShape(input_shape).as_list()
- shape[-1] = self.output_dim
- return tf.TensorShape(shape)
-
- def get_config(self):
- base_config = super(MyLayer, self).get_config()
- base_config['output_dim'] = self.output_dim
-
- @classmethod
- def from_config(cls, config):
- return cls(**config)
-```
+# Save weights to a HDF5 file
+model.save_weights('my_model.h5', save_format='h5')
----
-
-## Eager execution
+# Restore the model's state
+model.load_weights('my_model.h5')
+```
-[Eager execution](https://www.tensorflow.org/programmers_guide/eager)
-is a way to write TensorFlow code imperatively.
-All three `tf.keras` model-building APIs
-(`Sequential`, the functional API `Model(inputs, outputs)`,
-and the subclassing API `MyModel(Model)`) are compatible with eager execution.
-When using `Sequential` or the functional API, it makes no difference to the
-user experience whether the model is executing eagerly or not.
-Eager execution is most beneficial when used with the `Model` subclassing API,
-or when prototyping a custom layer -- that is to say, in APIs that require you
-to *write a forward pass as code*, rather than in APIs that allow you to create
-models by assembling together existing layers.
+### Configuration only
-While the same training and evaluating APIs presented in this guide work
-as usual with eager execution, you can in addition
-write custom training loops using the eager `GradientTape`
-and define-by-run autodifferentiation:
+A model's configuration can be saved—this serializes the model architecture
+without any weights. A saved configuration can recreate and initialize the same
+model, even without the code that defined the original model. Keras supports
+JSON and YAML serialization formats:
```python
-import tensorflow as tf
-from tensorflow.contrib import eager as tfe
-
-# This call begins the eager execution session.
-tf.enable_eager_execution()
-
-model = ... # Defines a Keras model (we recommend Model subclassing in this case).
-dataset = ... # Defines a `tf.data` dataset.
+# Serialize a model to JSON format
+json_string = model.to_json()
-optimizer = tf.train.AdamOptimizer(0.01)
+# Recreate the model (freshly initialized)
+fresh_model = keras.models.from_json(json_string)
-for data, labels in dataset:
- # Runs the forward pass and loss computation under a `GradientTape` scope,
- # which will record all operations in order to prepare for the backward pass.
- with tfe.GradientTape() as tape:
- predictions = model(data)
- loss = loss_function(labels, predictions)
+# Serializes a model to YAML format
+yaml_string = model.to_yaml()
- # Runs the backward pass manually using the operations recorded
- # by the gradient tape.
- grads = tape.gradient(loss, model.trainable_weights)
- optimizer.apply_gradients(zip(grads, model.trainable_weights),
- global_step=tf.train.get_or_create_global_step())
+# Recreate the model
+fresh_model = keras.models.from_yaml(yaml_string)
```
----
+Caution: Subclassed models are not serializable because their architecture is
+defined by the Python code in the body of the `call` method.
-## Further reading
-### Documentation
+### Entire model
-- [tf.keras documentation](https://www.tensorflow.org/api_docs/python/tf/keras)
-- [keras.io](https://keras.io/)
+The entire model can be saved to a file that contains the weight values, the
+model's configuration, and even the optimizer's configuration. This allows you
+to checkpoint a model and resume training later—from the exact same
+state—without access to the original code.
-### tf.keras tutorials and examples
-
-- [Fashion-MNIST with tf.Keras](https://medium.com/tensorflow/hello-deep-learning-fashion-mnist-with-keras-50fcff8cd74a)
-- [Predicting the price of wine with the Keras Functional API and TensorFlow](
- https://medium.com/tensorflow/predicting-the-price-of-wine-with-the-keras-functional-api-and-tensorflow-a95d1c2c1b03)
+```python
+# Create a trivial model
+model = keras.Sequential([
+ keras.layers.Dense(10, activation='softmax', input_shape=(32,)),
+ keras.layers.Dense(10, activation='softmax')
+])
+model.compile(optimizer='rmsprop',
+ loss='categorical_crossentropy',
+ metrics=['accuracy'])
+model.fit(data, targets, batch_size=32, epochs=5)
----
+# Save entire model to a HDF5 file
+model.save('my_model.h5')
-## FAQ
+# Recreate the exact same model, including weights and optimizer.
+model = keras.models.load_model('my_model.h5')
+```
-### What are the differences between tf.keras and the multi-backend Keras implementation?
-`tf.keras` includes first-class support for important TensorFlow-specific
-functionality not found in other Keras implementations, in particular:
+## Eager execution
-- Support for eager execution.
-- Support for the `tf.data` API.
-- Integration with the
- [`tf.estimator` API](https://www.tensorflow.org/programmers_guide/estimators),
- via `tf.keras.estimator.model_to_estimator`.
+[Eager execution](/programmers_guide/eager) is an imperative programming
+environment that evaluates operations immediately. This is not required for
+Keras, but is supported by `tf.keras` and useful for inspecting your program and
+debugging.
-In terms of API differences: `tf.keras` is a full implementation of the
-Keras API, so any code targeting the Keras API will run on `tf.keras`.
-However, keep in mind that:
+All of the `tf.keras` model-building APIs are compatible with eager execution.
+And while the `Sequential` and functional APIs can be used, eager execution
+especially benefits *model subclassing* and building *custom layers*—the APIs
+that require you to write the forward pass as code (instead of the APIs that
+create models by assembling existing layers).
-- The `tf.keras` API version in the latest TensorFlow release might not be the
- same as the latest `keras` version from PyPI.
- Check out `tf.keras.__version__` if in doubt.
-- In `tf.keras`, the default file format saved by `model.save_weights` is the
- TensorFlow `SavedModel` format.
- To use HDF5, you can pass the `format='h5'` argument.
+See the [eager execution guide](/programmers_guide/eager#build_a_model) for
+examples of using Keras models with custom training loops and `tf.GradientTape`.
-### What is the relationship between tf.keras and tf.estimator?
+## Distribution
-The [`tf.estimator` API](https://www.tensorflow.org/programmers_guide/estimators)
-is a high-level TensorFlow API for training "estimator" models,
-in particular in distributed settings.
-This API targets industry use cases, such as distributed training
-on large datasets with a focus on eventually exporting a production model.
+### Estimators
-If you have a `tf.keras` model that would like to train with the `tf.estimator`
-API, you can convert your model to an `Estimator` object via the
-`model_to_estimator` utility](https://www.tensorflow.org/programmers_guide/estimators#creating_estimators_from_keras_models):
+The [Estimators](/programmers_guide/estimators) API is used for training models
+for distributed environments. This targets industry use cases such as
+distributed training on large datasets that can export a model for production.
+A `tf.keras.Model` can be trained with the `tf.estimator` API by converting the
+model to an `tf.estimator.Estimator` object with
+`tf.keras.estimator.model_to_estimator`. See
+[Creating Estimators from Keras models](/programmers_guide/estimators#creating_estimators_from_keras_models).
```python
-estimator = tf.keras.estimator.model_to_estimator(model)
-```
+model = keras.Sequential([layers.Dense(10,activation='softmax'),
+ layers.Dense(10,activation='softmax')])
-When using `model_to_estimator`, enabling eager execution is helpful for
-developing and debugging your `input_fn`
-(as it allows you to easily print your data).
+model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
+ loss='categorical_crossentropy',
+ metrics=['accuracy'])
+
+estimator = keras.estimator.model_to_estimator(model)
+```
+Note: Enable [eager execution](/programmers_guide/eager) for debugging
+[Estimator input functions](/programmers_guide/premade_estimators#create_input_functions)
+and inspecting data.
-### How can I run tf.keras models on multiple GPUs?
+### Multiple GPUs
-You can run tf.keras models on multiple GPUs using the
-[`DistributionStrategy API`](https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/distribute/DistributionStrategy).
-The `DistributionStrategy` API allow you to distribute training on multiple GPUs
-with almost no changes to your existing code.
+`tf.keras` models can run on multiple GPUs using
+`tf.contrib.distribute.DistributionStrategy`. This API provides distributed
+training on multiple GPUs with almost no changes to existing code.
-Currently [`MirroredStrategy`](https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/distribute/MirroredStrategy)
-is the only supported strategy.
-`MirroredStrategy` allows you to do in-graph replication with synchronous
-training using all-reduce on a single machine.
-To use `DistributionStrategy` with a `tf.keras` model,
-you can use the `model_to_estimator` utility to convert a `tf.keras` model to
-an `Estimator` and then train the estimator.
+Currently, `tf.contrib.distribute.MirroredStrategy` is the only supported
+distribution strategy. `MirroredStrategy` does in-graph replication with
+synchronous training using all-reduce on a single machine. To use
+`DistributionStrategy` with Keras, convert the `tf.keras.Model` to a
+`tf.estimator.Estimator` with `tf.keras.estimator.model_to_estimator`, then
+train the estimator
-Here is a simple example of distributing a `tf.keras` model across multiple GPUs
-on a single machine.
+The following example distributes a `tf.keras.Model` across multiple GPUs on a
+single machine.
-Let's first define a simple model:
+First, define a simple model:
```python
-model = tf.keras.Sequential()
-model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=(10,)))
-model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
+model = keras.Sequential()
+model.add(keras.layers.Dense(16, activation='relu', input_shape=(10,)))
+model.add(keras.layers.Dense(1, activation='sigmoid'))
+
optimizer = tf.train.GradientDescentOptimizer(0.2)
+
model.compile(loss='binary_crossentropy', optimizer=optimizer)
model.summary()
```
-Let's use `model_to_estimator` to create an `Estimator` instance from the
-`tf.keras` model defined above.
+Convert the Keras model to a `tf.estimator.Estimator` instance:
```python
-keras_estimator = tf.keras.estimator.model_to_estimator(
- keras_model=model,
- config=config,
- model_dir='/tmp/model_dir')
+keras_estimator = keras.estimator.model_to_estimator(
+ keras_model=model,
+ config=config,
+ model_dir='/tmp/model_dir')
```
-We'll use `tf.data.Datasets` to define our input pipeline.
-Our `input_fn` returns a `tf.data.Dataset` object that we then use to distribute
-the data across multiple devices with each device processing
+Define an *input pipeline*. The `input_fn` returns a `tf.data.Dataset` object
+used to distribute the data across multiple devices—with each device processing
a slice of the input batch.
```python
def input_fn():
- x = np.random.random((1024, 10))
- y = np.random.randint(2, size=(1024, 1))
- x = tf.cast(x, tf.float32)
- dataset = tf.data.Dataset.from_tensor_slices((x, y))
- dataset = dataset.repeat(10)
- dataset = dataset.batch(32)
- return dataset
+ x = np.random.random((1024, 10))
+ y = np.random.randint(2, size=(1024, 1))
+ x = tf.cast(x, tf.float32)
+ dataset = tf.data.Dataset.from_tensor_slices((x, y))
+ dataset = dataset.repeat(10)
+ dataset = dataset.batch(32)
+ return dataset
```
-The next step is to create a `RunConfig` and set the train_distribute argument
-to the new `MirroredStrategy` instance.
-You can specify a list of devices or the `num_gpus` argument when creating
-a `MirroredStrategy` instance.
-Not specifying any arguments defaults to using all the available GPUs like we do
-in this example.
+Next, create a `tf.estimator.RunConfig` and set the `train_distribute` argument
+to the `tf.contrib.distribute.MirroredStrategy` instance. When creating
+`MirroredStrategy`, you can specify a list of devices or set the `num_gpus`
+argument. The default uses all available GPUs, like the following:
```python
strategy = tf.contrib.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(train_distribute=strategy)
```
-Call train on the `Estimator` instance providing the `input_fn` and `steps`
-arguments as input:
+Finally, train the `Estimator` instance by providing the `input_fn` and `steps`
+arguments:
```python
keras_estimator.train(input_fn=input_fn, steps=10)
--
GitLab
From 7e859ebc65bf7d77ed89f736c7fd6fede0a93c92 Mon Sep 17 00:00:00 2001
From: Michael Case
Date: Mon, 18 Jun 2018 11:07:48 -0700
Subject: [PATCH 0035/1193] Add missing Eager relnotes for TensorFlow 1.9.
(#20101)
---
RELEASE.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/RELEASE.md b/RELEASE.md
index 879ce6e440..510eca5467 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -22,6 +22,8 @@
* (C++) `DatasetBase::MakeIterator()` has been renamed to `DatasetBase::MakeIteratorInternal()`.
* (C++) `IteratorBase::Initialize()` method was added to support raising errors during iterator construction.
* Eager Execution:
+ * Added the ability to pause recording operations for gradient computation via `tf.GradientTape.stop_recording`.
+ * Updated documentation, introductory notebooks.
* `tf.keras`:
* Move Keras code out of _impl folder and remove API files.
* `tf.keras.Model.save_weights` now saves in TensorFlow format by default.
--
GitLab
From 86a6b0d7efbe5a3fa1f511237b85c926a6aef3a5 Mon Sep 17 00:00:00 2001
From: Brennan Saeta
Date: Tue, 19 Jun 2018 17:47:37 -0700
Subject: [PATCH 0036/1193] [GCS] Typo in ConfigureGcsHook.
This commit fixes a typo on ConfigureGcsHook that prevented its correct
operation.
---
tensorflow/contrib/cloud/python/ops/gcs_config_ops.py | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py b/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py
index 8c8c5acb31..4f7300fd1f 100644
--- a/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py
+++ b/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py
@@ -120,13 +120,17 @@ class ConfigureGcsHook(training.SessionRunHook):
def begin(self):
if self._credentials:
self._credentials_placeholder = array_ops.placeholder(dtypes.string)
- self._credentials_ops = gen_gcs_config_ops.gcs_configure_credentials(
+ self._credentials_op = gen_gcs_config_ops.gcs_configure_credentials(
self._credentials_placeholder)
+ else:
+ self._credentials_op = None
if self._block_cache:
self._block_cache_op = gen_gcs_config_ops.gcs_configure_block_cache(
max_cache_size=self._block_cache.max_bytes,
block_size=self._block_cache.block_size,
max_staleness=self._block_cache.max_staleness)
+ else:
+ self._block_cache_op = None
def after_create_session(self, session, coord):
del coord
--
GitLab
From cb255e292b6a4378990d02557a37c89d751edb8a Mon Sep 17 00:00:00 2001
From: Christian Ertler
Date: Thu, 21 Jun 2018 16:36:49 +0200
Subject: [PATCH 0037/1193] Adding tf.image.non_max_suppression_overlaps
This commit introduces tf.image.non_max_suppression_overlaps.
It allows to perform non-max-suppression with an overlap
criterion different to IOU by providing a n-by-n matrix with
precomputed overlap values for each box pair.
---
...pi_def_NonMaxSuppressionWithOverlaps.pbtxt | 62 +++++
...pi_def_NonMaxSuppressionWithOverlaps.pbtxt | 4 +
.../core/kernels/non_max_suppression_op.cc | 181 +++++++++++---
.../kernels/non_max_suppression_op_test.cc | 229 ++++++++++++++++++
tensorflow/core/ops/image_ops.cc | 32 +++
tensorflow/python/ops/image_ops_impl.py | 42 ++++
6 files changed, 515 insertions(+), 35 deletions(-)
create mode 100644 tensorflow/core/api_def/base_api/api_def_NonMaxSuppressionWithOverlaps.pbtxt
create mode 100644 tensorflow/core/api_def/python_api/api_def_NonMaxSuppressionWithOverlaps.pbtxt
diff --git a/tensorflow/core/api_def/base_api/api_def_NonMaxSuppressionWithOverlaps.pbtxt b/tensorflow/core/api_def/base_api/api_def_NonMaxSuppressionWithOverlaps.pbtxt
new file mode 100644
index 0000000000..180edb15a4
--- /dev/null
+++ b/tensorflow/core/api_def/base_api/api_def_NonMaxSuppressionWithOverlaps.pbtxt
@@ -0,0 +1,62 @@
+op {
+ graph_op_name: "NonMaxSuppressionWithOverlaps"
+ in_arg {
+ name: "overlaps"
+ description: <
#include
+#include
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
@@ -38,9 +39,34 @@ namespace {
typedef Eigen::ThreadPoolDevice CPUDevice;
+static inline void CheckScoreSizes(OpKernelContext* context,
+ int num_boxes,
+ const Tensor& scores) {
+ // The shape of 'scores' is [num_boxes]
+ OP_REQUIRES(context, scores.dims() == 1,
+ errors::InvalidArgument("scores must be 1-D",
+ scores.shape().DebugString()));
+ OP_REQUIRES(context, scores.dim_size(0) == num_boxes,
+ errors::InvalidArgument("scores has incompatible shape"));
+}
+
+static inline void ParseAndCheckOverlapSizes(OpKernelContext* context,
+ const Tensor& overlaps,
+ int* num_boxes) {
+ // the shape of 'overlaps' is [num_boxes, num_boxes]
+ OP_REQUIRES(context, overlaps.dims() == 2,
+ errors::InvalidArgument("overlaps must be 2-D",
+ overlaps.shape().DebugString()));
+
+ *num_boxes = overlaps.dim_size(0);
+ OP_REQUIRES(context, overlaps.dim_size(1) == *num_boxes,
+ errors::InvalidArgument("overlaps must be square",
+ overlaps.shape().DebugString()));
+}
+
static inline void ParseAndCheckBoxSizes(OpKernelContext* context,
const Tensor& boxes,
- const Tensor& scores, int* num_boxes) {
+ int* num_boxes) {
// The shape of 'boxes' is [num_boxes, 4]
OP_REQUIRES(context, boxes.dims() == 2,
errors::InvalidArgument("boxes must be 2-D",
@@ -48,18 +74,11 @@ static inline void ParseAndCheckBoxSizes(OpKernelContext* context,
*num_boxes = boxes.dim_size(0);
OP_REQUIRES(context, boxes.dim_size(1) == 4,
errors::InvalidArgument("boxes must have 4 columns"));
-
- // The shape of 'scores' is [num_boxes]
- OP_REQUIRES(context, scores.dims() == 1,
- errors::InvalidArgument("scores must be 1-D",
- scores.shape().DebugString()));
- OP_REQUIRES(context, scores.dim_size(0) == *num_boxes,
- errors::InvalidArgument("scores has incompatible shape"));
}
// Return intersection-over-union overlap between boxes i and j
-static inline float IOU(typename TTypes::ConstTensor boxes, int i,
- int j) {
+static inline float IOUGreaterThanThreshold(typename TTypes::ConstTensor boxes,
+ int i, int j, float iou_threshold) {
const float ymin_i = std::min(boxes(i, 0), boxes(i, 2));
const float xmin_i = std::min(boxes(i, 1), boxes(i, 3));
const float ymax_i = std::max(boxes(i, 0), boxes(i, 2));
@@ -78,24 +97,39 @@ static inline float IOU(typename TTypes::ConstTensor boxes, int i,
const float intersection_area =
std::max(intersection_ymax - intersection_ymin, 0.0) *
std::max(intersection_xmax - intersection_xmin, 0.0);
- return intersection_area / (area_i + area_j - intersection_area);
+ const float iou = intersection_area / (area_i + area_j - intersection_area);
+ return iou > iou_threshold;
}
-void DoNonMaxSuppressionOp(OpKernelContext* context, const Tensor& boxes,
- const Tensor& scores, const Tensor& max_output_size,
- const float iou_threshold,
- const float score_threshold) {
- OP_REQUIRES(context, iou_threshold >= 0 && iou_threshold <= 1,
- errors::InvalidArgument("iou_threshold must be in [0, 1]"));
-
- int num_boxes = 0;
- ParseAndCheckBoxSizes(context, boxes, scores, &num_boxes);
- if (!context->status().ok()) {
- return;
- }
+static inline bool OverlapsGreaterThanThreshold(typename TTypes::ConstTensor overlaps,
+ int i, int j, float overlap_threshold) {
+ return overlaps(i, j) > overlap_threshold;
+}
+
+static inline std::function CreateIOUSuppressCheckFn(const Tensor& boxes,
+ float threshold) {
+ typename TTypes::ConstTensor boxes_data = boxes.tensor();
+ return std::bind(&IOUGreaterThanThreshold, boxes_data,
+ std::placeholders::_1, std::placeholders::_2,
+ threshold);
+}
+
+static inline std::function CreateOverlapsSuppressCheckFn(const Tensor& overlaps,
+ float threshold) {
+ typename TTypes::ConstTensor overlaps_data = overlaps.tensor();
+ return std::bind(&OverlapsGreaterThanThreshold, overlaps_data,
+ std::placeholders::_1, std::placeholders::_2,
+ threshold);
+}
+
+void DoNonMaxSuppressionOp(OpKernelContext* context,
+ const Tensor& scores,
+ int num_boxes,
+ const Tensor& max_output_size,
+ const float score_threshold,
+ std::function suppress_check_fn) {
const int output_size = std::min(max_output_size.scalar()(), num_boxes);
- TTypes::ConstTensor boxes_data = boxes.tensor();
std::vector scores_data(num_boxes);
std::copy_n(scores.flat().data(), num_boxes, scores_data.begin());
@@ -120,11 +154,9 @@ void DoNonMaxSuppressionOp(OpKernelContext* context, const Tensor& boxes,
std::vector selected;
std::vector selected_scores;
Candidate next_candidate;
- float iou, original_score;
while (selected.size() < output_size && !candidate_priority_queue.empty()) {
next_candidate = candidate_priority_queue.top();
- original_score = next_candidate.score;
candidate_priority_queue.pop();
// Overlapping boxes are likely to have similar scores,
@@ -132,9 +164,10 @@ void DoNonMaxSuppressionOp(OpKernelContext* context, const Tensor& boxes,
// in order to see if `next_candidate` should be suppressed.
bool should_select = true;
for (int j = selected.size() - 1; j >= 0; --j) {
- iou = IOU(boxes_data, next_candidate.box_index, selected[j]);
- if (iou == 0.0) continue;
- if (iou > iou_threshold) should_select = false;
+ if (suppress_check_fn(next_candidate.box_index, selected[j])) {
+ should_select = false;
+ break;
+ }
}
if (should_select) {
@@ -174,9 +207,19 @@ class NonMaxSuppressionOp : public OpKernel {
errors::InvalidArgument("max_output_size must be 0-D, got shape ",
max_output_size.shape().DebugString()));
+ OP_REQUIRES(context, iou_threshold_ >= 0 && iou_threshold_ <= 1,
+ errors::InvalidArgument("iou_threshold must be in [0, 1]"));
+ int num_boxes = 0;
+ ParseAndCheckBoxSizes(context , boxes, &num_boxes);
+ CheckScoreSizes(context, num_boxes, scores);
+ if (!context->status().ok()) {
+ return;
+ }
+ auto suppress_check_fn = CreateIOUSuppressCheckFn(boxes, iou_threshold_);
+
const float score_threshold_val = std::numeric_limits::lowest();
- DoNonMaxSuppressionOp(context, boxes, scores, max_output_size,
- iou_threshold_, score_threshold_val);
+ DoNonMaxSuppressionOp(context, scores, num_boxes, max_output_size,
+ score_threshold_val, suppress_check_fn);
}
private:
@@ -207,9 +250,19 @@ class NonMaxSuppressionV2Op : public OpKernel {
iou_threshold.shape().DebugString()));
const float iou_threshold_val = iou_threshold.scalar()();
+ OP_REQUIRES(context, iou_threshold_val >= 0 && iou_threshold_val <= 1,
+ errors::InvalidArgument("iou_threshold must be in [0, 1]"));
+ int num_boxes = 0;
+ ParseAndCheckBoxSizes(context , boxes, &num_boxes);
+ CheckScoreSizes(context, num_boxes, scores);
+ if (!context->status().ok()) {
+ return;
+ }
+ auto suppress_check_fn = CreateIOUSuppressCheckFn(boxes, iou_threshold_val);
+
const float score_threshold_val = std::numeric_limits::lowest();
- DoNonMaxSuppressionOp(context, boxes, scores, max_output_size,
- iou_threshold_val, score_threshold_val);
+ DoNonMaxSuppressionOp(context, scores, num_boxes, max_output_size,
+ score_threshold_val, suppress_check_fn);
}
};
@@ -245,11 +298,66 @@ class NonMaxSuppressionV3Op : public OpKernel {
score_threshold.shape().DebugString()));
const float score_threshold_val = score_threshold.scalar()();
- DoNonMaxSuppressionOp(context, boxes, scores, max_output_size,
- iou_threshold_val, score_threshold_val);
+ OP_REQUIRES(context, iou_threshold_val >= 0 && iou_threshold_val <= 1,
+ errors::InvalidArgument("iou_threshold must be in [0, 1]"));
+ int num_boxes = 0;
+ ParseAndCheckBoxSizes(context , boxes, &num_boxes);
+ CheckScoreSizes(context, num_boxes, scores);
+ if (!context->status().ok()) {
+ return;
+ }
+ auto suppress_check_fn = CreateIOUSuppressCheckFn(boxes, iou_threshold_val);
+
+ DoNonMaxSuppressionOp(context, scores, num_boxes, max_output_size,
+ score_threshold_val, suppress_check_fn);
}
};
+template
+class NonMaxSuppressionWithOverlapsOp : public OpKernel {
+ public:
+ explicit NonMaxSuppressionWithOverlapsOp(OpKernelConstruction* context)
+ : OpKernel(context) {}
+
+ void Compute(OpKernelContext* context) override {
+ // overlaps: [num_boxes, num_boxes]
+ const Tensor& overlaps = context->input(0);
+ // scores: [num_boxes]
+ const Tensor& scores = context->input(1);
+ // max_output_size: scalar
+ const Tensor& max_output_size = context->input(2);
+ OP_REQUIRES(
+ context, TensorShapeUtils::IsScalar(max_output_size.shape()),
+ errors::InvalidArgument("max_output_size must be 0-D, got shape ",
+ max_output_size.shape().DebugString()));
+ // overlap_threshold: scalar
+ const Tensor& overlap_threshold = context->input(3);
+ OP_REQUIRES(context, TensorShapeUtils::IsScalar(overlap_threshold.shape()),
+ errors::InvalidArgument("overlap_threshold must be 0-D, got shape ",
+ overlap_threshold.shape().DebugString()));
+ const float overlap_threshold_val = overlap_threshold.scalar()();
+
+ // score_threshold: scalar
+ const Tensor& score_threshold = context->input(4);
+ OP_REQUIRES(
+ context, TensorShapeUtils::IsScalar(score_threshold.shape()),
+ errors::InvalidArgument("score_threshold must be 0-D, got shape ",
+ score_threshold.shape().DebugString()));
+ const float score_threshold_val = score_threshold.scalar()();
+
+ int num_boxes = 0;
+ ParseAndCheckOverlapSizes(context, overlaps, &num_boxes);
+ CheckScoreSizes(context, num_boxes, scores);
+ if (!context->status().ok()) {
+ return;
+ }
+ auto suppress_check_fn = CreateOverlapsSuppressCheckFn(overlaps, overlap_threshold_val);
+
+ DoNonMaxSuppressionOp(context, scores, num_boxes, max_output_size,
+ score_threshold_val, suppress_check_fn);
+ }
+};
+
REGISTER_KERNEL_BUILDER(Name("NonMaxSuppression").Device(DEVICE_CPU),
NonMaxSuppressionOp);
@@ -259,4 +367,7 @@ REGISTER_KERNEL_BUILDER(Name("NonMaxSuppressionV2").Device(DEVICE_CPU),
REGISTER_KERNEL_BUILDER(Name("NonMaxSuppressionV3").Device(DEVICE_CPU),
NonMaxSuppressionV3Op);
+REGISTER_KERNEL_BUILDER(Name("NonMaxSuppressionWithOverlaps").Device(DEVICE_CPU),
+ NonMaxSuppressionWithOverlapsOp);
+
} // namespace tensorflow
diff --git a/tensorflow/core/kernels/non_max_suppression_op_test.cc b/tensorflow/core/kernels/non_max_suppression_op_test.cc
index ed7db313bd..19003be1fa 100644
--- a/tensorflow/core/kernels/non_max_suppression_op_test.cc
+++ b/tensorflow/core/kernels/non_max_suppression_op_test.cc
@@ -569,4 +569,233 @@ TEST_F(NonMaxSuppressionV3OpTest, TestEmptyInput) {
test::ExpectTensorEqual(expected, *GetOutput(0));
}
+//
+// NonMaxSuppressionWithOverlapsOp Tests
+//
+
+class NonMaxSuppressionWithOverlapsOpTest : public OpsTestBase {
+ protected:
+ void MakeOp() {
+ TF_EXPECT_OK(NodeDefBuilder("non_max_suppression_op", "NonMaxSuppressionWithOverlaps")
+ .Input(FakeInput(DT_FLOAT))
+ .Input(FakeInput(DT_FLOAT))
+ .Input(FakeInput(DT_INT32))
+ .Input(FakeInput(DT_FLOAT))
+ .Input(FakeInput(DT_FLOAT))
+ .Finalize(node_def()));
+ TF_EXPECT_OK(InitOp());
+ }
+
+ void AddIoUInput(const std::vector& boxes) {
+ ASSERT_TRUE((boxes.size() % 4) == 0);
+ size_t num_boxes = boxes.size() / 4;
+ std::vector iou_overlaps(num_boxes*num_boxes);
+
+ // compute the pairwise IoU overlaps
+ auto corner_access = [&boxes](size_t box_idx, size_t corner_idx) { return boxes[box_idx * 4 + corner_idx]; };
+ for (size_t i = 0; i < num_boxes; ++i) {
+ for (size_t j = 0; j < num_boxes; ++j) {
+ const float ymin_i = std::min(corner_access(i, 0), corner_access(i, 2));
+ const float xmin_i = std::min(corner_access(i, 1), corner_access(i, 3));
+ const float ymax_i = std::max(corner_access(i, 0), corner_access(i, 2));
+ const float xmax_i = std::max(corner_access(i, 1), corner_access(i, 3));
+ const float ymin_j = std::min(corner_access(j, 0), corner_access(j, 2));
+ const float xmin_j = std::min(corner_access(j, 1), corner_access(j, 3));
+ const float ymax_j = std::max(corner_access(j, 0), corner_access(j, 2));
+ const float xmax_j = std::max(corner_access(j, 1), corner_access(j, 3));
+ const float area_i = (ymax_i - ymin_i) * (xmax_i - xmin_i);
+ const float area_j = (ymax_j - ymin_j) * (xmax_j - xmin_j);
+
+ float iou;
+ if (area_i <= 0 || area_j <= 0) {
+ iou = 0.0;
+ } else {
+ const float intersection_ymin = std::max(ymin_i, ymin_j);
+ const float intersection_xmin = std::max(xmin_i, xmin_j);
+ const float intersection_ymax = std::min(ymax_i, ymax_j);
+ const float intersection_xmax = std::min(xmax_i, xmax_j);
+ const float intersection_area =
+ std::max(intersection_ymax - intersection_ymin, 0.0) *
+ std::max(intersection_xmax - intersection_xmin, 0.0);
+ iou = intersection_area / (area_i + area_j - intersection_area);
+ }
+ iou_overlaps[i * num_boxes + j] = iou;
+ }
+ }
+
+ AddInputFromArray(TensorShape({static_cast(num_boxes), static_cast(num_boxes)}), iou_overlaps);
+ }
+};
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestSelectFromThreeClusters) {
+ MakeOp();
+ AddIoUInput(
+ {0, 0, 1, 1, 0, 0.1f, 1, 1.1f, 0, -0.1f, 1, 0.9f,
+ 0, 10, 1, 11, 0, 10.1f, 1, 11.1f, 0, 100, 1, 101});
+ AddInputFromArray(TensorShape({6}), {.9f, .75f, .6f, .95f, .5f, .3f});
+ AddInputFromArray(TensorShape({}), {3});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({3}));
+ test::FillValues(&expected, {3, 0, 5});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest,
+ TestSelectFromThreeClustersFlippedCoordinates) {
+ MakeOp();
+ AddIoUInput(
+ {1, 1, 0, 0, 0, 0.1f, 1, 1.1f, 0, .9f, 1, -0.1f,
+ 0, 10, 1, 11, 1, 10.1f, 0, 11.1f, 1, 101, 0, 100});
+ AddInputFromArray(TensorShape({6}), {.9f, .75f, .6f, .95f, .5f, .3f});
+ AddInputFromArray(TensorShape({}), {3});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({3}));
+ test::FillValues(&expected, {3, 0, 5});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestSelectAtMostTwoBoxesFromThreeClusters) {
+ MakeOp();
+ AddIoUInput(
+ {0, 0, 1, 1, 0, 0.1f, 1, 1.1f, 0, -0.1f, 1, 0.9f,
+ 0, 10, 1, 11, 0, 10.1f, 1, 11.1f, 0, 100, 1, 101});
+ AddInputFromArray(TensorShape({6}), {.9f, .75f, .6f, .95f, .5f, .3f});
+ AddInputFromArray(TensorShape({}), {2});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({2}));
+ test::FillValues(&expected, {3, 0});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest,
+ TestSelectAtMostThirtyBoxesFromThreeClusters) {
+ MakeOp();
+ AddIoUInput(
+ {0, 0, 1, 1, 0, 0.1f, 1, 1.1f, 0, -0.1f, 1, 0.9f,
+ 0, 10, 1, 11, 0, 10.1f, 1, 11.1f, 0, 100, 1, 101});
+ AddInputFromArray(TensorShape({6}), {.9f, .75f, .6f, .95f, .5f, .3f});
+ AddInputFromArray(TensorShape({}), {30});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({3}));
+ test::FillValues(&expected, {3, 0, 5});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestSelectSingleBox) {
+ MakeOp();
+ AddIoUInput({0, 0, 1, 1});
+ AddInputFromArray(TensorShape({1}), {.9f});
+ AddInputFromArray(TensorShape({}), {3});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({1}));
+ test::FillValues(&expected, {0});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestSelectFromTenIdenticalBoxes) {
+ MakeOp();
+
+ int num_boxes = 10;
+ std::vector corners(num_boxes * 4);
+ std::vector scores(num_boxes);
+ for (int i = 0; i < num_boxes; ++i) {
+ corners[i * 4 + 0] = 0;
+ corners[i * 4 + 1] = 0;
+ corners[i * 4 + 2] = 1;
+ corners[i * 4 + 3] = 1;
+ scores[i] = .9;
+ }
+ AddIoUInput(corners);
+ AddInputFromArray(TensorShape({num_boxes}), scores);
+ AddInputFromArray(TensorShape({}), {3});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({1}));
+ test::FillValues(&expected, {0});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestInconsistentBoxAndScoreShapes) {
+ MakeOp();
+ AddIoUInput(
+ {0, 0, 1, 1, 0, 0.1f, 1, 1.1f, 0, -0.1f, 1, 0.9f,
+ 0, 10, 1, 11, 0, 10.1f, 1, 11.1f, 0, 100, 1, 101});
+ AddInputFromArray(TensorShape({5}), {.9f, .75f, .6f, .95f, .5f});
+ AddInputFromArray(TensorShape({}), {30});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ Status s = RunOpKernel();
+
+ ASSERT_FALSE(s.ok());
+ EXPECT_TRUE(
+ str_util::StrContains(s.ToString(), "scores has incompatible shape"))
+ << s;
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestInvalidOverlapsShape) {
+ MakeOp();
+ AddInputFromArray(TensorShape({2, 3}), {0, 0, 0, 0, 0, 0});
+ AddInputFromArray(TensorShape({2}), {0.5f, 0.5f});
+ AddInputFromArray(TensorShape({}), {30});
+ AddInputFromArray(TensorShape({}), {0.f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ Status s = RunOpKernel();
+
+ ASSERT_FALSE(s.ok());
+ EXPECT_TRUE(
+ str_util::StrContains(s.ToString(), "overlaps must be square"))
+ << s;
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestThresholdGreaterOne) {
+ MakeOp();
+ AddIoUInput({0, 0, 1, 1});
+ AddInputFromArray(TensorShape({1}), {.9f});
+ AddInputFromArray(TensorShape({}), {3});
+ AddInputFromArray(TensorShape({}), {1.2f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestThresholdSmallerZero) {
+ MakeOp();
+ AddIoUInput({0, 0, 1, 1});
+ AddInputFromArray(TensorShape({1}), {.9f});
+ AddInputFromArray(TensorShape({}), {3});
+ AddInputFromArray(TensorShape({}), {-0.2f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+}
+
+TEST_F(NonMaxSuppressionWithOverlapsOpTest, TestEmptyInput) {
+ MakeOp();
+ AddIoUInput({});
+ AddInputFromArray(TensorShape({0}), {});
+ AddInputFromArray(TensorShape({}), {30});
+ AddInputFromArray(TensorShape({}), {.5f});
+ AddInputFromArray(TensorShape({}), {0.0f});
+ TF_ASSERT_OK(RunOpKernel());
+
+ Tensor expected(allocator(), DT_INT32, TensorShape({0}));
+ test::FillValues(&expected, {});
+ test::ExpectTensorEqual(expected, *GetOutput(0));
+}
+
} // namespace tensorflow
diff --git a/tensorflow/core/ops/image_ops.cc b/tensorflow/core/ops/image_ops.cc
index 87f4991134..50ced1ff73 100644
--- a/tensorflow/core/ops/image_ops.cc
+++ b/tensorflow/core/ops/image_ops.cc
@@ -709,4 +709,36 @@ REGISTER_OP("NonMaxSuppressionV3")
return Status::OK();
});
+REGISTER_OP("NonMaxSuppressionWithOverlaps")
+ .Input("overlaps: float")
+ .Input("scores: float")
+ .Input("max_output_size: int32")
+ .Input("overlap_threshold: float")
+ .Input("score_threshold: float")
+ .Output("selected_indices: int32")
+ .SetShapeFn([](InferenceContext* c) {
+ // Get inputs and validate ranks.
+ ShapeHandle overlaps;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &overlaps));
+ ShapeHandle scores;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &scores));
+ ShapeHandle max_output_size;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 0, &max_output_size));
+ ShapeHandle overlap_threshold;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &overlap_threshold));
+ ShapeHandle score_threshold;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 0, &score_threshold));
+ // The boxes is a 2-D float Tensor of shape [num_boxes, 4].
+ DimensionHandle unused;
+ // The boxes[0] and scores[0] are both num_boxes.
+ TF_RETURN_IF_ERROR(
+ c->Merge(c->Dim(overlaps, 0), c->Dim(scores, 0), &unused));
+ // The boxes[1] is 4.
+ TF_RETURN_IF_ERROR(
+ c->Merge(c->Dim(overlaps, 0), c->Dim(overlaps, 1), &unused));
+
+ c->set_output(0, c->Vector(c->UnknownDim()));
+ return Status::OK();
+ });
+
} // namespace tensorflow
diff --git a/tensorflow/python/ops/image_ops_impl.py b/tensorflow/python/ops/image_ops_impl.py
index 2c7751f792..3170e3098a 100644
--- a/tensorflow/python/ops/image_ops_impl.py
+++ b/tensorflow/python/ops/image_ops_impl.py
@@ -55,6 +55,7 @@ ops.NotDifferentiable('SampleDistortedBoundingBoxV2')
ops.NotDifferentiable('ExtractGlimpse')
ops.NotDifferentiable('NonMaxSuppression')
ops.NotDifferentiable('NonMaxSuppressionV2')
+ops.NotDifferentiable('NonMaxSuppressionWithOverlaps')
def _assert(cond, ex_type, msg):
@@ -2090,6 +2091,47 @@ def non_max_suppression(boxes,
return gen_image_ops.non_max_suppression_v3(boxes, scores, max_output_size,
iou_threshold, score_threshold)
+@tf_export('image.non_max_suppression_overlaps')
+def non_max_suppression_with_overlaps(overlaps,
+ scores,
+ max_output_size,
+ overlap_threshold=0.5,
+ score_threshold=float('-inf'),
+ name=None):
+ """Greedily selects a subset of bounding boxes in descending order of score.
+
+ Prunes away boxes that have high overlap with previously selected boxes.
+ N-by-n overlap values are supplied as square matrix.
+ The output of this operation is a set of integers indexing into the input
+ collection of bounding boxes representing the selected boxes. The bounding
+ box coordinates corresponding to the selected indices can then be obtained
+ using the `tf.gather operation`. For example:
+ selected_indices = tf.image.non_max_suppression_overlaps(
+ overlaps, scores, max_output_size, iou_threshold)
+ selected_boxes = tf.gather(boxes, selected_indices)
+
+ Args:
+ overlaps: A 2-D float `Tensor` of shape `[num_boxes, num_boxes]`.
+ scores: A 1-D float `Tensor` of shape `[num_boxes]` representing a single
+ score corresponding to each box (each row of boxes).
+ max_output_size: A scalar integer `Tensor` representing the maximum number
+ of boxes to be selected by non max suppression.
+ overlap_threshold: A float representing the threshold for deciding whether boxes
+ overlap too much with respect to the provided overlap values.
+ score_threshold: A float representing the threshold for deciding when to
+ remove boxes based on score.
+ name: A name for the operation (optional).
+
+ Returns:
+ selected_indices: A 1-D integer `Tensor` of shape `[M]` representing the
+ selected indices from the overlaps tensor, where `M <= max_output_size`.
+ """
+ with ops.name_scope(name, 'non_max_suppression_overlaps'):
+ overlap_threshold = ops.convert_to_tensor(overlap_threshold, name='overlap_threshold')
+ # pylint: disable=protected-access
+ return gen_image_ops._non_max_suppression_v3(overlaps, scores, max_output_size,
+ overlap_threshold, score_threshold)
+ # pylint: enable=protected-access
_rgb_to_yiq_kernel = [[0.299, 0.59590059,
0.2115], [0.587, -0.27455667, -0.52273617],
--
GitLab
From fdbb80f217d3a153b4eda66c766df921b3f73ab4 Mon Sep 17 00:00:00 2001
From: Michael Case
Date: Wed, 20 Jun 2018 14:08:57 -0700
Subject: [PATCH 0038/1193] Move external/ directory in pip package.
Moving external/ directory in the pip packages (which is currently
installed directly into site-packages directory). Moving the
directory to tensorflow/include/external/. Also, removing all
python files from external (since it should really only contain
headers and license files.)
---
.../tools/pip_package/build_pip_package.sh | 21 ++++++++++++-------
1 file changed, 13 insertions(+), 8 deletions(-)
diff --git a/tensorflow/tools/pip_package/build_pip_package.sh b/tensorflow/tools/pip_package/build_pip_package.sh
index f7e42ce536..9e41514cfa 100755
--- a/tensorflow/tools/pip_package/build_pip_package.sh
+++ b/tensorflow/tools/pip_package/build_pip_package.sh
@@ -24,9 +24,15 @@ function real_path() {
function cp_external() {
local src_dir=$1
local dest_dir=$2
- for f in `find "$src_dir" -maxdepth 1 -mindepth 1 ! -name '*local_config_cuda*' ! -name '*local_config_tensorrt*' ! -name '*org_tensorflow*'`; do
- cp -R "$f" "$dest_dir"
+
+ pushd .
+ cd "$src_dir"
+ for f in `find . ! -type d ! -name '*.py' ! -name '*local_config_cuda*' ! -name '*local_config_tensorrt*' ! -name '*org_tensorflow*'`; do
+ mkdir -p "${dest_dir}/$(dirname ${f})"
+ cp "${f}" "${dest_dir}/$(dirname ${f})/"
done
+ popd
+
mkdir -p "${dest_dir}/local_config_cuda/cuda/cuda/"
cp "${src_dir}/local_config_cuda/cuda/cuda/cuda_config.h" "${dest_dir}/local_config_cuda/cuda/cuda/"
}
@@ -49,6 +55,8 @@ function prepare_src() {
TMPDIR="$1"
mkdir -p "$TMPDIR"
+ EXTERNAL_INCLUDES="${TMPDIR}/tensorflow/include/external"
+
echo $(date) : "=== Preparing sources in dir: ${TMPDIR}"
if [ ! -d bazel-bin/tensorflow ]; then
@@ -66,10 +74,9 @@ function prepare_src() {
cp -R \
bazel-bin/tensorflow/tools/pip_package/simple_console_for_window_unzip/runfiles/org_tensorflow/tensorflow \
"${TMPDIR}"
- mkdir "${TMPDIR}/external"
cp_external \
bazel-bin/tensorflow/tools/pip_package/simple_console_for_window_unzip/runfiles \
- "${TMPDIR}/external"
+ "${EXTERNAL_INCLUDES}/"
RUNFILES=bazel-bin/tensorflow/tools/pip_package/simple_console_for_window_unzip/runfiles/org_tensorflow
else
RUNFILES=bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/org_tensorflow
@@ -78,10 +85,9 @@ function prepare_src() {
cp -R \
bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/org_tensorflow/tensorflow \
"${TMPDIR}"
- mkdir "${TMPDIR}/external"
cp_external \
bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/org_tensorflow/external \
- "${TMPDIR}/external"
+ "${EXTERNAL_INCLUDES}"
# Copy MKL libs over so they can be loaded at runtime
so_lib_dir=$(ls $RUNFILES | grep solib) || true
if [ -n "${so_lib_dir}" ]; then
@@ -96,10 +102,9 @@ function prepare_src() {
cp -R \
bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/org_tensorflow/tensorflow \
"${TMPDIR}"
- mkdir "${TMPDIR}/external"
cp_external \
bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles \
- "${TMPDIR}/external"
+ "${EXTERNAL_INCLUDES}"
# Copy MKL libs over so they can be loaded at runtime
so_lib_dir=$(ls $RUNFILES | grep solib) || true
if [ -n "${so_lib_dir}" ]; then
--
GitLab
From 1adbc5aa6927d1a5d7151c31aea1da6e73a1b53c Mon Sep 17 00:00:00 2001
From: Allen Lavoie
Date: Thu, 31 May 2018 19:03:21 -0700
Subject: [PATCH 0039/1193] Add a single positional argument mode for shape
inference in subclassed Models.
Allows fit() when call's signature looks something like call(x, training=True).
Calling conventions are "inputs", single positional, and multiple positional. Right now the distinction between "inputs" and single positional calling conventions is the text of one error message. Both support shape inference (which just hasn't been implemented for multiple positional input arguments yet).
PiperOrigin-RevId: 198815483
---
tensorflow/python/keras/engine/base_layer.py | 45 ++++++++++++++---
tensorflow/python/keras/engine/network.py | 50 ++++++++++++++++---
tensorflow/python/keras/engine/training.py | 27 ++++++----
.../python/keras/model_subclassing_test.py | 4 +-
4 files changed, 98 insertions(+), 28 deletions(-)
diff --git a/tensorflow/python/keras/engine/base_layer.py b/tensorflow/python/keras/engine/base_layer.py
index 24716cfbe4..4814275fd5 100644
--- a/tensorflow/python/keras/engine/base_layer.py
+++ b/tensorflow/python/keras/engine/base_layer.py
@@ -19,6 +19,7 @@ from __future__ import division
from __future__ import print_function
import collections
+import enum # pylint: disable=g-bad-import-order
import inspect # Necessary supplement to tf_inspect to deal with variadic args.
import numpy as np
@@ -50,6 +51,20 @@ from tensorflow.python.util import tf_inspect
from tensorflow.python.util.tf_export import tf_export
+class CallConvention(enum.Enum):
+ """Calling conventions for passing `Layer` inputs to `Layer.call`."""
+ # The Layer takes inputs as its first argument, named "inputs" for
+ # compatibility with the signature of Layer.__call__. This is the mode assumed
+ # for Layers which are not subclassed Models.
+ EXPLICIT_INPUTS_ARGUMENT = 1
+ # The Layer takes a single positional argument, not named "inputs". It's
+ # treated like an "inputs" argument.
+ SINGLE_POSITIONAL_ARGUMENT = 2
+ # The Layer has multiple positional arguments to which its inputs should be
+ # bound.
+ POSITIONAL_ARGUMENTS_ARE_INPUTS = 3
+
+
@tf_export('keras.layers.Layer')
class Layer(checkpointable.CheckpointableBase):
"""Base layer class.
@@ -149,7 +164,7 @@ class Layer(checkpointable.CheckpointableBase):
self._call_fn_args = function_utils.fn_args(self.call)
self._compute_previous_mask = ('mask' in self._call_fn_args or
hasattr(self, 'compute_mask'))
- self._uses_inputs_arg = True
+ self._call_convention = CallConvention.EXPLICIT_INPUTS_ARGUMENT
# These lists will be filled via successive calls
# to self._add_inbound_node().
@@ -793,12 +808,22 @@ class Layer(checkpointable.CheckpointableBase):
pass # C type such as dict. Masking not supported in this case.
def _set_connectivity_metadata_(self, inputs, outputs, args, kwargs):
- if args and getattr(self, '_uses_inputs_arg', True):
- raise TypeError(
- 'This Layer takes an `inputs` argument to call(), and only the '
- '`inputs` argument may be specified as a positional argument. '
- 'Pass everything else as a keyword argument (those arguments will'
- ' not be tracked as inputs to the Layer).')
+ call_convention = getattr(self, '_call_convention',
+ CallConvention.EXPLICIT_INPUTS_ARGUMENT)
+ if args:
+ if call_convention == CallConvention.EXPLICIT_INPUTS_ARGUMENT:
+ raise TypeError(
+ 'This Layer takes an `inputs` argument to call(), and only the '
+ '`inputs` argument may be specified as a positional argument. '
+ 'Pass everything else as a keyword argument (those arguments will'
+ ' not be tracked as inputs to the Layer).')
+ elif call_convention == CallConvention.SINGLE_POSITIONAL_ARGUMENT:
+ raise TypeError(
+ 'This Layer takes a single positional argument to call(), which is '
+ 'by convention the inputs argument, and only this argument may be '
+ 'specified as a positional argument. Pass everything else as a '
+ 'keyword argument (those arguments will not be tracked as inputs '
+ 'to the Layer).')
# If the layer returns tensors from its inputs, unmodified,
# we copy them to avoid loss of tensor metadata.
@@ -834,7 +859,11 @@ class Layer(checkpointable.CheckpointableBase):
A tuple of (inputs, non_input_kwargs). These may be the same objects as
were passed in (call_args and call_kwargs).
"""
- if getattr(self, '_uses_inputs_arg', True):
+ call_convention = getattr(self, '_call_convention',
+ CallConvention.EXPLICIT_INPUTS_ARGUMENT)
+ if (call_convention in (
+ CallConvention.EXPLICIT_INPUTS_ARGUMENT,
+ CallConvention.SINGLE_POSITIONAL_ARGUMENT)):
assert len(call_args) == 1 # TypeError raised earlier in __call__.
return call_args[0], call_kwargs
else:
diff --git a/tensorflow/python/keras/engine/network.py b/tensorflow/python/keras/engine/network.py
index 3d567b8378..6f27eea1e7 100644
--- a/tensorflow/python/keras/engine/network.py
+++ b/tensorflow/python/keras/engine/network.py
@@ -135,7 +135,7 @@ class Network(base_layer.Layer):
self._in_progress_restore_finalizer = None
def _init_graph_network(self, inputs, outputs, name=None):
- self._uses_inputs_arg = True
+ self._call_convention = base_layer.CallConvention.EXPLICIT_INPUTS_ARGUMENT
# Normalize and set self.inputs, self.outputs.
if isinstance(inputs, (list, tuple)):
self.inputs = list(inputs) # Tensor or list of tensors.
@@ -295,19 +295,55 @@ class Network(base_layer.Layer):
def _init_subclassed_network(self, name=None):
self._base_init(name=name)
self._is_graph_network = False
- call_args = tf_inspect.getargspec(self.call).args
- if 'training' in call_args:
+ call_argspec = tf_inspect.getargspec(self.call)
+ if 'training' in call_argspec.args:
self._expects_training_arg = True
else:
self._expects_training_arg = False
- if 'inputs' in call_args:
- self._uses_inputs_arg = True
- else:
- self._uses_inputs_arg = False
+ self._call_convention = self._determine_call_convention(call_argspec)
self.outputs = None
self.inputs = None
self.built = False
+ def _determine_call_convention(self, call_argspec):
+ """Decides how `self.call()` is invoked. See base_layer.CallConvention."""
+ if call_argspec.varargs:
+ may_take_single_argument = False
+ else:
+ try:
+ # Note: tf_inspect doesn't raise a TypeError when regular inspect would,
+ # so we need to keep in mind that "getcallargs" may have returned
+ # something even though we under-specified positional arguments.
+ all_args = tf_inspect.getcallargs(self.call, None)
+ self_args = set()
+ for arg_name, obj in all_args.items():
+ if obj is self:
+ self_args.add(arg_name)
+ may_take_single_argument = True
+ except TypeError:
+ may_take_single_argument = False
+ if may_take_single_argument:
+ # A single positional argument (plus "self") is considered equivalent to
+ # an "inputs" argument.
+ all_positional_args = len(call_argspec.args)
+ if call_argspec.defaults is not None:
+ all_positional_args -= len(call_argspec.defaults)
+ non_self_positional_args = all_positional_args
+ for positional_arg_name in call_argspec.args[:all_positional_args]:
+ if positional_arg_name in self_args:
+ non_self_positional_args -= 1
+ if non_self_positional_args == 1:
+ if 'inputs' in call_argspec.args[all_positional_args:]:
+ raise TypeError(
+ "Model.call() takes a single positional argument (to which "
+ "inputs are passed by convention) and a separate 'inputs' "
+ "argument. Unable to determine which arguments are inputs.")
+ return base_layer.CallConvention.SINGLE_POSITIONAL_ARGUMENT
+ if 'inputs' in call_argspec.args:
+ return base_layer.CallConvention.EXPLICIT_INPUTS_ARGUMENT
+ else:
+ return base_layer.CallConvention.POSITIONAL_ARGUMENTS_ARE_INPUTS
+
def _track_layers(self, layers):
"""Add Checkpointable dependencies on a list of Layers."""
weight_layer_index = 0
diff --git a/tensorflow/python/keras/engine/training.py b/tensorflow/python/keras/engine/training.py
index 6d625f16c2..04a2aa7664 100644
--- a/tensorflow/python/keras/engine/training.py
+++ b/tensorflow/python/keras/engine/training.py
@@ -31,12 +31,11 @@ from tensorflow.python.keras import backend as K
from tensorflow.python.keras import losses
from tensorflow.python.keras import metrics as metrics_module
from tensorflow.python.keras import optimizers
+from tensorflow.python.keras.engine import base_layer
from tensorflow.python.keras.engine import training_arrays
from tensorflow.python.keras.engine import training_eager
from tensorflow.python.keras.engine import training_generator
from tensorflow.python.keras.engine import training_utils
-from tensorflow.python.keras.engine.base_layer import DeferredTensor
-from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.keras.engine.network import Network
from tensorflow.python.keras.utils.generic_utils import slice_arrays
from tensorflow.python.ops import array_ops
@@ -523,7 +522,7 @@ class Model(Network):
# Keep track of state updates created by
# stateful metrics (i.e. metrics layers).
- if isinstance(metric_fn, Layer) and metric_fn.stateful:
+ if isinstance(metric_fn, base_layer.Layer) and metric_fn.stateful:
self.stateful_metric_names.append(metric_name)
self.stateful_metric_functions.append(metric_fn)
self.metrics_updates += metric_fn.updates
@@ -959,11 +958,17 @@ class Model(Network):
whether to build the model's graph in inference mode (False), training
mode (True), or using the Keras learning phase (None).
"""
- if not getattr(self, '_uses_inputs_arg', True):
+ call_convention = getattr(
+ self,
+ '_call_convention',
+ base_layer.CallConvention.EXPLICIT_INPUTS_ARGUMENT)
+ if call_convention not in (
+ base_layer.CallConvention.EXPLICIT_INPUTS_ARGUMENT,
+ base_layer.CallConvention.SINGLE_POSITIONAL_ARGUMENT):
raise NotImplementedError(
- 'Subclassed Models without "inputs" in their call() signatures do '
- 'not yet support shape inference. File a feature request if this '
- 'limitation bothers you.')
+ 'Subclassed Models without "inputs" (or single positional arguments) '
+ 'in their call() signatures do not yet support shape inference. File '
+ 'a feature request if this limitation bothers you.')
if self.__class__.__name__ == 'Sequential':
# Note: we can't test whether the model is `Sequential` via `isinstance`
# since `Sequential` depends on `Model`.
@@ -1020,11 +1025,11 @@ class Model(Network):
else:
dummy_output_values = [dummy_output_values]
self.outputs = [
- DeferredTensor(shape=(None for _ in v.shape),
- dtype=v.dtype) for v in dummy_output_values]
+ base_layer.DeferredTensor(shape=(None for _ in v.shape),
+ dtype=v.dtype) for v in dummy_output_values]
self.inputs = [
- DeferredTensor(shape=(None for _ in v.shape),
- dtype=v.dtype) for v in dummy_input_values]
+ base_layer.DeferredTensor(shape=(None for _ in v.shape),
+ dtype=v.dtype) for v in dummy_input_values]
self.input_names = [
'input_%d' % (i + 1) for i in range(len(dummy_input_values))]
self.output_names = [
diff --git a/tensorflow/python/keras/model_subclassing_test.py b/tensorflow/python/keras/model_subclassing_test.py
index 86f7e20bec..8fb957da43 100644
--- a/tensorflow/python/keras/model_subclassing_test.py
+++ b/tensorflow/python/keras/model_subclassing_test.py
@@ -56,8 +56,8 @@ class SimpleTestModel(keras.Model):
if self.use_bn:
self.bn = keras.layers.BatchNormalization(axis=-1)
- def call(self, inputs):
- x = self.dense1(inputs)
+ def call(self, x):
+ x = self.dense1(x)
if self.use_dp:
x = self.dp(x)
if self.use_bn:
--
GitLab
From 6fb75293ec2cb5cd8d815cf98ec33aa953442b34 Mon Sep 17 00:00:00 2001
From: Derek Murray
Date: Wed, 20 Jun 2018 10:10:55 -0700
Subject: [PATCH 0040/1193] [tf.data] Properly export
`tf.contrib.data.choose_from_datasets()`
PiperOrigin-RevId: 201371642
---
tensorflow/contrib/data/__init__.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/tensorflow/contrib/data/__init__.py b/tensorflow/contrib/data/__init__.py
index 1af1ed08b5..9c6a13333e 100644
--- a/tensorflow/contrib/data/__init__.py
+++ b/tensorflow/contrib/data/__init__.py
@@ -72,6 +72,7 @@ from tensorflow.contrib.data.python.ops.error_ops import ignore_errors
from tensorflow.contrib.data.python.ops.get_single_element import get_single_element
from tensorflow.contrib.data.python.ops.grouping import bucket_by_sequence_length
from tensorflow.contrib.data.python.ops.grouping import group_by_window
+from tensorflow.contrib.data.python.ops.interleave_ops import choose_from_datasets
from tensorflow.contrib.data.python.ops.interleave_ops import parallel_interleave
from tensorflow.contrib.data.python.ops.interleave_ops import sample_from_datasets
from tensorflow.contrib.data.python.ops.interleave_ops import sloppy_interleave
--
GitLab
From 7413a353c62b96472a430878b5dc3d0d48244e67 Mon Sep 17 00:00:00 2001
From: Christian Ertler
Date: Fri, 22 Jun 2018 08:58:56 +0200
Subject: [PATCH 0041/1193] pylint errors in non_max_suppression_with_overlaps
---
tensorflow/python/ops/image_ops_impl.py | 13 ++++++++-----
1 file changed, 8 insertions(+), 5 deletions(-)
diff --git a/tensorflow/python/ops/image_ops_impl.py b/tensorflow/python/ops/image_ops_impl.py
index 3170e3098a..fcb2b49a50 100644
--- a/tensorflow/python/ops/image_ops_impl.py
+++ b/tensorflow/python/ops/image_ops_impl.py
@@ -2116,8 +2116,8 @@ def non_max_suppression_with_overlaps(overlaps,
score corresponding to each box (each row of boxes).
max_output_size: A scalar integer `Tensor` representing the maximum number
of boxes to be selected by non max suppression.
- overlap_threshold: A float representing the threshold for deciding whether boxes
- overlap too much with respect to the provided overlap values.
+ overlap_threshold: A float representing the threshold for deciding whether
+ boxes overlap too much with respect to the provided overlap values.
score_threshold: A float representing the threshold for deciding when to
remove boxes based on score.
name: A name for the operation (optional).
@@ -2127,10 +2127,13 @@ def non_max_suppression_with_overlaps(overlaps,
selected indices from the overlaps tensor, where `M <= max_output_size`.
"""
with ops.name_scope(name, 'non_max_suppression_overlaps'):
- overlap_threshold = ops.convert_to_tensor(overlap_threshold, name='overlap_threshold')
+ overlap_threshold = ops.convert_to_tensor(overlap_threshold,
+ name='overlap_threshold')
# pylint: disable=protected-access
- return gen_image_ops._non_max_suppression_v3(overlaps, scores, max_output_size,
- overlap_threshold, score_threshold)
+ return gen_image_ops._non_max_suppression_v3(overlaps,
+ scores, max_output_size,
+ overlap_threshold,
+ score_threshold)
# pylint: enable=protected-access
_rgb_to_yiq_kernel = [[0.299, 0.59590059,
--
GitLab
From 579b598862b14b7a8e242cb1b094221f7e08b499 Mon Sep 17 00:00:00 2001
From: Yu Yi
Date: Fri, 22 Jun 2018 11:46:33 -0400
Subject: [PATCH 0042/1193] update the py/py3 toolchain config
- the python3 are installed in /opt/python3.6 in the base toolchain
container:
https://console.cloud.google.com/launcher/details/google/rbe-ubuntu16-04
---
third_party/toolchains/cpus/py/BUILD | 242 ++++++++++++--------------
third_party/toolchains/cpus/py3/BUILD | 234 +++++++++++++------------
2 files changed, 231 insertions(+), 245 deletions(-)
diff --git a/third_party/toolchains/cpus/py/BUILD b/third_party/toolchains/cpus/py/BUILD
index c175742cbf..10184e215b 100644
--- a/third_party/toolchains/cpus/py/BUILD
+++ b/third_party/toolchains/cpus/py/BUILD
@@ -6,20 +6,26 @@ licenses(["restricted"])
package(default_visibility = ["//visibility:public"])
+# To build Python C/C++ extension on Windows, we need to link to python import library pythonXY.lib
+# See https://docs.python.org/3/extending/windows.html
+cc_import(
+ name = "python_lib",
+ interface_library = select({
+ ":windows": ":python_import_lib",
+ # A placeholder for Unix platforms which makes --no_build happy.
+ "//conditions:default": "not-existing.lib",
+ }),
+ system_provided = 1,
+)
+
cc_library(
name = "python_headers",
hdrs = [":python_include"],
- data = select({
- ":windows": [":python_import_lib"],
+ deps = select({
+ ":windows": [":python_lib"],
"//conditions:default": [],
}),
includes = ["python_include"],
- linkopts = select({
- # TODO(pcloudy): Ideally, this should just go into deps after resolving
- # https://github.com/bazelbuild/bazel/issues/3237,
- ":windows": ["$(locations :python_import_lib)"],
- "//conditions:default": [],
- }),
)
cc_library(
@@ -37,161 +43,135 @@ config_setting(
genrule(
name = "python_include",
outs = [
+ "python_include/Python-ast.h",
+ "python_include/Python.h",
+ "python_include/abstract.h",
+ "python_include/asdl.h",
+ "python_include/ast.h",
+ "python_include/bitset.h",
+ "python_include/boolobject.h",
+ "python_include/bufferobject.h",
+ "python_include/bytearrayobject.h",
+ "python_include/bytes_methods.h",
+ "python_include/bytesobject.h",
+ "python_include/cStringIO.h",
+ "python_include/cellobject.h",
+ "python_include/ceval.h",
+ "python_include/classobject.h",
+ "python_include/cobject.h",
"python_include/code.h",
+ "python_include/codecs.h",
+ "python_include/compile.h",
+ "python_include/complexobject.h",
+ "python_include/datetime.h",
+ "python_include/descrobject.h",
+ "python_include/dictobject.h",
"python_include/dtoa.h",
- "python_include/tupleobject.h",
- "python_include/object.h",
- "python_include/ast.h",
- "python_include/pymacconfig.h",
+ "python_include/enumobject.h",
"python_include/errcode.h",
+ "python_include/eval.h",
+ "python_include/fileobject.h",
+ "python_include/floatobject.h",
"python_include/frameobject.h",
- "python_include/pgenheaders.h",
- "python_include/cellobject.h",
+ "python_include/funcobject.h",
+ "python_include/genobject.h",
+ "python_include/graminit.h",
+ "python_include/grammar.h",
+ "python_include/import.h",
"python_include/intobject.h",
- "python_include/pythread.h",
- "python_include/cStringIO.h",
- "python_include/boolobject.h",
+ "python_include/intrcheck.h",
+ "python_include/iterobject.h",
+ "python_include/listobject.h",
+ "python_include/longintrepr.h",
+ "python_include/longobject.h",
+ "python_include/marshal.h",
+ "python_include/memoryobject.h",
+ "python_include/metagrammar.h",
+ "python_include/methodobject.h",
"python_include/modsupport.h",
- "python_include/import.h",
- "python_include/pymath.h",
+ "python_include/moduleobject.h",
"python_include/node.h",
- "python_include/funcobject.h",
- "python_include/eval.h",
- "python_include/longintrepr.h",
- "python_include/floatobject.h",
- "python_include/rangeobject.h",
- "python_include/pyfpe.h",
- "python_include/pystrcmp.h",
- "python_include/dictobject.h",
- "python_include/pyarena.h",
+ "python_include/object.h",
"python_include/objimpl.h",
- "python_include/bitset.h",
- "python_include/memoryobject.h",
- "python_include/bytearrayobject.h",
+ "python_include/opcode.h",
+ "python_include/osdefs.h",
+ "python_include/parsetok.h",
+ "python_include/patchlevel.h",
+ "python_include/pgen.h",
+ "python_include/pgenheaders.h",
+ "python_include/py_curses.h",
+ "python_include/pyarena.h",
+ "python_include/pycapsule.h",
+ "python_include/pyconfig.h",
+ "python_include/pyctype.h",
"python_include/pydebug.h",
"python_include/pyerrors.h",
- "python_include/weakrefobject.h",
- "python_include/grammar.h",
- "python_include/symtable.h",
- "python_include/longobject.h",
- "python_include/structmember.h",
- "python_include/enumobject.h",
- "python_include/classobject.h",
- "python_include/unicodeobject.h",
- "python_include/sliceobject.h",
- "python_include/pystrtod.h",
- "python_include/genobject.h",
- "python_include/pymactoolbox.h",
- "python_include/compile.h",
"python_include/pyexpat.h",
- "python_include/asdl.h",
- "python_include/codecs.h",
- "python_include/pyctype.h",
- "python_include/sysmodule.h",
- "python_include/methodobject.h",
- "python_include/graminit.h",
- "python_include/cobject.h",
- "python_include/intrcheck.h",
- "python_include/pyport.h",
- "python_include/warnings.h",
- "python_include/osdefs.h",
- "python_include/fileobject.h",
- "python_include/stringobject.h",
- "python_include/timefuncs.h",
- "python_include/traceback.h",
- "python_include/ceval.h",
- "python_include/bytes_methods.h",
- "python_include/pyconfig.h",
- "python_include/Python.h",
- "python_include/moduleobject.h",
- "python_include/pystate.h",
- "python_include/descrobject.h",
- "python_include/ucnhash.h",
+ "python_include/pyfpe.h",
"python_include/pygetopt.h",
+ "python_include/pymacconfig.h",
+ "python_include/pymactoolbox.h",
+ "python_include/pymath.h",
"python_include/pymem.h",
- "python_include/complexobject.h",
- "python_include/structseq.h",
- "python_include/datetime.h",
+ "python_include/pyport.h",
+ "python_include/pystate.h",
+ "python_include/pystrcmp.h",
+ "python_include/pystrtod.h",
"python_include/pythonrun.h",
- "python_include/numpy/oldnumeric.h",
- "python_include/numpy/npy_1_7_deprecated_api.h",
- "python_include/numpy/ufunc_api.txt",
- "python_include/numpy/multiarray_api.txt",
- "python_include/numpy/halffloat.h",
- "python_include/numpy/npy_common.h",
- "python_include/numpy/utils.h",
- "python_include/numpy/npy_interrupt.h",
- "python_include/numpy/npy_endian.h",
- "python_include/numpy/__ufunc_api.h",
- "python_include/numpy/_neighborhood_iterator_imp.h",
- "python_include/numpy/ufuncobject.h",
- "python_include/numpy/ndarraytypes.h",
- "python_include/numpy/npy_math.h",
- "python_include/numpy/noprefix.h",
- "python_include/numpy/npy_3kcompat.h",
- "python_include/numpy/arrayscalars.h",
- "python_include/numpy/npy_os.h",
- "python_include/numpy/ndarrayobject.h",
- "python_include/numpy/npy_no_deprecated_api.h",
- "python_include/numpy/arrayobject.h",
- "python_include/numpy/_numpyconfig.h",
- "python_include/numpy/__multiarray_api.h",
- "python_include/numpy/npy_cpu.h",
- "python_include/numpy/old_defines.h",
- "python_include/numpy/numpyconfig.h",
- "python_include/pycapsule.h",
+ "python_include/pythread.h",
+ "python_include/rangeobject.h",
"python_include/setobject.h",
- "python_include/listobject.h",
- "python_include/bytesobject.h",
- "python_include/pgen.h",
- "python_include/patchlevel.h",
- "python_include/opcode.h",
- "python_include/parsetok.h",
- "python_include/marshal.h",
+ "python_include/sliceobject.h",
+ "python_include/stringobject.h",
+ "python_include/structmember.h",
+ "python_include/structseq.h",
+ "python_include/symtable.h",
+ "python_include/sysmodule.h",
+ "python_include/timefuncs.h",
"python_include/token.h",
- "python_include/iterobject.h",
- "python_include/abstract.h",
- "python_include/py_curses.h",
- "python_include/metagrammar.h",
- "python_include/bufferobject.h",
- "python_include/Python-ast.h",
+ "python_include/traceback.h",
+ "python_include/tupleobject.h",
+ "python_include/ucnhash.h",
+ "python_include/unicodeobject.h",
+ "python_include/warnings.h",
+ "python_include/weakrefobject.h",
],
cmd = """
-cp "/usr/include/python2.7/code.h" "$(@D)/python_include/code.h" && cp "/usr/include/python2.7/dtoa.h" "$(@D)/python_include/dtoa.h" && cp "/usr/include/python2.7/tupleobject.h" "$(@D)/python_include/tupleobject.h" && cp "/usr/include/python2.7/object.h" "$(@D)/python_include/object.h" && cp "/usr/include/python2.7/ast.h" "$(@D)/python_include/ast.h" && cp "/usr/include/python2.7/pymacconfig.h" "$(@D)/python_include/pymacconfig.h" && cp "/usr/include/python2.7/errcode.h" "$(@D)/python_include/errcode.h" && cp "/usr/include/python2.7/frameobject.h" "$(@D)/python_include/frameobject.h" && cp "/usr/include/python2.7/pgenheaders.h" "$(@D)/python_include/pgenheaders.h" && cp "/usr/include/python2.7/cellobject.h" "$(@D)/python_include/cellobject.h" && cp "/usr/include/python2.7/intobject.h" "$(@D)/python_include/intobject.h" && cp "/usr/include/python2.7/pythread.h" "$(@D)/python_include/pythread.h" && cp "/usr/include/python2.7/cStringIO.h" "$(@D)/python_include/cStringIO.h" && cp "/usr/include/python2.7/boolobject.h" "$(@D)/python_include/boolobject.h" && cp "/usr/include/python2.7/modsupport.h" "$(@D)/python_include/modsupport.h" && cp "/usr/include/python2.7/import.h" "$(@D)/python_include/import.h" && cp "/usr/include/python2.7/pymath.h" "$(@D)/python_include/pymath.h" && cp "/usr/include/python2.7/node.h" "$(@D)/python_include/node.h" && cp "/usr/include/python2.7/funcobject.h" "$(@D)/python_include/funcobject.h" && cp "/usr/include/python2.7/eval.h" "$(@D)/python_include/eval.h" && cp "/usr/include/python2.7/longintrepr.h" "$(@D)/python_include/longintrepr.h" && cp "/usr/include/python2.7/floatobject.h" "$(@D)/python_include/floatobject.h" && cp "/usr/include/python2.7/rangeobject.h" "$(@D)/python_include/rangeobject.h" && cp "/usr/include/python2.7/pyfpe.h" "$(@D)/python_include/pyfpe.h" && cp "/usr/include/python2.7/pystrcmp.h" "$(@D)/python_include/pystrcmp.h" && cp "/usr/include/python2.7/dictobject.h" "$(@D)/python_include/dictobject.h" && cp "/usr/include/python2.7/pyarena.h" "$(@D)/python_include/pyarena.h" && cp "/usr/include/python2.7/objimpl.h" "$(@D)/python_include/objimpl.h" && cp "/usr/include/python2.7/bitset.h" "$(@D)/python_include/bitset.h" && cp "/usr/include/python2.7/memoryobject.h" "$(@D)/python_include/memoryobject.h" && cp "/usr/include/python2.7/bytearrayobject.h" "$(@D)/python_include/bytearrayobject.h" && cp "/usr/include/python2.7/pydebug.h" "$(@D)/python_include/pydebug.h" && cp "/usr/include/python2.7/pyerrors.h" "$(@D)/python_include/pyerrors.h" && cp "/usr/include/python2.7/weakrefobject.h" "$(@D)/python_include/weakrefobject.h" && cp "/usr/include/python2.7/grammar.h" "$(@D)/python_include/grammar.h" && cp "/usr/include/python2.7/symtable.h" "$(@D)/python_include/symtable.h" && cp "/usr/include/python2.7/longobject.h" "$(@D)/python_include/longobject.h" && cp "/usr/include/python2.7/structmember.h" "$(@D)/python_include/structmember.h" && cp "/usr/include/python2.7/enumobject.h" "$(@D)/python_include/enumobject.h" && cp "/usr/include/python2.7/classobject.h" "$(@D)/python_include/classobject.h" && cp "/usr/include/python2.7/unicodeobject.h" "$(@D)/python_include/unicodeobject.h" && cp "/usr/include/python2.7/sliceobject.h" "$(@D)/python_include/sliceobject.h" && cp "/usr/include/python2.7/pystrtod.h" "$(@D)/python_include/pystrtod.h" && cp "/usr/include/python2.7/genobject.h" "$(@D)/python_include/genobject.h" && cp "/usr/include/python2.7/pymactoolbox.h" "$(@D)/python_include/pymactoolbox.h" && cp "/usr/include/python2.7/compile.h" "$(@D)/python_include/compile.h" && cp "/usr/include/python2.7/pyexpat.h" "$(@D)/python_include/pyexpat.h" && cp "/usr/include/python2.7/asdl.h" "$(@D)/python_include/asdl.h" && cp "/usr/include/python2.7/codecs.h" "$(@D)/python_include/codecs.h" && cp "/usr/include/python2.7/pyctype.h" "$(@D)/python_include/pyctype.h" && cp "/usr/include/python2.7/sysmodule.h" "$(@D)/python_include/sysmodule.h" && cp "/usr/include/python2.7/methodobject.h" "$(@D)/python_include/methodobject.h" && cp "/usr/include/python2.7/graminit.h" "$(@D)/python_include/graminit.h" && cp "/usr/include/python2.7/cobject.h" "$(@D)/python_include/cobject.h" && cp "/usr/include/python2.7/intrcheck.h" "$(@D)/python_include/intrcheck.h" && cp "/usr/include/python2.7/pyport.h" "$(@D)/python_include/pyport.h" && cp "/usr/include/python2.7/warnings.h" "$(@D)/python_include/warnings.h" && cp "/usr/include/python2.7/osdefs.h" "$(@D)/python_include/osdefs.h" && cp "/usr/include/python2.7/fileobject.h" "$(@D)/python_include/fileobject.h" && cp "/usr/include/python2.7/stringobject.h" "$(@D)/python_include/stringobject.h" && cp "/usr/include/python2.7/timefuncs.h" "$(@D)/python_include/timefuncs.h" && cp "/usr/include/python2.7/traceback.h" "$(@D)/python_include/traceback.h" && cp "/usr/include/python2.7/ceval.h" "$(@D)/python_include/ceval.h" && cp "/usr/include/python2.7/bytes_methods.h" "$(@D)/python_include/bytes_methods.h" && cp "/usr/include/python2.7/pyconfig.h" "$(@D)/python_include/pyconfig.h" && cp "/usr/include/python2.7/Python.h" "$(@D)/python_include/Python.h" && cp "/usr/include/python2.7/moduleobject.h" "$(@D)/python_include/moduleobject.h" && cp "/usr/include/python2.7/pystate.h" "$(@D)/python_include/pystate.h" && cp "/usr/include/python2.7/descrobject.h" "$(@D)/python_include/descrobject.h" && cp "/usr/include/python2.7/ucnhash.h" "$(@D)/python_include/ucnhash.h" && cp "/usr/include/python2.7/pygetopt.h" "$(@D)/python_include/pygetopt.h" && cp "/usr/include/python2.7/pymem.h" "$(@D)/python_include/pymem.h" && cp "/usr/include/python2.7/complexobject.h" "$(@D)/python_include/complexobject.h" && cp "/usr/include/python2.7/structseq.h" "$(@D)/python_include/structseq.h" && cp "/usr/include/python2.7/datetime.h" "$(@D)/python_include/datetime.h" && cp "/usr/include/python2.7/pythonrun.h" "$(@D)/python_include/pythonrun.h" && cp "/usr/include/python2.7/numpy/oldnumeric.h" "$(@D)/python_include/numpy/oldnumeric.h" && cp "/usr/include/python2.7/numpy/npy_1_7_deprecated_api.h" "$(@D)/python_include/numpy/npy_1_7_deprecated_api.h" && cp "/usr/include/python2.7/numpy/ufunc_api.txt" "$(@D)/python_include/numpy/ufunc_api.txt" && cp "/usr/include/python2.7/numpy/multiarray_api.txt" "$(@D)/python_include/numpy/multiarray_api.txt" && cp "/usr/include/python2.7/numpy/halffloat.h" "$(@D)/python_include/numpy/halffloat.h" && cp "/usr/include/python2.7/numpy/npy_common.h" "$(@D)/python_include/numpy/npy_common.h" && cp "/usr/include/python2.7/numpy/utils.h" "$(@D)/python_include/numpy/utils.h" && cp "/usr/include/python2.7/numpy/npy_interrupt.h" "$(@D)/python_include/numpy/npy_interrupt.h" && cp "/usr/include/python2.7/numpy/npy_endian.h" "$(@D)/python_include/numpy/npy_endian.h" && cp "/usr/include/python2.7/numpy/__ufunc_api.h" "$(@D)/python_include/numpy/__ufunc_api.h" && cp "/usr/include/python2.7/numpy/_neighborhood_iterator_imp.h" "$(@D)/python_include/numpy/_neighborhood_iterator_imp.h" && cp "/usr/include/python2.7/numpy/ufuncobject.h" "$(@D)/python_include/numpy/ufuncobject.h" && cp "/usr/include/python2.7/numpy/ndarraytypes.h" "$(@D)/python_include/numpy/ndarraytypes.h" && cp "/usr/include/python2.7/numpy/npy_math.h" "$(@D)/python_include/numpy/npy_math.h" && cp "/usr/include/python2.7/numpy/noprefix.h" "$(@D)/python_include/numpy/noprefix.h" && cp "/usr/include/python2.7/numpy/npy_3kcompat.h" "$(@D)/python_include/numpy/npy_3kcompat.h" && cp "/usr/include/python2.7/numpy/arrayscalars.h" "$(@D)/python_include/numpy/arrayscalars.h" && cp "/usr/include/python2.7/numpy/npy_os.h" "$(@D)/python_include/numpy/npy_os.h" && cp "/usr/include/python2.7/numpy/ndarrayobject.h" "$(@D)/python_include/numpy/ndarrayobject.h" && cp "/usr/include/python2.7/numpy/npy_no_deprecated_api.h" "$(@D)/python_include/numpy/npy_no_deprecated_api.h" && cp "/usr/include/python2.7/numpy/arrayobject.h" "$(@D)/python_include/numpy/arrayobject.h" && cp "/usr/include/python2.7/numpy/_numpyconfig.h" "$(@D)/python_include/numpy/_numpyconfig.h" && cp "/usr/include/python2.7/numpy/__multiarray_api.h" "$(@D)/python_include/numpy/__multiarray_api.h" && cp "/usr/include/python2.7/numpy/npy_cpu.h" "$(@D)/python_include/numpy/npy_cpu.h" && cp "/usr/include/python2.7/numpy/old_defines.h" "$(@D)/python_include/numpy/old_defines.h" && cp "/usr/include/python2.7/numpy/numpyconfig.h" "$(@D)/python_include/numpy/numpyconfig.h" && cp "/usr/include/python2.7/pycapsule.h" "$(@D)/python_include/pycapsule.h" && cp "/usr/include/python2.7/setobject.h" "$(@D)/python_include/setobject.h" && cp "/usr/include/python2.7/listobject.h" "$(@D)/python_include/listobject.h" && cp "/usr/include/python2.7/bytesobject.h" "$(@D)/python_include/bytesobject.h" && cp "/usr/include/python2.7/pgen.h" "$(@D)/python_include/pgen.h" && cp "/usr/include/python2.7/patchlevel.h" "$(@D)/python_include/patchlevel.h" && cp "/usr/include/python2.7/opcode.h" "$(@D)/python_include/opcode.h" && cp "/usr/include/python2.7/parsetok.h" "$(@D)/python_include/parsetok.h" && cp "/usr/include/python2.7/marshal.h" "$(@D)/python_include/marshal.h" && cp "/usr/include/python2.7/token.h" "$(@D)/python_include/token.h" && cp "/usr/include/python2.7/iterobject.h" "$(@D)/python_include/iterobject.h" && cp "/usr/include/python2.7/abstract.h" "$(@D)/python_include/abstract.h" && cp "/usr/include/python2.7/py_curses.h" "$(@D)/python_include/py_curses.h" && cp "/usr/include/python2.7/metagrammar.h" "$(@D)/python_include/metagrammar.h" && cp "/usr/include/python2.7/bufferobject.h" "$(@D)/python_include/bufferobject.h" && cp "/usr/include/python2.7/Python-ast.h" "$(@D)/python_include/Python-ast.h"
+cp "/usr/include/python2.7/Python-ast.h" "$(@D)/python_include/Python-ast.h" && cp "/usr/include/python2.7/Python.h" "$(@D)/python_include/Python.h" && cp "/usr/include/python2.7/abstract.h" "$(@D)/python_include/abstract.h" && cp "/usr/include/python2.7/asdl.h" "$(@D)/python_include/asdl.h" && cp "/usr/include/python2.7/ast.h" "$(@D)/python_include/ast.h" && cp "/usr/include/python2.7/bitset.h" "$(@D)/python_include/bitset.h" && cp "/usr/include/python2.7/boolobject.h" "$(@D)/python_include/boolobject.h" && cp "/usr/include/python2.7/bufferobject.h" "$(@D)/python_include/bufferobject.h" && cp "/usr/include/python2.7/bytearrayobject.h" "$(@D)/python_include/bytearrayobject.h" && cp "/usr/include/python2.7/bytes_methods.h" "$(@D)/python_include/bytes_methods.h" && cp "/usr/include/python2.7/bytesobject.h" "$(@D)/python_include/bytesobject.h" && cp "/usr/include/python2.7/cStringIO.h" "$(@D)/python_include/cStringIO.h" && cp "/usr/include/python2.7/cellobject.h" "$(@D)/python_include/cellobject.h" && cp "/usr/include/python2.7/ceval.h" "$(@D)/python_include/ceval.h" && cp "/usr/include/python2.7/classobject.h" "$(@D)/python_include/classobject.h" && cp "/usr/include/python2.7/cobject.h" "$(@D)/python_include/cobject.h" && cp "/usr/include/python2.7/code.h" "$(@D)/python_include/code.h" && cp "/usr/include/python2.7/codecs.h" "$(@D)/python_include/codecs.h" && cp "/usr/include/python2.7/compile.h" "$(@D)/python_include/compile.h" && cp "/usr/include/python2.7/complexobject.h" "$(@D)/python_include/complexobject.h" && cp "/usr/include/python2.7/datetime.h" "$(@D)/python_include/datetime.h" && cp "/usr/include/python2.7/descrobject.h" "$(@D)/python_include/descrobject.h" && cp "/usr/include/python2.7/dictobject.h" "$(@D)/python_include/dictobject.h" && cp "/usr/include/python2.7/dtoa.h" "$(@D)/python_include/dtoa.h" && cp "/usr/include/python2.7/enumobject.h" "$(@D)/python_include/enumobject.h" && cp "/usr/include/python2.7/errcode.h" "$(@D)/python_include/errcode.h" && cp "/usr/include/python2.7/eval.h" "$(@D)/python_include/eval.h" && cp "/usr/include/python2.7/fileobject.h" "$(@D)/python_include/fileobject.h" && cp "/usr/include/python2.7/floatobject.h" "$(@D)/python_include/floatobject.h" && cp "/usr/include/python2.7/frameobject.h" "$(@D)/python_include/frameobject.h" && cp "/usr/include/python2.7/funcobject.h" "$(@D)/python_include/funcobject.h" && cp "/usr/include/python2.7/genobject.h" "$(@D)/python_include/genobject.h" && cp "/usr/include/python2.7/graminit.h" "$(@D)/python_include/graminit.h" && cp "/usr/include/python2.7/grammar.h" "$(@D)/python_include/grammar.h" && cp "/usr/include/python2.7/import.h" "$(@D)/python_include/import.h" && cp "/usr/include/python2.7/intobject.h" "$(@D)/python_include/intobject.h" && cp "/usr/include/python2.7/intrcheck.h" "$(@D)/python_include/intrcheck.h" && cp "/usr/include/python2.7/iterobject.h" "$(@D)/python_include/iterobject.h" && cp "/usr/include/python2.7/listobject.h" "$(@D)/python_include/listobject.h" && cp "/usr/include/python2.7/longintrepr.h" "$(@D)/python_include/longintrepr.h" && cp "/usr/include/python2.7/longobject.h" "$(@D)/python_include/longobject.h" && cp "/usr/include/python2.7/marshal.h" "$(@D)/python_include/marshal.h" && cp "/usr/include/python2.7/memoryobject.h" "$(@D)/python_include/memoryobject.h" && cp "/usr/include/python2.7/metagrammar.h" "$(@D)/python_include/metagrammar.h" && cp "/usr/include/python2.7/methodobject.h" "$(@D)/python_include/methodobject.h" && cp "/usr/include/python2.7/modsupport.h" "$(@D)/python_include/modsupport.h" && cp "/usr/include/python2.7/moduleobject.h" "$(@D)/python_include/moduleobject.h" && cp "/usr/include/python2.7/node.h" "$(@D)/python_include/node.h" && cp "/usr/include/python2.7/object.h" "$(@D)/python_include/object.h" && cp "/usr/include/python2.7/objimpl.h" "$(@D)/python_include/objimpl.h" && cp "/usr/include/python2.7/opcode.h" "$(@D)/python_include/opcode.h" && cp "/usr/include/python2.7/osdefs.h" "$(@D)/python_include/osdefs.h" && cp "/usr/include/python2.7/parsetok.h" "$(@D)/python_include/parsetok.h" && cp "/usr/include/python2.7/patchlevel.h" "$(@D)/python_include/patchlevel.h" && cp "/usr/include/python2.7/pgen.h" "$(@D)/python_include/pgen.h" && cp "/usr/include/python2.7/pgenheaders.h" "$(@D)/python_include/pgenheaders.h" && cp "/usr/include/python2.7/py_curses.h" "$(@D)/python_include/py_curses.h" && cp "/usr/include/python2.7/pyarena.h" "$(@D)/python_include/pyarena.h" && cp "/usr/include/python2.7/pycapsule.h" "$(@D)/python_include/pycapsule.h" && cp "/usr/include/python2.7/pyconfig.h" "$(@D)/python_include/pyconfig.h" && cp "/usr/include/python2.7/pyctype.h" "$(@D)/python_include/pyctype.h" && cp "/usr/include/python2.7/pydebug.h" "$(@D)/python_include/pydebug.h" && cp "/usr/include/python2.7/pyerrors.h" "$(@D)/python_include/pyerrors.h" && cp "/usr/include/python2.7/pyexpat.h" "$(@D)/python_include/pyexpat.h" && cp "/usr/include/python2.7/pyfpe.h" "$(@D)/python_include/pyfpe.h" && cp "/usr/include/python2.7/pygetopt.h" "$(@D)/python_include/pygetopt.h" && cp "/usr/include/python2.7/pymacconfig.h" "$(@D)/python_include/pymacconfig.h" && cp "/usr/include/python2.7/pymactoolbox.h" "$(@D)/python_include/pymactoolbox.h" && cp "/usr/include/python2.7/pymath.h" "$(@D)/python_include/pymath.h" && cp "/usr/include/python2.7/pymem.h" "$(@D)/python_include/pymem.h" && cp "/usr/include/python2.7/pyport.h" "$(@D)/python_include/pyport.h" && cp "/usr/include/python2.7/pystate.h" "$(@D)/python_include/pystate.h" && cp "/usr/include/python2.7/pystrcmp.h" "$(@D)/python_include/pystrcmp.h" && cp "/usr/include/python2.7/pystrtod.h" "$(@D)/python_include/pystrtod.h" && cp "/usr/include/python2.7/pythonrun.h" "$(@D)/python_include/pythonrun.h" && cp "/usr/include/python2.7/pythread.h" "$(@D)/python_include/pythread.h" && cp "/usr/include/python2.7/rangeobject.h" "$(@D)/python_include/rangeobject.h" && cp "/usr/include/python2.7/setobject.h" "$(@D)/python_include/setobject.h" && cp "/usr/include/python2.7/sliceobject.h" "$(@D)/python_include/sliceobject.h" && cp "/usr/include/python2.7/stringobject.h" "$(@D)/python_include/stringobject.h" && cp "/usr/include/python2.7/structmember.h" "$(@D)/python_include/structmember.h" && cp "/usr/include/python2.7/structseq.h" "$(@D)/python_include/structseq.h" && cp "/usr/include/python2.7/symtable.h" "$(@D)/python_include/symtable.h" && cp "/usr/include/python2.7/sysmodule.h" "$(@D)/python_include/sysmodule.h" && cp "/usr/include/python2.7/timefuncs.h" "$(@D)/python_include/timefuncs.h" && cp "/usr/include/python2.7/token.h" "$(@D)/python_include/token.h" && cp "/usr/include/python2.7/traceback.h" "$(@D)/python_include/traceback.h" && cp "/usr/include/python2.7/tupleobject.h" "$(@D)/python_include/tupleobject.h" && cp "/usr/include/python2.7/ucnhash.h" "$(@D)/python_include/ucnhash.h" && cp "/usr/include/python2.7/unicodeobject.h" "$(@D)/python_include/unicodeobject.h" && cp "/usr/include/python2.7/warnings.h" "$(@D)/python_include/warnings.h" && cp "/usr/include/python2.7/weakrefobject.h" "$(@D)/python_include/weakrefobject.h"
""",
)
genrule(
name = "numpy_include",
outs = [
- "numpy_include/numpy/oldnumeric.h",
- "numpy_include/numpy/npy_1_7_deprecated_api.h",
- "numpy_include/numpy/ufunc_api.txt",
- "numpy_include/numpy/multiarray_api.txt",
- "numpy_include/numpy/halffloat.h",
- "numpy_include/numpy/npy_common.h",
- "numpy_include/numpy/utils.h",
- "numpy_include/numpy/npy_interrupt.h",
- "numpy_include/numpy/npy_endian.h",
+ "numpy_include/numpy/__multiarray_api.h",
"numpy_include/numpy/__ufunc_api.h",
"numpy_include/numpy/_neighborhood_iterator_imp.h",
- "numpy_include/numpy/ufuncobject.h",
+ "numpy_include/numpy/_numpyconfig.h",
+ "numpy_include/numpy/arrayobject.h",
+ "numpy_include/numpy/arrayscalars.h",
+ "numpy_include/numpy/halffloat.h",
+ "numpy_include/numpy/multiarray_api.txt",
+ "numpy_include/numpy/ndarrayobject.h",
"numpy_include/numpy/ndarraytypes.h",
- "numpy_include/numpy/npy_math.h",
"numpy_include/numpy/noprefix.h",
+ "numpy_include/numpy/npy_1_7_deprecated_api.h",
"numpy_include/numpy/npy_3kcompat.h",
- "numpy_include/numpy/arrayscalars.h",
- "numpy_include/numpy/npy_os.h",
- "numpy_include/numpy/ndarrayobject.h",
- "numpy_include/numpy/npy_no_deprecated_api.h",
- "numpy_include/numpy/arrayobject.h",
- "numpy_include/numpy/_numpyconfig.h",
- "numpy_include/numpy/__multiarray_api.h",
+ "numpy_include/numpy/npy_common.h",
"numpy_include/numpy/npy_cpu.h",
- "numpy_include/numpy/old_defines.h",
+ "numpy_include/numpy/npy_endian.h",
+ "numpy_include/numpy/npy_interrupt.h",
+ "numpy_include/numpy/npy_math.h",
+ "numpy_include/numpy/npy_no_deprecated_api.h",
+ "numpy_include/numpy/npy_os.h",
"numpy_include/numpy/numpyconfig.h",
+ "numpy_include/numpy/old_defines.h",
+ "numpy_include/numpy/oldnumeric.h",
+ "numpy_include/numpy/ufunc_api.txt",
+ "numpy_include/numpy/ufuncobject.h",
+ "numpy_include/numpy/utils.h",
],
cmd = """
-cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/oldnumeric.h" "$(@D)/numpy_include/numpy/oldnumeric.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_1_7_deprecated_api.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ufunc_api.txt" "$(@D)/numpy_include/numpy/ufunc_api.txt" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/multiarray_api.txt" "$(@D)/numpy_include/numpy/multiarray_api.txt" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/halffloat.h" "$(@D)/numpy_include/numpy/halffloat.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_common.h" "$(@D)/numpy_include/numpy/npy_common.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/utils.h" "$(@D)/numpy_include/numpy/utils.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_interrupt.h" "$(@D)/numpy_include/numpy/npy_interrupt.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_endian.h" "$(@D)/numpy_include/numpy/npy_endian.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/__ufunc_api.h" "$(@D)/numpy_include/numpy/__ufunc_api.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/_neighborhood_iterator_imp.h" "$(@D)/numpy_include/numpy/_neighborhood_iterator_imp.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ufuncobject.h" "$(@D)/numpy_include/numpy/ufuncobject.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h" "$(@D)/numpy_include/numpy/ndarraytypes.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_math.h" "$(@D)/numpy_include/numpy/npy_math.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/noprefix.h" "$(@D)/numpy_include/numpy/noprefix.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_3kcompat.h" "$(@D)/numpy_include/numpy/npy_3kcompat.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayscalars.h" "$(@D)/numpy_include/numpy/arrayscalars.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_os.h" "$(@D)/numpy_include/numpy/npy_os.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h" "$(@D)/numpy_include/numpy/ndarrayobject.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_no_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_no_deprecated_api.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h" "$(@D)/numpy_include/numpy/arrayobject.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/_numpyconfig.h" "$(@D)/numpy_include/numpy/_numpyconfig.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/__multiarray_api.h" "$(@D)/numpy_include/numpy/__multiarray_api.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_cpu.h" "$(@D)/numpy_include/numpy/npy_cpu.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/old_defines.h" "$(@D)/numpy_include/numpy/old_defines.h" && cp "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/numpyconfig.h" "$(@D)/numpy_include/numpy/numpyconfig.h"
+cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/__multiarray_api.h" "$(@D)/numpy_include/numpy/__multiarray_api.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/__ufunc_api.h" "$(@D)/numpy_include/numpy/__ufunc_api.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/_neighborhood_iterator_imp.h" "$(@D)/numpy_include/numpy/_neighborhood_iterator_imp.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/_numpyconfig.h" "$(@D)/numpy_include/numpy/_numpyconfig.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h" "$(@D)/numpy_include/numpy/arrayobject.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayscalars.h" "$(@D)/numpy_include/numpy/arrayscalars.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/halffloat.h" "$(@D)/numpy_include/numpy/halffloat.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/multiarray_api.txt" "$(@D)/numpy_include/numpy/multiarray_api.txt" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h" "$(@D)/numpy_include/numpy/ndarrayobject.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h" "$(@D)/numpy_include/numpy/ndarraytypes.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/noprefix.h" "$(@D)/numpy_include/numpy/noprefix.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_1_7_deprecated_api.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_3kcompat.h" "$(@D)/numpy_include/numpy/npy_3kcompat.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_common.h" "$(@D)/numpy_include/numpy/npy_common.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_cpu.h" "$(@D)/numpy_include/numpy/npy_cpu.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_endian.h" "$(@D)/numpy_include/numpy/npy_endian.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_interrupt.h" "$(@D)/numpy_include/numpy/npy_interrupt.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_math.h" "$(@D)/numpy_include/numpy/npy_math.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_no_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_no_deprecated_api.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_os.h" "$(@D)/numpy_include/numpy/npy_os.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/numpyconfig.h" "$(@D)/numpy_include/numpy/numpyconfig.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/old_defines.h" "$(@D)/numpy_include/numpy/old_defines.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/oldnumeric.h" "$(@D)/numpy_include/numpy/oldnumeric.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ufunc_api.txt" "$(@D)/numpy_include/numpy/ufunc_api.txt" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ufuncobject.h" "$(@D)/numpy_include/numpy/ufuncobject.h" && cp "/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/utils.h" "$(@D)/numpy_include/numpy/utils.h"
""",
)
diff --git a/third_party/toolchains/cpus/py3/BUILD b/third_party/toolchains/cpus/py3/BUILD
index 932a25239f..28712a7cb1 100644
--- a/third_party/toolchains/cpus/py3/BUILD
+++ b/third_party/toolchains/cpus/py3/BUILD
@@ -6,20 +6,26 @@ licenses(["restricted"])
package(default_visibility = ["//visibility:public"])
+# To build Python C/C++ extension on Windows, we need to link to python import library pythonXY.lib
+# See https://docs.python.org/3/extending/windows.html
+cc_import(
+ name = "python_lib",
+ interface_library = select({
+ ":windows": ":python_import_lib",
+ # A placeholder for Unix platforms which makes --no_build happy.
+ "//conditions:default": "not-existing.lib",
+ }),
+ system_provided = 1,
+)
+
cc_library(
name = "python_headers",
hdrs = [":python_include"],
- data = select({
- ":windows": [":python_import_lib"],
+ deps = select({
+ ":windows": [":python_lib"],
"//conditions:default": [],
}),
includes = ["python_include"],
- linkopts = select({
- # TODO(pcloudy): Ideally, this should just go into deps after resolving
- # https://github.com/bazelbuild/bazel/issues/3237,
- ":windows": ["$(locations :python_import_lib)"],
- "//conditions:default": [],
- }),
)
cc_library(
@@ -37,143 +43,143 @@ config_setting(
genrule(
name = "python_include",
outs = [
- "python_include/code.h",
- "python_include/dtoa.h",
- "python_include/tupleobject.h",
- "python_include/object.h",
- "python_include/ast.h",
- "python_include/pymacconfig.h",
- "python_include/errcode.h",
- "python_include/frameobject.h",
- "python_include/typeslots.h",
- "python_include/pgenheaders.h",
- "python_include/cellobject.h",
- "python_include/pythread.h",
- "python_include/boolobject.h",
+ "python_include/Python-ast.h",
+ "python_include/Python.h",
+ "python_include/abstract.h",
"python_include/accu.h",
- "python_include/modsupport.h",
- "python_include/import.h",
- "python_include/pymath.h",
- "python_include/node.h",
- "python_include/funcobject.h",
- "python_include/eval.h",
- "python_include/pyatomic.h",
- "python_include/longintrepr.h",
- "python_include/floatobject.h",
- "python_include/rangeobject.h",
- "python_include/pyfpe.h",
- "python_include/pystrcmp.h",
- "python_include/fileutils.h",
- "python_include/dictobject.h",
- "python_include/pyarena.h",
- "python_include/osmodule.h",
- "python_include/objimpl.h",
+ "python_include/asdl.h",
+ "python_include/ast.h",
"python_include/bitset.h",
- "python_include/memoryobject.h",
+ "python_include/bltinmodule.h",
+ "python_include/boolobject.h",
"python_include/bytearrayobject.h",
- "python_include/pydebug.h",
- "python_include/pyerrors.h",
- "python_include/weakrefobject.h",
- "python_include/grammar.h",
- "python_include/symtable.h",
- "python_include/longobject.h",
- "python_include/structmember.h",
- "python_include/enumobject.h",
- "python_include/pymacro.h",
+ "python_include/bytes_methods.h",
+ "python_include/bytesobject.h",
+ "python_include/cellobject.h",
+ "python_include/ceval.h",
"python_include/classobject.h",
- "python_include/unicodeobject.h",
- "python_include/sliceobject.h",
- "python_include/pystrtod.h",
- "python_include/genobject.h",
- "python_include/compile.h",
- "python_include/pyexpat.h",
- "python_include/asdl.h",
+ "python_include/code.h",
"python_include/codecs.h",
+ "python_include/compile.h",
+ "python_include/complexobject.h",
+ "python_include/datetime.h",
+ "python_include/descrobject.h",
+ "python_include/dictobject.h",
+ "python_include/dtoa.h",
"python_include/dynamic_annotations.h",
- "python_include/pyctype.h",
- "python_include/sysmodule.h",
- "python_include/methodobject.h",
+ "python_include/enumobject.h",
+ "python_include/errcode.h",
+ "python_include/eval.h",
+ "python_include/fileobject.h",
+ "python_include/fileutils.h",
+ "python_include/floatobject.h",
+ "python_include/frameobject.h",
+ "python_include/funcobject.h",
+ "python_include/genobject.h",
"python_include/graminit.h",
- "python_include/bltinmodule.h",
+ "python_include/grammar.h",
+ "python_include/import.h",
"python_include/intrcheck.h",
- "python_include/pyport.h",
- "python_include/warnings.h",
- "python_include/osdefs.h",
- "python_include/pydtrace.h",
- "python_include/pylifecycle.h",
- "python_include/fileobject.h",
- "python_include/pytime.h",
- "python_include/traceback.h",
- "python_include/ceval.h",
- "python_include/bytes_methods.h",
- "python_include/namespaceobject.h",
- "python_include/pyconfig.h",
- "python_include/Python.h",
+ "python_include/iterobject.h",
+ "python_include/listobject.h",
+ "python_include/longintrepr.h",
+ "python_include/longobject.h",
+ "python_include/marshal.h",
+ "python_include/memoryobject.h",
+ "python_include/metagrammar.h",
+ "python_include/methodobject.h",
+ "python_include/modsupport.h",
"python_include/moduleobject.h",
- "python_include/pystate.h",
- "python_include/descrobject.h",
+ "python_include/namespaceobject.h",
+ "python_include/node.h",
+ "python_include/object.h",
+ "python_include/objimpl.h",
"python_include/odictobject.h",
- "python_include/ucnhash.h",
+ "python_include/opcode.h",
+ "python_include/osdefs.h",
+ "python_include/osmodule.h",
+ "python_include/parsetok.h",
+ "python_include/patchlevel.h",
+ "python_include/pgen.h",
+ "python_include/pgenheaders.h",
+ "python_include/py_curses.h",
+ "python_include/pyarena.h",
+ "python_include/pyatomic.h",
+ "python_include/pycapsule.h",
+ "python_include/pyconfig.h",
+ "python_include/pyctype.h",
+ "python_include/pydebug.h",
+ "python_include/pydtrace.h",
+ "python_include/pyerrors.h",
+ "python_include/pyexpat.h",
+ "python_include/pyfpe.h",
"python_include/pygetopt.h",
+ "python_include/pyhash.h",
+ "python_include/pylifecycle.h",
+ "python_include/pymacconfig.h",
+ "python_include/pymacro.h",
+ "python_include/pymath.h",
"python_include/pymem.h",
- "python_include/complexobject.h",
- "python_include/structseq.h",
- "python_include/datetime.h",
+ "python_include/pyport.h",
+ "python_include/pystate.h",
+ "python_include/pystrcmp.h",
+ "python_include/pystrhex.h",
+ "python_include/pystrtod.h",
"python_include/pythonrun.h",
- "python_include/pyhash.h",
- "python_include/pycapsule.h",
+ "python_include/pythread.h",
+ "python_include/pytime.h",
+ "python_include/rangeobject.h",
"python_include/setobject.h",
- "python_include/listobject.h",
- "python_include/bytesobject.h",
- "python_include/pgen.h",
- "python_include/patchlevel.h",
- "python_include/opcode.h",
- "python_include/parsetok.h",
- "python_include/pystrhex.h",
- "python_include/marshal.h",
+ "python_include/sliceobject.h",
+ "python_include/structmember.h",
+ "python_include/structseq.h",
+ "python_include/symtable.h",
+ "python_include/sysmodule.h",
"python_include/token.h",
- "python_include/iterobject.h",
- "python_include/abstract.h",
- "python_include/py_curses.h",
- "python_include/metagrammar.h",
- "python_include/Python-ast.h",
+ "python_include/traceback.h",
+ "python_include/tupleobject.h",
+ "python_include/typeslots.h",
+ "python_include/ucnhash.h",
+ "python_include/unicodeobject.h",
+ "python_include/warnings.h",
+ "python_include/weakrefobject.h",
],
cmd = """
-cp "/opt/python3.6/include/python3.6m/code.h" "$(@D)/python_include/code.h" && cp "/opt/python3.6/include/python3.6m/dtoa.h" "$(@D)/python_include/dtoa.h" && cp "/opt/python3.6/include/python3.6m/tupleobject.h" "$(@D)/python_include/tupleobject.h" && cp "/opt/python3.6/include/python3.6m/object.h" "$(@D)/python_include/object.h" && cp "/opt/python3.6/include/python3.6m/ast.h" "$(@D)/python_include/ast.h" && cp "/opt/python3.6/include/python3.6m/pymacconfig.h" "$(@D)/python_include/pymacconfig.h" && cp "/opt/python3.6/include/python3.6m/errcode.h" "$(@D)/python_include/errcode.h" && cp "/opt/python3.6/include/python3.6m/frameobject.h" "$(@D)/python_include/frameobject.h" && cp "/opt/python3.6/include/python3.6m/typeslots.h" "$(@D)/python_include/typeslots.h" && cp "/opt/python3.6/include/python3.6m/pgenheaders.h" "$(@D)/python_include/pgenheaders.h" && cp "/opt/python3.6/include/python3.6m/cellobject.h" "$(@D)/python_include/cellobject.h" && cp "/opt/python3.6/include/python3.6m/pythread.h" "$(@D)/python_include/pythread.h" && cp "/opt/python3.6/include/python3.6m/boolobject.h" "$(@D)/python_include/boolobject.h" && cp "/opt/python3.6/include/python3.6m/accu.h" "$(@D)/python_include/accu.h" && cp "/opt/python3.6/include/python3.6m/modsupport.h" "$(@D)/python_include/modsupport.h" && cp "/opt/python3.6/include/python3.6m/import.h" "$(@D)/python_include/import.h" && cp "/opt/python3.6/include/python3.6m/pymath.h" "$(@D)/python_include/pymath.h" && cp "/opt/python3.6/include/python3.6m/node.h" "$(@D)/python_include/node.h" && cp "/opt/python3.6/include/python3.6m/funcobject.h" "$(@D)/python_include/funcobject.h" && cp "/opt/python3.6/include/python3.6m/eval.h" "$(@D)/python_include/eval.h" && cp "/opt/python3.6/include/python3.6m/pyatomic.h" "$(@D)/python_include/pyatomic.h" && cp "/opt/python3.6/include/python3.6m/longintrepr.h" "$(@D)/python_include/longintrepr.h" && cp "/opt/python3.6/include/python3.6m/floatobject.h" "$(@D)/python_include/floatobject.h" && cp "/opt/python3.6/include/python3.6m/rangeobject.h" "$(@D)/python_include/rangeobject.h" && cp "/opt/python3.6/include/python3.6m/pyfpe.h" "$(@D)/python_include/pyfpe.h" && cp "/opt/python3.6/include/python3.6m/pystrcmp.h" "$(@D)/python_include/pystrcmp.h" && cp "/opt/python3.6/include/python3.6m/fileutils.h" "$(@D)/python_include/fileutils.h" && cp "/opt/python3.6/include/python3.6m/dictobject.h" "$(@D)/python_include/dictobject.h" && cp "/opt/python3.6/include/python3.6m/pyarena.h" "$(@D)/python_include/pyarena.h" && cp "/opt/python3.6/include/python3.6m/osmodule.h" "$(@D)/python_include/osmodule.h" && cp "/opt/python3.6/include/python3.6m/objimpl.h" "$(@D)/python_include/objimpl.h" && cp "/opt/python3.6/include/python3.6m/bitset.h" "$(@D)/python_include/bitset.h" && cp "/opt/python3.6/include/python3.6m/memoryobject.h" "$(@D)/python_include/memoryobject.h" && cp "/opt/python3.6/include/python3.6m/bytearrayobject.h" "$(@D)/python_include/bytearrayobject.h" && cp "/opt/python3.6/include/python3.6m/pydebug.h" "$(@D)/python_include/pydebug.h" && cp "/opt/python3.6/include/python3.6m/pyerrors.h" "$(@D)/python_include/pyerrors.h" && cp "/opt/python3.6/include/python3.6m/weakrefobject.h" "$(@D)/python_include/weakrefobject.h" && cp "/opt/python3.6/include/python3.6m/grammar.h" "$(@D)/python_include/grammar.h" && cp "/opt/python3.6/include/python3.6m/symtable.h" "$(@D)/python_include/symtable.h" && cp "/opt/python3.6/include/python3.6m/longobject.h" "$(@D)/python_include/longobject.h" && cp "/opt/python3.6/include/python3.6m/structmember.h" "$(@D)/python_include/structmember.h" && cp "/opt/python3.6/include/python3.6m/enumobject.h" "$(@D)/python_include/enumobject.h" && cp "/opt/python3.6/include/python3.6m/pymacro.h" "$(@D)/python_include/pymacro.h" && cp "/opt/python3.6/include/python3.6m/classobject.h" "$(@D)/python_include/classobject.h" && cp "/opt/python3.6/include/python3.6m/unicodeobject.h" "$(@D)/python_include/unicodeobject.h" && cp "/opt/python3.6/include/python3.6m/sliceobject.h" "$(@D)/python_include/sliceobject.h" && cp "/opt/python3.6/include/python3.6m/pystrtod.h" "$(@D)/python_include/pystrtod.h" && cp "/opt/python3.6/include/python3.6m/genobject.h" "$(@D)/python_include/genobject.h" && cp "/opt/python3.6/include/python3.6m/compile.h" "$(@D)/python_include/compile.h" && cp "/opt/python3.6/include/python3.6m/pyexpat.h" "$(@D)/python_include/pyexpat.h" && cp "/opt/python3.6/include/python3.6m/asdl.h" "$(@D)/python_include/asdl.h" && cp "/opt/python3.6/include/python3.6m/codecs.h" "$(@D)/python_include/codecs.h" && cp "/opt/python3.6/include/python3.6m/dynamic_annotations.h" "$(@D)/python_include/dynamic_annotations.h" && cp "/opt/python3.6/include/python3.6m/pyctype.h" "$(@D)/python_include/pyctype.h" && cp "/opt/python3.6/include/python3.6m/sysmodule.h" "$(@D)/python_include/sysmodule.h" && cp "/opt/python3.6/include/python3.6m/methodobject.h" "$(@D)/python_include/methodobject.h" && cp "/opt/python3.6/include/python3.6m/graminit.h" "$(@D)/python_include/graminit.h" && cp "/opt/python3.6/include/python3.6m/bltinmodule.h" "$(@D)/python_include/bltinmodule.h" && cp "/opt/python3.6/include/python3.6m/intrcheck.h" "$(@D)/python_include/intrcheck.h" && cp "/opt/python3.6/include/python3.6m/pyport.h" "$(@D)/python_include/pyport.h" && cp "/opt/python3.6/include/python3.6m/warnings.h" "$(@D)/python_include/warnings.h" && cp "/opt/python3.6/include/python3.6m/osdefs.h" "$(@D)/python_include/osdefs.h" && cp "/opt/python3.6/include/python3.6m/pydtrace.h" "$(@D)/python_include/pydtrace.h" && cp "/opt/python3.6/include/python3.6m/pylifecycle.h" "$(@D)/python_include/pylifecycle.h" && cp "/opt/python3.6/include/python3.6m/fileobject.h" "$(@D)/python_include/fileobject.h" && cp "/opt/python3.6/include/python3.6m/pytime.h" "$(@D)/python_include/pytime.h" && cp "/opt/python3.6/include/python3.6m/traceback.h" "$(@D)/python_include/traceback.h" && cp "/opt/python3.6/include/python3.6m/ceval.h" "$(@D)/python_include/ceval.h" && cp "/opt/python3.6/include/python3.6m/bytes_methods.h" "$(@D)/python_include/bytes_methods.h" && cp "/opt/python3.6/include/python3.6m/namespaceobject.h" "$(@D)/python_include/namespaceobject.h" && cp "/opt/python3.6/include/python3.6m/pyconfig.h" "$(@D)/python_include/pyconfig.h" && cp "/opt/python3.6/include/python3.6m/Python.h" "$(@D)/python_include/Python.h" && cp "/opt/python3.6/include/python3.6m/moduleobject.h" "$(@D)/python_include/moduleobject.h" && cp "/opt/python3.6/include/python3.6m/pystate.h" "$(@D)/python_include/pystate.h" && cp "/opt/python3.6/include/python3.6m/descrobject.h" "$(@D)/python_include/descrobject.h" && cp "/opt/python3.6/include/python3.6m/odictobject.h" "$(@D)/python_include/odictobject.h" && cp "/opt/python3.6/include/python3.6m/ucnhash.h" "$(@D)/python_include/ucnhash.h" && cp "/opt/python3.6/include/python3.6m/pygetopt.h" "$(@D)/python_include/pygetopt.h" && cp "/opt/python3.6/include/python3.6m/pymem.h" "$(@D)/python_include/pymem.h" && cp "/opt/python3.6/include/python3.6m/complexobject.h" "$(@D)/python_include/complexobject.h" && cp "/opt/python3.6/include/python3.6m/structseq.h" "$(@D)/python_include/structseq.h" && cp "/opt/python3.6/include/python3.6m/datetime.h" "$(@D)/python_include/datetime.h" && cp "/opt/python3.6/include/python3.6m/pythonrun.h" "$(@D)/python_include/pythonrun.h" && cp "/opt/python3.6/include/python3.6m/pyhash.h" "$(@D)/python_include/pyhash.h" && cp "/opt/python3.6/include/python3.6m/pycapsule.h" "$(@D)/python_include/pycapsule.h" && cp "/opt/python3.6/include/python3.6m/setobject.h" "$(@D)/python_include/setobject.h" && cp "/opt/python3.6/include/python3.6m/listobject.h" "$(@D)/python_include/listobject.h" && cp "/opt/python3.6/include/python3.6m/bytesobject.h" "$(@D)/python_include/bytesobject.h" && cp "/opt/python3.6/include/python3.6m/pgen.h" "$(@D)/python_include/pgen.h" && cp "/opt/python3.6/include/python3.6m/patchlevel.h" "$(@D)/python_include/patchlevel.h" && cp "/opt/python3.6/include/python3.6m/opcode.h" "$(@D)/python_include/opcode.h" && cp "/opt/python3.6/include/python3.6m/parsetok.h" "$(@D)/python_include/parsetok.h" && cp "/opt/python3.6/include/python3.6m/pystrhex.h" "$(@D)/python_include/pystrhex.h" && cp "/opt/python3.6/include/python3.6m/marshal.h" "$(@D)/python_include/marshal.h" && cp "/opt/python3.6/include/python3.6m/token.h" "$(@D)/python_include/token.h" && cp "/opt/python3.6/include/python3.6m/iterobject.h" "$(@D)/python_include/iterobject.h" && cp "/opt/python3.6/include/python3.6m/abstract.h" "$(@D)/python_include/abstract.h" && cp "/opt/python3.6/include/python3.6m/py_curses.h" "$(@D)/python_include/py_curses.h" && cp "/opt/python3.6/include/python3.6m/metagrammar.h" "$(@D)/python_include/metagrammar.h" && cp "/opt/python3.6/include/python3.6m/Python-ast.h" "$(@D)/python_include/Python-ast.h"
+cp "/opt/python3.6/include/python3.6m/Python-ast.h" "$(@D)/python_include/Python-ast.h" && cp "/opt/python3.6/include/python3.6m/Python.h" "$(@D)/python_include/Python.h" && cp "/opt/python3.6/include/python3.6m/abstract.h" "$(@D)/python_include/abstract.h" && cp "/opt/python3.6/include/python3.6m/accu.h" "$(@D)/python_include/accu.h" && cp "/opt/python3.6/include/python3.6m/asdl.h" "$(@D)/python_include/asdl.h" && cp "/opt/python3.6/include/python3.6m/ast.h" "$(@D)/python_include/ast.h" && cp "/opt/python3.6/include/python3.6m/bitset.h" "$(@D)/python_include/bitset.h" && cp "/opt/python3.6/include/python3.6m/bltinmodule.h" "$(@D)/python_include/bltinmodule.h" && cp "/opt/python3.6/include/python3.6m/boolobject.h" "$(@D)/python_include/boolobject.h" && cp "/opt/python3.6/include/python3.6m/bytearrayobject.h" "$(@D)/python_include/bytearrayobject.h" && cp "/opt/python3.6/include/python3.6m/bytes_methods.h" "$(@D)/python_include/bytes_methods.h" && cp "/opt/python3.6/include/python3.6m/bytesobject.h" "$(@D)/python_include/bytesobject.h" && cp "/opt/python3.6/include/python3.6m/cellobject.h" "$(@D)/python_include/cellobject.h" && cp "/opt/python3.6/include/python3.6m/ceval.h" "$(@D)/python_include/ceval.h" && cp "/opt/python3.6/include/python3.6m/classobject.h" "$(@D)/python_include/classobject.h" && cp "/opt/python3.6/include/python3.6m/code.h" "$(@D)/python_include/code.h" && cp "/opt/python3.6/include/python3.6m/codecs.h" "$(@D)/python_include/codecs.h" && cp "/opt/python3.6/include/python3.6m/compile.h" "$(@D)/python_include/compile.h" && cp "/opt/python3.6/include/python3.6m/complexobject.h" "$(@D)/python_include/complexobject.h" && cp "/opt/python3.6/include/python3.6m/datetime.h" "$(@D)/python_include/datetime.h" && cp "/opt/python3.6/include/python3.6m/descrobject.h" "$(@D)/python_include/descrobject.h" && cp "/opt/python3.6/include/python3.6m/dictobject.h" "$(@D)/python_include/dictobject.h" && cp "/opt/python3.6/include/python3.6m/dtoa.h" "$(@D)/python_include/dtoa.h" && cp "/opt/python3.6/include/python3.6m/dynamic_annotations.h" "$(@D)/python_include/dynamic_annotations.h" && cp "/opt/python3.6/include/python3.6m/enumobject.h" "$(@D)/python_include/enumobject.h" && cp "/opt/python3.6/include/python3.6m/errcode.h" "$(@D)/python_include/errcode.h" && cp "/opt/python3.6/include/python3.6m/eval.h" "$(@D)/python_include/eval.h" && cp "/opt/python3.6/include/python3.6m/fileobject.h" "$(@D)/python_include/fileobject.h" && cp "/opt/python3.6/include/python3.6m/fileutils.h" "$(@D)/python_include/fileutils.h" && cp "/opt/python3.6/include/python3.6m/floatobject.h" "$(@D)/python_include/floatobject.h" && cp "/opt/python3.6/include/python3.6m/frameobject.h" "$(@D)/python_include/frameobject.h" && cp "/opt/python3.6/include/python3.6m/funcobject.h" "$(@D)/python_include/funcobject.h" && cp "/opt/python3.6/include/python3.6m/genobject.h" "$(@D)/python_include/genobject.h" && cp "/opt/python3.6/include/python3.6m/graminit.h" "$(@D)/python_include/graminit.h" && cp "/opt/python3.6/include/python3.6m/grammar.h" "$(@D)/python_include/grammar.h" && cp "/opt/python3.6/include/python3.6m/import.h" "$(@D)/python_include/import.h" && cp "/opt/python3.6/include/python3.6m/intrcheck.h" "$(@D)/python_include/intrcheck.h" && cp "/opt/python3.6/include/python3.6m/iterobject.h" "$(@D)/python_include/iterobject.h" && cp "/opt/python3.6/include/python3.6m/listobject.h" "$(@D)/python_include/listobject.h" && cp "/opt/python3.6/include/python3.6m/longintrepr.h" "$(@D)/python_include/longintrepr.h" && cp "/opt/python3.6/include/python3.6m/longobject.h" "$(@D)/python_include/longobject.h" && cp "/opt/python3.6/include/python3.6m/marshal.h" "$(@D)/python_include/marshal.h" && cp "/opt/python3.6/include/python3.6m/memoryobject.h" "$(@D)/python_include/memoryobject.h" && cp "/opt/python3.6/include/python3.6m/metagrammar.h" "$(@D)/python_include/metagrammar.h" && cp "/opt/python3.6/include/python3.6m/methodobject.h" "$(@D)/python_include/methodobject.h" && cp "/opt/python3.6/include/python3.6m/modsupport.h" "$(@D)/python_include/modsupport.h" && cp "/opt/python3.6/include/python3.6m/moduleobject.h" "$(@D)/python_include/moduleobject.h" && cp "/opt/python3.6/include/python3.6m/namespaceobject.h" "$(@D)/python_include/namespaceobject.h" && cp "/opt/python3.6/include/python3.6m/node.h" "$(@D)/python_include/node.h" && cp "/opt/python3.6/include/python3.6m/object.h" "$(@D)/python_include/object.h" && cp "/opt/python3.6/include/python3.6m/objimpl.h" "$(@D)/python_include/objimpl.h" && cp "/opt/python3.6/include/python3.6m/odictobject.h" "$(@D)/python_include/odictobject.h" && cp "/opt/python3.6/include/python3.6m/opcode.h" "$(@D)/python_include/opcode.h" && cp "/opt/python3.6/include/python3.6m/osdefs.h" "$(@D)/python_include/osdefs.h" && cp "/opt/python3.6/include/python3.6m/osmodule.h" "$(@D)/python_include/osmodule.h" && cp "/opt/python3.6/include/python3.6m/parsetok.h" "$(@D)/python_include/parsetok.h" && cp "/opt/python3.6/include/python3.6m/patchlevel.h" "$(@D)/python_include/patchlevel.h" && cp "/opt/python3.6/include/python3.6m/pgen.h" "$(@D)/python_include/pgen.h" && cp "/opt/python3.6/include/python3.6m/pgenheaders.h" "$(@D)/python_include/pgenheaders.h" && cp "/opt/python3.6/include/python3.6m/py_curses.h" "$(@D)/python_include/py_curses.h" && cp "/opt/python3.6/include/python3.6m/pyarena.h" "$(@D)/python_include/pyarena.h" && cp "/opt/python3.6/include/python3.6m/pyatomic.h" "$(@D)/python_include/pyatomic.h" && cp "/opt/python3.6/include/python3.6m/pycapsule.h" "$(@D)/python_include/pycapsule.h" && cp "/opt/python3.6/include/python3.6m/pyconfig.h" "$(@D)/python_include/pyconfig.h" && cp "/opt/python3.6/include/python3.6m/pyctype.h" "$(@D)/python_include/pyctype.h" && cp "/opt/python3.6/include/python3.6m/pydebug.h" "$(@D)/python_include/pydebug.h" && cp "/opt/python3.6/include/python3.6m/pydtrace.h" "$(@D)/python_include/pydtrace.h" && cp "/opt/python3.6/include/python3.6m/pyerrors.h" "$(@D)/python_include/pyerrors.h" && cp "/opt/python3.6/include/python3.6m/pyexpat.h" "$(@D)/python_include/pyexpat.h" && cp "/opt/python3.6/include/python3.6m/pyfpe.h" "$(@D)/python_include/pyfpe.h" && cp "/opt/python3.6/include/python3.6m/pygetopt.h" "$(@D)/python_include/pygetopt.h" && cp "/opt/python3.6/include/python3.6m/pyhash.h" "$(@D)/python_include/pyhash.h" && cp "/opt/python3.6/include/python3.6m/pylifecycle.h" "$(@D)/python_include/pylifecycle.h" && cp "/opt/python3.6/include/python3.6m/pymacconfig.h" "$(@D)/python_include/pymacconfig.h" && cp "/opt/python3.6/include/python3.6m/pymacro.h" "$(@D)/python_include/pymacro.h" && cp "/opt/python3.6/include/python3.6m/pymath.h" "$(@D)/python_include/pymath.h" && cp "/opt/python3.6/include/python3.6m/pymem.h" "$(@D)/python_include/pymem.h" && cp "/opt/python3.6/include/python3.6m/pyport.h" "$(@D)/python_include/pyport.h" && cp "/opt/python3.6/include/python3.6m/pystate.h" "$(@D)/python_include/pystate.h" && cp "/opt/python3.6/include/python3.6m/pystrcmp.h" "$(@D)/python_include/pystrcmp.h" && cp "/opt/python3.6/include/python3.6m/pystrhex.h" "$(@D)/python_include/pystrhex.h" && cp "/opt/python3.6/include/python3.6m/pystrtod.h" "$(@D)/python_include/pystrtod.h" && cp "/opt/python3.6/include/python3.6m/pythonrun.h" "$(@D)/python_include/pythonrun.h" && cp "/opt/python3.6/include/python3.6m/pythread.h" "$(@D)/python_include/pythread.h" && cp "/opt/python3.6/include/python3.6m/pytime.h" "$(@D)/python_include/pytime.h" && cp "/opt/python3.6/include/python3.6m/rangeobject.h" "$(@D)/python_include/rangeobject.h" && cp "/opt/python3.6/include/python3.6m/setobject.h" "$(@D)/python_include/setobject.h" && cp "/opt/python3.6/include/python3.6m/sliceobject.h" "$(@D)/python_include/sliceobject.h" && cp "/opt/python3.6/include/python3.6m/structmember.h" "$(@D)/python_include/structmember.h" && cp "/opt/python3.6/include/python3.6m/structseq.h" "$(@D)/python_include/structseq.h" && cp "/opt/python3.6/include/python3.6m/symtable.h" "$(@D)/python_include/symtable.h" && cp "/opt/python3.6/include/python3.6m/sysmodule.h" "$(@D)/python_include/sysmodule.h" && cp "/opt/python3.6/include/python3.6m/token.h" "$(@D)/python_include/token.h" && cp "/opt/python3.6/include/python3.6m/traceback.h" "$(@D)/python_include/traceback.h" && cp "/opt/python3.6/include/python3.6m/tupleobject.h" "$(@D)/python_include/tupleobject.h" && cp "/opt/python3.6/include/python3.6m/typeslots.h" "$(@D)/python_include/typeslots.h" && cp "/opt/python3.6/include/python3.6m/ucnhash.h" "$(@D)/python_include/ucnhash.h" && cp "/opt/python3.6/include/python3.6m/unicodeobject.h" "$(@D)/python_include/unicodeobject.h" && cp "/opt/python3.6/include/python3.6m/warnings.h" "$(@D)/python_include/warnings.h" && cp "/opt/python3.6/include/python3.6m/weakrefobject.h" "$(@D)/python_include/weakrefobject.h"
""",
)
genrule(
name = "numpy_include",
outs = [
- "numpy_include/numpy/oldnumeric.h",
- "numpy_include/numpy/npy_1_7_deprecated_api.h",
- "numpy_include/numpy/ufunc_api.txt",
- "numpy_include/numpy/multiarray_api.txt",
- "numpy_include/numpy/halffloat.h",
- "numpy_include/numpy/npy_common.h",
- "numpy_include/numpy/utils.h",
- "numpy_include/numpy/npy_interrupt.h",
- "numpy_include/numpy/npy_endian.h",
+ "numpy_include/numpy/__multiarray_api.h",
"numpy_include/numpy/__ufunc_api.h",
"numpy_include/numpy/_neighborhood_iterator_imp.h",
- "numpy_include/numpy/ufuncobject.h",
+ "numpy_include/numpy/_numpyconfig.h",
+ "numpy_include/numpy/arrayobject.h",
+ "numpy_include/numpy/arrayscalars.h",
+ "numpy_include/numpy/halffloat.h",
+ "numpy_include/numpy/multiarray_api.txt",
+ "numpy_include/numpy/ndarrayobject.h",
"numpy_include/numpy/ndarraytypes.h",
- "numpy_include/numpy/npy_math.h",
"numpy_include/numpy/noprefix.h",
+ "numpy_include/numpy/npy_1_7_deprecated_api.h",
"numpy_include/numpy/npy_3kcompat.h",
- "numpy_include/numpy/arrayscalars.h",
- "numpy_include/numpy/npy_os.h",
- "numpy_include/numpy/ndarrayobject.h",
- "numpy_include/numpy/npy_no_deprecated_api.h",
- "numpy_include/numpy/arrayobject.h",
- "numpy_include/numpy/_numpyconfig.h",
- "numpy_include/numpy/__multiarray_api.h",
+ "numpy_include/numpy/npy_common.h",
"numpy_include/numpy/npy_cpu.h",
- "numpy_include/numpy/old_defines.h",
+ "numpy_include/numpy/npy_endian.h",
+ "numpy_include/numpy/npy_interrupt.h",
+ "numpy_include/numpy/npy_math.h",
+ "numpy_include/numpy/npy_no_deprecated_api.h",
+ "numpy_include/numpy/npy_os.h",
"numpy_include/numpy/numpyconfig.h",
+ "numpy_include/numpy/old_defines.h",
+ "numpy_include/numpy/oldnumeric.h",
+ "numpy_include/numpy/ufunc_api.txt",
+ "numpy_include/numpy/ufuncobject.h",
+ "numpy_include/numpy/utils.h",
],
cmd = """
-cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/oldnumeric.h" "$(@D)/numpy_include/numpy/oldnumeric.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_1_7_deprecated_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ufunc_api.txt" "$(@D)/numpy_include/numpy/ufunc_api.txt" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/multiarray_api.txt" "$(@D)/numpy_include/numpy/multiarray_api.txt" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/halffloat.h" "$(@D)/numpy_include/numpy/halffloat.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_common.h" "$(@D)/numpy_include/numpy/npy_common.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/utils.h" "$(@D)/numpy_include/numpy/utils.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_interrupt.h" "$(@D)/numpy_include/numpy/npy_interrupt.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_endian.h" "$(@D)/numpy_include/numpy/npy_endian.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/__ufunc_api.h" "$(@D)/numpy_include/numpy/__ufunc_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/_neighborhood_iterator_imp.h" "$(@D)/numpy_include/numpy/_neighborhood_iterator_imp.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ufuncobject.h" "$(@D)/numpy_include/numpy/ufuncobject.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ndarraytypes.h" "$(@D)/numpy_include/numpy/ndarraytypes.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_math.h" "$(@D)/numpy_include/numpy/npy_math.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/noprefix.h" "$(@D)/numpy_include/numpy/noprefix.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_3kcompat.h" "$(@D)/numpy_include/numpy/npy_3kcompat.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/arrayscalars.h" "$(@D)/numpy_include/numpy/arrayscalars.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_os.h" "$(@D)/numpy_include/numpy/npy_os.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ndarrayobject.h" "$(@D)/numpy_include/numpy/ndarrayobject.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_no_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_no_deprecated_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/arrayobject.h" "$(@D)/numpy_include/numpy/arrayobject.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/_numpyconfig.h" "$(@D)/numpy_include/numpy/_numpyconfig.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/__multiarray_api.h" "$(@D)/numpy_include/numpy/__multiarray_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_cpu.h" "$(@D)/numpy_include/numpy/npy_cpu.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/old_defines.h" "$(@D)/numpy_include/numpy/old_defines.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/numpyconfig.h" "$(@D)/numpy_include/numpy/numpyconfig.h"
+cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/__multiarray_api.h" "$(@D)/numpy_include/numpy/__multiarray_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/__ufunc_api.h" "$(@D)/numpy_include/numpy/__ufunc_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/_neighborhood_iterator_imp.h" "$(@D)/numpy_include/numpy/_neighborhood_iterator_imp.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/_numpyconfig.h" "$(@D)/numpy_include/numpy/_numpyconfig.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/arrayobject.h" "$(@D)/numpy_include/numpy/arrayobject.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/arrayscalars.h" "$(@D)/numpy_include/numpy/arrayscalars.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/halffloat.h" "$(@D)/numpy_include/numpy/halffloat.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/multiarray_api.txt" "$(@D)/numpy_include/numpy/multiarray_api.txt" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ndarrayobject.h" "$(@D)/numpy_include/numpy/ndarrayobject.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ndarraytypes.h" "$(@D)/numpy_include/numpy/ndarraytypes.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/noprefix.h" "$(@D)/numpy_include/numpy/noprefix.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_1_7_deprecated_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_3kcompat.h" "$(@D)/numpy_include/numpy/npy_3kcompat.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_common.h" "$(@D)/numpy_include/numpy/npy_common.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_cpu.h" "$(@D)/numpy_include/numpy/npy_cpu.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_endian.h" "$(@D)/numpy_include/numpy/npy_endian.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_interrupt.h" "$(@D)/numpy_include/numpy/npy_interrupt.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_math.h" "$(@D)/numpy_include/numpy/npy_math.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_no_deprecated_api.h" "$(@D)/numpy_include/numpy/npy_no_deprecated_api.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/npy_os.h" "$(@D)/numpy_include/numpy/npy_os.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/numpyconfig.h" "$(@D)/numpy_include/numpy/numpyconfig.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/old_defines.h" "$(@D)/numpy_include/numpy/old_defines.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/oldnumeric.h" "$(@D)/numpy_include/numpy/oldnumeric.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ufunc_api.txt" "$(@D)/numpy_include/numpy/ufunc_api.txt" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/ufuncobject.h" "$(@D)/numpy_include/numpy/ufuncobject.h" && cp "/opt/python3.6/lib/python3.6/site-packages/numpy/core/include/numpy/utils.h" "$(@D)/numpy_include/numpy/utils.h"
""",
)
--
GitLab
From f283e65a1bdb797070be9b84a69ef323268f7c3c Mon Sep 17 00:00:00 2001
From: Tom Hennigan
Date: Tue, 5 Jun 2018 03:56:47 -0700
Subject: [PATCH 0043/1193] Handle scalar input to assert_equal in eager.
PiperOrigin-RevId: 199274329
---
tensorflow/python/kernel_tests/check_ops_test.py | 7 +++++++
tensorflow/python/ops/check_ops.py | 4 ++--
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/tensorflow/python/kernel_tests/check_ops_test.py b/tensorflow/python/kernel_tests/check_ops_test.py
index 5a83ec8d30..7ef841c96b 100644
--- a/tensorflow/python/kernel_tests/check_ops_test.py
+++ b/tensorflow/python/kernel_tests/check_ops_test.py
@@ -88,6 +88,13 @@ class AssertEqualTest(test.TestCase):
out = array_ops.identity(small)
self.evaluate(out)
+ @test_util.run_in_graph_and_eager_modes()
+ def test_scalar_comparison(self):
+ const_true = constant_op.constant(True, name="true")
+ const_false = constant_op.constant(False, name="false")
+ with self.assertRaisesRegexp(errors.InvalidArgumentError, "fail"):
+ check_ops.assert_equal(const_true, const_false, message="fail")
+
def test_returns_none_with_eager(self):
with context.eager_mode():
small = constant_op.constant([1, 2], name="small")
diff --git a/tensorflow/python/ops/check_ops.py b/tensorflow/python/ops/check_ops.py
index cabc1e724c..375a5ec2c3 100644
--- a/tensorflow/python/ops/check_ops.py
+++ b/tensorflow/python/ops/check_ops.py
@@ -341,8 +341,8 @@ def assert_equal(x, y, data=None, summarize=None, message=None, name=None):
y_sum, y_np[:y_sum]))
index_and_values_str = ''
- if x.shape == y.shape:
- # If the shapes of x and y are the same,
+ if x.shape == y.shape and x.shape.as_list():
+ # If the shapes of x and y are the same (and not scalars),
# Get the values that actually differed and their indices.
# If shapes are different this information is more confusing
# than useful.
--
GitLab
From e71f9b863097086c91b2a3f5aea1e081f275ceca Mon Sep 17 00:00:00 2001
From: "A. Unique TensorFlower"
Date: Thu, 21 Jun 2018 18:53:05 -0700
Subject: [PATCH 0044/1193] Update Eigen version to commit
e5e305a158a029f5b5f837bf821411a51439a970.
PiperOrigin-RevId: 201624024
---
.../distributions/dirichlet_multinomial_test.py | 6 +++---
tensorflow/workspace.bzl | 8 ++++----
2 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/tensorflow/python/kernel_tests/distributions/dirichlet_multinomial_test.py b/tensorflow/python/kernel_tests/distributions/dirichlet_multinomial_test.py
index 7922fb0606..daea699514 100644
--- a/tensorflow/python/kernel_tests/distributions/dirichlet_multinomial_test.py
+++ b/tensorflow/python/kernel_tests/distributions/dirichlet_multinomial_test.py
@@ -250,9 +250,9 @@ class DirichletMultinomialTest(test.TestCase):
dist.variance(),
dist.stddev(),
])
- self.assertAllClose(sample_mean_, analytic_mean, atol=0., rtol=0.04)
- self.assertAllClose(sample_cov_, analytic_cov, atol=0., rtol=0.05)
- self.assertAllClose(sample_var_, analytic_var, atol=0., rtol=0.05)
+ self.assertAllClose(sample_mean_, analytic_mean, atol=0., rtol=0.06)
+ self.assertAllClose(sample_cov_, analytic_cov, atol=0., rtol=0.07)
+ self.assertAllClose(sample_var_, analytic_var, atol=0., rtol=0.07)
self.assertAllClose(sample_stddev_, analytic_stddev, atol=0., rtol=0.02)
def testCovariance(self):
diff --git a/tensorflow/workspace.bzl b/tensorflow/workspace.bzl
index 50a69598a1..43152c88cf 100644
--- a/tensorflow/workspace.bzl
+++ b/tensorflow/workspace.bzl
@@ -107,11 +107,11 @@ def tf_workspace(path_prefix="", tf_repo_name=""):
tf_http_archive(
name = "eigen_archive",
urls = [
- "https://mirror.bazel.build/bitbucket.org/eigen/eigen/get/6913f0cf7d06.tar.gz",
- "https://bitbucket.org/eigen/eigen/get/6913f0cf7d06.tar.gz",
+ "https://mirror.bazel.build/bitbucket.org/eigen/eigen/get/e5e305a158a0.tar.gz",
+ "https://bitbucket.org/eigen/eigen/get/e5e305a158a0.tar.gz",
],
- sha256 = "791b836cacd03e20bae5bdd25f1c4a5505a0a9975ba94a61eb4e2631fbd1d53a",
- strip_prefix = "eigen-eigen-6913f0cf7d06",
+ sha256 = "8bbe676d69e7f59070c83a949454b8b6344034e0ebbf686b337528e5dc04c7de",
+ strip_prefix = "eigen-eigen-e5e305a158a0",
build_file = clean_dep("//third_party:eigen.BUILD"),
patch_file = clean_dep("//third_party:eigen_fix_cuda_compilation.patch")
)
--
GitLab
From 5c450d2e1d0d3a1abae4997df0da1b8d73684e01 Mon Sep 17 00:00:00 2001
From: Rasmus Munk Larsen
Date: Fri, 22 Jun 2018 13:36:57 -0700
Subject: [PATCH 0045/1193] Update workspace.bzl
---
tensorflow/workspace.bzl | 1 -
1 file changed, 1 deletion(-)
diff --git a/tensorflow/workspace.bzl b/tensorflow/workspace.bzl
index 43152c88cf..3c657c4a5b 100644
--- a/tensorflow/workspace.bzl
+++ b/tensorflow/workspace.bzl
@@ -113,7 +113,6 @@ def tf_workspace(path_prefix="", tf_repo_name=""):
sha256 = "8bbe676d69e7f59070c83a949454b8b6344034e0ebbf686b337528e5dc04c7de",
strip_prefix = "eigen-eigen-e5e305a158a0",
build_file = clean_dep("//third_party:eigen.BUILD"),
- patch_file = clean_dep("//third_party:eigen_fix_cuda_compilation.patch")
)
tf_http_archive(
--
GitLab
From 0dbf461ddbdf032ee64993f9ef2925e3444d7954 Mon Sep 17 00:00:00 2001
From: Yong Tang
Date: Fri, 22 Jun 2018 13:16:47 +0000
Subject: [PATCH 0046/1193] Update gflags from f8a0efe to v2.2.1
This fix bumps gflags from f8a0efe to the latest versioned
release of v2.2.1
Signed-off-by: Yong Tang
---
tensorflow/workspace.bzl | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/tensorflow/workspace.bzl b/tensorflow/workspace.bzl
index 779b6a3d9a..a9b16392d6 100644
--- a/tensorflow/workspace.bzl
+++ b/tensorflow/workspace.bzl
@@ -384,11 +384,11 @@ def tf_workspace(path_prefix="", tf_repo_name=""):
tf_http_archive(
name = "com_github_gflags_gflags",
urls = [
- "https://mirror.bazel.build/github.com/gflags/gflags/archive/f8a0efe03aa69b3336d8e228b37d4ccb17324b88.tar.gz",
- "https://github.com/gflags/gflags/archive/f8a0efe03aa69b3336d8e228b37d4ccb17324b88.tar.gz",
+ "https://mirror.bazel.build/github.com/gflags/gflags/archive/v2.2.1.tar.gz",
+ "https://github.com/gflags/gflags/archive/v2.2.1.tar.gz",
],
- sha256 = "4d222fab8f1ede4709cdff417d15a1336f862d7334a81abf76d09c15ecf9acd1",
- strip_prefix = "gflags-f8a0efe03aa69b3336d8e228b37d4ccb17324b88",
+ sha256 = "ae27cdbcd6a2f935baa78e4f21f675649271634c092b1be01469440495609d0e",
+ strip_prefix = "gflags-2.2.1",
)
tf_http_archive(
--
GitLab
From ac0734db606eb79faa30298eb29a9ce308b2ac1b Mon Sep 17 00:00:00 2001
From: Christian Ertler
Date: Mon, 25 Jun 2018 11:41:47 +0200
Subject: [PATCH 0047/1193] api golden files (non_max_suppression_overlaps)
---
tensorflow/tools/api/golden/tensorflow.image.pbtxt | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/tensorflow/tools/api/golden/tensorflow.image.pbtxt b/tensorflow/tools/api/golden/tensorflow.image.pbtxt
index e268fa3f61..d1055cb882 100644
--- a/tensorflow/tools/api/golden/tensorflow.image.pbtxt
+++ b/tensorflow/tools/api/golden/tensorflow.image.pbtxt
@@ -116,6 +116,10 @@ tf_module {
name: "non_max_suppression"
argspec: "args=[\'boxes\', \'scores\', \'max_output_size\', \'iou_threshold\', \'score_threshold\', \'name\'], varargs=None, keywords=None, defaults=[\'0.5\', \'-inf\', \'None\'], "
}
+ member_method {
+ name: "non_max_suppression_overlaps"
+ argspec: "args=[\'overlaps\', \'scores\', \'max_output_size\', \'overlap_threshold\', \'score_threshold\', \'name\'], varargs=None, keywords=None, defaults=[\'0.5\', \'-inf\', \'None\'], "
+ }
member_method {
name: "pad_to_bounding_box"
argspec: "args=[\'image\', \'offset_height\', \'offset_width\', \'target_height\', \'target_width\'], varargs=None, keywords=None, defaults=None"
--
GitLab
From df2c8315211895afab0d7ba1ff64e831d9d3ce3b Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Tue, 19 Jun 2018 23:11:00 -0700
Subject: [PATCH 0048/1193] Get started landing page. Move "Datasets
Quickstart" to "Datasets for Estimators" under guide.
PiperOrigin-RevId: 201301717
---
tensorflow/docs_src/get_started/_index.yaml | 255 ++++++++++++++++++
.../get_started/basic_classification.md | 3 +
.../docs_src/get_started/basic_regression.md | 3 +
.../get_started/basic_text_classification.md | 3 +
tensorflow/docs_src/get_started/eager.md | 2 +-
tensorflow/docs_src/get_started/index.md | 29 --
tensorflow/docs_src/get_started/leftnav_files | 12 +-
tensorflow/docs_src/get_started/next_steps.md | 36 +++
.../get_started/overfit_and_underfit.md | 3 +
.../get_started/save_and_restore_models.md | 3 +
tensorflow/docs_src/install/install_linux.md | 8 +-
tensorflow/docs_src/install/install_mac.md | 6 +-
.../docs_src/install/install_raspbian.md | 6 +-
.../docs_src/install/install_sources.md | 2 +-
.../docs_src/install/install_windows.md | 7 +-
.../datasets_for_estimators.md} | 2 +-
.../docs_src/programmers_guide/index.md | 1 +
.../docs_src/programmers_guide/leftnav_files | 1 +
.../programmers_guide/premade_estimators.md | 8 +-
tensorflow/docs_src/tutorials/index.md | 5 +-
20 files changed, 329 insertions(+), 66 deletions(-)
create mode 100644 tensorflow/docs_src/get_started/_index.yaml
create mode 100644 tensorflow/docs_src/get_started/basic_classification.md
create mode 100644 tensorflow/docs_src/get_started/basic_regression.md
create mode 100644 tensorflow/docs_src/get_started/basic_text_classification.md
delete mode 100644 tensorflow/docs_src/get_started/index.md
create mode 100644 tensorflow/docs_src/get_started/next_steps.md
create mode 100644 tensorflow/docs_src/get_started/overfit_and_underfit.md
create mode 100644 tensorflow/docs_src/get_started/save_and_restore_models.md
rename tensorflow/docs_src/{get_started/datasets_quickstart.md => programmers_guide/datasets_for_estimators.md} (99%)
diff --git a/tensorflow/docs_src/get_started/_index.yaml b/tensorflow/docs_src/get_started/_index.yaml
new file mode 100644
index 0000000000..af255a482d
--- /dev/null
+++ b/tensorflow/docs_src/get_started/_index.yaml
@@ -0,0 +1,255 @@
+project_path: /_project.yaml
+book_path: /_book.yaml
+description:
+landing_page:
+ show_side_navs: True
+ rows:
+ - description: >
+ Get Started with TensorFlow
+
+ TensorFlow is an open-source machine learning library for research and
+ production. TensorFlow offers APIs for beginners and experts to develop
+ for desktop, mobile, web, and cloud. See the sections below to get
+ started.
+
+ items:
+ - custom_html: >
+
+
+ - classname: tfo-landing-row-item-code-block
+ code_block: |
+
+ import tensorflow as tf
+ mnist = tf.keras.datasets.mnist
+
+ (x_train, y_train),(x_test, y_test) = mnist.load_data()
+ x_train, x_test = x_train / 255.0, x_test / 255.0
+
+ model = tf.keras.models.Sequential([
+ tf.keras.layers.Flatten(),
+ tf.keras.layers.Dense(512, activation=tf.nn.relu),
+ tf.keras.layers.Dropout(0.2),
+ tf.keras.layers.Dense(10, activation=tf.nn.softmax)
+ ])
+ model.compile(optimizer='adam',
+ loss='sparse_categorical_crossentropy',
+ metrics=['accuracy'])
+
+ model.fit(x_train, y_train, epochs=5)
+ model.evaluate(x_test, y_test)
+
+ {% dynamic if request.tld != 'cn' %}
+ Run in a Notebook
+ {% dynamic endif %}
+
+ - items:
+ - custom_html: >
+
+ - custom_html: >
+
+
+ - description: >
+ Google Colab: An easy way to learn and use TensorFlow
+
+ Colaboratory
+ is a Google research project created to help disseminate machine learning
+ education and research. It's a Jupyter notebook environment that requires
+ no setup to use and runs entirely in the cloud.
+ Read the blog post.
+
+
+ - description: >
+ Build your first ML app
+ Create and deploy TensorFlow models on web and mobile.
+ background: grey
+ items:
+ - custom_html: >
+
+
+ Web developers
+
+
+ TensorFlow.js is a WebGL accelerated, JavaScript library to train and
+ deploy ML models in the browser and for Node.js.
+
+
+ - custom_html: >
+
+
+ - description: >
+ Videos and updates
+
+ Subscribe to the TensorFlow
+ YouTube channel
+ and blog for
+ the latest videos and updates.
+
+ items:
+ - description: >
+ Get started with TensorFlow's High-Level APIs
+ youtube_id: tjsHSIG8I08
+ buttons:
+ - label: Watch the video
+ path: https://www.youtube.com/watch?v=tjsHSIG8I08
+ - description: >
+ Eager execution
+ youtube_id: T8AW0fKP0Hs
+ background: grey
+ buttons:
+ - label: Watch the video
+ path: https://www.youtube.com/watch?v=T8AW0fKP0Hs
+ - description: >
+ tf.data: Fast, flexible, and easy-to-use input pipelines
+ youtube_id: uIcqeP7MFH0
+ buttons:
+ - label: Watch the video
+ path: https://www.youtube.com/watch?v=uIcqeP7MFH0
diff --git a/tensorflow/docs_src/get_started/basic_classification.md b/tensorflow/docs_src/get_started/basic_classification.md
new file mode 100644
index 0000000000..91bbd85b24
--- /dev/null
+++ b/tensorflow/docs_src/get_started/basic_classification.md
@@ -0,0 +1,3 @@
+# Basic Classification
+
+[Colab notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/basic_classification.ipynb)
diff --git a/tensorflow/docs_src/get_started/basic_regression.md b/tensorflow/docs_src/get_started/basic_regression.md
new file mode 100644
index 0000000000..a535f22f5a
--- /dev/null
+++ b/tensorflow/docs_src/get_started/basic_regression.md
@@ -0,0 +1,3 @@
+# Basic Regression
+
+[Colab notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/basic_regression.ipynb)
diff --git a/tensorflow/docs_src/get_started/basic_text_classification.md b/tensorflow/docs_src/get_started/basic_text_classification.md
new file mode 100644
index 0000000000..7c5d4f7896
--- /dev/null
+++ b/tensorflow/docs_src/get_started/basic_text_classification.md
@@ -0,0 +1,3 @@
+# Basic Text Classification
+
+[Colab notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/basic_text_classification.ipynb)
diff --git a/tensorflow/docs_src/get_started/eager.md b/tensorflow/docs_src/get_started/eager.md
index bbb25e20c6..ddf239485a 100644
--- a/tensorflow/docs_src/get_started/eager.md
+++ b/tensorflow/docs_src/get_started/eager.md
@@ -1,3 +1,3 @@
-# Get Started with Eager Execution
+# Custom Training Walkthrough
[Colab notebook](https://colab.research.google.com/github/tensorflow/models/blob/r1.9.0/samples/core/get_started/eager.ipynb)
diff --git a/tensorflow/docs_src/get_started/index.md b/tensorflow/docs_src/get_started/index.md
deleted file mode 100644
index 232d2f1547..0000000000
--- a/tensorflow/docs_src/get_started/index.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Get Started
-
-If you are new to machine learning, we recommend taking the following online
-course prior to diving into TensorFlow documentation:
-
- * [Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course/),
- which introduces machine learning concepts and encourages experimentation
- with existing TensorFlow code.
-
-TensorFlow is a tool for machine learning. While it contains a wide range of
-functionality, TensorFlow is mainly designed for deep neural network models.
-
-The easiest way to get started with TensorFlow is by using Eager Execution.
-
- * @{$get_started/eager}, is for anyone new to machine learning or TensorFlow.
-
-TensorFlow provides many APIs. The remainder of this section focuses on the
-Estimator API which provide scalable, high-performance models. See the
-@{$estimators} guide.
-
-For more advanced users:
-
- * The @{$low_level_intro$Low Level Introduction} demonstrates how to use
- TensorFlow outside of the Estimator framework, for debugging and
- experimentation.
- * The @{$programmers_guide$Programmer's Guide} details major
- TensorFlow components.
- * The @{$tutorials$Tutorials} provide walkthroughs of a variety of
- TensorFlow models.
diff --git a/tensorflow/docs_src/get_started/leftnav_files b/tensorflow/docs_src/get_started/leftnav_files
index e6cc8d5658..9a60496cb5 100644
--- a/tensorflow/docs_src/get_started/leftnav_files
+++ b/tensorflow/docs_src/get_started/leftnav_files
@@ -1,4 +1,10 @@
-index.md
+### Learn and use ML
+basic_classification.md
+basic_text_classification.md
+basic_regression.md
+overfit_and_underfit.md
+save_and_restore_models.md
+next_steps.md
-eager.md
-datasets_quickstart.md
+### Research and experimentation
+custom_training_walkthrough.md
diff --git a/tensorflow/docs_src/get_started/next_steps.md b/tensorflow/docs_src/get_started/next_steps.md
new file mode 100644
index 0000000000..79c0ef3346
--- /dev/null
+++ b/tensorflow/docs_src/get_started/next_steps.md
@@ -0,0 +1,36 @@
+# Next Steps
+
+## Learn more about TensorFlow
+
+* The [TensorFlow Guide](/programmers_guide) includes usage guides for the
+ high-level APIs, as well as advanced TensorFlow operations.
+* [Premade Estimators](/programmers_guide/premade_estimators) are designed to
+ get results out of the box. Use TensorFlow without building your own models.
+* [TensorFlow.js](https://js.tensorflow.org/) allows web developers to train and
+ deploy ML models in the browser and using Node.js.
+* [TFLite](/mobile/tflite) allows mobile developers to do inference efficiently
+ on mobile devices.
+* [TensorFlow Serving](/serving) is an open-source project that can put
+ TensorFlow models in production quickly.
+* The [ecosystem](/ecosystem) contains more projects, including
+ [Magenta](https://magenta.tensorflow.org/), [TFX](/tfx),
+ [Swift for TensorFlow](https://github.com/tensorflow/swift), and more.
+
+## Learn more about machine learning
+
+Recommended resources include:
+
+* [Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course/),
+ a course from Google that introduces machine learning concepts.
+* [CS 20: Tensorflow for Deep Learning Research](http://web.stanford.edu/class/cs20si/),
+ notes from an intro course from Stanford.
+* [CS231n: Convolutional Neural Networks for Visual Recognition](http://cs231n.stanford.edu/),
+ a course that teaches how convolutional networks work.
+* [Machine Learning Recipes](https://www.youtube.com/watch?v=cKxRvEZd3Mw&list=PLOU2XLYxmsIIuiBfYad6rFYQU_jL2ryal),
+ a video series that introduces basic machine learning concepts with few prerequisites.
+* [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python),
+ a book by Francois Chollet about the Keras API, as well as an excellent hands on intro to Deep Learning.
+* [Hands-on Machine Learning with Scikit-Learn and TensorFlow](https://github.com/ageron/handson-ml),
+ a book by Aurélien Geron's that is a clear getting-started guide to data science and deep learning.
+* [Deep Learning](https://www.deeplearningbook.org/), a book by Ian Goodfellow et al.
+ that provides a technical dive into learning machine learning.
diff --git a/tensorflow/docs_src/get_started/overfit_and_underfit.md b/tensorflow/docs_src/get_started/overfit_and_underfit.md
new file mode 100644
index 0000000000..e5b5ae7b5a
--- /dev/null
+++ b/tensorflow/docs_src/get_started/overfit_and_underfit.md
@@ -0,0 +1,3 @@
+# Overfitting and Underfitting
+
+[Colab notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/overfit_and_underfit.ipynb)
diff --git a/tensorflow/docs_src/get_started/save_and_restore_models.md b/tensorflow/docs_src/get_started/save_and_restore_models.md
new file mode 100644
index 0000000000..44b3772945
--- /dev/null
+++ b/tensorflow/docs_src/get_started/save_and_restore_models.md
@@ -0,0 +1,3 @@
+# Save and restore Models
+
+[Colab notebook](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/save_and_restore_models.ipynb)
diff --git a/tensorflow/docs_src/install/install_linux.md b/tensorflow/docs_src/install/install_linux.md
index 9baf6870be..41619ca230 100644
--- a/tensorflow/docs_src/install/install_linux.md
+++ b/tensorflow/docs_src/install/install_linux.md
@@ -491,13 +491,7 @@ TensorFlow programs:
If the system outputs an error message instead of a greeting, see [Common
installation problems](#common_installation_problems).
-If you are new to machine learning, we recommend the following:
-
-* [Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course)
-* @{$get_started/eager}
-
-If you are experienced with machine learning but new to TensorFlow, see
-@{$get_started/eager}.
+To learn more, see [Get Started with TensorFlow](https://www.tensorflow.org/get_started).
## TensorFlow GPU support
diff --git a/tensorflow/docs_src/install/install_mac.md b/tensorflow/docs_src/install/install_mac.md
index 693254f876..eeca389617 100644
--- a/tensorflow/docs_src/install/install_mac.md
+++ b/tensorflow/docs_src/install/install_mac.md
@@ -403,11 +403,7 @@ writing TensorFlow programs:
If the system outputs an error message instead of a greeting, see
[Common installation problems](#common_installation_problems).
-If you are new to machine learning, we recommend the
-[Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course).
-
-If you are experienced with machine learning but new to TensorFlow, see
-@{$get_started/eager}.
+To learn more, see [Get Started with TensorFlow](https://www.tensorflow.org/get_started).
## Common installation problems
diff --git a/tensorflow/docs_src/install/install_raspbian.md b/tensorflow/docs_src/install/install_raspbian.md
index 2f425162a1..0caab6d335 100644
--- a/tensorflow/docs_src/install/install_raspbian.md
+++ b/tensorflow/docs_src/install/install_raspbian.md
@@ -230,11 +230,7 @@ problems, despite the log message.
If the system outputs an error message instead of a greeting, see [Common
installation problems](#common_installation_problems).
-If you are new to machine learning, we recommend the [Machine Learning Crash
-Course](https://developers.google.com/machine-learning/crash-course).
-
-If you are experienced with machine learning but new to TensorFlow, see
-@{$get_started/eager}.
+To learn more, see [Get Started with TensorFlow](https://www.tensorflow.org/get_started).
## Common installation problems
diff --git a/tensorflow/docs_src/install/install_sources.md b/tensorflow/docs_src/install/install_sources.md
index 70e97cf556..7afcd340aa 100644
--- a/tensorflow/docs_src/install/install_sources.md
+++ b/tensorflow/docs_src/install/install_sources.md
@@ -362,7 +362,7 @@ TensorFlow programs:
Hello, TensorFlow!
-If you are new to TensorFlow, see @{$get_started/eager}.
+To learn more, see [Get Started with TensorFlow](https://www.tensorflow.org/get_started).
If the system outputs an error message instead of a greeting, see [Common
installation problems](#common_installation_problems).
diff --git a/tensorflow/docs_src/install/install_windows.md b/tensorflow/docs_src/install/install_windows.md
index 6c4f5b85ab..7fe94f0bc3 100644
--- a/tensorflow/docs_src/install/install_windows.md
+++ b/tensorflow/docs_src/install/install_windows.md
@@ -157,12 +157,7 @@ TensorFlow programs:
If the system outputs an error message instead of a greeting, see [Common
installation problems](#common_installation_problems).
-If you are new to machine learning, we recommend the
-[Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course).
-
-If you are experienced with machine learning but new to TensorFlow, see
-@{$get_started/eager}.
-
+To learn more, see [Get Started with TensorFlow](https://www.tensorflow.org/get_started).
## Common installation problems
diff --git a/tensorflow/docs_src/get_started/datasets_quickstart.md b/tensorflow/docs_src/programmers_guide/datasets_for_estimators.md
similarity index 99%
rename from tensorflow/docs_src/get_started/datasets_quickstart.md
rename to tensorflow/docs_src/programmers_guide/datasets_for_estimators.md
index 020e40dd3b..345a31b985 100644
--- a/tensorflow/docs_src/get_started/datasets_quickstart.md
+++ b/tensorflow/docs_src/programmers_guide/datasets_for_estimators.md
@@ -1,4 +1,4 @@
-# Datasets Quick Start
+# Datasets for Estimators
The @{tf.data} module contains a collection of classes that allows you to
easily load data, manipulate it, and pipe it into your model. This document
diff --git a/tensorflow/docs_src/programmers_guide/index.md b/tensorflow/docs_src/programmers_guide/index.md
index 0c2d4afb11..9c58a3b45e 100644
--- a/tensorflow/docs_src/programmers_guide/index.md
+++ b/tensorflow/docs_src/programmers_guide/index.md
@@ -22,6 +22,7 @@ works. The units are as follows:
design yourself.
* @{$feature_columns}, which shows how an Estimator can handle a variety of input
data types without changes to the model.
+* @{$datasets_for_estimators} describes using tf.data with estimators.
* @{$checkpoints}, which explains how to save training progress and resume where
you left off.
diff --git a/tensorflow/docs_src/programmers_guide/leftnav_files b/tensorflow/docs_src/programmers_guide/leftnav_files
index 3bcf864e13..357a2a1cb9 100644
--- a/tensorflow/docs_src/programmers_guide/leftnav_files
+++ b/tensorflow/docs_src/programmers_guide/leftnav_files
@@ -10,6 +10,7 @@ estimators.md: Introduction to Estimators
premade_estimators.md
custom_estimators.md
feature_columns.md
+datasets_for_estimators.md
checkpoints.md
### Accelerators
diff --git a/tensorflow/docs_src/programmers_guide/premade_estimators.md b/tensorflow/docs_src/programmers_guide/premade_estimators.md
index f6dd75eaca..02e2caf64b 100644
--- a/tensorflow/docs_src/programmers_guide/premade_estimators.md
+++ b/tensorflow/docs_src/programmers_guide/premade_estimators.md
@@ -81,7 +81,7 @@ We strongly recommend writing TensorFlow programs with the following APIs:
* @{$programmers_guide/estimators$Estimators}, which represent a complete model.
The Estimator API provides methods to train the model, to judge the model's
accuracy, and to generate predictions.
-* @{$get_started/datasets_quickstart$Datasets}, which build a data input
+* @{$programmers_guide/datasets_for_estimators}, which build a data input
pipeline. The Dataset API has methods to load and manipulate data, and feed
it into your model. The Dataset API meshes well with the Estimators API.
@@ -424,9 +424,7 @@ Now that you've gotten started writing TensorFlow programs, consider the
following material:
* @{$checkpoints$Checkpoints} to learn how to save and restore models.
-* @{$get_started/datasets_quickstart$Datasets} to learn more about importing
- data into your
- model.
+* @{$programmers_guide/datasets_for_estimators} to learn more about importing
+ data into your model.
* @{$custom_estimators$Creating Custom Estimators} to learn how to
write your own Estimator, customized for a particular problem.
-
diff --git a/tensorflow/docs_src/tutorials/index.md b/tensorflow/docs_src/tutorials/index.md
index af01d3eaa1..6bd3a3a897 100644
--- a/tensorflow/docs_src/tutorials/index.md
+++ b/tensorflow/docs_src/tutorials/index.md
@@ -2,9 +2,8 @@
This section contains tutorials demonstrating how to do specific tasks
-in TensorFlow. If you are new to TensorFlow, we recommend reading the
-documents in the "@{$get_started$Get Started}" section before reading
-these tutorials.
+in TensorFlow. If you are new to TensorFlow, we recommend reading
+[Get Started with TensorFlow](/get_started/).
## Images
--
GitLab
From d9e006e80990e54913c25de70a1f8e7db2f22bc8 Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Wed, 20 Jun 2018 10:02:25 -0700
Subject: [PATCH 0049/1193] Fix eager path in get_started leftnav
PiperOrigin-RevId: 201370156
---
tensorflow/docs_src/get_started/leftnav_files | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/tensorflow/docs_src/get_started/leftnav_files b/tensorflow/docs_src/get_started/leftnav_files
index 9a60496cb5..5c400a67f0 100644
--- a/tensorflow/docs_src/get_started/leftnav_files
+++ b/tensorflow/docs_src/get_started/leftnav_files
@@ -7,4 +7,4 @@ save_and_restore_models.md
next_steps.md
### Research and experimentation
-custom_training_walkthrough.md
+eager.md
--
GitLab
From 4e0b1612e0a71b0e14da2bc37c49e3d65744342c Mon Sep 17 00:00:00 2001
From: Mark Daoust
Date: Fri, 22 Jun 2018 15:37:58 -0700
Subject: [PATCH 0050/1193] Add Install Raspbian to leftnav.
PiperOrigin-RevId: 201752380
---
tensorflow/docs_src/install/leftnav_files | 1 +
1 file changed, 1 insertion(+)
diff --git a/tensorflow/docs_src/install/leftnav_files b/tensorflow/docs_src/install/leftnav_files
index e523e06f67..ace275c0e8 100644
--- a/tensorflow/docs_src/install/leftnav_files
+++ b/tensorflow/docs_src/install/leftnav_files
@@ -4,6 +4,7 @@ index.md
install_linux.md: Ubuntu
install_mac.md: MacOS
install_windows.md: Windows
+install_raspbian.md: Raspbian
install_sources.md: From source
>>>
migration.md
--
GitLab
From 2897538b938dcd6d9c63a97f0870232ac9e4819e Mon Sep 17 00:00:00 2001
From: Mark Daoust
Date: Mon, 25 Jun 2018 12:48:40 -0700
Subject: [PATCH 0051/1193] Update r1.9 release notes.
- link to new get_started.
- Add keras CuDNN layers.
- Links for gradient boosted estimators.
- Added new contrib-estimators and string-processing.
- Bumped some minor sounding things down from "Major" to "Bugfix+Other"
---
RELEASE.md | 35 +++++++++++++++++++++++++++--------
1 file changed, 27 insertions(+), 8 deletions(-)
diff --git a/RELEASE.md b/RELEASE.md
index 510eca5467..bfe0da8739 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -1,18 +1,37 @@
# Release 1.9.0
## Major Features And Improvements
-* Update tf.keras to the Keras 2.1.6 API.
+* New `tf.keras` based [get_started](http://tensorflow.org/versions/r1.9/get_started)
+* Update `tf.keras` to the Keras 2.1.6 API.
+* Added [`tf.keras.layers.CuDNNGRU`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/keras/layers/CuDNNGRU) and [`tf.keras.layers.CuDNNLSTM`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/keras/layers/CuDNNLSTM) layers. [Try it](https://colab.sandbox.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb?linkId=53292082).
+* Adding support of core [feature columns](https://www.tensorflow.org/get_started/feature_columns) and [losses](https://www.tensorflow.org/api_docs/python/tf/losses) to [gradient boosted trees estimators](https://github.com/tensorflow/models/tree/master/official/boosted_trees).
+* The [python interface](https://tensorflow-dot-devsite.googleplex.com/versions/r1.9/api_docs/python/tf/contrib/lite)
+ for the [TFLite Optimizing Converter](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/toco/README.md)
+ has been expanded, and the command line interface (AKA: `toco`, `tflite_convert`) is once again
+ included in the standard `pip` installation.
+* Improved data-loading and text processing with:
+ * [`tf.decode_compressed`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/decode_compressed)
+ * [`tf.string_strip`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/string_strip)
+ * [`tf.strings.regex_full_match`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/strings/regex_full_match)
+* Added experimental support for new pre-made Estimators:
+ * [`tf.contrib.estimator.BaselineEstimator`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/contrib/estimator/BaselineEstimator)
+ * [`tf.contrib.estimator.RNNClassifier`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/contrib/estimator/RNNEstimator)
+ * [`tf.contrib.estimator.RNNEstimator`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/contrib/estimator/RNNClassifier)
+* The [distributions.Bijector](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/contrib/distributions/bijectors/Bijector)
+ API supports broadcasting for Bijectors with new API changes.
+
+## Breaking Chances
+ * If you're opening empty variable scopes; replace `variable_scope('', ...)` by
+ `variable_scope(tf.get_variable_scope(), ...)`.
+
+## Bug Fixes and Other Changes
+
* `tfe.Network` is deprecated. Please inherit from `tf.keras.Model`.
-* Adding support of core feature columns and losses to gradient boosted trees estimators.
-* The distributions.Bijector API supports broadcasting for Bijectors with new API changes. See [here](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/distributions/bijectors/Bijector) for more details.
* Layered variable names have changed in the following conditions:
* Using `tf.keras.layers` with custom variable scopes.
- * Using `tf.layers` in a subclassed `tf.keras.Model` class. See [here](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/layers) for more details
+ * Using `tf.layers` in a subclassed `tf.keras.Model` class. See
+ [here](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/layers) for more details
-## Breaking Chances
- * If you're opening empty variable scopes; replace `variable_scope`('', ...) by `variable_scope`(`tf.get_variable_scope()`, ...).
-
-## Bug Fixes and Other Changes
* `tf.data`:
* `Dataset.from_generator()` now accepts an `args` list, in order to create nested generators.
* `Dataset.list_files()` now produces determinstic results when `shuffle=False` or a `seed` is passed.
--
GitLab
From 56fba15b868145f87109bd5cb155527b0c0640d1 Mon Sep 17 00:00:00 2001
From: Mark Daoust
Date: Mon, 25 Jun 2018 13:16:52 -0700
Subject: [PATCH 0052/1193] Update RELEASE.md
---
RELEASE.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/RELEASE.md b/RELEASE.md
index bfe0da8739..f6a52a2951 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -1,7 +1,7 @@
# Release 1.9.0
## Major Features And Improvements
-* New `tf.keras` based [get_started](http://tensorflow.org/versions/r1.9/get_started)
+* New `tf.keras` based [get_started](http://tensorflow.org/versions/r1.9/get_started), and [programmers_guide](http://tensorflow.org/versions/r1.9/programmers_guide/keras).
* Update `tf.keras` to the Keras 2.1.6 API.
* Added [`tf.keras.layers.CuDNNGRU`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/keras/layers/CuDNNGRU) and [`tf.keras.layers.CuDNNLSTM`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/keras/layers/CuDNNLSTM) layers. [Try it](https://colab.sandbox.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb?linkId=53292082).
* Adding support of core [feature columns](https://www.tensorflow.org/get_started/feature_columns) and [losses](https://www.tensorflow.org/api_docs/python/tf/losses) to [gradient boosted trees estimators](https://github.com/tensorflow/models/tree/master/official/boosted_trees).
--
GitLab
From ce03a10d70884d2b6d8134b30ad3c5d181877403 Mon Sep 17 00:00:00 2001
From: Mark Daoust
Date: Mon, 25 Jun 2018 13:22:14 -0700
Subject: [PATCH 0053/1193] Update RELEASE.md
---
RELEASE.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/RELEASE.md b/RELEASE.md
index f6a52a2951..5c79ebec34 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -1,7 +1,8 @@
# Release 1.9.0
## Major Features And Improvements
-* New `tf.keras` based [get_started](http://tensorflow.org/versions/r1.9/get_started), and [programmers_guide](http://tensorflow.org/versions/r1.9/programmers_guide/keras).
+* Updated docs for `tf.keras`: New Keras-based [get started](http://tensorflow.org/versions/r1.9/get_started),
+ and [programmers guide page](http://tensorflow.org/versions/r1.9/programmers_guide/keras).
* Update `tf.keras` to the Keras 2.1.6 API.
* Added [`tf.keras.layers.CuDNNGRU`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/keras/layers/CuDNNGRU) and [`tf.keras.layers.CuDNNLSTM`](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/keras/layers/CuDNNLSTM) layers. [Try it](https://colab.sandbox.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb?linkId=53292082).
* Adding support of core [feature columns](https://www.tensorflow.org/get_started/feature_columns) and [losses](https://www.tensorflow.org/api_docs/python/tf/losses) to [gradient boosted trees estimators](https://github.com/tensorflow/models/tree/master/official/boosted_trees).
--
GitLab
From b0f2eee339a041de4e7837b68a9ff4fc77ca7c4a Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Fri, 22 Jun 2018 17:40:27 -0700
Subject: [PATCH 0054/1193] Rename programmers_guide/ directory to guide/.
Update references in source files and docs in tensorflow and related
projects.
PiperOrigin-RevId: 201766994
---
README.md | 2 +-
RELEASE.md | 6 ++--
tensorflow/contrib/autograph/README.md | 2 +-
tensorflow/contrib/data/__init__.py | 2 +-
tensorflow/contrib/eager/README.md | 2 +-
.../examples/notebooks/3_datasets.ipynb | 6 ++--
.../contrib/eager/python/g3doc/guide.md | 4 +--
tensorflow/contrib/lite/toco/README.md | 2 +-
.../contrib/tpu/python/tpu/tpu_estimator.py | 2 +-
tensorflow/core/protobuf/config.proto | 6 ++--
.../docs_src/api_guides/python/client.md | 2 +-
.../api_guides/python/input_dataset.md | 3 +-
.../api_guides/python/reading_data.md | 8 ++---
tensorflow/docs_src/deploy/distributed.md | 2 +-
tensorflow/docs_src/extend/architecture.md | 5 ++-
tensorflow/docs_src/get_started/_index.yaml | 12 +++----
tensorflow/docs_src/get_started/next_steps.md | 4 +--
.../checkpoints.md | 8 ++---
.../custom_estimators.md | 0
.../{programmers_guide => guide}/datasets.md | 0
.../datasets_for_estimators.md | 8 ++---
.../{programmers_guide => guide}/debugger.md | 0
.../{programmers_guide => guide}/eager.md | 0
.../{programmers_guide => guide}/embedding.md | 0
.../estimators.md | 2 +-
.../{programmers_guide => guide}/faq.md | 0
.../feature_columns.md | 2 +-
.../{programmers_guide => guide}/graph_viz.md | 0
.../{programmers_guide => guide}/graphs.md | 2 +-
.../{programmers_guide => guide}/index.md | 34 +++++++++----------
.../{programmers_guide => guide}/keras.md | 28 +++++++--------
.../leftnav_files | 0
.../low_level_intro.md | 2 +-
.../premade_estimators.md | 8 ++---
.../saved_model.md | 4 +--
.../summaries_and_tensorboard.md | 0
.../tensorboard_histograms.md | 0
.../{programmers_guide => guide}/tensors.md | 4 +--
.../{programmers_guide => guide}/using_gpu.md | 0
.../{programmers_guide => guide}/using_tpu.md | 4 +--
.../{programmers_guide => guide}/variables.md | 0
.../version_compat.md | 0
tensorflow/docs_src/install/install_go.md | 2 +-
tensorflow/docs_src/install/install_java.md | 2 +-
tensorflow/docs_src/tutorials/deep_cnn.md | 2 +-
tensorflow/docs_src/tutorials/layers.md | 2 +-
.../reading_data/fully_connected_reader.py | 2 +-
tensorflow/java/README.md | 5 ++-
.../java/org/tensorflow/package-info.java | 2 +-
tensorflow/python/data/__init__.py | 2 +-
tensorflow/python/data/ops/dataset_ops.py | 14 ++++++++
tensorflow/python/debug/BUILD | 2 +-
tensorflow/python/debug/README.md | 4 +--
tensorflow/python/debug/examples/README.md | 4 +--
tensorflow/python/estimator/keras.py | 2 +-
tensorflow/python/ops/script_ops.py | 2 +-
tensorflow/python/tools/saved_model_cli.py | 4 +--
third_party/examples/eager/spinn/README.md | 2 +-
58 files changed, 119 insertions(+), 110 deletions(-)
rename tensorflow/docs_src/{programmers_guide => guide}/checkpoints.md (96%)
rename tensorflow/docs_src/{programmers_guide => guide}/custom_estimators.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/datasets.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/datasets_for_estimators.md (97%)
rename tensorflow/docs_src/{programmers_guide => guide}/debugger.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/eager.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/embedding.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/estimators.md (99%)
rename tensorflow/docs_src/{programmers_guide => guide}/faq.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/feature_columns.md (99%)
rename tensorflow/docs_src/{programmers_guide => guide}/graph_viz.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/graphs.md (99%)
rename tensorflow/docs_src/{programmers_guide => guide}/index.md (72%)
rename tensorflow/docs_src/{programmers_guide => guide}/keras.md (95%)
rename tensorflow/docs_src/{programmers_guide => guide}/leftnav_files (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/low_level_intro.md (99%)
rename tensorflow/docs_src/{programmers_guide => guide}/premade_estimators.md (98%)
rename tensorflow/docs_src/{programmers_guide => guide}/saved_model.md (99%)
rename tensorflow/docs_src/{programmers_guide => guide}/summaries_and_tensorboard.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/tensorboard_histograms.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/tensors.md (98%)
rename tensorflow/docs_src/{programmers_guide => guide}/using_gpu.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/using_tpu.md (98%)
rename tensorflow/docs_src/{programmers_guide => guide}/variables.md (100%)
rename tensorflow/docs_src/{programmers_guide => guide}/version_compat.md (100%)
diff --git a/README.md b/README.md
index 6fb4486d0d..4e4d139bd1 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ data flow graphs. The graph nodes represent mathematical operations, while
the graph edges represent the multidimensional data arrays (tensors) that flow
between them. This flexible architecture enables you to deploy computation to one
or more CPUs or GPUs in a desktop, server, or mobile device without rewriting
-code. TensorFlow also includes [TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard), a data visualization toolkit.
+code. TensorFlow also includes [TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard), a data visualization toolkit.
TensorFlow was originally developed by researchers and engineers
working on the Google Brain team within Google's Machine Intelligence Research
diff --git a/RELEASE.md b/RELEASE.md
index 510eca5467..5fec61af7e 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -467,7 +467,7 @@ answered questions, and were part of inspiring discussions.
## Major Features And Improvements
* `tf.keras` is now part of the core TensorFlow API.
-* [`tf.data`](http://tensorflow.org/programmers_guide/datasets) is now part of
+* [`tf.data`](http://tensorflow.org/guide/datasets) is now part of
the core TensorFlow API.
* The API is now subject to backwards compatibility guarantees.
@@ -495,7 +495,7 @@ answered questions, and were part of inspiring discussions.
* TensorFlow Debugger (tfdbg):
* Add `eval` command to allow evaluation of arbitrary Python/numpy expressions
in tfdbg command-line interface. See
- [Debugging TensorFlow Programs](https://www.tensorflow.org/programmers_guide/debugger)
+ [Debugging TensorFlow Programs](https://www.tensorflow.org/guide/debugger)
for more details.
* Usability improvement: The frequently used tensor filter `has_inf_or_nan` is
now added to `Session` wrappers and hooks by default. So there is no need
@@ -782,7 +782,7 @@ answered questions, and were part of inspiring discussions.
* Support client-provided ClusterSpec's and propagate them to all workers to enable the creation of dynamic TensorFlow clusters.
* TensorFlow C library now available for Windows.
* We released a new open-source version of TensorBoard.
-* [`SavedModel CLI`](https://www.tensorflow.org/versions/master/programmers_guide/saved_model_cli) tool available to inspect and execute MetaGraph in SavedModel
+* [`SavedModel CLI`](https://www.tensorflow.org/versions/master/guide/saved_model_cli) tool available to inspect and execute MetaGraph in SavedModel
* Android releases of TensorFlow are now pushed to jcenter for easier
integration into apps. See
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/android/README.md
diff --git a/tensorflow/contrib/autograph/README.md b/tensorflow/contrib/autograph/README.md
index 674859bed4..47b1d4a99a 100644
--- a/tensorflow/contrib/autograph/README.md
+++ b/tensorflow/contrib/autograph/README.md
@@ -4,7 +4,7 @@ IMPORTANT: AutoGraph is alpha software, and under active development. Expect rou
AutoGraph is a Python to TensorFlow compiler.
-With AutoGraph, you can write [Eager style](https://www.tensorflow.org/programmers_guide/eager) code in a concise manner, and run it as a TensorFlow graph. AutoGraph uses source code transformation and partial evaluation to generate Python code that builds an equivalent TensorFlow subgraph. The result is code that behaves like ops and can be freely combined with other TensorFlow ops.
+With AutoGraph, you can write [Eager style](https://www.tensorflow.org/guide/eager) code in a concise manner, and run it as a TensorFlow graph. AutoGraph uses source code transformation and partial evaluation to generate Python code that builds an equivalent TensorFlow subgraph. The result is code that behaves like ops and can be freely combined with other TensorFlow ops.
For example, this Python function:
diff --git a/tensorflow/contrib/data/__init__.py b/tensorflow/contrib/data/__init__.py
index 9c6a13333e..3510e7b1ad 100644
--- a/tensorflow/contrib/data/__init__.py
+++ b/tensorflow/contrib/data/__init__.py
@@ -20,7 +20,7 @@ be used in conjunction with the @{tf.data.Dataset} API. Note that the
guarantees as `tf.data`, but we will provide deprecation advice in advance of
removing existing functionality.
-See the @{$datasets$Importing Data} Programmer's Guide for an overview.
+See @{$guide/datasets$Importing Data} for an overview.
@@Counter
@@CheckpointInputPipelineHook
diff --git a/tensorflow/contrib/eager/README.md b/tensorflow/contrib/eager/README.md
index 4384431e7b..86d203452e 100644
--- a/tensorflow/contrib/eager/README.md
+++ b/tensorflow/contrib/eager/README.md
@@ -44,7 +44,7 @@ Installation instructions at https://www.tensorflow.org/install/
For an introduction to eager execution in TensorFlow, see:
-- [User Guide](https://www.tensorflow.org/programmers_guide/eager) ([source](../../docs_src/programmers_guide/eager.md))
+- [User Guide](https://www.tensorflow.org/guide/eager) ([source](../../docs_src/guide/eager.md))
- Notebook: [Basic Usage](python/examples/notebooks/1_basics.ipynb)
- Notebook: [Gradients](python/examples/notebooks/2_gradients.ipynb)
- Notebook: [Importing Data](python/examples/notebooks/3_datasets.ipynb)
diff --git a/tensorflow/contrib/eager/python/examples/notebooks/3_datasets.ipynb b/tensorflow/contrib/eager/python/examples/notebooks/3_datasets.ipynb
index bfcc7feb07..d268cbcd91 100644
--- a/tensorflow/contrib/eager/python/examples/notebooks/3_datasets.ipynb
+++ b/tensorflow/contrib/eager/python/examples/notebooks/3_datasets.ipynb
@@ -9,7 +9,7 @@
"source": [
"# Eager Execution Tutorial: Importing Data\n",
"\n",
- "This notebook demonstrates the use of the [`tf.data.Dataset` API](https://www.tensorflow.org/programmers_guide/datasets) to build pipelines to feed data to your program. It covers:\n",
+ "This notebook demonstrates the use of the [`tf.data.Dataset` API](https://www.tensorflow.org/guide/datasets) to build pipelines to feed data to your program. It covers:\n",
"\n",
"* Creating a `Dataset`.\n",
"* Iteration over a `Dataset` with eager execution enabled.\n",
@@ -18,7 +18,7 @@
"\n",
"If you're familiar with TensorFlow graphs, the API for constructing the `Dataset` object remains exactly the same when eager execution is enabled, but the process of iterating over elements of the dataset is slightly simpler.\n",
"You can use Python iteration over the `tf.data.Dataset` object and do not need to explicitly create an `tf.data.Iterator` object.\n",
- "As a result, the discussion on iterators in the [Programmer's Guide](https://www.tensorflow.org/programmers_guide/datasets) is not relevant when eager execution is enabled."
+ "As a result, the discussion on iterators in the [TensorFlow Guide](https://www.tensorflow.org/guide/datasets) is not relevant when eager execution is enabled."
]
},
{
@@ -63,7 +63,7 @@
"source": [
"# Step 1: Create a source `Dataset`\n",
"\n",
- "Create a _source_ dataset using one of the factory functions like [`Dataset.from_tensors`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensors), [`Dataset.from_tensor_slices`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices) or using objects that read from files like [`TextLineDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) or [`TFRecordDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset). See the [Programmer's Guide](https://www.google.com/url?sa=D\u0026q=https%3A%2F%2Fwww.tensorflow.org%2Fprogrammers_guide%2Fdatasets%23reading_input_data) for more information."
+ "Create a _source_ dataset using one of the factory functions like [`Dataset.from_tensors`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensors), [`Dataset.from_tensor_slices`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices) or using objects that read from files like [`TextLineDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) or [`TFRecordDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset). See the [TensorFlow Guide](https://www.tensorflow.org/guide/datasets#reading_input_data) for more information."
]
},
{
diff --git a/tensorflow/contrib/eager/python/g3doc/guide.md b/tensorflow/contrib/eager/python/g3doc/guide.md
index 2d2aba6908..23f33d0230 100644
--- a/tensorflow/contrib/eager/python/g3doc/guide.md
+++ b/tensorflow/contrib/eager/python/g3doc/guide.md
@@ -4,8 +4,8 @@ Eager execution is a feature that makes TensorFlow execute operations
immediately: concrete values are returned, instead of creating a computational
graph that is executed later.
-A user guide is available: https://www.tensorflow.org/programmers_guide/eager
-([source file](../../../../docs_src/programmers_guide/eager.md))
+A user guide is available: https://www.tensorflow.org/guide/eager
+([source file](../../../../docs_src/guide/eager.md))
We welcome feedback through [GitHub issues](https://github.com/tensorflow/tensorflow/labels/comp:eager).
diff --git a/tensorflow/contrib/lite/toco/README.md b/tensorflow/contrib/lite/toco/README.md
index 522e260ad2..ee83c7a6e3 100644
--- a/tensorflow/contrib/lite/toco/README.md
+++ b/tensorflow/contrib/lite/toco/README.md
@@ -17,7 +17,7 @@ Usage information is given in these documents:
Once an application developer has a trained TensorFlow model, TOCO will accept
that model and generate a TensorFlow Lite
[FlatBuffer](https://google.github.io/flatbuffers/) file. TOCO currently supports
-[SavedModels](https://www.tensorflow.org/programmers_guide/saved_model#using_savedmodel_with_estimators)
+[SavedModels](https://www.tensorflow.org/guide/saved_model#using_savedmodel_with_estimators)
and frozen graphs (models generated via
[freeze_graph.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py)).
The TensorFlow Lite FlatBuffer file can be shipped to client devices, generally
diff --git a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
index 7c770912b4..c57acd0a2d 100644
--- a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
+++ b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
@@ -1103,7 +1103,7 @@ class _InputPipeline(object):
err_msg = ('Input pipeline contains one or more QueueRunners. '
'It could be slow and not scalable. Please consider '
'converting your input pipeline to use `tf.data` instead (see '
- 'https://www.tensorflow.org/programmers_guide/datasets for '
+ 'https://www.tensorflow.org/guide/datasets for '
'instructions.')
if _WRAP_INPUT_FN_INTO_WHILE_LOOP:
raise RuntimeError(err_msg)
diff --git a/tensorflow/core/protobuf/config.proto b/tensorflow/core/protobuf/config.proto
index 9a48f43a63..d83215d5c2 100644
--- a/tensorflow/core/protobuf/config.proto
+++ b/tensorflow/core/protobuf/config.proto
@@ -147,7 +147,7 @@ message GPUOptions {
// Everything inside experimental is subject to change and is not subject
// to API stability guarantees in
- // https://www.tensorflow.org/programmers_guide/version_compat.
+ // https://www.tensorflow.org/guide/version_compat.
Experimental experimental = 9;
};
@@ -381,7 +381,7 @@ message ConfigProto {
// Everything inside Experimental is subject to change and is not subject
// to API stability guarantees in
- // https://www.tensorflow.org/programmers_guide/version_compat.
+ // https://www.tensorflow.org/guide/version_compat.
message Experimental {
// Task name for group resolution.
string collective_group_leader = 1;
@@ -426,7 +426,7 @@ message RunOptions {
// Everything inside Experimental is subject to change and is not subject
// to API stability guarantees in
- // https://www.tensorflow.org/programmers_guide/version_compat.
+ // https://www.tensorflow.org/guide/version_compat.
message Experimental {
// If non-zero, declares that this graph is going to use collective
// ops and must synchronize step_ids with any other graph with this
diff --git a/tensorflow/docs_src/api_guides/python/client.md b/tensorflow/docs_src/api_guides/python/client.md
index eef23696db..27fc8610bf 100644
--- a/tensorflow/docs_src/api_guides/python/client.md
+++ b/tensorflow/docs_src/api_guides/python/client.md
@@ -3,7 +3,7 @@
This library contains classes for launching graphs and executing operations.
-@{$programmers_guide/low_level_intro$This guide} has examples of how a graph
+@{$guide/low_level_intro$This guide} has examples of how a graph
is launched in a @{tf.Session}.
## Session management
diff --git a/tensorflow/docs_src/api_guides/python/input_dataset.md b/tensorflow/docs_src/api_guides/python/input_dataset.md
index a6e2fc48e0..a6612d1bf7 100644
--- a/tensorflow/docs_src/api_guides/python/input_dataset.md
+++ b/tensorflow/docs_src/api_guides/python/input_dataset.md
@@ -2,8 +2,7 @@
[TOC]
@{tf.data.Dataset} allows you to build complex input pipelines. See the
-@{$datasets$programmer's guide} for an in-depth explanation of how to use this
-API.
+@{$guide/datasets} for an in-depth explanation of how to use this API.
## Reader classes
diff --git a/tensorflow/docs_src/api_guides/python/reading_data.md b/tensorflow/docs_src/api_guides/python/reading_data.md
index 5bbbfd3216..d7d0904ae2 100644
--- a/tensorflow/docs_src/api_guides/python/reading_data.md
+++ b/tensorflow/docs_src/api_guides/python/reading_data.md
@@ -16,8 +16,8 @@ There are four methods of getting data into a TensorFlow program:
## `tf.data` API
-See the @{$datasets$programmer's guide} for an in-depth explanation of
-@{tf.data.Dataset}. The `tf.data` API enables you to extract and preprocess data
+See the @{$guide/datasets} for an in-depth explanation of @{tf.data.Dataset}.
+The `tf.data` API enables you to extract and preprocess data
from different input/file formats, and apply transformations such as batching,
shuffling, and mapping functions over the dataset. This is an improved version
of the old input methods---feeding and `QueueRunner`---which are described
@@ -511,8 +511,8 @@ You can have the train and eval in the same graph in the same process, and share
their trained variables or layers. See @{$variables$the shared variables tutorial}.
To support the single-graph approach
-@{$programmers_guide/datasets$`tf.data`} also supplies
-@{$programmers_guide/datasets#creating_an_iterator$advanced iterator types} that
+@{$guide/datasets$`tf.data`} also supplies
+@{$guide/datasets#creating_an_iterator$advanced iterator types} that
that allow the user to change the input pipeline without rebuilding the graph or
session.
diff --git a/tensorflow/docs_src/deploy/distributed.md b/tensorflow/docs_src/deploy/distributed.md
index d7ed6b1deb..8e2c818e39 100644
--- a/tensorflow/docs_src/deploy/distributed.md
+++ b/tensorflow/docs_src/deploy/distributed.md
@@ -2,7 +2,7 @@
This document shows how to create a cluster of TensorFlow servers, and how to
distribute a computation graph across that cluster. We assume that you are
-familiar with the @{$programmers_guide/low_level_intro$basic concepts} of
+familiar with the @{$guide/low_level_intro$basic concepts} of
writing low level TensorFlow programs.
## Hello distributed TensorFlow!
diff --git a/tensorflow/docs_src/extend/architecture.md b/tensorflow/docs_src/extend/architecture.md
index c8f522a03a..84435a57f2 100644
--- a/tensorflow/docs_src/extend/architecture.md
+++ b/tensorflow/docs_src/extend/architecture.md
@@ -7,9 +7,8 @@ learning models and system-level optimizations.
This document describes the system architecture that makes this
combination of scale and flexibility possible. It assumes that you have basic familiarity
with TensorFlow programming concepts such as the computation graph, operations,
-and sessions. See @{$programmers_guide/low_level_intro$this document}
-for an introduction to these topics. Some familiarity
-with @{$distributed$distributed TensorFlow}
+and sessions. See @{$guide/low_level_intro$this document} for an introduction to
+these topics. Some familiarity with @{$distributed$distributed TensorFlow}
will also be helpful.
This document is for developers who want to extend TensorFlow in some way not
diff --git a/tensorflow/docs_src/get_started/_index.yaml b/tensorflow/docs_src/get_started/_index.yaml
index af255a482d..277fc852fb 100644
--- a/tensorflow/docs_src/get_started/_index.yaml
+++ b/tensorflow/docs_src/get_started/_index.yaml
@@ -74,7 +74,7 @@ landing_page:
The high-level Keras API provides building blocks to create and
train deep learning models. Start with these beginner-friendly
notebook examples, then read the
- TensorFlow Keras guide.
+ TensorFlow Keras guide.
- Basic classification
@@ -85,7 +85,7 @@ landing_page:
- classname: tfo-landing-row-item-code-block
@@ -123,7 +123,7 @@ landing_page:
Eager execution provides an imperative, define-by-run interface for advanced operations. Write custom layers, forward passes, and training loops with auto‑differentiation. Start with
- these notebooks, then read the eager execution guide.
+ these notebooks, then read the eager execution guide.
-
@@ -165,7 +165,7 @@ landing_page:
- custom_html: >
@@ -177,7 +177,7 @@ landing_page:
Estimators can train large models on multiple machines in a
production environment. Try the examples below and read the
- Estimators guide.
+ Estimators guide.
- How to build a simple text classifier with TF-Hub
@@ -186,7 +186,7 @@ landing_page:
diff --git a/tensorflow/docs_src/get_started/next_steps.md b/tensorflow/docs_src/get_started/next_steps.md
index 79c0ef3346..6318a39c6c 100644
--- a/tensorflow/docs_src/get_started/next_steps.md
+++ b/tensorflow/docs_src/get_started/next_steps.md
@@ -2,9 +2,9 @@
## Learn more about TensorFlow
-* The [TensorFlow Guide](/programmers_guide) includes usage guides for the
+* The [TensorFlow Guide](/guide) includes usage guides for the
high-level APIs, as well as advanced TensorFlow operations.
-* [Premade Estimators](/programmers_guide/premade_estimators) are designed to
+* [Premade Estimators](/guide/premade_estimators) are designed to
get results out of the box. Use TensorFlow without building your own models.
* [TensorFlow.js](https://js.tensorflow.org/) allows web developers to train and
deploy ML models in the browser and using Node.js.
diff --git a/tensorflow/docs_src/programmers_guide/checkpoints.md b/tensorflow/docs_src/guide/checkpoints.md
similarity index 96%
rename from tensorflow/docs_src/programmers_guide/checkpoints.md
rename to tensorflow/docs_src/guide/checkpoints.md
index 8dfd91e3c8..dfb2626b86 100644
--- a/tensorflow/docs_src/programmers_guide/checkpoints.md
+++ b/tensorflow/docs_src/guide/checkpoints.md
@@ -8,9 +8,8 @@ Estimators. TensorFlow provides two model formats:
* SavedModel, which is a format independent of the code that created
the model.
-This document focuses on checkpoints. For details on SavedModel, see the
-@{$saved_model$Saving and Restoring} chapter of the
-*TensorFlow Programmer's Guide*.
+This document focuses on checkpoints. For details on `SavedModel`, see the
+@{$saved_model$Saving and Restoring} guide.
## Sample code
@@ -232,8 +231,7 @@ This separation will keep your checkpoints recoverable.
Checkpoints provide an easy automatic mechanism for saving and restoring
models created by Estimators.
-See the @{$saved_model$Saving and Restoring}
-chapter of the *TensorFlow Programmer's Guide* for details on:
+See the @{$saved_model$Saving and Restoring} guide for details about:
* Saving and restoring models using low-level TensorFlow APIs.
* Exporting and importing models in the SavedModel format, which is a
diff --git a/tensorflow/docs_src/programmers_guide/custom_estimators.md b/tensorflow/docs_src/guide/custom_estimators.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/custom_estimators.md
rename to tensorflow/docs_src/guide/custom_estimators.md
diff --git a/tensorflow/docs_src/programmers_guide/datasets.md b/tensorflow/docs_src/guide/datasets.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/datasets.md
rename to tensorflow/docs_src/guide/datasets.md
diff --git a/tensorflow/docs_src/programmers_guide/datasets_for_estimators.md b/tensorflow/docs_src/guide/datasets_for_estimators.md
similarity index 97%
rename from tensorflow/docs_src/programmers_guide/datasets_for_estimators.md
rename to tensorflow/docs_src/guide/datasets_for_estimators.md
index 345a31b985..b04af78cd8 100644
--- a/tensorflow/docs_src/programmers_guide/datasets_for_estimators.md
+++ b/tensorflow/docs_src/guide/datasets_for_estimators.md
@@ -91,8 +91,8 @@ print(mnist_ds)
```
This will print the following line, showing the
-@{$programmers_guide/tensors#shapes$shapes} and
-@{$programmers_guide/tensors#data_types$types} of the items in
+@{$guide/tensors#shapes$shapes} and
+@{$guide/tensors#data_types$types} of the items in
the dataset. Note that a `Dataset` does not know how many items it contains.
``` None
@@ -128,7 +128,7 @@ print(dataset)
Here we see that when a `Dataset` contains structured elements, the `shapes`
and `types` of the `Dataset` take on the same structure. This dataset contains
-dictionaries of @{$programmers_guide/tensors#rank$scalars}, all of type
+dictionaries of @{$guide/tensors#rank$scalars}, all of type
`tf.float64`.
The first line of the iris `train_input_fn` uses the same functionality, but
@@ -382,6 +382,6 @@ Estimator. Consider the following documents next:
* The @{$low_level_intro#datasets$Low Level Introduction}, which demonstrates
how to experiment directly with `tf.data.Datasets` using TensorFlow's low
level APIs.
-* @{$programmers_guide/datasets} which goes into great detail about additional
+* @{$guide/datasets} which goes into great detail about additional
functionality of `Datasets`.
diff --git a/tensorflow/docs_src/programmers_guide/debugger.md b/tensorflow/docs_src/guide/debugger.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/debugger.md
rename to tensorflow/docs_src/guide/debugger.md
diff --git a/tensorflow/docs_src/programmers_guide/eager.md b/tensorflow/docs_src/guide/eager.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/eager.md
rename to tensorflow/docs_src/guide/eager.md
diff --git a/tensorflow/docs_src/programmers_guide/embedding.md b/tensorflow/docs_src/guide/embedding.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/embedding.md
rename to tensorflow/docs_src/guide/embedding.md
diff --git a/tensorflow/docs_src/programmers_guide/estimators.md b/tensorflow/docs_src/guide/estimators.md
similarity index 99%
rename from tensorflow/docs_src/programmers_guide/estimators.md
rename to tensorflow/docs_src/guide/estimators.md
index b13b47184d..78b30c3040 100644
--- a/tensorflow/docs_src/programmers_guide/estimators.md
+++ b/tensorflow/docs_src/guide/estimators.md
@@ -81,7 +81,7 @@ of the following four steps:
... # manipulate dataset, extracting the feature dict and the label
return feature_dict, label
- (See @{$programmers_guide/datasets} for full details.)
+ (See @{$guide/datasets} for full details.)
2. **Define the feature columns.** Each @{tf.feature_column}
identifies a feature name, its type, and any input pre-processing.
diff --git a/tensorflow/docs_src/programmers_guide/faq.md b/tensorflow/docs_src/guide/faq.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/faq.md
rename to tensorflow/docs_src/guide/faq.md
diff --git a/tensorflow/docs_src/programmers_guide/feature_columns.md b/tensorflow/docs_src/guide/feature_columns.md
similarity index 99%
rename from tensorflow/docs_src/programmers_guide/feature_columns.md
rename to tensorflow/docs_src/guide/feature_columns.md
index 90f5c53a17..1013ec910c 100644
--- a/tensorflow/docs_src/programmers_guide/feature_columns.md
+++ b/tensorflow/docs_src/guide/feature_columns.md
@@ -534,7 +534,7 @@ embedding_column = tf.feature_column.embedding_column(
dimension=embedding_dimensions)
```
-@{$programmers_guide/embedding$Embeddings} is a significant topic within machine
+@{$guide/embedding$Embeddings} is a significant topic within machine
learning. This information was just to get you started using them as feature
columns.
diff --git a/tensorflow/docs_src/programmers_guide/graph_viz.md b/tensorflow/docs_src/guide/graph_viz.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/graph_viz.md
rename to tensorflow/docs_src/guide/graph_viz.md
diff --git a/tensorflow/docs_src/programmers_guide/graphs.md b/tensorflow/docs_src/guide/graphs.md
similarity index 99%
rename from tensorflow/docs_src/programmers_guide/graphs.md
rename to tensorflow/docs_src/guide/graphs.md
index f0dd8def17..e6246ef148 100644
--- a/tensorflow/docs_src/programmers_guide/graphs.md
+++ b/tensorflow/docs_src/guide/graphs.md
@@ -93,7 +93,7 @@ to all API functions in the same context. For example:
stored value. The @{tf.Variable} object also has methods such as
@{tf.Variable.assign$`assign`} and @{tf.Variable.assign_add$`assign_add`} that
create @{tf.Operation} objects that, when executed, update the stored value.
- (See @{$programmers_guide/variables} for more information about variables.)
+ (See @{$guide/variables} for more information about variables.)
* Calling @{tf.train.Optimizer.minimize} will add operations and tensors to the
default graph that calculates gradients, and return a @{tf.Operation} that,
diff --git a/tensorflow/docs_src/programmers_guide/index.md b/tensorflow/docs_src/guide/index.md
similarity index 72%
rename from tensorflow/docs_src/programmers_guide/index.md
rename to tensorflow/docs_src/guide/index.md
index 9c58a3b45e..eefdb9ceae 100644
--- a/tensorflow/docs_src/programmers_guide/index.md
+++ b/tensorflow/docs_src/guide/index.md
@@ -1,17 +1,17 @@
-# Programmer's Guide
+# TensorFlow Guide
The documents in this unit dive into the details of how TensorFlow
works. The units are as follows:
## High Level APIs
- * @{$programmers_guide/keras}, TensorFlow's high-level API for building and
+ * @{$guide/keras}, TensorFlow's high-level API for building and
training deep learning models.
- * @{$programmers_guide/eager}, an API for writing TensorFlow code
+ * @{$guide/eager}, an API for writing TensorFlow code
imperatively, like you would use Numpy.
- * @{$programmers_guide/estimators}, a high-level API that provides
+ * @{$guide/estimators}, a high-level API that provides
fully-packaged models ready for large-scale training and production.
- * @{$programmers_guide/datasets}, easy input pipelines to bring your data into
+ * @{$guide/datasets}, easy input pipelines to bring your data into
your TensorFlow program.
## Estimators
@@ -34,13 +34,13 @@ works. The units are as follows:
## Low Level APIs
- * @{$programmers_guide/low_level_intro}, which introduces the
+ * @{$guide/low_level_intro}, which introduces the
basics of how you can use TensorFlow outside of the high Level APIs.
- * @{$programmers_guide/tensors}, which explains how to create,
+ * @{$guide/tensors}, which explains how to create,
manipulate, and access Tensors--the fundamental object in TensorFlow.
- * @{$programmers_guide/variables}, which details how
+ * @{$guide/variables}, which details how
to represent shared, persistent state in your program.
- * @{$programmers_guide/graphs}, which explains:
+ * @{$guide/graphs}, which explains:
* dataflow graphs, which are TensorFlow's representation of computations
as dependencies between operations.
* sessions, which are TensorFlow's mechanism for running dataflow graphs
@@ -50,19 +50,19 @@ works. The units are as follows:
such as Estimators or Keras, the high-level API creates and manages
graphs and sessions for you, but understanding graphs and sessions
can still be helpful.
- * @{$programmers_guide/saved_model}, which
+ * @{$guide/saved_model}, which
explains how to save and restore variables and models.
## ML Concepts
- * @{$programmers_guide/embedding}, which introduces the concept
+ * @{$guide/embedding}, which introduces the concept
of embeddings, provides a simple example of training an embedding in
TensorFlow, and explains how to view embeddings with the TensorBoard
Embedding Projector.
## Debugging
- * @{$programmers_guide/debugger}, which
+ * @{$guide/debugger}, which
explains how to use the TensorFlow debugger (tfdbg).
## TensorBoard
@@ -70,17 +70,17 @@ works. The units are as follows:
TensorBoard is a utility to visualize different aspects of machine learning.
The following guides explain how to use TensorBoard:
- * @{$programmers_guide/summaries_and_tensorboard},
+ * @{$guide/summaries_and_tensorboard},
which introduces TensorBoard.
- * @{$programmers_guide/graph_viz}, which
+ * @{$guide/graph_viz}, which
explains how to visualize the computational graph.
- * @{$programmers_guide/tensorboard_histograms} which demonstrates the how to
+ * @{$guide/tensorboard_histograms} which demonstrates the how to
use TensorBoard's histogram dashboard.
## Misc
- * @{$programmers_guide/version_compat},
+ * @{$guide/version_compat},
which explains backward compatibility guarantees and non-guarantees.
- * @{$programmers_guide/faq}, which contains frequently asked
+ * @{$guide/faq}, which contains frequently asked
questions about TensorFlow.
diff --git a/tensorflow/docs_src/programmers_guide/keras.md b/tensorflow/docs_src/guide/keras.md
similarity index 95%
rename from tensorflow/docs_src/programmers_guide/keras.md
rename to tensorflow/docs_src/guide/keras.md
index c6aca7ebf4..83172dab7f 100644
--- a/tensorflow/docs_src/programmers_guide/keras.md
+++ b/tensorflow/docs_src/guide/keras.md
@@ -19,7 +19,7 @@ fast prototyping, advanced research, and production, with three key advantages:
[Keras API specification](https://keras.io){:.external}. This is a high-level
API to build and train models that includes first-class support for
TensorFlow-specific functionality, such as [eager execution](#eager_execution),
-`tf.data` pipelines, and [Estimators](/programmers_guide/estimators).
+`tf.data` pipelines, and [Estimators](./estimators.md).
`tf.keras` makes TensorFlow easier to use without sacrificing flexibility and
performance.
@@ -35,8 +35,8 @@ from tensorflow import keras
* The `tf.keras` version in the latest TensorFlow release might not be the same
as the latest `keras` version from PyPI. Check `tf.keras.__version__`.
* When [saving a model's weights](#weights_only), `tf.keras` defaults to the
- [checkpoint format](/get_started/checkpoints). Pass `save_format='h5'` to use
- HDF5.
+ [checkpoint format](../get_started/checkpoints.md). Pass `save_format='h5'` to
+ use HDF5.
## Build a simple model
@@ -179,7 +179,7 @@ model.fit(data, labels, epochs=10, batch_size=32,
### Input tf.data datasets
-Use the [Datasets API](/programmers_guide/datasets) to scale to large datasets
+Use the [Datasets API](./datasets.md) to scale to large datasets
or multi-device training. Pass a `tf.data.Dataset` instance to the `fit`
method:
@@ -285,7 +285,7 @@ your own forward pass. Create layers in the `__init__` method and set them as
attributes of the class instance. Define the forward pass in the `call` method.
Model subclassing is particularly useful when
-[eager execution](/programmers_guide/eager) is enabled since the forward pass
+[eager execution](./eager.md) is enabled since the forward pass
can be written imperatively.
Key Point: Use the right API for the job. While model subclassing offers
@@ -410,7 +410,7 @@ during training. You can write your own custom callback, or use the built-in
* `tf.keras.callbacks.EarlyStopping`: Interrupt training when validation
performance has stopped improving.
* `tf.keras.callbacks.TensorBoard`: Monitor the model's behavior using
- [TensorBoard](/programmers_guide/summaries_and_tensorboard).
+ [TensorBoard](./summaries_and_tensorboard.md).
To use a `tf.keras.callbacks.Callback`, pass it to the model's `fit` method:
@@ -442,8 +442,8 @@ model.load_weights('my_model')
```
By default, this saves the model's weights in the
-[TensorFlow checkpoint](/get_started/checkpoints) file format. Weights can also
-be saved to the Keras HDF5 format (the default for the multi-backend
+[TensorFlow checkpoint](../get_started/checkpoints.md) file format. Weights can
+also be saved to the Keras HDF5 format (the default for the multi-backend
implementation of Keras):
```python
@@ -509,7 +509,7 @@ model = keras.models.load_model('my_model.h5')
## Eager execution
-[Eager execution](/programmers_guide/eager) is an imperative programming
+[Eager execution](./eager.md) is an imperative programming
environment that evaluates operations immediately. This is not required for
Keras, but is supported by `tf.keras` and useful for inspecting your program and
debugging.
@@ -520,7 +520,7 @@ especially benefits *model subclassing* and building *custom layers*—the APIs
that require you to write the forward pass as code (instead of the APIs that
create models by assembling existing layers).
-See the [eager execution guide](/programmers_guide/eager#build_a_model) for
+See the [eager execution guide](./eager.md#build_a_model) for
examples of using Keras models with custom training loops and `tf.GradientTape`.
@@ -528,14 +528,14 @@ examples of using Keras models with custom training loops and `tf.GradientTape`.
### Estimators
-The [Estimators](/programmers_guide/estimators) API is used for training models
+The [Estimators](./estimators.md) API is used for training models
for distributed environments. This targets industry use cases such as
distributed training on large datasets that can export a model for production.
A `tf.keras.Model` can be trained with the `tf.estimator` API by converting the
model to an `tf.estimator.Estimator` object with
`tf.keras.estimator.model_to_estimator`. See
-[Creating Estimators from Keras models](/programmers_guide/estimators#creating_estimators_from_keras_models).
+[Creating Estimators from Keras models](./estimators.md#creating_estimators_from_keras_models).
```python
model = keras.Sequential([layers.Dense(10,activation='softmax'),
@@ -548,8 +548,8 @@ model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
estimator = keras.estimator.model_to_estimator(model)
```
-Note: Enable [eager execution](/programmers_guide/eager) for debugging
-[Estimator input functions](/programmers_guide/premade_estimators#create_input_functions)
+Note: Enable [eager execution](./eager.md) for debugging
+[Estimator input functions](./premade_estimators.md#create_input_functions)
and inspecting data.
### Multiple GPUs
diff --git a/tensorflow/docs_src/programmers_guide/leftnav_files b/tensorflow/docs_src/guide/leftnav_files
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/leftnav_files
rename to tensorflow/docs_src/guide/leftnav_files
diff --git a/tensorflow/docs_src/programmers_guide/low_level_intro.md b/tensorflow/docs_src/guide/low_level_intro.md
similarity index 99%
rename from tensorflow/docs_src/programmers_guide/low_level_intro.md
rename to tensorflow/docs_src/guide/low_level_intro.md
index 478e2bb70b..665a5568b4 100644
--- a/tensorflow/docs_src/programmers_guide/low_level_intro.md
+++ b/tensorflow/docs_src/guide/low_level_intro.md
@@ -303,7 +303,7 @@ while True:
break
```
-For more details on Datasets and Iterators see: @{$programmers_guide/datasets}.
+For more details on Datasets and Iterators see: @{$guide/datasets}.
## Layers
diff --git a/tensorflow/docs_src/programmers_guide/premade_estimators.md b/tensorflow/docs_src/guide/premade_estimators.md
similarity index 98%
rename from tensorflow/docs_src/programmers_guide/premade_estimators.md
rename to tensorflow/docs_src/guide/premade_estimators.md
index 02e2caf64b..3e910c1fe2 100644
--- a/tensorflow/docs_src/programmers_guide/premade_estimators.md
+++ b/tensorflow/docs_src/guide/premade_estimators.md
@@ -78,10 +78,10 @@ provides a programming stack consisting of multiple API layers:
We strongly recommend writing TensorFlow programs with the following APIs:
-* @{$programmers_guide/estimators$Estimators}, which represent a complete model.
+* @{$guide/estimators$Estimators}, which represent a complete model.
The Estimator API provides methods to train the model, to judge the model's
accuracy, and to generate predictions.
-* @{$programmers_guide/datasets_for_estimators}, which build a data input
+* @{$guide/datasets_for_estimators}, which build a data input
pipeline. The Dataset API has methods to load and manipulate data, and feed
it into your model. The Dataset API meshes well with the Estimators API.
@@ -173,7 +173,7 @@ example is an Iris Versicolor.
An Estimator is TensorFlow's high-level representation of a complete model. It
handles the details of initialization, logging, saving and restoring, and many
other features so you can concentrate on your model. For more details see
-@{$programmers_guide/estimators}.
+@{$guide/estimators}.
An Estimator is any class derived from @{tf.estimator.Estimator}. TensorFlow
provides a collection of
@@ -424,7 +424,7 @@ Now that you've gotten started writing TensorFlow programs, consider the
following material:
* @{$checkpoints$Checkpoints} to learn how to save and restore models.
-* @{$programmers_guide/datasets_for_estimators} to learn more about importing
+* @{$guide/datasets_for_estimators} to learn more about importing
data into your model.
* @{$custom_estimators$Creating Custom Estimators} to learn how to
write your own Estimator, customized for a particular problem.
diff --git a/tensorflow/docs_src/programmers_guide/saved_model.md b/tensorflow/docs_src/guide/saved_model.md
similarity index 99%
rename from tensorflow/docs_src/programmers_guide/saved_model.md
rename to tensorflow/docs_src/guide/saved_model.md
index c6ef87c54a..27ef7bb0da 100644
--- a/tensorflow/docs_src/programmers_guide/saved_model.md
+++ b/tensorflow/docs_src/guide/saved_model.md
@@ -3,7 +3,7 @@
The @{tf.train.Saver} class provides methods to save and restore models. The
@{tf.saved_model.simple_save} function is an easy way to build a
@{tf.saved_model$saved model} suitable for serving.
-[Estimators](@{$programmers_guide/estimators}) automatically save and restore
+[Estimators](@{$guide/estimators}) automatically save and restore
variables in the `model_dir`.
## Save and restore variables
@@ -299,7 +299,7 @@ following:
added attributes with defaults don't cause older model consumers to fail
loading models regenerated with newer training binaries.
-See [compatibility guidance](https://www.tensorflow.org/programmers_guide/version_compat)
+See [compatibility guidance](./version_compat.md)
for more information.
### Loading a SavedModel in Python
diff --git a/tensorflow/docs_src/programmers_guide/summaries_and_tensorboard.md b/tensorflow/docs_src/guide/summaries_and_tensorboard.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/summaries_and_tensorboard.md
rename to tensorflow/docs_src/guide/summaries_and_tensorboard.md
diff --git a/tensorflow/docs_src/programmers_guide/tensorboard_histograms.md b/tensorflow/docs_src/guide/tensorboard_histograms.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/tensorboard_histograms.md
rename to tensorflow/docs_src/guide/tensorboard_histograms.md
diff --git a/tensorflow/docs_src/programmers_guide/tensors.md b/tensorflow/docs_src/guide/tensors.md
similarity index 98%
rename from tensorflow/docs_src/programmers_guide/tensors.md
rename to tensorflow/docs_src/guide/tensors.md
index 1248c3cabe..7227260f1a 100644
--- a/tensorflow/docs_src/programmers_guide/tensors.md
+++ b/tensorflow/docs_src/guide/tensors.md
@@ -26,7 +26,7 @@ some cases it's only possible to find the shape of a tensor at graph execution
time.
Some types of tensors are special, and these will be covered in other
-units of the Programmer's guide. The main ones are:
+units of the TensorFlow guide. The main ones are:
* `tf.Variable`
* `tf.constant`
@@ -230,7 +230,7 @@ yet_another = tf.reshape(matrixAlt, [13, 2, -1]) # ERROR!
## Data types
In addition to dimensionality, Tensors have a data type. Refer to the
-`tf.DataType` page in the programmer's guide for a full list of the data types.
+`tf.DType` page for a complete list of the data types.
It is not possible to have a `tf.Tensor` with more than one data type. It is
possible, however, to serialize arbitrary data structures as `string`s and store
diff --git a/tensorflow/docs_src/programmers_guide/using_gpu.md b/tensorflow/docs_src/guide/using_gpu.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/using_gpu.md
rename to tensorflow/docs_src/guide/using_gpu.md
diff --git a/tensorflow/docs_src/programmers_guide/using_tpu.md b/tensorflow/docs_src/guide/using_tpu.md
similarity index 98%
rename from tensorflow/docs_src/programmers_guide/using_tpu.md
rename to tensorflow/docs_src/guide/using_tpu.md
index 44aabf0557..41d80d9d60 100644
--- a/tensorflow/docs_src/programmers_guide/using_tpu.md
+++ b/tensorflow/docs_src/guide/using_tpu.md
@@ -171,7 +171,7 @@ This section details the changes you must make to the model function
During regular usage TensorFlow attempts to determine the shapes of each
`tf.Tensor` during graph construction. During execution any unknown shape
dimensions are determined dynamically,
-see @{$programmers_guide/tensors#shape$Tensor Shapes} for more details.
+see @{$guide/tensors#shape$Tensor Shapes} for more details.
To run on Cloud TPUs TensorFlow models are compiled using @{$xla$XLA}.
XLA uses a similar system for determining shapes at compile time. XLA requires
@@ -195,7 +195,7 @@ TPU.
Build your evaluation metrics dictionary in a stand-alone `metric_fn`.
-
+
Evaluation metrics are an essential part of training a model. These are fully
supported on Cloud TPUs, but with a slightly different syntax.
diff --git a/tensorflow/docs_src/programmers_guide/variables.md b/tensorflow/docs_src/guide/variables.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/variables.md
rename to tensorflow/docs_src/guide/variables.md
diff --git a/tensorflow/docs_src/programmers_guide/version_compat.md b/tensorflow/docs_src/guide/version_compat.md
similarity index 100%
rename from tensorflow/docs_src/programmers_guide/version_compat.md
rename to tensorflow/docs_src/guide/version_compat.md
diff --git a/tensorflow/docs_src/install/install_go.md b/tensorflow/docs_src/install/install_go.md
index 1c03dd223e..5451e1b319 100644
--- a/tensorflow/docs_src/install/install_go.md
+++ b/tensorflow/docs_src/install/install_go.md
@@ -6,7 +6,7 @@ a Go application. This guide explains how to install and set up the
[TensorFlow Go package](https://godoc.org/github.com/tensorflow/tensorflow/tensorflow/go).
Warning: The TensorFlow Go API is *not* covered by the TensorFlow
-[API stability guarantees](https://www.tensorflow.org/programmers_guide/version_semantics).
+[API stability guarantees](../guide/version_semantics.md).
## Supported Platforms
diff --git a/tensorflow/docs_src/install/install_java.md b/tensorflow/docs_src/install/install_java.md
index c73e2f4281..ad3544b595 100644
--- a/tensorflow/docs_src/install/install_java.md
+++ b/tensorflow/docs_src/install/install_java.md
@@ -7,7 +7,7 @@ Java application. This guide explains how to install
and use it in a Java application.
Warning: The TensorFlow Java API is *not* covered by the TensorFlow
-[API stability guarantees](https://www.tensorflow.org/programmers_guide/version_semantics).
+[API stability guarantees](../guide/version_semantics.md).
## Supported Platforms
diff --git a/tensorflow/docs_src/tutorials/deep_cnn.md b/tensorflow/docs_src/tutorials/deep_cnn.md
index 6a4c9a9b07..44a32d9d1d 100644
--- a/tensorflow/docs_src/tutorials/deep_cnn.md
+++ b/tensorflow/docs_src/tutorials/deep_cnn.md
@@ -268,7 +268,7 @@ in `cifar10_input.py`.
`cifar10_train.py` periodically @{tf.train.Saver$saves}
all model parameters in
-@{$programmers_guide/saved_model$checkpoint files}
+@{$guide/saved_model$checkpoint files}
but it does *not* evaluate the model. The checkpoint file
will be used by `cifar10_eval.py` to measure the predictive
performance (see [Evaluating a Model](#evaluating-a-model) below).
diff --git a/tensorflow/docs_src/tutorials/layers.md b/tensorflow/docs_src/tutorials/layers.md
index 0f17899dae..212e337637 100644
--- a/tensorflow/docs_src/tutorials/layers.md
+++ b/tensorflow/docs_src/tutorials/layers.md
@@ -627,7 +627,7 @@ operation earlier when we generated the probabilities in `cnn_model_fn`.
> argument, TensorFlow will assign a default name. A couple easy ways to
> discover the names applied to operations are to visualize your graph on
> @{$graph_viz$TensorBoard}) or to enable the
-> @{$programmers_guide/debugger$TensorFlow Debugger (tfdbg)}.
+> @{$guide/debugger$TensorFlow Debugger (tfdbg)}.
Next, we create the `LoggingTensorHook`, passing `tensors_to_log` to the
`tensors` argument. We set `every_n_iter=50`, which specifies that probabilities
diff --git a/tensorflow/examples/how_tos/reading_data/fully_connected_reader.py b/tensorflow/examples/how_tos/reading_data/fully_connected_reader.py
index 307eede5c0..7402247448 100644
--- a/tensorflow/examples/how_tos/reading_data/fully_connected_reader.py
+++ b/tensorflow/examples/how_tos/reading_data/fully_connected_reader.py
@@ -17,7 +17,7 @@
This version is like fully_connected_feed.py but uses data converted
to a TFRecords file containing tf.train.Example protocol buffers.
See:
-https://www.tensorflow.org/programmers_guide/reading_data#reading_from_files
+https://www.tensorflow.org/guide/reading_data#reading_from_files
for context.
YOU MUST run convert_to_records before running this (but you only need to
diff --git a/tensorflow/java/README.md b/tensorflow/java/README.md
index 2f1ce253b2..c7382ff231 100644
--- a/tensorflow/java/README.md
+++ b/tensorflow/java/README.md
@@ -1,7 +1,7 @@
# TensorFlow for Java
> *WARNING*: The TensorFlow Java API is not currently covered by the TensorFlow
-> [API stability guarantees](https://www.tensorflow.org/programmers_guide/version_semantics).
+> [API stability guarantees](https://www.tensorflow.org/guide/version_semantics).
>
> For using TensorFlow on Android refer instead to
> [contrib/android](https://www.tensorflow.org/code/tensorflow/contrib/android),
@@ -23,8 +23,7 @@ native libraries will need to be built from source.
2. Setup the environment to build TensorFlow from source code
([Linux](https://www.tensorflow.org/install/install_sources#PrepareLinux)
- or [Mac OS
- X](https://www.tensorflow.org/install/install_sources#PrepareMac)).
+ or [macOS](https://www.tensorflow.org/install/install_sources#PrepareMac)).
If you'd like to skip reading those details and do not care about GPU
support, try the following:
diff --git a/tensorflow/java/src/main/java/org/tensorflow/package-info.java b/tensorflow/java/src/main/java/org/tensorflow/package-info.java
index 521c5c610c..f353ee3145 100644
--- a/tensorflow/java/src/main/java/org/tensorflow/package-info.java
+++ b/tensorflow/java/src/main/java/org/tensorflow/package-info.java
@@ -17,7 +17,7 @@ limitations under the License.
* Defines classes to build, save, load and execute TensorFlow models.
*
* WARNING: The API is currently experimental and is not covered by TensorFlow API stability
+ * href="https://www.tensorflow.org/guide/version_semantics">API stability
* guarantees. See README.md for installation
* instructions.
diff --git a/tensorflow/python/data/__init__.py b/tensorflow/python/data/__init__.py
index 7efe0948e7..3b9bf2469e 100644
--- a/tensorflow/python/data/__init__.py
+++ b/tensorflow/python/data/__init__.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""`tf.data.Dataset` API for input pipelines.
-See the @{$datasets$Importing Data} Programmer's Guide for an overview.
+See @{$guide/datasets$Importing Data} for an overview.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/data/ops/dataset_ops.py b/tensorflow/python/data/ops/dataset_ops.py
index 6f9b12b123..0e020d86d0 100644
--- a/tensorflow/python/data/ops/dataset_ops.py
+++ b/tensorflow/python/data/ops/dataset_ops.py
@@ -212,6 +212,13 @@ class Dataset(object):
def from_tensors(tensors):
"""Creates a `Dataset` with a single element, comprising the given tensors.
+ Note that if `tensors` contains a NumPy array, and eager execution is not
+ enabled, the values will be embedded in the graph as one or more
+ @{tf.constant} operations. For large datasets (> 1 GB), this can waste
+ memory and run into byte limits of graph serialization. If tensors contains
+ one or more large NumPy arrays, consider the alternative described in
+ @{$guide/datasets#consuming_numpy_arrays$this guide}.
+
Args:
tensors: A nested structure of tensors.
@@ -224,6 +231,13 @@ class Dataset(object):
def from_tensor_slices(tensors):
"""Creates a `Dataset` whose elements are slices of the given tensors.
+ Note that if `tensors` contains a NumPy array, and eager execution is not
+ enabled, the values will be embedded in the graph as one or more
+ @{tf.constant} operations. For large datasets (> 1 GB), this can waste
+ memory and run into byte limits of graph serialization. If tensors contains
+ one or more large NumPy arrays, consider the alternative described in
+ @{$guide/datasets#consuming_numpy_arrays$this guide}.
+
Args:
tensors: A nested structure of tensors, each having the same size in the
0th dimension.
diff --git a/tensorflow/python/debug/BUILD b/tensorflow/python/debug/BUILD
index 09062abd74..2d261f9be7 100644
--- a/tensorflow/python/debug/BUILD
+++ b/tensorflow/python/debug/BUILD
@@ -5,7 +5,7 @@
#
# ":debug_py": Public Python methods and classes of tfdbg.
# For API documentation, see https://www.tensorflow.org/api_docs/python/tfdbg
-# For a user interface walkthrough, see https://www.tensorflow.org/programmers_guide/debugger
+# For a user interface walkthrough, see https://www.tensorflow.org/guide/debugger
# ":grpc_debug_server": Server interface for grpc:// debug URLs.
package(
diff --git a/tensorflow/python/debug/README.md b/tensorflow/python/debug/README.md
index 269bbb19bd..9c16af4d79 100644
--- a/tensorflow/python/debug/README.md
+++ b/tensorflow/python/debug/README.md
@@ -28,7 +28,7 @@ models:
* Easy access through session wrappers
* Easy integration with common high-level APIs, such as
- [TensorFlow Estimators](https://www.tensorflow.org/programmers_guide/estimators) and
+ [TensorFlow Estimators](https://www.tensorflow.org/guide/estimators) and
[Keras](https://keras.io/)
* Inspection of runtime tensor values and node connections
* Conditional breaking after runs that generate tensors satisfying given
@@ -43,7 +43,7 @@ models:
## How to use TFDBG?
-* For a walkthrough of TFDBG command-line interface, see https://www.tensorflow.org/programmers_guide/debugger.
+* For a walkthrough of TFDBG command-line interface, see https://www.tensorflow.org/guide/debugger.
* For information on the web GUI of TFDBG (TensorBoard Debugger Plugin), see
[this README](https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/debugger/README.md).
* For programmatic use of the API of TFDBG, see https://www.tensorflow.org/api_docs/python/tfdbg.
diff --git a/tensorflow/python/debug/examples/README.md b/tensorflow/python/debug/examples/README.md
index cb4d484092..3b431e04dc 100644
--- a/tensorflow/python/debug/examples/README.md
+++ b/tensorflow/python/debug/examples/README.md
@@ -3,7 +3,7 @@ Hi, there!
The documentation of **TensorFlow Debugger (tfdbg)** has moved.
See the source version at
-[this new location](../../../docs_src/programmers_guide/debugger.md).
+[this new location](../../../docs_src/guide/debugger.md).
See the public website version at
-[https://www.tensorflow.org/programmers_guide/debugger](https://www.tensorflow.org/programmers_guide/debugger).
+[https://www.tensorflow.org/guide/debugger](https://www.tensorflow.org/guide/debugger).
diff --git a/tensorflow/python/estimator/keras.py b/tensorflow/python/estimator/keras.py
index 2f439f765e..6856b8b5a9 100644
--- a/tensorflow/python/estimator/keras.py
+++ b/tensorflow/python/estimator/keras.py
@@ -455,7 +455,7 @@ def model_to_estimator(keras_model=None,
"""Constructs an `Estimator` instance from given keras model.
For usage example, please see
- @{$programmers_guide/estimators$creating_estimators_from_keras_models}.
+ @{$guide/estimators$creating_estimators_from_keras_models}.
Args:
keras_model: A compiled Keras model object. This argument is mutually
diff --git a/tensorflow/python/ops/script_ops.py b/tensorflow/python/ops/script_ops.py
index 16c73213d5..f8df9b2c78 100644
--- a/tensorflow/python/ops/script_ops.py
+++ b/tensorflow/python/ops/script_ops.py
@@ -267,7 +267,7 @@ def eager_py_func(func, inp, Tout, name=None):
or print statements as desired, and wrap those functions in
`tf.contrib.eager.py_func`.
- For more information on eager execution, see @{$programmers_guide/eager}.
+ For more information on eager execution, see @{$guide/eager}.
`tf.contrib.eager.py_func` is similar in spirit to @{tf.py_func}, but unlike
the latter, the former lets you use TensorFlow operations in the wrapped
diff --git a/tensorflow/python/tools/saved_model_cli.py b/tensorflow/python/tools/saved_model_cli.py
index 5b9d25d449..38fed5335e 100644
--- a/tensorflow/python/tools/saved_model_cli.py
+++ b/tensorflow/python/tools/saved_model_cli.py
@@ -15,7 +15,7 @@
"""Command-line interface to inspect and execute a graph in a SavedModel.
For detailed usages and examples, please refer to:
-https://www.tensorflow.org/programmers_guide/saved_model_cli
+https://www.tensorflow.org/guide/saved_model_cli
"""
@@ -720,7 +720,7 @@ def create_parser():
'\'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]\' \\\n'
' --outdir=/out\n\n'
'For more information about input file format, please see:\n'
- 'https://www.tensorflow.org/programmers_guide/saved_model_cli\n')
+ 'https://www.tensorflow.org/guide/saved_model_cli\n')
parser_run = subparsers.add_parser(
'run', description=run_msg, formatter_class=argparse.RawTextHelpFormatter)
parser_run.add_argument(
diff --git a/third_party/examples/eager/spinn/README.md b/third_party/examples/eager/spinn/README.md
index fbb1fde837..e2fd8009a0 100644
--- a/third_party/examples/eager/spinn/README.md
+++ b/third_party/examples/eager/spinn/README.md
@@ -22,7 +22,7 @@ Other eager execution examples can be found under [tensorflow/contrib/eager/pyth
- [`data.py`](../../../../tensorflow/contrib/eager/python/examples/spinn/data.py): Pipeline for loading and preprocessing the
[SNLI](https://nlp.stanford.edu/projects/snli/) data and
[GloVe](https://nlp.stanford.edu/projects/glove/) word embedding, written
- using the [`tf.data`](https://www.tensorflow.org/programmers_guide/datasets)
+ using the [`tf.data`](https://www.tensorflow.org/guide/datasets)
API.
- [`spinn.py`](./spinn.py): Model definition and training routines.
This example illustrates how one might perform the following actions with
--
GitLab
From ab60fbc1fcfc600b800ad12c9f76cfccc4fb7087 Mon Sep 17 00:00:00 2001
From: Pete Warden
Date: Tue, 26 Jun 2018 09:32:12 -0700
Subject: [PATCH 0055/1193] Fix for RPi OpenBLAS compile issues, by pinning to
known good version
---
.../ci_build/install/install_pi_python3_toolchain.sh | 8 ++++++++
tensorflow/tools/ci_build/pi/build_raspberry_pi.sh | 4 ++++
2 files changed, 12 insertions(+)
diff --git a/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh b/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh
index 9d8e3df3b5..4afb2f1534 100755
--- a/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh
+++ b/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh
@@ -27,3 +27,11 @@ curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
apt-get update
rm -rf /usr/local/bin/bazel
apt-get install -y bazel python3 python3-numpy python3-dev python3-pip
+
+# We're using Ubuntu 14.04 as our base image because that's needed by the Pi
+# cross-compilation chain, but that doesn't have built-in Python 3.5 support, so
+# install from a separate repository.
+apt-get install -y software-properties-common
+add-apt-repository ppa:fkrull/deadsnakes
+apt-get update
+apt-get install -y python3.5 python3.5-dev
diff --git a/tensorflow/tools/ci_build/pi/build_raspberry_pi.sh b/tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
index 4d1a30601e..5eff3e415d 100755
--- a/tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
+++ b/tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
@@ -65,6 +65,10 @@ OPENBLAS_SRC_PATH=/tmp/openblas_src/
sudo rm -rf ${OPENBLAS_SRC_PATH}
git clone https://github.com/xianyi/OpenBLAS ${OPENBLAS_SRC_PATH}
cd ${OPENBLAS_SRC_PATH}
+# The commit after this introduced Fortran compile issues. In theory they should
+# be solvable using NOFORTRAN=1 on the make command, but my initial tries didn't
+# work, so pinning to the last know good version.
+git checkout 5a6a2bed9aff0ba8a18651d5514d029c8cae336a
# If this path is changed, you'll also need to update
# cxx_builtin_include_directory in third_party/toolchains/cpus/arm/CROSSTOOL.tpl
OPENBLAS_INSTALL_PATH=/tmp/openblas_install/
--
GitLab
From fe374d31f38ba7fa84284b58d28c55dc0087f2b3 Mon Sep 17 00:00:00 2001
From: Pete Warden
Date: Tue, 26 Jun 2018 09:36:22 -0700
Subject: [PATCH 0056/1193] Removed Python 3.5 updates for RPi
---
.../ci_build/install/install_pi_python3_toolchain.sh | 8 --------
1 file changed, 8 deletions(-)
diff --git a/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh b/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh
index 4afb2f1534..9d8e3df3b5 100755
--- a/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh
+++ b/tensorflow/tools/ci_build/install/install_pi_python3_toolchain.sh
@@ -27,11 +27,3 @@ curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
apt-get update
rm -rf /usr/local/bin/bazel
apt-get install -y bazel python3 python3-numpy python3-dev python3-pip
-
-# We're using Ubuntu 14.04 as our base image because that's needed by the Pi
-# cross-compilation chain, but that doesn't have built-in Python 3.5 support, so
-# install from a separate repository.
-apt-get install -y software-properties-common
-add-apt-repository ppa:fkrull/deadsnakes
-apt-get update
-apt-get install -y python3.5 python3.5-dev
--
GitLab
From 8025ac34099ed1b38c3cf0c0f84244496b42fedb Mon Sep 17 00:00:00 2001
From: Michael Case
Date: Tue, 26 Jun 2018 13:05:25 -0700
Subject: [PATCH 0057/1193] Moving StatusOr from XLA to stream_executor.
PiperOrigin-RevId: 202179928
---
tensorflow/compiler/xla/BUILD | 17 +-
tensorflow/compiler/xla/service/gpu/BUILD | 1 +
.../xla/service/gpu/stream_executor_util.h | 1 +
tensorflow/compiler/xla/statusor.h | 286 +----------------
tensorflow/stream_executor/BUILD | 2 -
.../xla => stream_executor/lib}/statusor.cc | 8 +-
tensorflow/stream_executor/lib/statusor.h | 290 +++++++++++++++++-
.../lib}/statusor_internals.h | 15 +-
.../lib}/statusor_test.cc | 11 +-
9 files changed, 310 insertions(+), 321 deletions(-)
rename tensorflow/{compiler/xla => stream_executor/lib}/statusor.cc (89%)
rename tensorflow/{compiler/xla => stream_executor/lib}/statusor_internals.h (94%)
rename tensorflow/{compiler/xla => stream_executor/lib}/statusor_test.cc (99%)
diff --git a/tensorflow/compiler/xla/BUILD b/tensorflow/compiler/xla/BUILD
index c6deb959a5..afa8ce730b 100644
--- a/tensorflow/compiler/xla/BUILD
+++ b/tensorflow/compiler/xla/BUILD
@@ -143,30 +143,15 @@ cc_library(
cc_library(
name = "statusor",
- srcs = ["statusor.cc"],
hdrs = [
"statusor.h",
- "statusor_internals.h",
],
visibility = ["//visibility:public"],
deps = [
":status",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
- ],
-)
-
-tf_cc_test(
- name = "statusor_test",
- size = "small",
- srcs = ["statusor_test.cc"],
- deps = [
- ":statusor",
- ":test",
- ":types",
- "//tensorflow/core:lib",
- "//tensorflow/core:test",
- "//tensorflow/core:test_main",
+ "//tensorflow/stream_executor",
],
)
diff --git a/tensorflow/compiler/xla/service/gpu/BUILD b/tensorflow/compiler/xla/service/gpu/BUILD
index 68297ad4ae..fe597bfb45 100644
--- a/tensorflow/compiler/xla/service/gpu/BUILD
+++ b/tensorflow/compiler/xla/service/gpu/BUILD
@@ -727,6 +727,7 @@ cc_library(
hdrs = ["stream_executor_util.h"],
deps = [
"//tensorflow/compiler/xla:shape_util",
+ "//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/core:stream_executor_no_cuda",
],
diff --git a/tensorflow/compiler/xla/service/gpu/stream_executor_util.h b/tensorflow/compiler/xla/service/gpu/stream_executor_util.h
index 8218f4fd11..39a6a38d00 100644
--- a/tensorflow/compiler/xla/service/gpu/stream_executor_util.h
+++ b/tensorflow/compiler/xla/service/gpu/stream_executor_util.h
@@ -16,6 +16,7 @@ limitations under the License.
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_
+#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/stream_executor_no_cuda.h"
diff --git a/tensorflow/compiler/xla/statusor.h b/tensorflow/compiler/xla/statusor.h
index 0e1387c939..a32e2ad985 100644
--- a/tensorflow/compiler/xla/statusor.h
+++ b/tensorflow/compiler/xla/statusor.h
@@ -12,297 +12,17 @@ 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.
==============================================================================*/
-
-// StatusOr is the union of a Status object and a T object. StatusOr models
-// the concept of an object that is either a value, or an error Status
-// explaining why such a value is not present. To this end, StatusOr does not
-// allow its Status value to be Status::OK.
-//
-// The primary use-case for StatusOr is as the return value of a
-// function which may fail.
-//
-// Example client usage for a StatusOr, where T is not a pointer:
-//
-// StatusOr result = DoBigCalculationThatCouldFail();
-// if (result.ok()) {
-// float answer = result.ValueOrDie();
-// printf("Big calculation yielded: %f", answer);
-// } else {
-// LOG(ERROR) << result.status();
-// }
-//
-// Example client usage for a StatusOr:
-//
-// StatusOr result = FooFactory::MakeNewFoo(arg);
-// if (result.ok()) {
-// std::unique_ptr foo(result.ValueOrDie());
-// foo->DoSomethingCool();
-// } else {
-// LOG(ERROR) << result.status();
-// }
-//
-// Example client usage for a StatusOr>:
-//
-// StatusOr> result = FooFactory::MakeNewFoo(arg);
-// if (result.ok()) {
-// std::unique_ptr foo = std::move(result.ValueOrDie());
-// foo->DoSomethingCool();
-// } else {
-// LOG(ERROR) << result.status();
-// }
-//
-// Example factory implementation returning StatusOr:
-//
-// StatusOr FooFactory::MakeNewFoo(int arg) {
-// if (arg <= 0) {
-// return tensorflow::InvalidArgument("Arg must be positive");
-// } else {
-// return new Foo(arg);
-// }
-// }
-//
-// Note that the assignment operators require that destroying the currently
-// stored value cannot invalidate the argument; in other words, the argument
-// cannot be an alias for the current value, or anything owned by the current
-// value.
#ifndef TENSORFLOW_COMPILER_XLA_STATUSOR_H_
#define TENSORFLOW_COMPILER_XLA_STATUSOR_H_
#include "tensorflow/compiler/xla/status.h"
-#include "tensorflow/compiler/xla/statusor_internals.h"
-#include "tensorflow/core/platform/macros.h"
+#include "tensorflow/stream_executor/lib/statusor.h"
namespace xla {
-#if defined(__clang__)
-// Only clang supports warn_unused_result as a type annotation.
-template
-class TF_MUST_USE_RESULT StatusOr;
-#endif
-
-template
-class StatusOr : private internal_statusor::StatusOrData,
- private internal_statusor::TraitsBase<
- std::is_copy_constructible::value,
- std::is_move_constructible::value> {
- template
- friend class StatusOr;
-
- typedef internal_statusor::StatusOrData Base;
-
- public:
- typedef T element_type;
-
- // Constructs a new StatusOr with Status::UNKNOWN status. This is marked
- // 'explicit' to try to catch cases like 'return {};', where people think
- // StatusOr> will be initialized with an empty vector,
- // instead of a Status::UNKNOWN status.
- explicit StatusOr();
-
- // StatusOr will be copy constructible/assignable if T is copy
- // constructible.
- StatusOr(const StatusOr&) = default;
- StatusOr& operator=(const StatusOr&) = default;
-
- // StatusOr will be move constructible/assignable if T is move
- // constructible.
- StatusOr(StatusOr&&) = default;
- StatusOr& operator=(StatusOr&&) = default;
-
- // Conversion copy/move constructor, T must be convertible from U.
- template ::value>::type* = nullptr>
- StatusOr(const StatusOr& other);
- template ::value>::type* = nullptr>
- StatusOr(StatusOr&& other);
-
- // Conversion copy/move assignment operator, T must be convertible from U.
- template ::value>::type* = nullptr>
- StatusOr& operator=(const StatusOr& other);
- template ::value>::type* = nullptr>
- StatusOr& operator=(StatusOr&& other);
-
- // Constructs a new StatusOr with the given value. After calling this
- // constructor, calls to ValueOrDie() will succeed, and calls to status() will
- // return OK.
- //
- // NOTE: Not explicit - we want to use StatusOr as a return type
- // so it is convenient and sensible to be able to do 'return T()'
- // when the return type is StatusOr.
- //
- // REQUIRES: T is copy constructible.
- StatusOr(const T& value);
-
- // Constructs a new StatusOr with the given non-ok status. After calling
- // this constructor, calls to ValueOrDie() will CHECK-fail.
- //
- // NOTE: Not explicit - we want to use StatusOr as a return
- // value, so it is convenient and sensible to be able to do 'return
- // Status()' when the return type is StatusOr.
- //
- // REQUIRES: !status.ok(). This requirement is DCHECKed.
- // In optimized builds, passing Status::OK() here will have the effect
- // of passing tensorflow::error::INTERNAL as a fallback.
- StatusOr(const Status& status);
- StatusOr& operator=(const Status& status);
-
- // TODO(b/62186997): Add operator=(T) overloads.
-
- // Similar to the `const T&` overload.
- //
- // REQUIRES: T is move constructible.
- StatusOr(T&& value);
-
- // RValue versions of the operations declared above.
- StatusOr(Status&& status);
- StatusOr& operator=(Status&& status);
-
- // Returns this->status().ok()
- bool ok() const { return this->status_.ok(); }
-
- // Returns a reference to our status. If this contains a T, then
- // returns Status::OK().
- const Status& status() const &;
- Status status() &&;
-
- // Returns a reference to our current value, or CHECK-fails if !this->ok().
- //
- // Note: for value types that are cheap to copy, prefer simple code:
- //
- // T value = statusor.ValueOrDie();
- //
- // Otherwise, if the value type is expensive to copy, but can be left
- // in the StatusOr, simply assign to a reference:
- //
- // T& value = statusor.ValueOrDie(); // or `const T&`
- //
- // Otherwise, if the value type supports an efficient move, it can be
- // used as follows:
- //
- // T value = std::move(statusor).ValueOrDie();
- //
- // The std::move on statusor instead of on the whole expression enables
- // warnings about possible uses of the statusor object after the move.
- // C++ style guide waiver for ref-qualified overloads granted in cl/143176389
- // See go/ref-qualifiers for more details on such overloads.
- const T& ValueOrDie() const &;
- T& ValueOrDie() &;
- const T&& ValueOrDie() const &&;
- T&& ValueOrDie() &&;
-
- T ConsumeValueOrDie() { return std::move(ValueOrDie()); }
-
- // Ignores any errors. This method does nothing except potentially suppress
- // complaints from any tools that are checking that errors are not dropped on
- // the floor.
- void IgnoreError() const;
-};
-
-////////////////////////////////////////////////////////////////////////////////
-// Implementation details for StatusOr
-
-template
-StatusOr::StatusOr() : Base(Status(tensorflow::error::UNKNOWN, "")) {}
-
-template
-StatusOr::StatusOr(const T& value) : Base(value) {}
-
-template
-StatusOr::StatusOr(const Status& status) : Base(status) {}
-
-template
-StatusOr& StatusOr::operator=(const Status& status) {
- this->Assign(status);
- return *this;
-}
-
-template
-StatusOr::StatusOr(T&& value) : Base(std::move(value)) {}
-
-template
-StatusOr::StatusOr(Status&& status) : Base(std::move(status)) {}
-
-template
-StatusOr& StatusOr::operator=(Status&& status) {
- this->Assign(std::move(status));
- return *this;
-}
-
-template
-template ::value>::type*>
-inline StatusOr::StatusOr(const StatusOr& other)
- : Base(static_cast::Base&>(other)) {}
-
-template
-template ::value>::type*>
-inline StatusOr& StatusOr::operator=(const StatusOr& other) {
- if (other.ok())
- this->Assign(other.ValueOrDie());
- else
- this->Assign(other.status());
- return *this;
-}
-
-template
-template ::value>::type*>
-inline StatusOr::StatusOr(StatusOr&& other)
- : Base(static_cast::Base&&>(other)) {}
-
-template
-template ::value>::type*>
-inline StatusOr& StatusOr::operator=(StatusOr&& other) {
- if (other.ok()) {
- this->Assign(std::move(other).ValueOrDie());
- } else {
- this->Assign(std::move(other).status());
- }
- return *this;
-}
-
-template
-const Status& StatusOr::status() const & {
- return this->status_;
-}
-template
-Status StatusOr::status() && {
- return ok() ? Status::OK() : std::move(this->status_);
-}
-
-template
-const T& StatusOr::ValueOrDie() const & {
- this->EnsureOk();
- return this->data_;
-}
-
-template
-T& StatusOr::ValueOrDie() & {
- this->EnsureOk();
- return this->data_;
-}
-
-template
-const T&& StatusOr::ValueOrDie() const && {
- this->EnsureOk();
- return std::move(this->data_);
-}
-
-template
-T&& StatusOr::ValueOrDie() && {
- this->EnsureOk();
- return std::move(this->data_);
-}
-
+// Use steam_executor's StatusOr so we don't duplicate code.
template
-void StatusOr::IgnoreError() const {
- // no-op
-}
+using StatusOr = ::stream_executor::port::StatusOr;
} // namespace xla
diff --git a/tensorflow/stream_executor/BUILD b/tensorflow/stream_executor/BUILD
index c68cda0100..21295abed1 100644
--- a/tensorflow/stream_executor/BUILD
+++ b/tensorflow/stream_executor/BUILD
@@ -33,7 +33,6 @@ cc_library(
}),
visibility = ["//visibility:public"],
deps = [
- "//tensorflow/compiler/xla:statusor",
"//tensorflow/core:lib",
"//tensorflow/core:ptr_util",
"@local_config_cuda//cuda:cuda_headers",
@@ -48,7 +47,6 @@ cc_library(
deps = [
"//tensorflow/core:lib",
"//tensorflow/core:ptr_util",
- "//tensorflow/compiler/xla:statusor",
"@local_config_cuda//cuda:cuda_headers",
] + if_static([":stream_executor_impl"]),
)
diff --git a/tensorflow/compiler/xla/statusor.cc b/tensorflow/stream_executor/lib/statusor.cc
similarity index 89%
rename from tensorflow/compiler/xla/statusor.cc
rename to tensorflow/stream_executor/lib/statusor.cc
index 72ab67ff81..e0e851f96e 100644
--- a/tensorflow/compiler/xla/statusor.cc
+++ b/tensorflow/stream_executor/lib/statusor.cc
@@ -13,12 +13,13 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#include "tensorflow/compiler/xla/statusor.h"
+#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
-namespace xla {
+namespace stream_executor {
+namespace port {
namespace internal_statusor {
void Helper::HandleInvalidStatusCtorArg(Status* status) {
@@ -35,4 +36,5 @@ void Helper::Crash(const Status& status) {
}
} // namespace internal_statusor
-} // namespace xla
+} // namespace port
+} // namespace stream_executor
diff --git a/tensorflow/stream_executor/lib/statusor.h b/tensorflow/stream_executor/lib/statusor.h
index dab5909674..3c716acb46 100644
--- a/tensorflow/stream_executor/lib/statusor.h
+++ b/tensorflow/stream_executor/lib/statusor.h
@@ -1,4 +1,4 @@
-/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
+/* Copyright 2017 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.
@@ -13,19 +13,297 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-// IWYU pragma: private, include "third_party/tensorflow/stream_executor/stream_executor.h"
-
+// StatusOr is the union of a Status object and a T object. StatusOr models
+// the concept of an object that is either a value, or an error Status
+// explaining why such a value is not present. To this end, StatusOr does not
+// allow its Status value to be Status::OK.
+//
+// The primary use-case for StatusOr is as the return value of a
+// function which may fail.
+//
+// Example client usage for a StatusOr, where T is not a pointer:
+//
+// StatusOr result = DoBigCalculationThatCouldFail();
+// if (result.ok()) {
+// float answer = result.ValueOrDie();
+// printf("Big calculation yielded: %f", answer);
+// } else {
+// LOG(ERROR) << result.status();
+// }
+//
+// Example client usage for a StatusOr:
+//
+// StatusOr result = FooFactory::MakeNewFoo(arg);
+// if (result.ok()) {
+// std::unique_ptr foo(result.ValueOrDie());
+// foo->DoSomethingCool();
+// } else {
+// LOG(ERROR) << result.status();
+// }
+//
+// Example client usage for a StatusOr>:
+//
+// StatusOr> result = FooFactory::MakeNewFoo(arg);
+// if (result.ok()) {
+// std::unique_ptr foo = std::move(result.ValueOrDie());
+// foo->DoSomethingCool();
+// } else {
+// LOG(ERROR) << result.status();
+// }
+//
+// Example factory implementation returning StatusOr:
+//
+// StatusOr FooFactory::MakeNewFoo(int arg) {
+// if (arg <= 0) {
+// return tensorflow::InvalidArgument("Arg must be positive");
+// } else {
+// return new Foo(arg);
+// }
+// }
+//
+// Note that the assignment operators require that destroying the currently
+// stored value cannot invalidate the argument; in other words, the argument
+// cannot be an alias for the current value, or anything owned by the current
+// value.
#ifndef TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_H_
#define TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_H_
-#include "tensorflow/compiler/xla/statusor.h"
+#include "tensorflow/core/platform/macros.h"
+#include "tensorflow/stream_executor/lib/status.h"
+#include "tensorflow/stream_executor/lib/statusor_internals.h"
namespace stream_executor {
namespace port {
-// Use XLA's StatusOr so we don't duplicate code.
+#if defined(__clang__)
+// Only clang supports warn_unused_result as a type annotation.
+template
+class TF_MUST_USE_RESULT StatusOr;
+#endif
+
+template
+class StatusOr : private internal_statusor::StatusOrData,
+ private internal_statusor::TraitsBase<
+ std::is_copy_constructible::value,
+ std::is_move_constructible::value> {
+ template
+ friend class StatusOr;
+
+ typedef internal_statusor::StatusOrData Base;
+
+ public:
+ typedef T element_type;
+
+ // Constructs a new StatusOr with Status::UNKNOWN status. This is marked
+ // 'explicit' to try to catch cases like 'return {};', where people think
+ // StatusOr> will be initialized with an empty vector,
+ // instead of a Status::UNKNOWN status.
+ explicit StatusOr();
+
+ // StatusOr will be copy constructible/assignable if T is copy
+ // constructible.
+ StatusOr(const StatusOr&) = default;
+ StatusOr& operator=(const StatusOr&) = default;
+
+ // StatusOr will be move constructible/assignable if T is move
+ // constructible.
+ StatusOr(StatusOr&&) = default;
+ StatusOr& operator=(StatusOr&&) = default;
+
+ // Conversion copy/move constructor, T must be convertible from U.
+ template ::value>::type* = nullptr>
+ StatusOr(const StatusOr& other);
+ template ::value>::type* = nullptr>
+ StatusOr(StatusOr&& other);
+
+ // Conversion copy/move assignment operator, T must be convertible from U.
+ template ::value>::type* = nullptr>
+ StatusOr& operator=(const StatusOr& other);
+ template ::value>::type* = nullptr>
+ StatusOr& operator=(StatusOr&& other);
+
+ // Constructs a new StatusOr with the given value. After calling this
+ // constructor, calls to ValueOrDie() will succeed, and calls to status() will
+ // return OK.
+ //
+ // NOTE: Not explicit - we want to use StatusOr as a return type
+ // so it is convenient and sensible to be able to do 'return T()'
+ // when the return type is StatusOr.
+ //
+ // REQUIRES: T is copy constructible.
+ StatusOr(const T& value);
+
+ // Constructs a new StatusOr with the given non-ok status. After calling
+ // this constructor, calls to ValueOrDie() will CHECK-fail.
+ //
+ // NOTE: Not explicit - we want to use StatusOr as a return
+ // value, so it is convenient and sensible to be able to do 'return
+ // Status()' when the return type is StatusOr.
+ //
+ // REQUIRES: !status.ok(). This requirement is DCHECKed.
+ // In optimized builds, passing Status::OK() here will have the effect
+ // of passing tensorflow::error::INTERNAL as a fallback.
+ StatusOr(const Status& status);
+ StatusOr& operator=(const Status& status);
+
+ // TODO(b/62186997): Add operator=(T) overloads.
+
+ // Similar to the `const T&` overload.
+ //
+ // REQUIRES: T is move constructible.
+ StatusOr(T&& value);
+
+ // RValue versions of the operations declared above.
+ StatusOr(Status&& status);
+ StatusOr& operator=(Status&& status);
+
+ // Returns this->status().ok()
+ bool ok() const { return this->status_.ok(); }
+
+ // Returns a reference to our status. If this contains a T, then
+ // returns Status::OK().
+ const Status& status() const &;
+ Status status() &&;
+
+ // Returns a reference to our current value, or CHECK-fails if !this->ok().
+ //
+ // Note: for value types that are cheap to copy, prefer simple code:
+ //
+ // T value = statusor.ValueOrDie();
+ //
+ // Otherwise, if the value type is expensive to copy, but can be left
+ // in the StatusOr, simply assign to a reference:
+ //
+ // T& value = statusor.ValueOrDie(); // or `const T&`
+ //
+ // Otherwise, if the value type supports an efficient move, it can be
+ // used as follows:
+ //
+ // T value = std::move(statusor).ValueOrDie();
+ //
+ // The std::move on statusor instead of on the whole expression enables
+ // warnings about possible uses of the statusor object after the move.
+ // C++ style guide waiver for ref-qualified overloads granted in cl/143176389
+ // See go/ref-qualifiers for more details on such overloads.
+ const T& ValueOrDie() const &;
+ T& ValueOrDie() &;
+ const T&& ValueOrDie() const &&;
+ T&& ValueOrDie() &&;
+
+ T ConsumeValueOrDie() { return std::move(ValueOrDie()); }
+
+ // Ignores any errors. This method does nothing except potentially suppress
+ // complaints from any tools that are checking that errors are not dropped on
+ // the floor.
+ void IgnoreError() const;
+};
+
+////////////////////////////////////////////////////////////////////////////////
+// Implementation details for StatusOr
+
+template
+StatusOr::StatusOr() : Base(Status(tensorflow::error::UNKNOWN, "")) {}
+
+template
+StatusOr::StatusOr(const T& value) : Base(value) {}
+
+template
+StatusOr::StatusOr(const Status& status) : Base(status) {}
+
+template
+StatusOr& StatusOr::operator=(const Status& status) {
+ this->Assign(status);
+ return *this;
+}
+
+template
+StatusOr::StatusOr(T&& value) : Base(std::move(value)) {}
+
+template
+StatusOr::StatusOr(Status&& status) : Base(std::move(status)) {}
+
+template
+StatusOr& StatusOr::operator=(Status&& status) {
+ this->Assign(std::move(status));
+ return *this;
+}
+
+template
+template ::value>::type*>
+inline StatusOr::StatusOr(const StatusOr& other)
+ : Base(static_cast::Base&>(other)) {}
+
+template
+template ::value>::type*>
+inline StatusOr& StatusOr::operator=(const StatusOr& other) {
+ if (other.ok())
+ this->Assign(other.ValueOrDie());
+ else
+ this->Assign(other.status());
+ return *this;
+}
+
+template
+template ::value>::type*>
+inline StatusOr::StatusOr(StatusOr&& other)
+ : Base(static_cast::Base&&>(other)) {}
+
+template
+template ::value>::type*>
+inline StatusOr& StatusOr::operator=(StatusOr&& other) {
+ if (other.ok()) {
+ this->Assign(std::move(other).ValueOrDie());
+ } else {
+ this->Assign(std::move(other).status());
+ }
+ return *this;
+}
+
+template
+const Status& StatusOr::status() const & {
+ return this->status_;
+}
+template
+Status StatusOr::status() && {
+ return ok() ? Status::OK() : std::move(this->status_);
+}
+
+template
+const T& StatusOr::ValueOrDie() const & {
+ this->EnsureOk();
+ return this->data_;
+}
+
+template
+T& StatusOr::ValueOrDie() & {
+ this->EnsureOk();
+ return this->data_;
+}
+
+template
+const T&& StatusOr::ValueOrDie() const && {
+ this->EnsureOk();
+ return std::move(this->data_);
+}
+
+template
+T&& StatusOr::ValueOrDie() && {
+ this->EnsureOk();
+ return std::move(this->data_);
+}
+
template
-using StatusOr = ::xla::StatusOr;
+void StatusOr::IgnoreError() const {
+ // no-op
+}
} // namespace port
} // namespace stream_executor
diff --git a/tensorflow/compiler/xla/statusor_internals.h b/tensorflow/stream_executor/lib/statusor_internals.h
similarity index 94%
rename from tensorflow/compiler/xla/statusor_internals.h
rename to tensorflow/stream_executor/lib/statusor_internals.h
index 14636bd144..09f88f5825 100644
--- a/tensorflow/compiler/xla/statusor_internals.h
+++ b/tensorflow/stream_executor/lib/statusor_internals.h
@@ -13,13 +13,15 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_COMPILER_XLA_STATUSOR_INTERNALS_H_
-#define TENSORFLOW_COMPILER_XLA_STATUSOR_INTERNALS_H_
+#ifndef TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_INTERNALS_H_
+#define TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_INTERNALS_H_
+
-#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/core/platform/macros.h"
+#include "tensorflow/stream_executor/lib/status.h"
-namespace xla {
+namespace stream_executor {
+namespace port {
namespace internal_statusor {
class Helper {
@@ -240,6 +242,7 @@ struct TraitsBase {
};
} // namespace internal_statusor
-} // namespace xla
+} // namespace port
+} // namespace stream_executor
-#endif // TENSORFLOW_COMPILER_XLA_STATUSOR_INTERNALS_H_
+#endif // TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_INTERNALS_H_
diff --git a/tensorflow/compiler/xla/statusor_test.cc b/tensorflow/stream_executor/lib/statusor_test.cc
similarity index 99%
rename from tensorflow/compiler/xla/statusor_test.cc
rename to tensorflow/stream_executor/lib/statusor_test.cc
index 377a618ffb..56584e1892 100644
--- a/tensorflow/compiler/xla/statusor_test.cc
+++ b/tensorflow/stream_executor/lib/statusor_test.cc
@@ -15,18 +15,18 @@ limitations under the License.
// Unit tests for StatusOr
-#include "tensorflow/compiler/xla/statusor.h"
+#include "tensorflow/stream_executor/lib/statusor.h"
#include
#include
-#include "tensorflow/compiler/xla/test.h"
-#include "tensorflow/compiler/xla/types.h"
+#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/test_benchmark.h"
-namespace xla {
+namespace stream_executor {
+namespace port {
namespace {
class Base1 {
@@ -672,4 +672,5 @@ void BM_StatusOrFactoryFailLongMsg(int iters) {
BENCHMARK(BM_StatusOrFactoryFailLongMsg);
} // namespace
-} // namespace xla
+} // namespace port
+} // namespace stream_executor
--
GitLab
From b8c1732664f41d5af2587e2f093880a3a7d83f43 Mon Sep 17 00:00:00 2001
From: Michael Case
Date: Tue, 26 Jun 2018 15:07:23 -0700
Subject: [PATCH 0058/1193] Fix small typo in RELEASE.md
---
RELEASE.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/RELEASE.md b/RELEASE.md
index 879b995a5a..52cd9ef72b 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -21,7 +21,7 @@
* The [distributions.Bijector](https://www.tensorflow.org/versions/r1.9/api_docs/python/tf/contrib/distributions/bijectors/Bijector)
API supports broadcasting for Bijectors with new API changes.
-## Breaking Chances
+## Breaking Changes
* If you're opening empty variable scopes; replace `variable_scope('', ...)` by
`variable_scope(tf.get_variable_scope(), ...)`.
--
GitLab
From 74ca837950536aaef358abf3e05b31b4d62248f7 Mon Sep 17 00:00:00 2001
From: Gunhan Gulsoy
Date: Tue, 26 Jun 2018 15:29:48 -0700
Subject: [PATCH 0059/1193] Update eigen version to a fixed version for ppc64.
---
tensorflow/workspace.bzl | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/tensorflow/workspace.bzl b/tensorflow/workspace.bzl
index 3c657c4a5b..79274d66ad 100644
--- a/tensorflow/workspace.bzl
+++ b/tensorflow/workspace.bzl
@@ -107,11 +107,11 @@ def tf_workspace(path_prefix="", tf_repo_name=""):
tf_http_archive(
name = "eigen_archive",
urls = [
- "https://mirror.bazel.build/bitbucket.org/eigen/eigen/get/e5e305a158a0.tar.gz",
- "https://bitbucket.org/eigen/eigen/get/e5e305a158a0.tar.gz",
+ "https://mirror.bazel.build/bitbucket.org/eigen/eigen/get/fd6845384b86.tar.gz",
+ "https://bitbucket.org/eigen/eigen/get/fd6845384b86.tar.gz",
],
- sha256 = "8bbe676d69e7f59070c83a949454b8b6344034e0ebbf686b337528e5dc04c7de",
- strip_prefix = "eigen-eigen-e5e305a158a0",
+ sha256 = "d956415d784fa4e42b6a2a45c32556d6aec9d0a3d8ef48baee2522ab762556a9",
+ strip_prefix = "eigen-eigen-fd6845384b86",
build_file = clean_dep("//third_party:eigen.BUILD"),
)
--
GitLab
From 388a267b1191adf2df4006bf205a19b8a24813db Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Tue, 26 Jun 2018 11:24:37 -0700
Subject: [PATCH 0060/1193] Remove section links that don't go anywhere.
---
tensorflow/docs_src/get_started/_index.yaml | 12 +++---------
1 file changed, 3 insertions(+), 9 deletions(-)
diff --git a/tensorflow/docs_src/get_started/_index.yaml b/tensorflow/docs_src/get_started/_index.yaml
index 277fc852fb..4060804892 100644
--- a/tensorflow/docs_src/get_started/_index.yaml
+++ b/tensorflow/docs_src/get_started/_index.yaml
@@ -66,9 +66,7 @@ landing_page:
}
-
- Learn and use ML
-
+
Learn and use ML
The high-level Keras API provides building blocks to create and
@@ -117,9 +115,7 @@ landing_page:
- items:
- custom_html: >
-
- Research and experimentation
-
+
Research and experimentation
Eager execution provides an imperative, define-by-run interface for advanced operations. Write custom layers, forward passes, and training loops with auto‑differentiation. Start with
@@ -170,9 +166,7 @@ landing_page:
- custom_html: >
-
- ML at production scale
-
+
ML at production scale
Estimators can train large models on multiple machines in a
--
GitLab
From 9f4fbdb05e35b512dd4a3da5ae80558021a291e5 Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Tue, 26 Jun 2018 14:56:57 -0700
Subject: [PATCH 0061/1193] Fix leftnav for get_started
---
tensorflow/docs_src/get_started/leftnav_files | 6 +++---
tensorflow/docs_src/get_started/next_steps.md | 2 +-
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/tensorflow/docs_src/get_started/leftnav_files b/tensorflow/docs_src/get_started/leftnav_files
index 5c400a67f0..99d2b2c3e1 100644
--- a/tensorflow/docs_src/get_started/leftnav_files
+++ b/tensorflow/docs_src/get_started/leftnav_files
@@ -1,7 +1,7 @@
### Learn and use ML
-basic_classification.md
-basic_text_classification.md
-basic_regression.md
+basic_classification.md: Basic classification
+basic_text_classification.md: Text classification
+basic_regression.md: Regression
overfit_and_underfit.md
save_and_restore_models.md
next_steps.md
diff --git a/tensorflow/docs_src/get_started/next_steps.md b/tensorflow/docs_src/get_started/next_steps.md
index 6318a39c6c..01c9f7204a 100644
--- a/tensorflow/docs_src/get_started/next_steps.md
+++ b/tensorflow/docs_src/get_started/next_steps.md
@@ -1,4 +1,4 @@
-# Next Steps
+# Next steps
## Learn more about TensorFlow
--
GitLab
From 9809978ea09845d5429925b64c20cda461c20a66 Mon Sep 17 00:00:00 2001
From: Billy Lamberta
Date: Tue, 26 Jun 2018 21:34:07 -0700
Subject: [PATCH 0062/1193] Fix checkpoints link in keras guide
---
tensorflow/docs_src/guide/keras.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/tensorflow/docs_src/guide/keras.md b/tensorflow/docs_src/guide/keras.md
index 83172dab7f..c799e9b12c 100644
--- a/tensorflow/docs_src/guide/keras.md
+++ b/tensorflow/docs_src/guide/keras.md
@@ -35,7 +35,7 @@ from tensorflow import keras
* The `tf.keras` version in the latest TensorFlow release might not be the same
as the latest `keras` version from PyPI. Check `tf.keras.__version__`.
* When [saving a model's weights](#weights_only), `tf.keras` defaults to the
- [checkpoint format](../get_started/checkpoints.md). Pass `save_format='h5'` to
+ [checkpoint format](./checkpoints.md). Pass `save_format='h5'` to
use HDF5.
## Build a simple model
@@ -442,7 +442,7 @@ model.load_weights('my_model')
```
By default, this saves the model's weights in the
-[TensorFlow checkpoint](../get_started/checkpoints.md) file format. Weights can
+[TensorFlow checkpoint](./checkpoints.md) file format. Weights can
also be saved to the Keras HDF5 format (the default for the multi-backend
implementation of Keras):
--
GitLab
From 7e99fff9a4e516809abe506dcd85fa96070ce3bb Mon Sep 17 00:00:00 2001
From: Koan-Sin Tan
Date: Wed, 27 Jun 2018 13:26:46 +0800
Subject: [PATCH 0063/1193] make benchmark_model for tflite build
---
tensorflow/contrib/lite/profiling/profile_summarizer.cc | 2 +-
tensorflow/contrib/lite/tools/benchmark/benchmark_params.h | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/tensorflow/contrib/lite/profiling/profile_summarizer.cc b/tensorflow/contrib/lite/profiling/profile_summarizer.cc
index c37a096588..36e87b666a 100644
--- a/tensorflow/contrib/lite/profiling/profile_summarizer.cc
+++ b/tensorflow/contrib/lite/profiling/profile_summarizer.cc
@@ -83,7 +83,7 @@ OperatorDetails GetOperatorDetails(const tflite::Interpreter& interpreter,
OperatorDetails details;
details.name = op_name;
if (profiling_string) {
- details.name += ":" + string(profiling_string);
+ details.name += ":" + std::string(profiling_string);
}
details.inputs = GetTensorNames(interpreter, inputs);
details.outputs = GetTensorNames(interpreter, outputs);
diff --git a/tensorflow/contrib/lite/tools/benchmark/benchmark_params.h b/tensorflow/contrib/lite/tools/benchmark/benchmark_params.h
index 33448dd162..d9471145a9 100644
--- a/tensorflow/contrib/lite/tools/benchmark/benchmark_params.h
+++ b/tensorflow/contrib/lite/tools/benchmark/benchmark_params.h
@@ -46,11 +46,11 @@ class BenchmarkParam {
}
virtual ~BenchmarkParam() {}
BenchmarkParam(ParamType type) : type_(type) {}
+ template
+ static ParamType GetValueType();
private:
static void AssertHasSameType(ParamType a, ParamType b);
- template
- static ParamType GetValueType();
const ParamType type_;
};
--
GitLab
From 25804da02063df8d3836e8fcf197c9304379e4ae Mon Sep 17 00:00:00 2001
From: Jie
Date: Mon, 25 Jun 2018 17:33:41 -0700
Subject: [PATCH 0064/1193] TRT 4.0 update code is compatible with TRT 3.0.4
updated feature support for TRT 4.0 layers added error checking for
converter disabled broken shape inference (added TODO)
---
.../contrib/tensorrt/convert/convert_graph.cc | 21 +
.../contrib/tensorrt/convert/convert_nodes.cc | 975 +++++++++++++-----
.../contrib/tensorrt/kernels/trt_engine_op.cc | 11 +
.../contrib/tensorrt/ops/trt_engine_op.cc | 5 +-
4 files changed, 738 insertions(+), 274 deletions(-)
diff --git a/tensorflow/contrib/tensorrt/convert/convert_graph.cc b/tensorflow/contrib/tensorrt/convert/convert_graph.cc
index 13986127ba..9ae569ac78 100644
--- a/tensorflow/contrib/tensorrt/convert/convert_graph.cc
+++ b/tensorflow/contrib/tensorrt/convert/convert_graph.cc
@@ -104,6 +104,27 @@ bool IsTensorRTCandidate(const tensorflow::Node* node) {
"DepthwiseConv2dNative",
"FusedBatchNorm",
"FusedBatchNormV2",
+ "Div",
+ "RealDiv",
+ "Rsqrt",
+ "Reciprocal",
+ "Exp",
+ "Log",
+ "Sqrt",
+ "Abs",
+ "Neg",
+#if NV_TENSORRT_MAJOR > 3
+ "MatMul",
+ "BatchMatMul",
+ "Softmax",
+ "Minimum",
+ "Maximum",
+ "TopKV2",
+ "Sum",
+ "Prod",
+ "Max",
+ "Min",
+#endif
// TODO(ben,jie): ...
};
// LINT.ThenChange(//tensorflow/contrib/tensorrt/convert/convert_nodes.h)
diff --git a/tensorflow/contrib/tensorrt/convert/convert_nodes.cc b/tensorflow/contrib/tensorrt/convert/convert_nodes.cc
index 146b9c7344..22f92d38bf 100644
--- a/tensorflow/contrib/tensorrt/convert/convert_nodes.cc
+++ b/tensorflow/contrib/tensorrt/convert/convert_nodes.cc
@@ -53,6 +53,31 @@ limitations under the License.
// would work!
#define CHECK_EQ_TYPE(val1, val2) CHECK_EQ((int)val1, (int)val2)
+#define TFTRT_RETURN_ERROR_IF_FALSE(ptr, node) \
+ do { \
+ if (ptr == false) { \
+ return tensorflow::errors::Internal(string("TFTRT::") + __FUNCTION__ + \
+ "failed to add TRT layer, at: " + \
+ node); \
+ } \
+ } while (0)
+
+#define TFTRT_RETURN_ERROR_IF_NULLPTR(ptr, node) \
+ do { \
+ if (ptr == nullptr) { \
+ return tensorflow::errors::Internal(string("TFTRT::") + __FUNCTION__ + \
+ "failed to add TRT layer, at: " + \
+ node); \
+ } \
+ } while (0)
+
+#define TF_RETURN_IF_OK(status) \
+ do { \
+ if (status.ok()) { \
+ return tensorflow::Status::OK(); \
+ } \
+ } while (0)
+
namespace tensorflow {
namespace tensorrt {
namespace convert {
@@ -75,6 +100,11 @@ inline tensorflow::Status ConvertDType(tensorflow::DataType tf_dtype,
case tensorflow::DataType::DT_HALF:
*trt_dtype = nvinfer1::DataType::kHALF;
break;
+#if NV_TENSORRT_MAJOR > 3
+ case tensorflow::DataType::DT_INT32:
+ *trt_dtype = nvinfer1::DataType::kINT32;
+ break;
+#endif
default:
return tensorflow::errors::InvalidArgument(
"Unsupported data type " + tensorflow::DataTypeString(tf_dtype));
@@ -82,6 +112,96 @@ inline tensorflow::Status ConvertDType(tensorflow::DataType tf_dtype,
return tensorflow::Status::OK();
}
+// return whether or not the broadcast is feasible;
+bool TensorRTGetBroadcastShape(const nvinfer1::Dims& operand_l,
+ const bool operand_l_is_tensor,
+ const nvinfer1::Dims& operand_r,
+ const bool operand_r_is_tensor,
+ nvinfer1::Dims* operand_l_new_shape,
+ nvinfer1::Dims* operand_r_new_shape) {
+ /*******************************************************************************
+ TensorRT Elementwise op supports broadcast but requires both tensor to be of
+ Identical rank
+
+ We consider case of: i. Tensor op Const; ii. Tensor op Tensor
+ note: const op const (constant folding) should fallback to TensorFlow
+
+ broadcast scheme:
+ T: 1 3 5 (tensor would not have batch dimension)
+ W: 1 1 3 1 (weight would have all explicit dimensions)
+ i. fill in explicit dimensions
+ -> T: -1 1 3 5 (we put a -1 for batch dimension)
+ -> W: 1 1 3 1
+ ii. compare broadcast feasibility
+
+ we cannot support these since TensorRT does not allow manipulation on batch
+ dimension, we cannot generate output with proper shape
+ T: 3 5 1
+ W: 1 1 1 1 3 5 1
+ -> T: 1 1 1 -1 3 5 1
+ -> W: 1 1 1 1 3 5 1
+ *******************************************************************************/
+ static const int max_nb_dims = nvinfer1::Dims::MAX_DIMS + 1;
+ const size_t element_size = sizeof(operand_l.d[0]);
+
+ // fill in dimensions
+ int l_s[max_nb_dims];
+ std::fill(l_s, l_s + max_nb_dims, 1);
+ int l_d = operand_l_is_tensor ? operand_l.nbDims + 1 : operand_l.nbDims;
+ int r_s[max_nb_dims];
+ std::fill(r_s, r_s + max_nb_dims, 1);
+ int r_d = operand_r_is_tensor ? operand_r.nbDims + 1 : operand_r.nbDims;
+
+ int max_d = std::max(l_d, r_d);
+ std::memcpy(l_s + max_d - operand_l.nbDims, operand_l.d,
+ operand_l.nbDims * element_size);
+ std::memcpy(r_s + max_d - operand_r.nbDims, operand_r.d,
+ operand_r.nbDims * element_size);
+
+ // set -1 for batch dimension, since batch size is not supposed to be
+ // broadcasted
+ if (operand_l_is_tensor) {
+ if (max_d != l_d) { // if broadcast beyond batch dimension, fail
+ return false;
+ }
+ l_s[0] = -1;
+ }
+ if (operand_r_is_tensor) {
+ if (max_d != r_d) { // if broadcast beyond batch dimension, fail
+ return false;
+ }
+ r_s[0] = -1;
+ }
+
+ // compare broadcast feasibility
+ for (int i = max_d - 1; i >= 0; i--) {
+ if ((l_s[i] != r_s[i]) && (l_s[i] != 1) && (r_s[i] != 1)) {
+ return false;
+ }
+ }
+
+ // output new TensorRT Dimension (stripping the batch dimension)
+ operand_l_new_shape->nbDims = max_d - 1;
+ std::memcpy(operand_l_new_shape->d, l_s + 1, (max_d - 1) * element_size);
+ operand_r_new_shape->nbDims = max_d - 1;
+ std::memcpy(operand_r_new_shape->d, r_s + 1, (max_d - 1) * element_size);
+
+ return true;
+}
+
+inline bool DimsEqual(const nvinfer1::Dims& dim_l,
+ const nvinfer1::Dims& dim_r) {
+ if (dim_l.nbDims != dim_r.nbDims) {
+ return false;
+ }
+ for (int i = 0; i < dim_l.nbDims; i++) {
+ if (dim_l.d[i] != dim_r.d[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
inline nvinfer1::Dims GetTensorShape(const tensorflow::Tensor& tensor) {
nvinfer1::Dims dims;
dims.nbDims = tensor.dims();
@@ -342,7 +462,7 @@ void Reorder2(nvinfer1::DimsHW shape, const T* idata, nvinfer1::DimsHW istrides,
for (int h = 0; h < shape.h(); ++h) {
for (int w = 0; w < shape.w(); ++w) {
odata[h * ostrides.h() + w * ostrides.w()] =
- idata[h * ostrides.h() + w * ostrides.w()];
+ idata[h * istrides.h() + w * istrides.w()];
}
}
}
@@ -365,11 +485,10 @@ void ReorderCKtoKC(const TRT_ShapedWeights& iweights,
break;
}
case tensorflow::DataType::DT_HALF: {
- Reorder2(
- {k, c}, static_cast(iweights.GetValues()),
- istrides,
- static_cast(const_cast(oweights->GetValues())),
- ostrides);
+ Reorder2({k, c}, static_cast(iweights.GetValues()),
+ istrides, static_cast(
+ const_cast(oweights->GetValues())),
+ ostrides);
break;
}
default:
@@ -547,6 +666,9 @@ class Converter {
LOG(ERROR) << "Dimension does not match, fail gracefully";
nvinfer1::IShuffleLayer* layer = this->network()->addShuffle(*input_tensor);
+ if (layer == nullptr) {
+ return nullptr;
+ }
nvinfer1::Permutation permutation;
for (int32_t i = 0; i < dims.nbDims; ++i) {
permutation.order[i] = order[i + 1] - 1;
@@ -583,7 +705,7 @@ TRT_ShapedWeights ConvertFP32ToFP16(Converter& ctx,
// there.
//*****************************************************************************/
struct LambdaFactory {
- enum class OP_CATEGORY : int { RSQRT = 0, NEG, ADD, MUL, SUB };
+ enum class OP_CATEGORY : int { RSQRT = 0, NEG, ADD, MUL, SUB, RECIP };
OP_CATEGORY op;
template
@@ -595,6 +717,8 @@ struct LambdaFactory {
}
case OP_CATEGORY::NEG:
return [](T t) -> T { return -t; };
+ case OP_CATEGORY::RECIP:
+ return [](T t) -> T { return 1.0 / t; };
default:
VLOG(2) << "Not supported op for unary: " << static_cast(op);
return nullptr;
@@ -790,118 +914,23 @@ tensorflow::Status BinaryCompute(const TRT_ShapedWeights& iweights_l,
return tensorflow::Status::OK();
}
-tensorflow::Status ConstantFoldUnary(
- Converter& ctx, const tensorflow::NodeDef& node_def,
- const std::vector& inputs,
- std::vector* outputs) {
- TRT_ShapedWeights weights_input = inputs.at(0).weights();
-
- // Allocate output weights
- TRT_ShapedWeights weights_output = ctx.get_temp_weights_like(weights_input);
-
- // FIXME assume type matches input weights
- // Get trt type & shape
- // Maybe this part has to be moved into the block of rsqrt later
- // Check type consistency
- CHECK_EQ(weights_input.type_,
- TFAttrs(node_def).get("T"));
-
- LambdaFactory unary_op;
- if (node_def.op() == "Rsqrt") {
- // Compute rsqrt
- unary_op.op = LambdaFactory::OP_CATEGORY::RSQRT;
- auto ret = UnaryCompute(weights_input, &weights_output, unary_op);
- // Pass the output
- if (ret == tensorflow::Status::OK()) {
- outputs->push_back(TRT_TensorOrWeights(weights_output));
- }
- return ret;
- } else {
- return tensorflow::errors::Unimplemented("Binary op not supported: " +
- node_def.op());
- }
-}
-
-// TODO(jie,ben) broadcast is needed yet not implemented
-// Let's get the simple stuff working first. Maybe we should fall back to TF
-// approach for constant folding
-tensorflow::Status ConstantFoldBinary(
- Converter& ctx, const tensorflow::NodeDef& node_def,
- const std::vector& inputs,
- std::vector* outputs) {
- TRT_ShapedWeights weights_input_l = inputs.at(0).weights();
- TRT_ShapedWeights weights_input_r = inputs.at(1).weights();
-
- // Check type consistency
- CHECK_EQ(weights_input_l.type_, weights_input_r.type_);
-
- if (weights_input_l.shape_.nbDims != weights_input_r.shape_.nbDims)
- return tensorflow::errors::Unimplemented(
- "Binary op implicit broadcast not supported: " + node_def.op());
-
- // TODO(jie): constant fold should really fall back to TF.
- int num_dims = weights_input_l.shape_.nbDims;
- nvinfer1::Dims output_shape;
- output_shape.nbDims = num_dims;
- VLOG(2) << "nb_dims: " << num_dims
- << ", the other: " << weights_input_r.shape_.nbDims;
- for (int i = 0; i < num_dims; i++) {
- if (weights_input_l.shape_.d[i] == weights_input_r.shape_.d[i]) {
- output_shape.d[i] = weights_input_l.shape_.d[i];
- } else if (weights_input_l.shape_.d[i] == 1 ||
- weights_input_r.shape_.d[i] == 1) {
- output_shape.d[i] =
- std::max(weights_input_l.shape_.d[i], weights_input_r.shape_.d[i]);
- } else {
- return tensorflow::errors::Unimplemented(
- "Binary op with incompatible shape at, " + node_def.op());
- }
- VLOG(2) << "left: " << weights_input_l.shape_.d[i]
- << "right: " << weights_input_r.shape_.d[i]
- << "output: " << output_shape.d[i];
- }
-
- // FIXME assume type matches input weights
- // Get trt type & shape
- TFAttrs attrs(node_def);
- // Maybe this part has to be moved into the block of rsqrt later
- tensorflow::DataType dtype = attrs.get("T");
-
- // Allocate output weights
- TRT_ShapedWeights weights_output = ctx.get_temp_weights(dtype, output_shape);
-
- LambdaFactory binary_op;
- if (node_def.op() == "Sub") {
- binary_op.op = LambdaFactory::OP_CATEGORY::SUB;
- } else if (node_def.op() == "Mul") {
- binary_op.op = LambdaFactory::OP_CATEGORY::MUL;
- } else if (node_def.op() == "Add") {
- binary_op.op = LambdaFactory::OP_CATEGORY::ADD;
- } else {
- return tensorflow::errors::Unimplemented("Binary op not supported: " +
- node_def.op());
- }
- auto ret = BinaryCompute(weights_input_l, weights_input_r, &weights_output,
- binary_op);
-
- // Pass the output
- if (ret == tensorflow::Status::OK()) {
- outputs->push_back(TRT_TensorOrWeights(weights_output));
- }
-
- return ret;
-}
-
// TODO(jie): broadcast is needed yet not implemented.
// Only implemented channel wise for the time being
tensorflow::Status BinaryTensorOpWeight(
Converter& ctx, const tensorflow::NodeDef& node_def,
const nvinfer1::ITensor* tensor, TRT_ShapedWeights weights,
- std::vector* outputs) {
+ std::vector* outputs, bool swapped_inputs) {
// FIXME assume type matches input weights
// Get trt type & shape
// Maybe this part has to be moved into the block of rsqrt later
+ if (node_def.op() != "Sub" && node_def.op() != "Add" &&
+ node_def.op() != "Mul" && node_def.op() != "Div" &&
+ node_def.op() != "RealDiv") {
+ return tensorflow::errors::Unimplemented(
+ "op not supported: " + node_def.op() + ", at: " + node_def.name());
+ }
+
// Check type consistency
nvinfer1::DataType ttype;
TF_RETURN_IF_ERROR(ConvertDType(weights.type_, &ttype));
@@ -910,6 +939,12 @@ tensorflow::Status BinaryTensorOpWeight(
auto dims_w = weights.shape_;
auto dims_t = tensor->getDimensions();
+ // TODO(jie): addScale checks for input tensor dimension
+ if (dims_t.nbDims != 3) {
+ return tensorflow::errors::InvalidArgument(
+ "addScale requires tensor with rank 3, " + node_def.name());
+ }
+
// default to element-wise
auto scale_mode = nvinfer1::ScaleMode::kELEMENTWISE;
@@ -980,6 +1015,7 @@ tensorflow::Status BinaryTensorOpWeight(
permutation[dims_t.nbDims] = 1;
tensor = ctx.TransposeTensor(const_cast(tensor),
permutation);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(tensor, node_def.name());
} else {
return tensorflow::errors::InvalidArgument(
"Transpose cannot be applied, " + node_def.name());
@@ -997,11 +1033,35 @@ tensorflow::Status BinaryTensorOpWeight(
// Maybe I should do a switch
if (node_def.op() == "Sub") {
- TRT_ShapedWeights neg_weights = ctx.get_temp_weights_like(weights);
- LambdaFactory unary_op;
- unary_op.op = LambdaFactory::OP_CATEGORY::NEG;
- TF_RETURN_IF_ERROR(UnaryCompute(weights, &neg_weights, unary_op));
- shift_weights = neg_weights;
+ if (swapped_inputs) {
+ shift_weights = weights;
+ nvinfer1::IUnaryLayer* layer =
+ ctx.network()->addUnary(*const_cast(tensor),
+ nvinfer1::UnaryOperation::kNEG);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
+ tensor = layer->getOutput(0);
+ } else {
+ TRT_ShapedWeights neg_weights = ctx.get_temp_weights_like(weights);
+ LambdaFactory unary_op;
+ unary_op.op = LambdaFactory::OP_CATEGORY::NEG;
+ TF_RETURN_IF_ERROR(UnaryCompute(weights, &neg_weights, unary_op));
+ shift_weights = neg_weights;
+ }
+ } else if (node_def.op() == "Div" || node_def.op() == "RealDiv") {
+ if (swapped_inputs) {
+ scale_weights = weights;
+ nvinfer1::IUnaryLayer* layer =
+ ctx.network()->addUnary(*const_cast(tensor),
+ nvinfer1::UnaryOperation::kRECIP);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
+ tensor = layer->getOutput(0);
+ } else {
+ TRT_ShapedWeights recip_weights = ctx.get_temp_weights_like(weights);
+ LambdaFactory unary_op;
+ unary_op.op = LambdaFactory::OP_CATEGORY::RECIP;
+ TF_RETURN_IF_ERROR(UnaryCompute(weights, &recip_weights, unary_op));
+ scale_weights = recip_weights;
+ }
} else if (node_def.op() == "Mul") {
scale_weights = weights;
} else if (node_def.op() == "Add") {
@@ -1014,11 +1074,13 @@ tensorflow::Status BinaryTensorOpWeight(
nvinfer1::IScaleLayer* layer = ctx.network()->addScale(
*const_cast(tensor), scale_mode, shift_weights,
scale_weights, power_weights);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
nvinfer1::ITensor* output_tensor = layer->getOutput(0);
// transpose back dimension
if (permutation_flag) {
output_tensor = ctx.TransposeTensor(output_tensor, permutation);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(output_tensor, node_def.name());
}
// Pass the output
@@ -1042,6 +1104,7 @@ tensorflow::Status ConvertConv2DHelper(
if (data_format == "NHWC") {
tensor = ctx.TransposeTensor(const_cast(tensor),
{0, 3, 1, 2});
+ TFTRT_RETURN_ERROR_IF_NULLPTR(tensor, node_def.name());
h_index = 1;
w_index = 2;
// TODO(jie): transpose it
@@ -1102,6 +1165,7 @@ tensorflow::Status ConvertConv2DHelper(
*const_cast(tensor),
nvinfer1::DimsHW(padding[0].first, padding[1].first),
nvinfer1::DimsHW(padding[0].second, padding[1].second));
+ TFTRT_RETURN_ERROR_IF_NULLPTR(pad_layer, node_def.name());
padding = {{0, 0}, {0, 0}};
tensor = pad_layer->getOutput(0);
auto dim_after = tensor->getDimensions();
@@ -1112,6 +1176,7 @@ tensorflow::Status ConvertConv2DHelper(
nvinfer1::IConvolutionLayer* layer =
ctx.network()->addConvolution(*const_cast(tensor),
noutput, kernel_size, weights, biases);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
layer->setStride(stride);
layer->setPadding({padding[0].first, padding[1].first});
@@ -1126,6 +1191,7 @@ tensorflow::Status ConvertConv2DHelper(
if (data_format == "NHWC") {
// TODO(jie): transpose it back!
output_tensor = ctx.TransposeTensor(output_tensor, {0, 2, 3, 1});
+ TFTRT_RETURN_ERROR_IF_NULLPTR(output_tensor, node_def.name());
} else {
VLOG(2) << "NCHW !!!!";
}
@@ -1147,18 +1213,71 @@ tensorflow::Status ConvertConv2DHelper(
node_def.name());
}
+bool PrepareTensorForShape(Converter& ctx, const TRT_TensorOrWeights& input,
+ const nvinfer1::ITensor** tensor,
+ const nvinfer1::Dims& dims) {
+ if (input.is_tensor()) {
+ if (DimsEqual(input.shape(), dims)) {
+ *tensor = input.tensor();
+ } else {
+ nvinfer1::IShuffleLayer* layer = ctx.network()->addShuffle(
+ *const_cast(input.tensor()));
+ if (layer != nullptr) {
+ layer->setReshapeDimensions(dims);
+ *tensor = layer->getOutput(0);
+ } else {
+ return false;
+ }
+ }
+ } else {
+#if NV_TENSORRT_MAJOR > 3
+ nvinfer1::IConstantLayer* layer =
+ ctx.network()->addConstant(dims, input.weights());
+ if (layer != nullptr) {
+ *tensor = layer->getOutput(0);
+ } else {
+ return false;
+ }
+#else
+ return false;
+#endif
+ }
+ return true;
+}
+
tensorflow::Status BinaryTensorOpTensor(
Converter& ctx, const tensorflow::NodeDef& node_def,
- const nvinfer1::ITensor* tensor_l, const nvinfer1::ITensor* tensor_r,
+ const TRT_TensorOrWeights operand_l, const TRT_TensorOrWeights operand_r,
std::vector* outputs) {
static const std::unordered_map ops{
{"Add", nvinfer1::ElementWiseOperation::kSUM},
{"Mul", nvinfer1::ElementWiseOperation::kPROD},
{"Sub", nvinfer1::ElementWiseOperation::kSUB},
{"Div", nvinfer1::ElementWiseOperation::kDIV},
+ {"RealDiv", nvinfer1::ElementWiseOperation::kDIV},
+ {"Minimum", nvinfer1::ElementWiseOperation::kMIN},
+ {"Maximum", nvinfer1::ElementWiseOperation::kMAX},
};
- // FIXME assume type matches input weights
+ const nvinfer1::ITensor* tensor_l;
+ const nvinfer1::ITensor* tensor_r;
+
+ nvinfer1::Dims dim_l;
+ nvinfer1::Dims dim_r;
+
+ if (!TensorRTGetBroadcastShape(operand_l.shape(), operand_l.is_tensor(),
+ operand_r.shape(), operand_r.is_tensor(),
+ &dim_l, &dim_r)) {
+ return tensorflow::errors::InvalidArgument(
+ "Binary op broadcast scheme not supported by TensorRT op: " +
+ node_def.op() + ", at: " + node_def.name());
+ }
+
+ TFTRT_RETURN_ERROR_IF_FALSE(
+ PrepareTensorForShape(ctx, operand_l, &tensor_l, dim_l), node_def.name());
+ TFTRT_RETURN_ERROR_IF_FALSE(
+ PrepareTensorForShape(ctx, operand_r, &tensor_r, dim_r), node_def.name());
+
// get trt type & shape
TFAttrs attrs(node_def);
// maybe this part has to be moved into the block of rsqrt later
@@ -1169,13 +1288,14 @@ tensorflow::Status BinaryTensorOpTensor(
CHECK_EQ_TYPE(tensor_r->getType(), dtype);
auto op_pair = ops.find(node_def.op());
if (op_pair == ops.end())
- return tensorflow::errors::Unimplemented(
- "binary op: " + node_def.op() +
- " not supported at: " + node_def.name());
+ return tensorflow::errors::Unimplemented("binary op: " + node_def.op() +
+ " not supported at: " +
+ node_def.name());
nvinfer1::IElementWiseLayer* layer = ctx.network()->addElementWise(
*const_cast(tensor_l),
*const_cast(tensor_r), op_pair->second);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
nvinfer1::ITensor* output_tensor = layer->getOutput(0);
@@ -1223,29 +1343,6 @@ tensorflow::Status ConvertPlugin(Converter& ctx,
return tensorflow::Status::OK();
}
-tensorflow::Status ConvertPlaceholder(
- Converter& ctx, const tensorflow::NodeDef& node_def,
- const std::vector& inputs,
- std::vector* outputs) {
- VLOG(2) << "Placeholder should have been replace already";
- return tensorflow::errors::Unimplemented("cannot convert Placeholder op");
- // OK this make sense since we are supposed to replace it with input
- TFAttrs attrs(node_def);
- nvinfer1::DataType dtype = attrs.get("dtype");
- nvinfer1::Dims dims = attrs.get("shape");
-
- dims.nbDims--;
- for (int i = 0; i < dims.nbDims; i++) dims.d[i] = dims.d[i + 1];
-
- nvinfer1::ITensor* output =
- ctx.network()->addInput(node_def.name().c_str(), dtype, dims);
- if (!output) {
- return tensorflow::errors::InvalidArgument("Failed to create Input layer");
- }
- outputs->push_back(TRT_TensorOrWeights(output));
- return tensorflow::Status::OK();
-}
-
tensorflow::Status ConvertConv2D(Converter& ctx,
const tensorflow::NodeDef& node_def,
const std::vector& inputs,
@@ -1277,11 +1374,10 @@ tensorflow::Status ConvertPool(Converter& ctx,
w_index = 2;
tensor = ctx.TransposeTensor(const_cast(tensor),
{0, 3, 1, 2});
- } else {
- VLOG(2) << "NCHW !!!!";
+ TFTRT_RETURN_ERROR_IF_NULLPTR(tensor, node_def.name());
}
+
nvinfer1::PoolingType type;
- // TODO(jie): support other pooling type
if (node_def.op() == "MaxPool")
type = nvinfer1::PoolingType::kMAX;
else if (node_def.op() == "AvgPool")
@@ -1289,7 +1385,6 @@ tensorflow::Status ConvertPool(Converter& ctx,
else
return tensorflow::errors::Unimplemented("Only supports Max pool");
- // TODO(jie): NCHW
auto tf_stride = attrs.get>("strides");
nvinfer1::DimsHW stride(tf_stride[h_index], tf_stride[w_index]);
@@ -1298,7 +1393,6 @@ tensorflow::Status ConvertPool(Converter& ctx,
auto tensor_dim = tensor->getDimensions();
std::vector> padding;
- // TODO(jie): padding.
if (attrs.get("padding") == "SAME") {
// This is NCHW tensor with no batch dimension.
// 1 -> h
@@ -1307,8 +1401,6 @@ tensorflow::Status ConvertPool(Converter& ctx,
stride, ksize,
{static_cast(tensor_dim.d[1]), static_cast(tensor_dim.d[2])});
} else if (attrs.get("padding") == "VALID") {
- // No padding for valid padding here
- VLOG(2) << "No padding added for VALID padding in pool" << node_def.name();
padding = {{0, 0}, {0, 0}};
} else {
return tensorflow::errors::Unimplemented(
@@ -1317,19 +1409,20 @@ tensorflow::Status ConvertPool(Converter& ctx,
if (padding[0].first != padding[0].second ||
padding[1].first != padding[1].second) {
- // TODO(jie): handle asymmetric padding
VLOG(2) << "Padding!!!: " << padding[0].first << padding[0].second
<< padding[1].first << padding[1].second;
auto pad_layer = ctx.network()->addPadding(
*const_cast(tensor),
nvinfer1::DimsHW(padding[0].first, padding[1].first),
nvinfer1::DimsHW(padding[0].second, padding[1].second));
+ TFTRT_RETURN_ERROR_IF_NULLPTR(pad_layer, node_def.name());
padding = {{0, 0}, {0, 0}};
tensor = pad_layer->getOutput(0);
}
nvinfer1::IPoolingLayer* layer = ctx.network()->addPooling(
*const_cast(tensor), type, ksize);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
layer->setStride(stride);
layer->setPadding({padding[0].first, padding[1].first});
@@ -1337,10 +1430,8 @@ tensorflow::Status ConvertPool(Converter& ctx,
nvinfer1::ITensor* output_tensor = layer->getOutput(0);
if (data_format == "NHWC") {
- // TODO(jie): transpose it back!
output_tensor = ctx.TransposeTensor(output_tensor, {0, 2, 3, 1});
- } else {
- VLOG(2) << "NCHW !!!!";
+ TFTRT_RETURN_ERROR_IF_NULLPTR(output_tensor, node_def.name());
}
outputs->push_back(TRT_TensorOrWeights(output_tensor));
return tensorflow::Status::OK();
@@ -1353,6 +1444,7 @@ tensorflow::Status ConvertActivation(
const nvinfer1::ITensor* tensor = inputs.at(0).tensor();
nvinfer1::IActivationLayer* layer = ctx.network()->addActivation(
*const_cast(tensor), nvinfer1::ActivationType::kRELU);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
nvinfer1::ITensor* output_tensor = layer->getOutput(0);
outputs->push_back(TRT_TensorOrWeights(output_tensor));
return tensorflow::Status::OK();
@@ -1366,7 +1458,7 @@ tensorflow::Status ConvertScale(Converter& ctx,
!inputs.at(1).is_weights())
return tensorflow::errors::Unimplemented(
"Only supports tensor op weight for now, at " + node_def.name());
- // Implement tensor binaryOp weight [channel wise] for now;
+
const nvinfer1::ITensor* tensor = inputs.at(0).tensor();
TRT_ShapedWeights weights = inputs.at(1).weights();
@@ -1378,25 +1470,48 @@ tensorflow::Status ConvertScale(Converter& ctx,
TFAttrs attrs(node_def);
- // Transpose NHWC
auto data_format = attrs.get("data_format");
+ int channel_index;
+ auto dims = tensor->getDimensions();
if (data_format == "NHWC") {
- tensor = ctx.TransposeTensor(const_cast(tensor),
- {0, 3, 1, 2});
- // TODO(jie): transpose it
+ // 1). NHWC is really N+C
+ channel_index = dims.nbDims - 1; // batch dimension is implicit here!
} else {
- VLOG(2) << "NCHW !!!!";
+ // 2). NCHW is really N+CHW
+ channel_index = dims.nbDims - 3; // batch dimension is implicit here!
}
- auto dims = tensor->getDimensions();
- VLOG(2) << "tensor dimensions: " << dims.nbDims;
- for (int i = 0; i < dims.nbDims; i++) {
- VLOG(2) << "i: " << dims.d[i];
+ nvinfer1::Permutation permutation;
+ for (int32_t i = 0; i < dims.nbDims; ++i) {
+ permutation.order[i] = i;
}
- dims = weights.shape_;
- VLOG(2) << "tensor dimensions: " << dims.nbDims;
- for (int i = 0; i < dims.nbDims; i++) {
- VLOG(2) << "i: " << dims.d[i];
+
+ if (channel_index >= 0) {
+ permutation.order[0] = channel_index;
+ permutation.order[channel_index] = 0;
+ } else {
+ return tensorflow::errors::Unimplemented(
+ "TFTRT::BiasAdd cannot apply on batch dimension, at " +
+ node_def.name());
+ }
+
+ // TensorRT addScale requires input to be of rank 3, we need to apply
+ // transpose as well as reshape
+ if (channel_index != 0 || dims.nbDims != 3) {
+ nvinfer1::IShuffleLayer* shuffle_layer =
+ ctx.network()->addShuffle(*const_cast(tensor));
+ TFTRT_RETURN_ERROR_IF_NULLPTR(shuffle_layer, node_def.name());
+ nvinfer1::Dims reshape_dims;
+ reshape_dims.nbDims = 3;
+ reshape_dims.d[0] = 0; // 0 copy from the input
+ reshape_dims.d[1] = dims.nbDims >= 2 ? 0 : 1; // 0 copy from the input
+ reshape_dims.d[2] = dims.nbDims >= 3 ? -1 : 1; // -1 infer from the rest
+ if (channel_index != 0) { // maybe we do not need this check. concerned
+ // about TRT optimization
+ shuffle_layer->setFirstTranspose(permutation);
+ }
+ shuffle_layer->setReshapeDimensions(reshape_dims);
+ tensor = shuffle_layer->getOutput(0);
}
nvinfer1::ScaleMode mode = nvinfer1::ScaleMode::kCHANNEL;
@@ -1407,14 +1522,26 @@ tensorflow::Status ConvertScale(Converter& ctx,
nvinfer1::IScaleLayer* layer =
ctx.network()->addScale(*const_cast(tensor), mode,
weights, empty_weights, empty_weights);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
nvinfer1::ITensor* output_tensor = layer->getOutput(0);
- if (data_format == "NHWC") {
- // TODO(jie): transpose it back!
- output_tensor = ctx.TransposeTensor(output_tensor, {0, 2, 3, 1});
- } else {
- VLOG(2) << "NCHW !!!!";
+
+ // restore transpose & reshape
+ if (channel_index != 0 || dims.nbDims != 3) {
+ nvinfer1::IShuffleLayer* shuffle_layer = ctx.network()->addShuffle(
+ *const_cast(output_tensor));
+ TFTRT_RETURN_ERROR_IF_NULLPTR(shuffle_layer, node_def.name());
+ nvinfer1::Dims reshape_dims = dims;
+ int tmp = reshape_dims.d[channel_index];
+ reshape_dims.d[channel_index] = reshape_dims.d[0];
+ reshape_dims.d[0] = tmp;
+ shuffle_layer->setReshapeDimensions(reshape_dims);
+ if (channel_index != 0) {
+ shuffle_layer->setSecondTranspose(permutation);
+ }
+ output_tensor = shuffle_layer->getOutput(0);
}
+
outputs->push_back(TRT_TensorOrWeights(output_tensor));
return tensorflow::Status::OK();
}
@@ -1567,47 +1694,105 @@ tensorflow::Status ConvertBinary(Converter& ctx,
return tensorflow::errors::FailedPrecondition(
"Binary ops require two tensor input, at " + node_def.name());
- if (inputs.at(0).is_weights() && inputs.at(1).is_weights())
- return ConstantFoldBinary(ctx, node_def, inputs, outputs);
+ // Constant folding should have been done by TensorFlow
- if (inputs.at(0).is_tensor() && inputs.at(1).is_weights())
- return BinaryTensorOpWeight(ctx, node_def, inputs.at(0).tensor(),
- inputs.at(1).weights(), outputs);
+ if (inputs.at(0).is_weights() && inputs.at(1).is_weights())
+ return tensorflow::errors::Unimplemented(
+ "Constant folding is falled back to TensorFlow, binary op received "
+ "both input as constant at: " +
+ node_def.name());
- if (inputs.at(0).is_weights() && inputs.at(1).is_tensor())
- return BinaryTensorOpWeight(ctx, node_def, inputs.at(1).tensor(),
- inputs.at(0).weights(), outputs);
+ // Try to convert into Scale layer first (for better performance)
+ // Since scale layer supports restricted broadcast policy and op types, we
+ // allow failure and try to handle it through Elementwise op
+ // (BinaryTensorOpTensor)
+ if (inputs.at(0).is_tensor() && inputs.at(1).is_weights()) {
+ auto status = BinaryTensorOpWeight(ctx, node_def, inputs.at(0).tensor(),
+ inputs.at(1).weights(), outputs, false);
+#if NV_TENSORRT_MAJOR == 3
+ TF_RETURN_IF_ERROR(status);
+#else
+ TF_RETURN_IF_OK(status);
+#endif
+ }
- if (inputs.at(0).is_tensor() && inputs.at(1).is_tensor())
- return BinaryTensorOpTensor(ctx, node_def, inputs.at(0).tensor(),
- inputs.at(1).tensor(), outputs);
+ if (inputs.at(0).is_weights() && inputs.at(1).is_tensor()) {
+ auto status = BinaryTensorOpWeight(ctx, node_def, inputs.at(1).tensor(),
+ inputs.at(0).weights(), outputs, true);
+#if NV_TENSORRT_MAJOR == 3
+ TF_RETURN_IF_ERROR(status);
+#else
+ TF_RETURN_IF_OK(status);
+#endif
+ }
- return tensorflow::errors::Unknown("Binary op input error, at " +
- node_def.name());
+#if NV_TENSORRT_MAJOR == 3
+ if (inputs.at(0).is_tensor() && inputs.at(1).is_tensor()) {
+#endif
+ return BinaryTensorOpTensor(ctx, node_def, inputs.at(0), inputs.at(1),
+ outputs);
+#if NV_TENSORRT_MAJOR == 3
+ }
+#endif
}
tensorflow::Status ConvertUnary(Converter& ctx,
const tensorflow::NodeDef& node_def,
const std::vector& inputs,
std::vector* outputs) {
+ static const std::unordered_map ops{
+ {"Neg", nvinfer1::UnaryOperation::kNEG},
+ {"Exp", nvinfer1::UnaryOperation::kEXP},
+ {"Log", nvinfer1::UnaryOperation::kLOG},
+ {"Sqrt", nvinfer1::UnaryOperation::kSQRT},
+ {"Abs", nvinfer1::UnaryOperation::kABS},
+ {"Reciprocal", nvinfer1::UnaryOperation::kRECIP},
+ };
+
if (inputs.size() != 1)
return tensorflow::errors::FailedPrecondition(
"Unary ops require single tensor input, at " + node_def.name());
+#if NV_TENSORRT_MAJOR == 3
if (inputs.at(0).is_weights())
- return ConstantFoldUnary(ctx, node_def, inputs, outputs);
- else if (inputs.at(0).is_tensor())
return tensorflow::errors::Unimplemented(
- "Unary op for tensor not supported, at " + node_def.name());
+ "Constant folding for unary op is not supported" + node_def.name());
+#endif
+
+ // TODO(jie): check type
+ const nvinfer1::ITensor* tensor;
+ TFTRT_RETURN_ERROR_IF_FALSE(
+ PrepareTensorForShape(ctx, inputs.at(0), &tensor, inputs.at(0).shape()),
+ node_def.name());
+
+ nvinfer1::IUnaryLayer* layer;
+ if (node_def.op() == "Rsqrt") {
+ layer = ctx.network()->addUnary(*const_cast(tensor),
+ nvinfer1::UnaryOperation::kSQRT);
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
+ tensor = layer->getOutput(0);
+ layer = ctx.network()->addUnary(*const_cast(tensor),
+ nvinfer1::UnaryOperation::kRECIP);
+ } else if (ops.count(node_def.op()) != 0) {
+ layer = ctx.network()->addUnary(*const_cast(tensor),
+ ops.at(node_def.op()));
+ } else {
+ return tensorflow::errors::InvalidArgument("Binary op: " + node_def.op() +
+ " not supported, at " +
+ node_def.name());
+ }
- return tensorflow::errors::Unknown("Binary op input error, at " +
- node_def.name());
+ TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name());
+ nvinfer1::ITensor* output_tensor = layer->getOutput(0);
+ outputs->push_back(TRT_TensorOrWeights(output_tensor));
+ return tensorflow::Status::OK();
}
-tensorflow::Status ConvertReduce(Converter& ctx,
- const tensorflow::NodeDef& node_def,
- const std::vector& inputs,
- std::vector* outputs) {
+#if NV_TENSORRT_MAJOR == 3
+tensorflow::Status ConvertReducePool(
+ Converter& ctx, const tensorflow::NodeDef& node_def,
+ const std::vector& inputs,
+ std::vector