aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--README.md26
-rw-r--r--RELEASE.md4
-rw-r--r--configure.py20
-rw-r--r--tensorflow/BUILD14
-rw-r--r--tensorflow/__init__.py3
-rw-r--r--tensorflow/c/c_api.cc3
-rw-r--r--tensorflow/c/eager/c_api_test.cc57
-rw-r--r--tensorflow/cc/BUILD3
-rw-r--r--tensorflow/cc/framework/cc_op_gen.cc9
-rw-r--r--tensorflow/cc/gradients/math_grad.cc35
-rw-r--r--tensorflow/cc/gradients/math_grad_test.cc43
-rw-r--r--tensorflow/compiler/aot/BUILD1
-rw-r--r--tensorflow/compiler/aot/codegen.cc169
-rw-r--r--tensorflow/compiler/aot/codegen_test.cc12
-rw-r--r--tensorflow/compiler/aot/codegen_test_h.golden58
-rw-r--r--tensorflow/compiler/aot/test.cc12
-rw-r--r--tensorflow/compiler/aot/tests/tfcompile_test.cc66
-rw-r--r--tensorflow/compiler/jit/BUILD8
-rw-r--r--tensorflow/compiler/jit/deadness_analysis.cc471
-rw-r--r--tensorflow/compiler/jit/deadness_analysis_internal.h8
-rw-r--r--tensorflow/compiler/jit/deadness_analysis_test.cc373
-rw-r--r--tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc3
-rw-r--r--tensorflow/compiler/jit/jit_compilation_pass_registration.cc8
-rw-r--r--tensorflow/compiler/jit/kernels/BUILD1
-rw-r--r--tensorflow/compiler/jit/kernels/xla_launch_op.cc6
-rw-r--r--tensorflow/compiler/jit/mark_for_compilation_pass.cc165
-rw-r--r--tensorflow/compiler/jit/mark_for_compilation_pass.h8
-rw-r--r--tensorflow/compiler/jit/mark_for_compilation_pass_test.cc70
-rw-r--r--tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.cc40
-rw-r--r--tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h35
-rw-r--r--tensorflow/compiler/jit/partially_decluster_pass.cc177
-rw-r--r--tensorflow/compiler/jit/partially_decluster_pass.h58
-rw-r--r--tensorflow/compiler/jit/partially_decluster_pass_test.cc284
-rw-r--r--tensorflow/compiler/jit/xla_cluster_util.cc22
-rw-r--r--tensorflow/compiler/jit/xla_cluster_util.h11
-rw-r--r--tensorflow/compiler/jit/xla_compile_on_demand_op.cc6
-rw-r--r--tensorflow/compiler/jit/xla_device.cc41
-rw-r--r--tensorflow/compiler/jit/xla_device.h14
-rw-r--r--tensorflow/compiler/jit/xla_device_context.cc89
-rw-r--r--tensorflow/compiler/jit/xla_device_context.h31
-rw-r--r--tensorflow/compiler/jit/xla_launch_util.cc62
-rw-r--r--tensorflow/compiler/jit/xla_launch_util.h6
-rw-r--r--tensorflow/compiler/jit/xla_tensor.cc7
-rw-r--r--tensorflow/compiler/jit/xla_tensor.h6
-rw-r--r--tensorflow/compiler/tests/adam_test.py9
-rw-r--r--tensorflow/compiler/tests/binary_ops_test.py10
-rw-r--r--tensorflow/compiler/tests/eager_test.py10
-rw-r--r--tensorflow/compiler/tests/random_ops_test.py14
-rw-r--r--tensorflow/compiler/tests/reverse_ops_test.py25
-rw-r--r--tensorflow/compiler/tests/unary_ops_test.py18
-rw-r--r--tensorflow/compiler/tf2xla/BUILD108
-rw-r--r--tensorflow/compiler/tf2xla/cpu_function_runtime.cc30
-rw-r--r--tensorflow/compiler/tf2xla/cpu_function_runtime.h133
-rw-r--r--tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc72
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_cond.cc1379
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_cond.h248
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_cond_test.cc180
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_control_flow.cc1518
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_control_flow.h6
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc69
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc72
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_control_flow_util.h56
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_while.cc668
-rw-r--r--tensorflow/compiler/tf2xla/functionalize_while.h32
-rw-r--r--tensorflow/compiler/tf2xla/kernels/BUILD14
-rw-r--r--tensorflow/compiler/tf2xla/kernels/conv_ops.cc78
-rw-r--r--tensorflow/compiler/tf2xla/kernels/gather_op.cc32
-rw-r--r--tensorflow/compiler/tf2xla/kernels/identity_op.cc12
-rw-r--r--tensorflow/compiler/tf2xla/kernels/if_op.cc29
-rw-r--r--tensorflow/compiler/tf2xla/kernels/reverse_op.cc20
-rw-r--r--tensorflow/compiler/tf2xla/kernels/tile_ops.cc2
-rw-r--r--tensorflow/compiler/tf2xla/lib/triangular_solve.cc14
-rw-r--r--tensorflow/compiler/tf2xla/tf2xla_util.cc26
-rw-r--r--tensorflow/compiler/tf2xla/tf2xla_util.h3
-rw-r--r--tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc60
-rw-r--r--tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h148
-rw-r--r--tensorflow/compiler/tf2xla/xla_compiler_test.cc5
-rw-r--r--tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc80
-rw-r--r--tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h8
-rw-r--r--tensorflow/compiler/xla/BUILD1
-rw-r--r--tensorflow/compiler/xla/client/BUILD1
-rw-r--r--tensorflow/compiler/xla/client/lib/math.cc6
-rw-r--r--tensorflow/compiler/xla/client/local_client.cc2
-rw-r--r--tensorflow/compiler/xla/client/xla_builder.cc145
-rw-r--r--tensorflow/compiler/xla/client/xla_builder.h57
-rw-r--r--tensorflow/compiler/xla/legacy_flags/debug_options_flags.cc27
-rw-r--r--tensorflow/compiler/xla/literal_comparison.cc57
-rw-r--r--tensorflow/compiler/xla/python/local_computation_builder.cc11
-rw-r--r--tensorflow/compiler/xla/python/local_computation_builder.h6
-rw-r--r--tensorflow/compiler/xla/python/local_computation_builder.i1
-rw-r--r--tensorflow/compiler/xla/python/xla_client.py9
-rw-r--r--tensorflow/compiler/xla/service/BUILD70
-rw-r--r--tensorflow/compiler/xla/service/algebraic_simplifier.cc23
-rw-r--r--tensorflow/compiler/xla/service/algebraic_simplifier_test.cc33
-rw-r--r--tensorflow/compiler/xla/service/batch_dot_simplification.cc9
-rw-r--r--tensorflow/compiler/xla/service/buffer_assignment.cc1
-rw-r--r--tensorflow/compiler/xla/service/call_graph.cc1
-rw-r--r--tensorflow/compiler/xla/service/compiler.h5
-rw-r--r--tensorflow/compiler/xla/service/convolution_feature_group_converter.cc248
-rw-r--r--tensorflow/compiler/xla/service/convolution_feature_group_converter.h43
-rw-r--r--tensorflow/compiler/xla/service/convolution_feature_group_converter_test.cc100
-rw-r--r--tensorflow/compiler/xla/service/copy_insertion.cc9
-rw-r--r--tensorflow/compiler/xla/service/copy_insertion_test.cc41
-rw-r--r--tensorflow/compiler/xla/service/cpu/BUILD28
-rw-r--r--tensorflow/compiler/xla/service/cpu/buffer_info_util.cc57
-rw-r--r--tensorflow/compiler/xla/service/cpu/buffer_info_util.h42
-rw-r--r--tensorflow/compiler/xla/service/cpu/cpu_compiler.cc54
-rw-r--r--tensorflow/compiler/xla/service/cpu/cpu_compiler.h17
-rw-r--r--tensorflow/compiler/xla/service/cpu/cpu_executable.cc38
-rw-r--r--tensorflow/compiler/xla/service/cpu/cpu_executable.h10
-rw-r--r--tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion_test.cc59
-rw-r--r--tensorflow/compiler/xla/service/cpu/dot_op_emitter.cc4
-rw-r--r--tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.cc74
-rw-r--r--tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h4
-rw-r--r--tensorflow/compiler/xla/service/cpu/ir_emitter.cc18
-rw-r--r--tensorflow/compiler/xla/service/cpu/parallel_task_assignment_test.cc5
-rw-r--r--tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.cc2
-rw-r--r--tensorflow/compiler/xla/service/cpu/tests/cpu_literal_caching_test.cc16
-rw-r--r--tensorflow/compiler/xla/service/cpu/tests/cpu_outfeed_test.cc3
-rw-r--r--tensorflow/compiler/xla/service/cpu/vector_support_library.cc5
-rw-r--r--tensorflow/compiler/xla/service/despecializer.cc25
-rw-r--r--tensorflow/compiler/xla/service/elemental_ir_emitter.cc19
-rw-r--r--tensorflow/compiler/xla/service/elemental_ir_emitter.h3
-rw-r--r--tensorflow/compiler/xla/service/gather_expander.cc185
-rw-r--r--tensorflow/compiler/xla/service/gather_expander_test.cc16
-rw-r--r--tensorflow/compiler/xla/service/gpu/BUILD40
-rw-r--r--tensorflow/compiler/xla/service/gpu/buffer_comparator.cc205
-rw-r--r--tensorflow/compiler/xla/service/gpu/buffer_comparator.h71
-rw-r--r--tensorflow/compiler/xla/service/gpu/buffer_comparator_test.cc126
-rw-r--r--tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.cc168
-rw-r--r--tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h9
-rw-r--r--tensorflow/compiler/xla/service/gpu/cudnn_convolution_runner.cc50
-rw-r--r--tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.cc43
-rw-r--r--tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h6
-rw-r--r--tensorflow/compiler/xla/service/gpu/fusion_merger.cc22
-rw-r--r--tensorflow/compiler/xla/service/gpu/gemm_thunk.h14
-rw-r--r--tensorflow/compiler/xla/service/gpu/gpu_executable.cc7
-rw-r--r--tensorflow/compiler/xla/service/gpu/ir_emitter.cc9
-rw-r--r--tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.cc28
-rw-r--r--tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/nvptx_backend_lib.cc2
-rw-r--r--tensorflow/compiler/xla/service/gpu/multi_output_fusion.cc7
-rw-r--r--tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc23
-rw-r--r--tensorflow/compiler/xla/service/gpu/thunk.h14
-rw-r--r--tensorflow/compiler/xla/service/hlo.proto8
-rw-r--r--tensorflow/compiler/xla/service/hlo_computation.cc7
-rw-r--r--tensorflow/compiler/xla/service/hlo_creation_utils.cc70
-rw-r--r--tensorflow/compiler/xla/service/hlo_creation_utils.h16
-rw-r--r--tensorflow/compiler/xla/service/hlo_creation_utils_test.cc2
-rw-r--r--tensorflow/compiler/xla/service/hlo_domain_test.cc33
-rw-r--r--tensorflow/compiler/xla/service/hlo_element_type_converter.cc1
-rw-r--r--tensorflow/compiler/xla/service/hlo_evaluator.cc162
-rw-r--r--tensorflow/compiler/xla/service/hlo_evaluator_test.cc590
-rw-r--r--tensorflow/compiler/xla/service/hlo_evaluator_typed_visitor.h412
-rw-r--r--tensorflow/compiler/xla/service/hlo_execution_profile.cc11
-rw-r--r--tensorflow/compiler/xla/service/hlo_instruction.cc83
-rw-r--r--tensorflow/compiler/xla/service/hlo_instruction.h26
-rw-r--r--tensorflow/compiler/xla/service/hlo_instruction_test.cc66
-rw-r--r--tensorflow/compiler/xla/service/hlo_instructions.cc111
-rw-r--r--tensorflow/compiler/xla/service/hlo_instructions.h35
-rw-r--r--tensorflow/compiler/xla/service/hlo_lexer.cc55
-rw-r--r--tensorflow/compiler/xla/service/hlo_lexer.h1
-rw-r--r--tensorflow/compiler/xla/service/hlo_matchers.h1
-rw-r--r--tensorflow/compiler/xla/service/hlo_module.cc7
-rw-r--r--tensorflow/compiler/xla/service/hlo_module_group_metadata.h4
-rw-r--r--tensorflow/compiler/xla/service/hlo_module_group_util.cc72
-rw-r--r--tensorflow/compiler/xla/service/hlo_opcode.h2
-rw-r--r--tensorflow/compiler/xla/service/hlo_parser.cc98
-rw-r--r--tensorflow/compiler/xla/service/hlo_parser_test.cc93
-rw-r--r--tensorflow/compiler/xla/service/hlo_pass_fix.h2
-rw-r--r--tensorflow/compiler/xla/service/hlo_sharding.cc2
-rw-r--r--tensorflow/compiler/xla/service/hlo_sharding_metadata.cc16
-rw-r--r--tensorflow/compiler/xla/service/hlo_token.h1
-rw-r--r--tensorflow/compiler/xla/service/hlo_verifier.cc119
-rw-r--r--tensorflow/compiler/xla/service/hlo_verifier.h7
-rw-r--r--tensorflow/compiler/xla/service/hlo_verifier_test.cc103
-rw-r--r--tensorflow/compiler/xla/service/indexed_array_analysis.cc107
-rw-r--r--tensorflow/compiler/xla/service/indexed_array_analysis.h2
-rw-r--r--tensorflow/compiler/xla/service/indexed_array_analysis_test.cc300
-rw-r--r--tensorflow/compiler/xla/service/instruction_fusion.cc3
-rw-r--r--tensorflow/compiler/xla/service/interpreter/executor.h2
-rw-r--r--tensorflow/compiler/xla/service/layout_assignment.cc2
-rw-r--r--tensorflow/compiler/xla/service/llvm_ir/BUILD1
-rw-r--r--tensorflow/compiler/xla/service/llvm_ir/ir_array.h3
-rw-r--r--tensorflow/compiler/xla/service/multi_output_fusion.h10
-rw-r--r--tensorflow/compiler/xla/service/reshape_mover.cc4
-rw-r--r--tensorflow/compiler/xla/service/reshape_mover_test.cc10
-rw-r--r--tensorflow/compiler/xla/service/scatter_expander.cc351
-rw-r--r--tensorflow/compiler/xla/service/scatter_expander.h34
-rw-r--r--tensorflow/compiler/xla/service/service.cc14
-rw-r--r--tensorflow/compiler/xla/service/shape_inference.cc225
-rw-r--r--tensorflow/compiler/xla/service/shape_inference.h7
-rw-r--r--tensorflow/compiler/xla/service/shape_inference_test.cc269
-rw-r--r--tensorflow/compiler/xla/service/while_loop_constant_sinking.cc11
-rw-r--r--tensorflow/compiler/xla/service/while_loop_constant_sinking_test.cc3
-rw-r--r--tensorflow/compiler/xla/service/while_loop_invariant_code_motion.cc15
-rw-r--r--tensorflow/compiler/xla/service/while_util.cc8
-rw-r--r--tensorflow/compiler/xla/service/while_util_test.cc3
-rw-r--r--tensorflow/compiler/xla/shape_util.cc11
-rw-r--r--tensorflow/compiler/xla/tests/BUILD25
-rw-r--r--tensorflow/compiler/xla/tests/client_library_test_base.h5
-rw-r--r--tensorflow/compiler/xla/tests/convert_test.cc13
-rw-r--r--tensorflow/compiler/xla/tests/convolution_test.cc177
-rw-r--r--tensorflow/compiler/xla/tests/gather_operation_test.cc312
-rw-r--r--tensorflow/compiler/xla/tests/hlo_test_base.cc46
-rw-r--r--tensorflow/compiler/xla/tests/hlo_test_base.h21
-rw-r--r--tensorflow/compiler/xla/tests/llvm_irgen_test_base.cc8
-rw-r--r--tensorflow/compiler/xla/tests/local_client_aot_test_helper.cc8
-rw-r--r--tensorflow/compiler/xla/tests/reduce_window_test.cc39
-rw-r--r--tensorflow/compiler/xla/tests/scatter_test.cc615
-rw-r--r--tensorflow/compiler/xla/tests/test_utils.cc253
-rw-r--r--tensorflow/compiler/xla/tests/test_utils.h19
-rw-r--r--tensorflow/compiler/xla/tests/test_utils_test.cc102
-rw-r--r--tensorflow/compiler/xla/tests/tuple_test.cc2
-rw-r--r--tensorflow/compiler/xla/tests/xla_hlo_profile_test.cc5
-rw-r--r--tensorflow/compiler/xla/tools/replay_computation.cc9
-rw-r--r--tensorflow/compiler/xla/util.h116
-rw-r--r--tensorflow/compiler/xla/xla.proto28
-rw-r--r--tensorflow/compiler/xla/xla_data.proto18
-rw-r--r--tensorflow/contrib/BUILD5
-rw-r--r--tensorflow/contrib/__init__.py3
-rw-r--r--tensorflow/contrib/all_reduce/python/all_reduce.py70
-rw-r--r--tensorflow/contrib/autograph/docs/pyfunc_dtypes.md33
-rw-r--r--tensorflow/contrib/autograph/impl/api.py120
-rw-r--r--tensorflow/contrib/autograph/operators/control_flow.py2
-rw-r--r--tensorflow/contrib/autograph/pyct/static_analysis/reaching_definitions.py2
-rw-r--r--tensorflow/contrib/autograph/pyct/testing/BUILD5
-rw-r--r--tensorflow/contrib/autograph/utils/builtins.py9
-rw-r--r--tensorflow/contrib/autograph/utils/builtins_test.py17
-rw-r--r--tensorflow/contrib/bayesflow/python/ops/monte_carlo_impl.py2
-rw-r--r--tensorflow/contrib/bigtable/README.md4
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_kernels.cc13
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_lookup_dataset_op.cc16
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_prefix_key_dataset_op.cc18
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_range_key_dataset_op.cc16
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_sample_key_pairs_dataset_op.cc14
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_sample_keys_dataset_op.cc14
-rw-r--r--tensorflow/contrib/bigtable/kernels/bigtable_scan_dataset_op.cc16
-rw-r--r--tensorflow/contrib/bigtable/python/ops/bigtable_api.py32
-rw-r--r--tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py61
-rw-r--r--tensorflow/contrib/boosted_trees/kernels/split_handler_ops.cc184
-rw-r--r--tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py75
-rw-r--r--tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler_test.py127
-rw-r--r--tensorflow/contrib/boosted_trees/ops/split_handler_ops.cc3
-rw-r--r--tensorflow/contrib/boosted_trees/proto/learner.proto8
-rw-r--r--tensorflow/contrib/boosted_trees/proto/split_info.proto7
-rw-r--r--tensorflow/contrib/boosted_trees/python/kernel_tests/split_handler_ops_test.py9
-rw-r--r--tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py18
-rw-r--r--tensorflow/contrib/checkpoint/__init__.py8
-rw-r--r--tensorflow/contrib/checkpoint/python/BUILD28
-rw-r--r--tensorflow/contrib/checkpoint/python/python_state.py166
-rw-r--r--tensorflow/contrib/checkpoint/python/python_state_test.py101
-rw-r--r--tensorflow/contrib/cloud/python/ops/gcs_config_ops.py5
-rw-r--r--tensorflow/contrib/cmake/external/nsync.cmake8
-rw-r--r--tensorflow/contrib/cmake/patches/nsync/CMakeLists.txt325
-rw-r--r--tensorflow/contrib/cmake/python_modules.txt4
-rwxr-xr-xtensorflow/contrib/cmake/tf_python.cmake93
-rw-r--r--tensorflow/contrib/cmake/tf_tests.cmake19
-rw-r--r--tensorflow/contrib/constrained_optimization/python/candidates.py2
-rw-r--r--tensorflow/contrib/constrained_optimization/python/constrained_minimization_problem.py19
-rw-r--r--tensorflow/contrib/constrained_optimization/python/constrained_optimizer.py128
-rw-r--r--tensorflow/contrib/constrained_optimization/python/external_regret_optimizer.py53
-rw-r--r--tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.py67
-rw-r--r--tensorflow/contrib/crf/__init__.py2
-rw-r--r--tensorflow/contrib/crf/python/kernel_tests/crf_test.py4
-rw-r--r--tensorflow/contrib/crf/python/ops/crf.py4
-rw-r--r--tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py4
-rw-r--r--tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py30
-rw-r--r--tensorflow/contrib/data/__init__.py4
-rw-r--r--tensorflow/contrib/data/kernels/assert_next_dataset_op.cc13
-rw-r--r--tensorflow/contrib/data/kernels/csv_dataset_op.cc7
-rw-r--r--tensorflow/contrib/data/kernels/directed_interleave_dataset_op.cc20
-rw-r--r--tensorflow/contrib/data/kernels/ignore_errors_dataset_op.cc13
-rw-r--r--tensorflow/contrib/data/kernels/prefetching_kernels.cc361
-rw-r--r--tensorflow/contrib/data/kernels/threadpool_dataset_op.cc14
-rw-r--r--tensorflow/contrib/data/kernels/unique_dataset_op.cc13
-rw-r--r--tensorflow/contrib/data/ops/dataset_ops.cc2
-rw-r--r--tensorflow/contrib/data/python/kernel_tests/BUILD2
-rw-r--r--tensorflow/contrib/data/python/kernel_tests/interleave_dataset_op_test.py28
-rw-r--r--tensorflow/contrib/data/python/kernel_tests/prefetching_ops_test.py4
-rw-r--r--tensorflow/contrib/data/python/ops/batching.py22
-rw-r--r--tensorflow/contrib/data/python/ops/enumerate_ops.py2
-rw-r--r--tensorflow/contrib/data/python/ops/error_ops.py2
-rw-r--r--tensorflow/contrib/data/python/ops/get_single_element.py14
-rw-r--r--tensorflow/contrib/data/python/ops/grouping.py10
-rw-r--r--tensorflow/contrib/data/python/ops/interleave_ops.py16
-rw-r--r--tensorflow/contrib/data/python/ops/iterator_ops.py2
-rw-r--r--tensorflow/contrib/data/python/ops/optimization.py4
-rw-r--r--tensorflow/contrib/data/python/ops/prefetching_ops.py17
-rw-r--r--tensorflow/contrib/data/python/ops/readers.py4
-rw-r--r--tensorflow/contrib/data/python/ops/resampling.py2
-rw-r--r--tensorflow/contrib/data/python/ops/scan_ops.py4
-rw-r--r--tensorflow/contrib/data/python/ops/shuffle_ops.py4
-rw-r--r--tensorflow/contrib/data/python/ops/sliding.py2
-rw-r--r--tensorflow/contrib/data/python/ops/stats_ops.py20
-rw-r--r--tensorflow/contrib/data/python/ops/threadpool.py2
-rw-r--r--tensorflow/contrib/data/python/ops/unique.py2
-rw-r--r--tensorflow/contrib/data/python/ops/writers.py6
-rw-r--r--tensorflow/contrib/distribute/BUILD1
-rw-r--r--tensorflow/contrib/distribute/__init__.py4
-rw-r--r--tensorflow/contrib/distribute/python/BUILD65
-rw-r--r--tensorflow/contrib/distribute/python/combinations.py32
-rw-r--r--tensorflow/contrib/distribute/python/cross_tower_ops.py12
-rw-r--r--tensorflow/contrib/distribute/python/cross_tower_ops_test.py10
-rw-r--r--tensorflow/contrib/distribute/python/estimator_integration_test.py23
-rw-r--r--tensorflow/contrib/distribute/python/keras_test.py45
-rw-r--r--tensorflow/contrib/distribute/python/metrics_v1_test.py2
-rw-r--r--tensorflow/contrib/distribute/python/minimize_loss_test.py308
-rw-r--r--tensorflow/contrib/distribute/python/mirrored_strategy.py150
-rw-r--r--tensorflow/contrib/distribute/python/mirrored_strategy_multigpu_test.py52
-rw-r--r--tensorflow/contrib/distribute/python/mirrored_strategy_test.py37
-rw-r--r--tensorflow/contrib/distribute/python/multi_worker_strategy.py141
-rw-r--r--tensorflow/contrib/distribute/python/multi_worker_strategy_test.py62
-rw-r--r--tensorflow/contrib/distribute/python/one_device_strategy.py16
-rw-r--r--tensorflow/contrib/distribute/python/parameter_server_strategy.py77
-rw-r--r--tensorflow/contrib/distribute/python/parameter_server_strategy_test.py27
-rw-r--r--tensorflow/contrib/distribute/python/prefetching_ops_v2.py8
-rw-r--r--tensorflow/contrib/distribute/python/single_loss_example.py10
-rw-r--r--tensorflow/contrib/distribute/python/step_fn.py67
-rw-r--r--tensorflow/contrib/distribute/python/step_fn_test.py17
-rw-r--r--tensorflow/contrib/distribute/python/strategy_test_lib.py12
-rw-r--r--tensorflow/contrib/distribute/python/tpu_strategy.py30
-rw-r--r--tensorflow/contrib/distribute/python/values.py39
-rw-r--r--tensorflow/contrib/distributions/python/kernel_tests/bijectors/matrix_inverse_tril_test.py13
-rw-r--r--tensorflow/contrib/distributions/python/kernel_tests/deterministic_test.py14
-rw-r--r--tensorflow/contrib/distributions/python/ops/deterministic.py3
-rw-r--r--tensorflow/contrib/distributions/python/ops/sample_stats.py4
-rw-r--r--tensorflow/contrib/eager/python/BUILD17
-rw-r--r--tensorflow/contrib/eager/python/datasets.py2
-rw-r--r--tensorflow/contrib/eager/python/examples/densenet/densenet_test.py11
-rw-r--r--tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb649
-rw-r--r--tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb263
-rw-r--r--tensorflow/contrib/eager/python/examples/generative_examples/text_generation.ipynb166
-rw-r--r--tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb582
-rw-r--r--tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb810
-rw-r--r--tensorflow/contrib/eager/python/examples/resnet50/resnet50_test.py11
-rw-r--r--tensorflow/contrib/eager/python/examples/revnet/revnet_test.py8
-rw-r--r--tensorflow/contrib/eager/python/remote_test.py178
-rw-r--r--tensorflow/contrib/eager/python/saver.py2
-rw-r--r--tensorflow/contrib/eager/python/saver_test.py51
-rw-r--r--tensorflow/contrib/eager/python/tfe.py4
-rw-r--r--tensorflow/contrib/estimator/BUILD31
-rw-r--r--tensorflow/contrib/estimator/__init__.py1
-rw-r--r--tensorflow/contrib/estimator/python/estimator/dnn_linear_combined.py2
-rw-r--r--tensorflow/contrib/estimator/python/estimator/export.py4
-rw-r--r--tensorflow/contrib/estimator/python/estimator/exporter.py280
-rw-r--r--tensorflow/contrib/estimator/python/estimator/exporter_test.py206
-rw-r--r--tensorflow/contrib/estimator/python/estimator/extenders.py10
-rw-r--r--tensorflow/contrib/estimator/python/estimator/hooks.py75
-rw-r--r--tensorflow/contrib/estimator/python/estimator/hooks_test.py83
-rw-r--r--tensorflow/contrib/estimator/python/estimator/linear.py2
-rw-r--r--tensorflow/contrib/factorization/BUILD4
-rw-r--r--tensorflow/contrib/factorization/python/ops/kmeans.py17
-rw-r--r--tensorflow/contrib/ffmpeg/__init__.py2
-rw-r--r--tensorflow/contrib/framework/__init__.py7
-rw-r--r--tensorflow/contrib/framework/python/ops/arg_scope.py5
-rw-r--r--tensorflow/contrib/framework/python/ops/arg_scope_test.py15
-rw-r--r--tensorflow/contrib/framework/python/ops/critical_section_ops.py5
-rw-r--r--tensorflow/contrib/framework/python/ops/script_ops.py2
-rw-r--r--tensorflow/contrib/framework/python/ops/variables.py8
-rw-r--r--tensorflow/contrib/fused_conv/kernels/fused_conv2d_bias_activation_op.h6
-rw-r--r--tensorflow/contrib/gan/BUILD13
-rw-r--r--tensorflow/contrib/gan/python/eval/python/summaries_impl.py91
-rw-r--r--tensorflow/contrib/gan/python/eval/python/summaries_test.py40
-rw-r--r--tensorflow/contrib/gan/python/train.py14
-rw-r--r--tensorflow/contrib/graph_editor/__init__.py4
-rw-r--r--tensorflow/contrib/graph_editor/transform.py2
-rw-r--r--tensorflow/contrib/hadoop/BUILD117
-rw-r--r--tensorflow/contrib/hadoop/__init__.py32
-rw-r--r--tensorflow/contrib/hadoop/kernels/hadoop_dataset_ops.cc340
-rw-r--r--tensorflow/contrib/hadoop/ops/dataset_ops.cc (renamed from tensorflow/contrib/lite/delegates/eager/constants.h)22
-rw-r--r--tensorflow/contrib/hadoop/python/kernel_tests/hadoop_test.py66
-rwxr-xr-xtensorflow/contrib/hadoop/python/kernel_tests/testdata/string.seqbin0 -> 603 bytes
-rw-r--r--tensorflow/contrib/hadoop/python/ops/hadoop_dataset_ops.py75
-rw-r--r--tensorflow/contrib/hadoop/python/ops/hadoop_op_loader.py24
-rw-r--r--tensorflow/contrib/image/kernels/image_ops.cc33
-rw-r--r--tensorflow/contrib/image/kernels/image_ops.h2
-rw-r--r--tensorflow/contrib/image/ops/image_ops.cc57
-rw-r--r--tensorflow/contrib/image/python/kernel_tests/image_ops_test.py44
-rw-r--r--tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py76
-rw-r--r--tensorflow/contrib/image/python/ops/image_ops.py52
-rw-r--r--tensorflow/contrib/image/python/ops/interpolate_spline.py35
-rw-r--r--tensorflow/contrib/image/python/ops/sparse_image_warp.py6
-rw-r--r--tensorflow/contrib/integrate/__init__.py4
-rw-r--r--tensorflow/contrib/integrate/python/ops/odes.py4
-rw-r--r--tensorflow/contrib/kafka/kernels/kafka_dataset_ops.cc9
-rw-r--r--tensorflow/contrib/keras/__init__.py2
-rw-r--r--tensorflow/contrib/kernel_methods/README.md16
-rw-r--r--tensorflow/contrib/kfac/examples/convnet.py8
-rw-r--r--tensorflow/contrib/kfac/python/ops/estimator.py6
-rw-r--r--tensorflow/contrib/kfac/python/ops/fisher_blocks.py2
-rw-r--r--tensorflow/contrib/kfac/python/ops/fisher_factors.py12
-rw-r--r--tensorflow/contrib/kfac/python/ops/layer_collection.py8
-rw-r--r--tensorflow/contrib/kfac/python/ops/loss_functions.py6
-rw-r--r--tensorflow/contrib/kfac/python/ops/optimizer.py8
-rw-r--r--tensorflow/contrib/kinesis/kernels/kinesis_dataset_ops.cc7
-rw-r--r--tensorflow/contrib/layers/__init__.py4
-rw-r--r--tensorflow/contrib/layers/python/layers/feature_column.py9
-rw-r--r--tensorflow/contrib/layers/python/layers/feature_column_test.py51
-rw-r--r--tensorflow/contrib/layers/python/layers/initializers.py6
-rw-r--r--tensorflow/contrib/layers/python/layers/layers.py2
-rw-r--r--tensorflow/contrib/layers/python/layers/layers_test.py4
-rw-r--r--tensorflow/contrib/learn/BUILD22
-rw-r--r--tensorflow/contrib/learn/__init__.py3
-rw-r--r--tensorflow/contrib/learn/python/learn/estimators/kmeans.py6
-rw-r--r--tensorflow/contrib/learn/python/learn/estimators/run_config.py2
-rw-r--r--tensorflow/contrib/learn/python/learn/experiment.py8
-rw-r--r--tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py8
-rw-r--r--tensorflow/contrib/linalg/__init__.py3
-rw-r--r--tensorflow/contrib/linear_optimizer/python/sdca_optimizer.py6
-rw-r--r--tensorflow/contrib/lite/BUILD8
-rw-r--r--tensorflow/contrib/lite/build_def.bzl2
-rw-r--r--tensorflow/contrib/lite/context.h25
-rw-r--r--tensorflow/contrib/lite/delegates/eager/BUILD107
-rw-r--r--tensorflow/contrib/lite/delegates/eager/buffer_map_test.cc4
-rw-r--r--tensorflow/contrib/lite/delegates/eager/delegate.cc50
-rw-r--r--tensorflow/contrib/lite/delegates/eager/delegate.h26
-rw-r--r--tensorflow/contrib/lite/delegates/eager/delegate_data.h10
-rw-r--r--tensorflow/contrib/lite/delegates/eager/delegate_data_test.cc7
-rw-r--r--tensorflow/contrib/lite/delegates/eager/delegate_test.cc64
-rw-r--r--tensorflow/contrib/lite/delegates/eager/kernel.cc7
-rw-r--r--tensorflow/contrib/lite/delegates/eager/kernel_test.cc8
-rw-r--r--tensorflow/contrib/lite/delegates/eager/test_util.cc3
-rw-r--r--tensorflow/contrib/lite/delegates/eager/util.cc6
-rw-r--r--tensorflow/contrib/lite/delegates/eager/util.h4
-rw-r--r--tensorflow/contrib/lite/delegates/eager/util_test.cc11
-rw-r--r--tensorflow/contrib/lite/delegates/nnapi/nnapi_delegate.cc418
-rw-r--r--tensorflow/contrib/lite/error_reporter.cc13
-rw-r--r--tensorflow/contrib/lite/examples/android/build.gradle1
-rw-r--r--tensorflow/contrib/lite/examples/ios/camera/CameraExampleViewController.mm4
-rw-r--r--tensorflow/contrib/lite/examples/ios/camera/Podfile2
-rw-r--r--tensorflow/contrib/lite/examples/ios/simple/Podfile2
-rw-r--r--tensorflow/contrib/lite/examples/ios/simple/RunModelViewController.mm2
-rw-r--r--tensorflow/contrib/lite/examples/ios/simple/ios_image_load.h6
-rw-r--r--tensorflow/contrib/lite/examples/python/BUILD13
-rw-r--r--tensorflow/contrib/lite/examples/python/label_image.md50
-rw-r--r--tensorflow/contrib/lite/examples/python/label_image.py86
-rw-r--r--tensorflow/contrib/lite/experimental/c/BUILD41
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api.cc64
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api.h59
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api_experimental.cc31
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api_experimental.h32
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api_experimental_test.cc46
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api_internal.h41
-rw-r--r--tensorflow/contrib/lite/experimental/c/c_api_test.cc20
-rw-r--r--tensorflow/contrib/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/SDK/Scripts/Interpreter.cs16
-rw-r--r--tensorflow/contrib/lite/g3doc/_book.yaml1
-rw-r--r--tensorflow/contrib/lite/g3doc/rpi.md4
-rw-r--r--tensorflow/contrib/lite/interpreter.cc4
-rw-r--r--tensorflow/contrib/lite/interpreter.h36
-rw-r--r--tensorflow/contrib/lite/interpreter_test.cc75
-rw-r--r--tensorflow/contrib/lite/java/demo/.gitignore28
-rw-r--r--tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/DataType.java44
-rw-r--r--tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Interpreter.java70
-rw-r--r--tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/NativeInterpreterWrapper.java29
-rw-r--r--tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Tensor.java51
-rw-r--r--tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/DataTypeTest.java15
-rw-r--r--tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/InterpreterTest.java19
-rw-r--r--tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/TensorTest.java22
-rw-r--r--tensorflow/contrib/lite/java/src/testhelper/java/org/tensorflow/lite/TestHelper.java19
-rw-r--r--tensorflow/contrib/lite/kernels/BUILD1
-rw-r--r--tensorflow/contrib/lite/kernels/activations.cc58
-rw-r--r--tensorflow/contrib/lite/kernels/activations_test.cc22
-rw-r--r--tensorflow/contrib/lite/kernels/conv.cc48
-rw-r--r--tensorflow/contrib/lite/kernels/conv_test.cc124
-rw-r--r--tensorflow/contrib/lite/kernels/dequantize.cc34
-rw-r--r--tensorflow/contrib/lite/kernels/fully_connected.cc7
-rw-r--r--tensorflow/contrib/lite/kernels/fully_connected_test.cc62
-rw-r--r--tensorflow/contrib/lite/kernels/internal/BUILD9
-rw-r--r--tensorflow/contrib/lite/kernels/internal/log_quantized_test.cc5
-rw-r--r--tensorflow/contrib/lite/kernels/internal/logsoftmax_quantized_test.cc1
-rw-r--r--tensorflow/contrib/lite/kernels/internal/optimized/legacy_optimized_ops.h48
-rw-r--r--tensorflow/contrib/lite/kernels/internal/optimized/optimized_ops.h625
-rw-r--r--tensorflow/contrib/lite/kernels/internal/quantization_util_test.cc32
-rw-r--r--tensorflow/contrib/lite/kernels/internal/reference/legacy_reference_ops.h60
-rw-r--r--tensorflow/contrib/lite/kernels/internal/reference/portable_tensor_utils.cc4
-rw-r--r--tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h729
-rw-r--r--tensorflow/contrib/lite/kernels/internal/softmax_quantized_test.cc1
-rw-r--r--tensorflow/contrib/lite/kernels/internal/tensor_utils_test.cc16
-rw-r--r--tensorflow/contrib/lite/kernels/internal/types.h238
-rw-r--r--tensorflow/contrib/lite/kernels/mul.cc5
-rw-r--r--tensorflow/contrib/lite/kernels/pack.cc47
-rw-r--r--tensorflow/contrib/lite/kernels/pack_test.cc40
-rw-r--r--tensorflow/contrib/lite/kernels/register.cc5
-rw-r--r--tensorflow/contrib/lite/model.cc11
-rw-r--r--tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h13
-rw-r--r--tensorflow/contrib/lite/nnapi_delegate.cc27
-rw-r--r--tensorflow/contrib/lite/python/BUILD3
-rw-r--r--tensorflow/contrib/lite/python/convert.py37
-rw-r--r--tensorflow/contrib/lite/python/convert_test.py93
-rw-r--r--tensorflow/contrib/lite/python/interpreter.py4
-rw-r--r--tensorflow/contrib/lite/python/interpreter_wrapper/interpreter_wrapper.h7
-rw-r--r--tensorflow/contrib/lite/python/lite.py81
-rw-r--r--tensorflow/contrib/lite/python/lite_test.py62
-rw-r--r--tensorflow/contrib/lite/python/op_hint.py898
-rw-r--r--tensorflow/contrib/lite/python/tflite_convert.py11
-rw-r--r--tensorflow/contrib/lite/rpi_makefile.inc33
-rw-r--r--tensorflow/contrib/lite/schema/upgrade_schema.py6
-rw-r--r--tensorflow/contrib/lite/string.h6
-rw-r--r--tensorflow/contrib/lite/testing/BUILD3
-rw-r--r--tensorflow/contrib/lite/testing/generate_examples.py134
-rw-r--r--tensorflow/contrib/lite/testing/generate_testspec.cc8
-rw-r--r--tensorflow/contrib/lite/testing/generated_examples_zip_test.cc94
-rw-r--r--tensorflow/contrib/lite/testing/tf_driver.cc4
-rw-r--r--tensorflow/contrib/lite/testing/tflite_diff_flags.h27
-rw-r--r--tensorflow/contrib/lite/testing/tflite_diff_util.cc2
-rw-r--r--tensorflow/contrib/lite/testing/tflite_diff_util.h3
-rw-r--r--tensorflow/contrib/lite/testing/tflite_driver.cc18
-rw-r--r--tensorflow/contrib/lite/testing/tflite_driver.h4
-rw-r--r--tensorflow/contrib/lite/toco/BUILD3
-rw-r--r--tensorflow/contrib/lite/toco/allocate_transient_arrays.cc16
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/convert_pure_conv_to_depthwise.cc12
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/fuse_binary_into_preceding_affine.cc24
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h2
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/hardcode_min_max.cc18
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc24
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.h3
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_fake_quant.cc1
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_reshape.cc8
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_select.cc78
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_tile.cc165
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_transpose.cc8
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_unary.cc4
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/resolve_tensorflow_switch.cc4
-rw-r--r--tensorflow/contrib/lite/toco/graph_transformations/unroll_batch_matmul.cc1
-rw-r--r--tensorflow/contrib/lite/toco/model.h2
-rw-r--r--tensorflow/contrib/lite/toco/python/toco_python_api.h6
-rw-r--r--tensorflow/contrib/lite/toco/tflite/BUILD1
-rw-r--r--tensorflow/contrib/lite/toco/tflite/operator.cc275
-rw-r--r--tensorflow/contrib/lite/toco/toco_port.cc14
-rw-r--r--tensorflow/contrib/lite/toco/toco_tooling.cc2
-rw-r--r--tensorflow/contrib/lite/toco/tooling_util.cc10
-rw-r--r--tensorflow/contrib/lite/toco/tooling_util.h3
-rw-r--r--tensorflow/contrib/lite/tools/benchmark/BUILD41
-rw-r--r--tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.cc13
-rw-r--r--tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.h8
-rw-r--r--tensorflow/contrib/lite/tools/make/Makefile (renamed from tensorflow/contrib/lite/Makefile)132
-rwxr-xr-xtensorflow/contrib/lite/tools/make/build_ios_universal_lib.sh (renamed from tensorflow/contrib/lite/build_ios_universal_lib.sh)18
-rwxr-xr-xtensorflow/contrib/lite/tools/make/build_rpi_lib.sh (renamed from tensorflow/contrib/lite/build_rpi_lib.sh)4
-rwxr-xr-xtensorflow/contrib/lite/tools/make/download_dependencies.sh (renamed from tensorflow/contrib/lite/download_dependencies.sh)4
-rw-r--r--tensorflow/contrib/lite/tools/make/targets/ios_makefile.inc (renamed from tensorflow/contrib/lite/ios_makefile.inc)26
-rw-r--r--tensorflow/contrib/lite/tools/make/targets/linux_makefile.inc10
-rw-r--r--tensorflow/contrib/lite/tools/make/targets/riscv_makefile.inc10
-rw-r--r--tensorflow/contrib/lite/tools/make/targets/rpi_makefile.inc60
-rw-r--r--tensorflow/contrib/lite/tools/make/targets/stm32f1_makefile.inc21
-rw-r--r--tensorflow/contrib/lite/tools/make/targets/stm32f7_makefile.inc41
-rw-r--r--tensorflow/contrib/lite/util.cc7
-rw-r--r--tensorflow/contrib/lite/util.h10
-rw-r--r--tensorflow/contrib/lite/util_test.cc10
-rw-r--r--tensorflow/contrib/lookup/BUILD1
-rw-r--r--tensorflow/contrib/lookup/lookup_ops.py88
-rw-r--r--tensorflow/contrib/lookup/lookup_ops_test.py179
-rw-r--r--tensorflow/contrib/losses/__init__.py2
-rw-r--r--tensorflow/contrib/losses/python/losses/__init__.py2
-rw-r--r--tensorflow/contrib/losses/python/metric_learning/__init__.py4
-rwxr-xr-xtensorflow/contrib/makefile/compile_nsync.sh1
-rwxr-xr-xtensorflow/contrib/makefile/download_dependencies.sh4
-rw-r--r--tensorflow/contrib/metrics/__init__.py4
-rw-r--r--tensorflow/contrib/metrics/python/metrics/classification.py4
-rw-r--r--tensorflow/contrib/mixed_precision/python/loss_scale_manager.py4
-rw-r--r--tensorflow/contrib/mixed_precision/python/loss_scale_optimizer.py6
-rw-r--r--tensorflow/contrib/model_pruning/BUILD1
-rw-r--r--tensorflow/contrib/model_pruning/python/layers/layers.py2
-rw-r--r--tensorflow/contrib/model_pruning/python/layers/rnn_cells.py2
-rw-r--r--tensorflow/contrib/model_pruning/python/pruning.py4
-rw-r--r--tensorflow/contrib/model_pruning/python/pruning_utils.py70
-rw-r--r--tensorflow/contrib/model_pruning/python/pruning_utils_test.py62
-rw-r--r--tensorflow/contrib/nccl/kernels/nccl_manager.h7
-rw-r--r--tensorflow/contrib/nn/python/ops/alpha_dropout.py2
-rw-r--r--tensorflow/contrib/nn/python/ops/sampling_ops.py10
-rw-r--r--tensorflow/contrib/opt/BUILD16
-rw-r--r--tensorflow/contrib/opt/__init__.py2
-rw-r--r--tensorflow/contrib/opt/python/training/elastic_average_optimizer.py166
-rw-r--r--tensorflow/contrib/opt/python/training/elastic_average_optimizer_test.py113
-rw-r--r--tensorflow/contrib/opt/python/training/lars_optimizer.py164
-rw-r--r--tensorflow/contrib/opt/python/training/lars_optimizer_test.py127
-rw-r--r--tensorflow/contrib/opt/python/training/shampoo.py6
-rw-r--r--tensorflow/contrib/optimizer_v2/optimizer_v2.py11
-rw-r--r--tensorflow/contrib/optimizer_v2/rmsprop.py32
-rw-r--r--tensorflow/contrib/optimizer_v2/rmsprop_test.py128
-rw-r--r--tensorflow/contrib/predictor/BUILD6
-rw-r--r--tensorflow/contrib/quantize/BUILD2
-rw-r--r--tensorflow/contrib/quantize/python/quant_ops_test.py4
-rw-r--r--tensorflow/contrib/quantize/python/quantize.py24
-rw-r--r--tensorflow/contrib/quantize/python/quantize_graph.py53
-rw-r--r--tensorflow/contrib/quantize/python/quantize_graph_test.py15
-rw-r--r--tensorflow/contrib/quantize/python/quantize_test.py54
-rw-r--r--tensorflow/contrib/rnn/BUILD8
-rw-r--r--tensorflow/contrib/rnn/__init__.py2
-rw-r--r--tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py5
-rw-r--r--tensorflow/contrib/rnn/python/ops/rnn_cell.py2
-rw-r--r--tensorflow/contrib/saved_model/BUILD1
-rw-r--r--tensorflow/contrib/seq2seq/BUILD2
-rw-r--r--tensorflow/contrib/seq2seq/__init__.py4
-rw-r--r--tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py10
-rw-r--r--tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py2
-rw-r--r--tensorflow/contrib/signal/__init__.py4
-rw-r--r--tensorflow/contrib/signal/python/kernel_tests/test_util.py6
-rw-r--r--tensorflow/contrib/signal/python/ops/mel_ops.py2
-rw-r--r--tensorflow/contrib/signal/python/ops/reconstruction_ops.py26
-rw-r--r--tensorflow/contrib/slim/python/slim/evaluation.py25
-rw-r--r--tensorflow/contrib/stat_summarizer/BUILD5
-rw-r--r--tensorflow/contrib/summary/summary.py2
-rw-r--r--tensorflow/contrib/tensor_forest/BUILD1
-rw-r--r--tensorflow/contrib/tensor_forest/client/random_forest.py334
-rw-r--r--tensorflow/contrib/tensor_forest/client/random_forest_test.py305
-rw-r--r--tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.cc19
-rw-r--r--tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.h4
-rw-r--r--tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator_test.cc34
-rw-r--r--tensorflow/contrib/tensorrt/BUILD18
-rw-r--r--tensorflow/contrib/tensorrt/convert/convert_nodes.cc261
-rw-r--r--tensorflow/contrib/tensorrt/custom_plugin_examples/inc_op_kernel.cu.cc9
-rw-r--r--tensorflow/contrib/tensorrt/segment/segment.cc78
-rw-r--r--tensorflow/contrib/tensorrt/test/base_test.py154
-rw-r--r--tensorflow/contrib/tensorrt/test/batch_matmul_test.py42
-rw-r--r--tensorflow/contrib/tensorrt/test/biasadd_matmul_test.py58
-rw-r--r--tensorflow/contrib/tensorrt/test/binary_tensor_weight_broadcast_test.py47
-rw-r--r--tensorflow/contrib/tensorrt/test/concatenation_test.py13
-rw-r--r--tensorflow/contrib/tensorrt/test/const_broadcast_test.py21
-rw-r--r--tensorflow/contrib/tensorrt/test/manual_test.py114
-rw-r--r--tensorflow/contrib/tensorrt/test/memory_alignment_test.py21
-rw-r--r--tensorflow/contrib/tensorrt/test/multi_connection_neighbor_engine_test.py13
-rw-r--r--tensorflow/contrib/tensorrt/test/neighboring_engine_test.py19
-rw-r--r--tensorflow/contrib/tensorrt/test/rank_two_test.py89
-rw-r--r--tensorflow/contrib/tensorrt/test/tf_trt_integration_test_base.py304
-rw-r--r--tensorflow/contrib/tensorrt/test/unary_test.py19
-rw-r--r--tensorflow/contrib/tensorrt/test/vgg_block_nchw_test.py21
-rw-r--r--tensorflow/contrib/tensorrt/test/vgg_block_test.py21
-rw-r--r--tensorflow/contrib/timeseries/examples/BUILD2
-rw-r--r--tensorflow/contrib/timeseries/examples/predict.py16
-rw-r--r--tensorflow/contrib/timeseries/python/timeseries/BUILD4
-rw-r--r--tensorflow/contrib/timeseries/python/timeseries/ar_model_test.py2
-rw-r--r--tensorflow/contrib/timeseries/python/timeseries/estimators_test.py6
-rw-r--r--tensorflow/contrib/timeseries/python/timeseries/head.py3
-rw-r--r--tensorflow/contrib/timeseries/python/timeseries/head_test.py2
-rw-r--r--tensorflow/contrib/tpu/BUILD8
-rw-r--r--tensorflow/contrib/tpu/profiler/pip_package/setup.py2
-rw-r--r--tensorflow/contrib/tpu/profiler/version.h2
-rw-r--r--tensorflow/contrib/tpu/python/tpu/keras_support.py95
-rw-r--r--tensorflow/contrib/tpu/python/tpu/tpu.py13
-rw-r--r--tensorflow/contrib/tpu/python/tpu/tpu_estimator.py225
-rw-r--r--tensorflow/contrib/tpu/python/tpu/tpu_estimator_signals_test.py53
-rw-r--r--tensorflow/contrib/training/BUILD4
-rw-r--r--tensorflow/contrib/training/__init__.py4
-rw-r--r--tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py6
-rw-r--r--tensorflow/contrib/training/python/training/tensor_queue_dataset.py2
-rw-r--r--tensorflow/contrib/training/python/training/training.py6
-rw-r--r--tensorflow/contrib/util/__init__.py2
-rw-r--r--tensorflow/core/BUILD72
-rw-r--r--tensorflow/core/api_def/api_test.cc4
-rw-r--r--tensorflow/core/api_def/base_api/api_def_DivNoNan.pbtxt9
-rw-r--r--tensorflow/core/api_def/base_api/api_def_Fill.pbtxt10
-rw-r--r--tensorflow/core/api_def/base_api/api_def_GatherNd.pbtxt4
-rw-r--r--tensorflow/core/api_def/base_api/api_def_GatherV2.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_HostConst.pbtxt11
-rw-r--r--tensorflow/core/api_def/base_api/api_def_Igamma.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ResourceScatterNdAdd.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ResourceScatterNdUpdate.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ScatterNd.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ScatterNdAdd.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ScatterNdNonAliasingAdd.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ScatterNdSub.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_ScatterNdUpdate.pbtxt2
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SegmentMax.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SegmentMean.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SegmentMin.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SegmentProd.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SegmentSum.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SparseSegmentMean.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SparseSegmentMeanWithNumSegments.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtN.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtNWithNumSegments.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SparseSegmentSum.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_SparseSegmentSumWithNumSegments.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_StaticRegexReplace.pbtxt26
-rw-r--r--tensorflow/core/api_def/base_api/api_def_StringLength.pbtxt20
-rw-r--r--tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMax.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMin.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_UnsortedSegmentProd.pbtxt5
-rw-r--r--tensorflow/core/api_def/base_api/api_def_UnsortedSegmentSum.pbtxt5
-rw-r--r--tensorflow/core/api_def/python_api/api_def_DivNoNan.pbtxt4
-rw-r--r--tensorflow/core/api_def/python_api/api_def_ScatterSub.pbtxt4
-rw-r--r--tensorflow/core/api_def/python_api/api_def_StringLength.pbtxt6
-rw-r--r--tensorflow/core/common_runtime/collective_rma_local.h2
-rw-r--r--tensorflow/core/common_runtime/direct_session.cc8
-rw-r--r--tensorflow/core/common_runtime/eager/attr_builder.cc8
-rw-r--r--tensorflow/core/common_runtime/eager/attr_builder.h3
-rw-r--r--tensorflow/core/common_runtime/eager/context.h4
-rw-r--r--tensorflow/core/common_runtime/eager/execute.cc17
-rw-r--r--tensorflow/core/common_runtime/eager/kernel_and_device.h7
-rw-r--r--tensorflow/core/common_runtime/executor.cc125
-rw-r--r--tensorflow/core/common_runtime/executor.h2
-rw-r--r--tensorflow/core/common_runtime/graph_execution_state.cc5
-rw-r--r--tensorflow/core/common_runtime/mkl_cpu_allocator.h4
-rw-r--r--tensorflow/core/common_runtime/step_stats_collector.cc86
-rw-r--r--tensorflow/core/common_runtime/step_stats_collector.h118
-rw-r--r--tensorflow/core/common_runtime/sycl/sycl_allocator.h6
-rw-r--r--tensorflow/core/distributed_runtime/eager/eager_service_impl.h2
-rw-r--r--tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc45
-rw-r--r--tensorflow/core/framework/dataset.cc78
-rw-r--r--tensorflow/core/framework/dataset.h213
-rw-r--r--tensorflow/core/framework/function.cc65
-rw-r--r--tensorflow/core/framework/function.h85
-rw-r--r--tensorflow/core/framework/op_def_util.cc9
-rw-r--r--tensorflow/core/framework/op_def_util.h5
-rw-r--r--tensorflow/core/framework/op_kernel.h6
-rw-r--r--tensorflow/core/framework/resource_mgr.h4
-rw-r--r--tensorflow/core/framework/shape_inference.cc3
-rw-r--r--tensorflow/core/framework/tensor.cc8
-rw-r--r--tensorflow/core/framework/tensor_test.cc7
-rw-r--r--tensorflow/core/graph/gradients.cc41
-rw-r--r--tensorflow/core/graph/mkl_layout_pass.cc45
-rw-r--r--tensorflow/core/graph/mkl_layout_pass_test.cc6
-rw-r--r--tensorflow/core/graph/testlib.cc25
-rw-r--r--tensorflow/core/grappler/costs/analytical_cost_estimator_test.cc4
-rw-r--r--tensorflow/core/grappler/costs/cost_estimator.h8
-rw-r--r--tensorflow/core/grappler/costs/op_level_cost_estimator.cc41
-rw-r--r--tensorflow/core/grappler/costs/op_level_cost_estimator_test.cc223
-rw-r--r--tensorflow/core/grappler/costs/virtual_scheduler.cc20
-rw-r--r--tensorflow/core/grappler/costs/virtual_scheduler.h1
-rw-r--r--tensorflow/core/grappler/costs/virtual_scheduler_test.cc7
-rw-r--r--tensorflow/core/grappler/optimizers/meta_optimizer.cc50
-rw-r--r--tensorflow/core/grappler/utils/functions.cc11
-rw-r--r--tensorflow/core/grappler/utils/functions.h6
-rw-r--r--tensorflow/core/grappler/utils/functions_test.cc27
-rw-r--r--tensorflow/core/kernels/BUILD171
-rw-r--r--tensorflow/core/kernels/as_string_op.cc11
-rw-r--r--tensorflow/core/kernels/batch_matmul_op_complex.cc2
-rw-r--r--tensorflow/core/kernels/batch_matmul_op_impl.h5
-rw-r--r--tensorflow/core/kernels/batch_matmul_op_real.cc5
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/BUILD63
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h132
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer_test.cc99
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream.h330
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream_test.cc276
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary.h344
-rw-r--r--tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary_test.cc223
-rw-r--r--tensorflow/core/kernels/cast_op.cc8
-rw-r--r--tensorflow/core/kernels/colorspace_op.h6
-rw-r--r--tensorflow/core/kernels/concat_lib_cpu.h5
-rw-r--r--tensorflow/core/kernels/concat_op.cc13
-rw-r--r--tensorflow/core/kernels/constant_op.cc43
-rw-r--r--tensorflow/core/kernels/constant_op.h20
-rw-r--r--tensorflow/core/kernels/constant_op_test.cc1
-rw-r--r--tensorflow/core/kernels/conv_grad_ops.cc2
-rw-r--r--tensorflow/core/kernels/cross_op.h6
-rw-r--r--tensorflow/core/kernels/cuda_solvers.h5
-rw-r--r--tensorflow/core/kernels/cwise_op_div.cc2
-rw-r--r--tensorflow/core/kernels/cwise_op_select.cc98
-rw-r--r--tensorflow/core/kernels/cwise_ops.h24
-rw-r--r--tensorflow/core/kernels/cwise_ops_gpu_common.cu.h6
-rw-r--r--tensorflow/core/kernels/cwise_ops_gpu_gradients.cu.h6
-rw-r--r--tensorflow/core/kernels/data/batch_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/cache_dataset_ops.cc36
-rw-r--r--tensorflow/core/kernels/data/concatenate_dataset_op.cc15
-rw-r--r--tensorflow/core/kernels/data/dataset_ops.cc6
-rw-r--r--tensorflow/core/kernels/data/dense_to_sparse_batch_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/filter_by_component_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/filter_dataset_op.cc15
-rw-r--r--tensorflow/core/kernels/data/flat_map_dataset_op.cc19
-rw-r--r--tensorflow/core/kernels/data/generator_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/group_by_reducer_dataset_op.cc22
-rw-r--r--tensorflow/core/kernels/data/group_by_window_dataset_op.cc24
-rw-r--r--tensorflow/core/kernels/data/interleave_dataset_op.cc19
-rw-r--r--tensorflow/core/kernels/data/iterator_ops.cc35
-rw-r--r--tensorflow/core/kernels/data/map_and_batch_dataset_op.cc17
-rw-r--r--tensorflow/core/kernels/data/map_dataset_op.cc15
-rw-r--r--tensorflow/core/kernels/data/optimize_dataset_op.cc33
-rw-r--r--tensorflow/core/kernels/data/padded_batch_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/parallel_interleave_dataset_op.cc27
-rw-r--r--tensorflow/core/kernels/data/parallel_map_dataset_op.cc11
-rw-r--r--tensorflow/core/kernels/data/parallel_map_iterator.cc4
-rw-r--r--tensorflow/core/kernels/data/prefetch_dataset_op.cc15
-rw-r--r--tensorflow/core/kernels/data/random_dataset_op.cc7
-rw-r--r--tensorflow/core/kernels/data/range_dataset_op.cc10
-rw-r--r--tensorflow/core/kernels/data/reader_dataset_ops.cc21
-rw-r--r--tensorflow/core/kernels/data/repeat_dataset_op.cc17
-rw-r--r--tensorflow/core/kernels/data/scan_dataset_op.cc15
-rw-r--r--tensorflow/core/kernels/data/shuffle_dataset_op.cc30
-rw-r--r--tensorflow/core/kernels/data/skip_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/slide_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc7
-rw-r--r--tensorflow/core/kernels/data/sql_dataset_ops.cc7
-rw-r--r--tensorflow/core/kernels/data/stats_aggregator_dataset_op.cc16
-rw-r--r--tensorflow/core/kernels/data/stats_dataset_ops.cc45
-rw-r--r--tensorflow/core/kernels/data/take_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/tensor_dataset_op.cc7
-rw-r--r--tensorflow/core/kernels/data/tensor_queue_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/tensor_slice_dataset_op.cc7
-rw-r--r--tensorflow/core/kernels/data/unbatch_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/data/window_dataset.cc14
-rw-r--r--tensorflow/core/kernels/data/window_dataset_op.cc15
-rw-r--r--tensorflow/core/kernels/data/writer_ops.cc11
-rw-r--r--tensorflow/core/kernels/data/zip_dataset_op.cc13
-rw-r--r--tensorflow/core/kernels/gemm_functors.h5
-rw-r--r--tensorflow/core/kernels/hexagon/soc_interface.h6
-rw-r--r--tensorflow/core/kernels/host_constant_op.cc78
-rw-r--r--tensorflow/core/kernels/host_constant_op.h42
-rw-r--r--tensorflow/core/kernels/image_resizer_state.h2
-rw-r--r--tensorflow/core/kernels/inplace_ops.cc12
-rw-r--r--tensorflow/core/kernels/inplace_ops_functor_gpu.cu.cc9
-rw-r--r--tensorflow/core/kernels/list_kernels.h7
-rw-r--r--tensorflow/core/kernels/lookup_table_op.cc73
-rw-r--r--tensorflow/core/kernels/lookup_table_op.h9
-rw-r--r--tensorflow/core/kernels/lookup_util.cc17
-rw-r--r--tensorflow/core/kernels/matmul_op.cc4
-rw-r--r--tensorflow/core/kernels/matrix_band_part_op.h6
-rw-r--r--tensorflow/core/kernels/matrix_diag_op.h6
-rw-r--r--tensorflow/core/kernels/matrix_solve_ls_op_impl.h5
-rw-r--r--tensorflow/core/kernels/mkl_aggregate_ops.cc7
-rw-r--r--tensorflow/core/kernels/mkl_avgpooling_op.cc6
-rw-r--r--tensorflow/core/kernels/mkl_batch_matmul_op.cc2
-rw-r--r--tensorflow/core/kernels/mkl_concat_op.cc7
-rw-r--r--tensorflow/core/kernels/mkl_conv_grad_bias_ops.cc6
-rw-r--r--tensorflow/core/kernels/mkl_conv_grad_filter_ops.cc183
-rw-r--r--tensorflow/core/kernels/mkl_conv_grad_input_ops.cc152
-rw-r--r--tensorflow/core/kernels/mkl_conv_ops.cc163
-rw-r--r--tensorflow/core/kernels/mkl_conv_ops.h421
-rw-r--r--tensorflow/core/kernels/mkl_fused_batch_norm_op.cc23
-rw-r--r--tensorflow/core/kernels/mkl_identity_op.cc6
-rw-r--r--tensorflow/core/kernels/mkl_input_conversion_op.cc4
-rw-r--r--tensorflow/core/kernels/mkl_lrn_op.cc6
-rw-r--r--tensorflow/core/kernels/mkl_matmul_op.cc8
-rw-r--r--tensorflow/core/kernels/mkl_maxpooling_op.cc6
-rw-r--r--tensorflow/core/kernels/mkl_pooling_ops_common.cc6
-rw-r--r--tensorflow/core/kernels/mkl_pooling_ops_common.h24
-rw-r--r--tensorflow/core/kernels/mkl_relu_op.cc12
-rw-r--r--tensorflow/core/kernels/mkl_reshape_op.cc7
-rw-r--r--tensorflow/core/kernels/mkl_softmax_op.cc4
-rw-r--r--tensorflow/core/kernels/mkl_tfconv_op.h13
-rw-r--r--tensorflow/core/kernels/mkl_transpose_op.cc105
-rw-r--r--tensorflow/core/kernels/non_max_suppression_op.cc2
-rw-r--r--tensorflow/core/kernels/padding_fifo_queue.cc4
-rw-r--r--tensorflow/core/kernels/partitioned_function_ops.cc41
-rw-r--r--tensorflow/core/kernels/pooling_ops_3d_gpu.h6
-rw-r--r--tensorflow/core/kernels/qr_op_impl.h7
-rw-r--r--tensorflow/core/kernels/reduction_gpu_kernels.cu.h7
-rw-r--r--tensorflow/core/kernels/regex_replace_op.cc80
-rw-r--r--tensorflow/core/kernels/regex_replace_op_test.cc137
-rw-r--r--tensorflow/core/kernels/resource_variable_ops.cc15
-rw-r--r--tensorflow/core/kernels/save_restore_tensor.cc23
-rw-r--r--tensorflow/core/kernels/scoped_allocator_ops.cc27
-rw-r--r--tensorflow/core/kernels/self_adjoint_eig_v2_op_impl.h5
-rw-r--r--tensorflow/core/kernels/shape_ops.h8
-rw-r--r--tensorflow/core/kernels/sparse_xent_op.h6
-rw-r--r--tensorflow/core/kernels/string_length_op.cc45
-rw-r--r--tensorflow/core/kernels/string_split_op.cc111
-rw-r--r--tensorflow/core/kernels/string_split_op_test.cc129
-rw-r--r--tensorflow/core/kernels/svd_op_impl.h5
-rw-r--r--tensorflow/core/kernels/tensor_array_ops.cc21
-rw-r--r--tensorflow/core/kernels/tile_ops.cc18
-rw-r--r--tensorflow/core/kernels/transpose_op.cc2
-rw-r--r--tensorflow/core/kernels/transpose_op.h4
-rw-r--r--tensorflow/core/kernels/unique_op.cc2
-rw-r--r--tensorflow/core/kernels/where_op_gpu.cu.h5
-rw-r--r--tensorflow/core/kernels/xent_op.h6
-rw-r--r--tensorflow/core/lib/core/stringpiece.h16
-rw-r--r--tensorflow/core/lib/core/stringpiece_test.cc4
-rw-r--r--tensorflow/core/lib/png/png_io.cc14
-rw-r--r--tensorflow/core/lib/png/testdata/lena_palette.pngbin0 -> 1355 bytes
-rw-r--r--tensorflow/core/lib/png/testdata/lena_palette_trns.pngbin0 -> 1368 bytes
-rw-r--r--tensorflow/core/ops/array_grad.cc21
-rw-r--r--tensorflow/core/ops/array_grad_test.cc66
-rw-r--r--tensorflow/core/ops/array_ops.cc73
-rw-r--r--tensorflow/core/ops/array_ops_test.cc33
-rw-r--r--tensorflow/core/ops/compat/ops_history.v1.pbtxt201
-rw-r--r--tensorflow/core/ops/image_ops.cc85
-rw-r--r--tensorflow/core/ops/lookup_ops.cc139
-rw-r--r--tensorflow/core/ops/math_grad.cc13
-rw-r--r--tensorflow/core/ops/math_grad_test.cc72
-rw-r--r--tensorflow/core/ops/math_ops.cc7
-rw-r--r--tensorflow/core/ops/math_ops_test.cc3
-rw-r--r--tensorflow/core/ops/nn_ops.cc95
-rw-r--r--tensorflow/core/ops/ops.pbtxt139
-rw-r--r--tensorflow/core/ops/string_ops.cc17
-rw-r--r--tensorflow/core/platform/cloud/gcs_file_system.cc16
-rw-r--r--tensorflow/core/platform/cloud/gcs_file_system_test.cc12
-rw-r--r--tensorflow/core/platform/default/build_config.bzl1192
-rw-r--r--tensorflow/core/platform/default/protobuf.h2
-rw-r--r--tensorflow/core/platform/default/protobuf_compiler.h25
-rw-r--r--tensorflow/core/platform/protobuf_compiler.h25
-rw-r--r--tensorflow/core/platform/s3/s3_file_system.cc44
-rw-r--r--tensorflow/core/public/version.h2
-rw-r--r--tensorflow/core/util/env_var.h5
-rw-r--r--tensorflow/core/util/events_writer.cc4
-rw-r--r--tensorflow/core/util/mkl_util.h151
-rw-r--r--tensorflow/core/util/mkl_util_test.cc4
-rw-r--r--tensorflow/core/util/strided_slice_op.cc2
-rw-r--r--tensorflow/core/util/tensor_format.cc4
-rw-r--r--tensorflow/core/util/tensor_format.h1
-rw-r--r--tensorflow/docs_src/about/index.md6
-rw-r--r--tensorflow/docs_src/api_guides/cc/guide.md6
-rw-r--r--tensorflow/docs_src/api_guides/python/client.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/constant_op.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/input_dataset.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/io_ops.md10
-rw-r--r--tensorflow/docs_src/api_guides/python/meta_graph.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/reading_data.md24
-rw-r--r--tensorflow/docs_src/api_guides/python/regression_examples.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/summary.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/threading_and_queues.md2
-rw-r--r--tensorflow/docs_src/api_guides/python/train.md8
-rw-r--r--tensorflow/docs_src/community/contributing.md6
-rw-r--r--tensorflow/docs_src/community/index.md16
-rw-r--r--tensorflow/docs_src/community/lists.md2
-rw-r--r--tensorflow/docs_src/community/style_guide.md2
-rw-r--r--tensorflow/docs_src/deploy/distributed.md2
-rw-r--r--tensorflow/docs_src/deploy/hadoop.md4
-rw-r--r--tensorflow/docs_src/deploy/index.md6
-rw-r--r--tensorflow/docs_src/deploy/s3.md4
-rw-r--r--tensorflow/docs_src/extend/add_filesys.md2
-rw-r--r--tensorflow/docs_src/extend/adding_an_op.md12
-rw-r--r--tensorflow/docs_src/extend/architecture.md8
-rw-r--r--tensorflow/docs_src/extend/index.md14
-rw-r--r--tensorflow/docs_src/extend/language_bindings.md2
-rw-r--r--tensorflow/docs_src/extend/new_data_formats.md10
-rw-r--r--tensorflow/docs_src/guide/checkpoints.md8
-rw-r--r--tensorflow/docs_src/guide/custom_estimators.md14
-rw-r--r--tensorflow/docs_src/guide/datasets.md16
-rw-r--r--tensorflow/docs_src/guide/datasets_for_estimators.md14
-rw-r--r--tensorflow/docs_src/guide/debugger.md6
-rw-r--r--tensorflow/docs_src/guide/eager.md5
-rw-r--r--tensorflow/docs_src/guide/embedding.md2
-rw-r--r--tensorflow/docs_src/guide/estimators.md4
-rw-r--r--tensorflow/docs_src/guide/faq.md38
-rw-r--r--tensorflow/docs_src/guide/feature_columns.md10
-rw-r--r--tensorflow/docs_src/guide/graph_viz.md4
-rw-r--r--tensorflow/docs_src/guide/graphs.md8
-rw-r--r--tensorflow/docs_src/guide/index.md46
-rw-r--r--tensorflow/docs_src/guide/low_level_intro.md18
-rw-r--r--tensorflow/docs_src/guide/premade_estimators.md18
-rw-r--r--tensorflow/docs_src/guide/saved_model.md10
-rw-r--r--tensorflow/docs_src/guide/summaries_and_tensorboard.md8
-rw-r--r--tensorflow/docs_src/guide/tensors.md2
-rw-r--r--tensorflow/docs_src/guide/using_gpu.md2
-rw-r--r--tensorflow/docs_src/guide/using_tpu.md16
-rw-r--r--tensorflow/docs_src/guide/version_compat.md10
-rw-r--r--tensorflow/docs_src/install/index.md18
-rw-r--r--tensorflow/docs_src/install/install_c.md6
-rw-r--r--tensorflow/docs_src/install/install_go.md6
-rw-r--r--tensorflow/docs_src/install/install_java.md28
-rw-r--r--tensorflow/docs_src/install/install_linux.md20
-rw-r--r--tensorflow/docs_src/install/install_mac.md10
-rw-r--r--tensorflow/docs_src/install/install_raspbian.md6
-rw-r--r--tensorflow/docs_src/install/install_sources.md13
-rw-r--r--tensorflow/docs_src/install/install_sources_windows.md320
-rw-r--r--tensorflow/docs_src/install/install_windows.md2
-rw-r--r--tensorflow/docs_src/install/leftnav_files1
-rw-r--r--tensorflow/docs_src/performance/index.md22
-rw-r--r--tensorflow/docs_src/performance/performance_guide.md16
-rw-r--r--tensorflow/docs_src/performance/performance_models.md2
-rw-r--r--tensorflow/docs_src/performance/quantization.md2
-rw-r--r--tensorflow/docs_src/performance/xla/index.md10
-rw-r--r--tensorflow/docs_src/performance/xla/jit.md2
-rw-r--r--tensorflow/docs_src/performance/xla/operation_semantics.md346
-rw-r--r--tensorflow/docs_src/performance/xla/tfcompile.md4
-rw-r--r--tensorflow/docs_src/tutorials/_toc.yaml31
-rw-r--r--tensorflow/docs_src/tutorials/eager/index.md1
-rw-r--r--tensorflow/docs_src/tutorials/estimators/cnn.md16
-rw-r--r--tensorflow/docs_src/tutorials/images/deep_cnn.md20
-rw-r--r--tensorflow/docs_src/tutorials/images/image_recognition.md4
-rw-r--r--tensorflow/docs_src/tutorials/representation/kernel_methods.md4
-rw-r--r--tensorflow/docs_src/tutorials/representation/linear.md4
-rw-r--r--tensorflow/docs_src/tutorials/representation/word2vec.md4
-rw-r--r--tensorflow/docs_src/tutorials/sequences/recurrent.md8
-rw-r--r--tensorflow/docs_src/tutorials/sequences/recurrent_quickdraw.md11
-rw-r--r--tensorflow/examples/android/.gitignore29
-rw-r--r--tensorflow/examples/android/README.md9
-rw-r--r--tensorflow/examples/ios/README.md7
-rw-r--r--tensorflow/examples/ios/benchmark/ios_image_load.h6
-rw-r--r--tensorflow/examples/ios/camera/ios_image_load.h6
-rw-r--r--tensorflow/g3doc/README.txt6
-rw-r--r--tensorflow/go/op/wrappers.go1392
-rw-r--r--tensorflow/java/BUILD6
-rw-r--r--tensorflow/java/maven/hadoop/pom.xml2
-rw-r--r--tensorflow/java/maven/libtensorflow/pom.xml2
-rw-r--r--tensorflow/java/maven/libtensorflow_jni/pom.xml2
-rw-r--r--tensorflow/java/maven/libtensorflow_jni_gpu/pom.xml2
-rw-r--r--tensorflow/java/maven/pom.xml2
-rw-r--r--tensorflow/java/maven/proto/pom.xml2
-rw-r--r--tensorflow/java/maven/run_inside_container.sh6
-rw-r--r--tensorflow/java/maven/spark-connector/pom.xml2
-rw-r--r--tensorflow/java/maven/tensorflow/pom.xml2
-rw-r--r--tensorflow/java/src/main/java/org/tensorflow/types/UInt8.java29
-rw-r--r--tensorflow/python/BUILD17
-rw-r--r--tensorflow/python/client/client_lib.py2
-rw-r--r--tensorflow/python/client/session.py46
-rw-r--r--tensorflow/python/compat/compat.py12
-rw-r--r--tensorflow/python/data/__init__.py2
-rw-r--r--tensorflow/python/data/ops/BUILD1
-rw-r--r--tensorflow/python/data/ops/dataset_ops.py40
-rw-r--r--tensorflow/python/data/ops/iterator_ops.py10
-rw-r--r--tensorflow/python/data/ops/optional_ops.py6
-rw-r--r--tensorflow/python/data/util/BUILD35
-rw-r--r--tensorflow/python/data/util/convert.py6
-rw-r--r--tensorflow/python/data/util/random_seed.py6
-rw-r--r--tensorflow/python/data/util/structure.py315
-rw-r--r--tensorflow/python/data/util/structure_test.py327
-rw-r--r--tensorflow/python/debug/BUILD1
-rw-r--r--tensorflow/python/debug/__init__.py2
-rw-r--r--tensorflow/python/debug/lib/debug_gradients.py6
-rw-r--r--tensorflow/python/debug/wrappers/dumping_wrapper.py2
-rw-r--r--tensorflow/python/distribute/BUILD40
-rw-r--r--tensorflow/python/distribute/distribute_coordinator.py204
-rw-r--r--tensorflow/python/distribute/distribute_coordinator_context.py31
-rw-r--r--tensorflow/python/distribute/distribute_coordinator_test.py248
-rw-r--r--tensorflow/python/distribute/multi_worker_util.py80
-rw-r--r--tensorflow/python/distribute/multi_worker_util_test.py107
-rw-r--r--tensorflow/python/eager/BUILD36
-rw-r--r--tensorflow/python/eager/backprop.py80
-rw-r--r--tensorflow/python/eager/benchmarks_test.py88
-rw-r--r--tensorflow/python/eager/context.py2
-rw-r--r--tensorflow/python/eager/function.py550
-rw-r--r--tensorflow/python/eager/function_test.py117
-rw-r--r--tensorflow/python/eager/graph_callable.py435
-rw-r--r--tensorflow/python/eager/graph_callable_test.py249
-rw-r--r--tensorflow/python/eager/pywrap_tensor.cc3
-rw-r--r--tensorflow/python/estimator/canned/boosted_trees.py118
-rw-r--r--tensorflow/python/estimator/canned/dnn_linear_combined.py4
-rw-r--r--tensorflow/python/estimator/canned/linear.py4
-rw-r--r--tensorflow/python/estimator/canned/prediction_keys.py1
-rw-r--r--tensorflow/python/estimator/estimator.py779
-rw-r--r--tensorflow/python/estimator/estimator_test.py91
-rw-r--r--tensorflow/python/estimator/export/export.py5
-rw-r--r--tensorflow/python/estimator/export/export_test.py15
-rw-r--r--tensorflow/python/estimator/exporter_test.py37
-rw-r--r--tensorflow/python/estimator/gc.py8
-rw-r--r--tensorflow/python/estimator/gc_test.py11
-rw-r--r--tensorflow/python/estimator/inputs/numpy_io_test.py162
-rw-r--r--tensorflow/python/estimator/keras.py319
-rw-r--r--tensorflow/python/estimator/keras_test.py10
-rw-r--r--tensorflow/python/estimator/model_fn.py2
-rw-r--r--tensorflow/python/estimator/training.py19
-rw-r--r--tensorflow/python/estimator/training_test.py33
-rw-r--r--tensorflow/python/feature_column/BUILD1
-rw-r--r--tensorflow/python/feature_column/feature_column.py10
-rw-r--r--tensorflow/python/feature_column/feature_column_test.py120
-rw-r--r--tensorflow/python/feature_column/feature_column_v2.py6
-rw-r--r--tensorflow/python/framework/constant_op.py13
-rw-r--r--tensorflow/python/framework/errors_impl.py38
-rw-r--r--tensorflow/python/framework/function.py2
-rw-r--r--tensorflow/python/framework/importer.py4
-rw-r--r--tensorflow/python/framework/ops.py114
-rw-r--r--tensorflow/python/framework/python_op_gen.cc9
-rw-r--r--tensorflow/python/framework/python_op_gen_internal.cc9
-rw-r--r--tensorflow/python/framework/random_seed.py2
-rw-r--r--tensorflow/python/framework/sparse_tensor.py2
-rw-r--r--tensorflow/python/framework/tensor_shape.py5
-rw-r--r--tensorflow/python/framework/test_util.py330
-rw-r--r--tensorflow/python/framework/test_util_test.py45
-rwxr-xr-xtensorflow/python/keras/BUILD113
-rw-r--r--tensorflow/python/keras/applications/__init__.py2
-rw-r--r--tensorflow/python/keras/applications/applications_test.py58
-rw-r--r--tensorflow/python/keras/applications/densenet_test.py101
-rw-r--r--tensorflow/python/keras/applications/imagenet_utils_test.py93
-rw-r--r--tensorflow/python/keras/applications/inception_resnet_v2_test.py59
-rw-r--r--tensorflow/python/keras/applications/inception_v3_test.py58
-rw-r--r--tensorflow/python/keras/applications/mobilenet_test.py71
-rw-r--r--tensorflow/python/keras/applications/mobilenet_v2.py12
-rw-r--r--tensorflow/python/keras/applications/nasnet_test.py76
-rw-r--r--tensorflow/python/keras/applications/resnet50_test.py51
-rw-r--r--tensorflow/python/keras/applications/vgg16_test.py50
-rw-r--r--tensorflow/python/keras/applications/vgg19_test.py50
-rw-r--r--tensorflow/python/keras/applications/xception_test.py57
-rw-r--r--tensorflow/python/keras/callbacks.py115
-rw-r--r--tensorflow/python/keras/callbacks_test.py4
-rw-r--r--tensorflow/python/keras/engine/base_layer.py8
-rw-r--r--tensorflow/python/keras/engine/distributed_training_utils.py66
-rw-r--r--tensorflow/python/keras/engine/network.py18
-rw-r--r--tensorflow/python/keras/engine/saving.py4
-rw-r--r--tensorflow/python/keras/engine/saving_test.py48
-rw-r--r--tensorflow/python/keras/engine/sequential.py4
-rw-r--r--tensorflow/python/keras/engine/sequential_test.py27
-rw-r--r--tensorflow/python/keras/engine/training.py324
-rw-r--r--tensorflow/python/keras/engine/training_arrays.py93
-rw-r--r--tensorflow/python/keras/engine/training_distributed.py65
-rw-r--r--tensorflow/python/keras/engine/training_eager.py241
-rw-r--r--tensorflow/python/keras/engine/training_eager_test.py9
-rw-r--r--tensorflow/python/keras/engine/training_generator.py76
-rw-r--r--tensorflow/python/keras/engine/training_test.py306
-rw-r--r--tensorflow/python/keras/engine/training_utils.py89
-rw-r--r--tensorflow/python/keras/integration_test.py26
-rw-r--r--tensorflow/python/keras/layers/local.py340
-rw-r--r--tensorflow/python/keras/layers/local_test.py461
-rw-r--r--tensorflow/python/keras/layers/normalization.py10
-rw-r--r--tensorflow/python/keras/layers/recurrent.py59
-rw-r--r--tensorflow/python/keras/layers/recurrent_test.py41
-rw-r--r--tensorflow/python/keras/metrics.py88
-rw-r--r--tensorflow/python/keras/metrics_test.py24
-rw-r--r--tensorflow/python/keras/model_subclassing_test.py7
-rw-r--r--tensorflow/python/keras/models.py218
-rw-r--r--tensorflow/python/keras/models_test.py134
-rw-r--r--tensorflow/python/keras/optimizers.py4
-rw-r--r--tensorflow/python/keras/utils/conv_utils.py166
-rw-r--r--tensorflow/python/keras/utils/conv_utils_test.py232
-rw-r--r--tensorflow/python/kernel_tests/BUILD24
-rw-r--r--tensorflow/python/kernel_tests/array_ops_test.py9
-rw-r--r--tensorflow/python/kernel_tests/as_string_op_test.py2
-rw-r--r--tensorflow/python/kernel_tests/batch_gather_op_test.py116
-rw-r--r--tensorflow/python/kernel_tests/clip_ops_test.py16
-rw-r--r--tensorflow/python/kernel_tests/cond_v2_test.py26
-rw-r--r--tensorflow/python/kernel_tests/confusion_matrix_test.py4
-rw-r--r--tensorflow/python/kernel_tests/control_flow_ops_py_test.py3
-rw-r--r--tensorflow/python/kernel_tests/functional_ops_test.py33
-rw-r--r--tensorflow/python/kernel_tests/list_ops_test.py25
-rw-r--r--tensorflow/python/kernel_tests/partitioned_variables_test.py115
-rw-r--r--tensorflow/python/kernel_tests/regex_replace_op_test.py76
-rw-r--r--tensorflow/python/kernel_tests/resource_variable_ops_test.py13
-rw-r--r--tensorflow/python/kernel_tests/rnn_test.py38
-rw-r--r--tensorflow/python/kernel_tests/split_op_test.py30
-rw-r--r--tensorflow/python/kernel_tests/string_length_op_test.py37
-rw-r--r--tensorflow/python/kernel_tests/string_split_op_test.py22
-rw-r--r--tensorflow/python/kernel_tests/template_test.py18
-rw-r--r--tensorflow/python/kernel_tests/where_op_test.py36
-rw-r--r--tensorflow/python/layers/base.py8
-rw-r--r--tensorflow/python/layers/core.py8
-rw-r--r--tensorflow/python/lib/core/py_func.cc13
-rw-r--r--tensorflow/python/lib/core/py_util.cc2
-rw-r--r--tensorflow/python/lib/io/py_record_writer.cc13
-rw-r--r--tensorflow/python/lib/io/py_record_writer.h2
-rw-r--r--tensorflow/python/lib/io/python_io.py2
-rw-r--r--tensorflow/python/lib/io/tf_record.py4
-rw-r--r--tensorflow/python/lib/io/tf_record_test.py6
-rw-r--r--tensorflow/python/ops/array_ops.py83
-rw-r--r--tensorflow/python/ops/check_ops.py3
-rw-r--r--tensorflow/python/ops/clip_ops.py6
-rw-r--r--tensorflow/python/ops/cond_v2_impl.py15
-rw-r--r--tensorflow/python/ops/control_flow_ops.py50
-rw-r--r--tensorflow/python/ops/custom_gradient.py4
-rw-r--r--tensorflow/python/ops/data_flow_ops.py32
-rw-r--r--tensorflow/python/ops/distributions/distribution.py4
-rw-r--r--tensorflow/python/ops/embedding_ops.py2
-rw-r--r--tensorflow/python/ops/functional_ops.py3
-rw-r--r--tensorflow/python/ops/histogram_ops.py2
-rw-r--r--tensorflow/python/ops/image_ops.py2
-rw-r--r--tensorflow/python/ops/image_ops_impl.py14
-rw-r--r--tensorflow/python/ops/image_ops_test.py50
-rw-r--r--tensorflow/python/ops/init_ops.py26
-rw-r--r--tensorflow/python/ops/io_ops.py3
-rw-r--r--tensorflow/python/ops/losses/losses_impl.py24
-rw-r--r--tensorflow/python/ops/math_grad.py18
-rw-r--r--tensorflow/python/ops/math_grad_test.py26
-rw-r--r--tensorflow/python/ops/math_ops.py66
-rw-r--r--tensorflow/python/ops/math_ops_test.py15
-rw-r--r--tensorflow/python/ops/metrics_impl.py207
-rw-r--r--tensorflow/python/ops/nn.py2
-rw-r--r--tensorflow/python/ops/nn_grad.py4
-rw-r--r--tensorflow/python/ops/nn_impl.py10
-rw-r--r--tensorflow/python/ops/nn_ops.py44
-rw-r--r--tensorflow/python/ops/nn_test.py2
-rw-r--r--tensorflow/python/ops/numerics.py4
-rw-r--r--tensorflow/python/ops/parallel_for/BUILD1
-rw-r--r--tensorflow/python/ops/parallel_for/pfor.py2
-rw-r--r--tensorflow/python/ops/random_ops.py18
-rw-r--r--tensorflow/python/ops/resource_variable_ops.py25
-rw-r--r--tensorflow/python/ops/rnn_cell_impl.py147
-rw-r--r--tensorflow/python/ops/script_ops.py15
-rw-r--r--tensorflow/python/ops/session_ops.py6
-rw-r--r--tensorflow/python/ops/sparse_ops.py105
-rw-r--r--tensorflow/python/ops/spectral_ops.py4
-rw-r--r--tensorflow/python/ops/state_ops.py63
-rw-r--r--tensorflow/python/ops/string_ops.py39
-rw-r--r--tensorflow/python/ops/summary_op_util.py4
-rw-r--r--tensorflow/python/ops/summary_ops_v2.py64
-rw-r--r--tensorflow/python/ops/template.py4
-rw-r--r--tensorflow/python/ops/variable_scope.py36
-rw-r--r--tensorflow/python/ops/variables.py29
-rw-r--r--tensorflow/python/platform/test.py2
-rw-r--r--tensorflow/python/saved_model/BUILD4
-rw-r--r--tensorflow/python/saved_model/builder_impl.py21
-rw-r--r--tensorflow/python/saved_model/loader_impl.py6
-rw-r--r--tensorflow/python/saved_model/utils_impl.py47
-rw-r--r--tensorflow/python/summary/summary.py12
-rw-r--r--tensorflow/python/summary/writer/writer.py6
-rw-r--r--tensorflow/python/tools/BUILD6
-rw-r--r--tensorflow/python/tools/api/generator/api_init_files.bzl1
-rw-r--r--tensorflow/python/tools/api/generator/api_init_files_v1.bzl1
-rw-r--r--tensorflow/python/tools/component_api_helper.py85
-rw-r--r--tensorflow/python/tools/freeze_graph.py20
-rw-r--r--tensorflow/python/training/adagrad.py26
-rw-r--r--tensorflow/python/training/adagrad_test.py33
-rw-r--r--tensorflow/python/training/basic_session_run_hooks.py117
-rw-r--r--tensorflow/python/training/checkpoint_management.py293
-rw-r--r--tensorflow/python/training/checkpoint_management_test.py201
-rw-r--r--tensorflow/python/training/checkpoint_state.proto8
-rw-r--r--tensorflow/python/training/checkpoint_utils.py6
-rw-r--r--tensorflow/python/training/checkpointable/BUILD18
-rw-r--r--tensorflow/python/training/checkpointable/base.py132
-rw-r--r--tensorflow/python/training/checkpointable/data_structures.py13
-rw-r--r--tensorflow/python/training/checkpointable/data_structures_test.py6
-rw-r--r--tensorflow/python/training/checkpointable/layer_utils.py9
-rw-r--r--tensorflow/python/training/checkpointable/util.py126
-rw-r--r--tensorflow/python/training/checkpointable/util_test.py58
-rw-r--r--tensorflow/python/training/distribute.py246
-rw-r--r--tensorflow/python/training/distribute_test.py53
-rw-r--r--tensorflow/python/training/distribution_strategy_context.py203
-rw-r--r--tensorflow/python/training/ftrl.py2
-rw-r--r--tensorflow/python/training/input.py3
-rw-r--r--tensorflow/python/training/monitored_session.py116
-rw-r--r--tensorflow/python/training/monitored_session_test.py118
-rw-r--r--tensorflow/python/training/moving_averages.py2
-rw-r--r--tensorflow/python/training/optimizer.py22
-rw-r--r--tensorflow/python/training/quantize_training.i2
-rw-r--r--tensorflow/python/training/saver.py148
-rw-r--r--tensorflow/python/training/saver_test.py26
-rw-r--r--tensorflow/python/training/server_lib.py10
-rw-r--r--tensorflow/python/training/slot_creator.py8
-rw-r--r--tensorflow/python/training/supervisor.py4
-rw-r--r--tensorflow/python/training/sync_replicas_optimizer.py6
-rw-r--r--tensorflow/python/training/training.py3
-rw-r--r--tensorflow/python/training/warm_starting_util.py2
-rw-r--r--tensorflow/python/util/deprecation.py4
-rw-r--r--tensorflow/python/util/nest.py76
-rw-r--r--tensorflow/python/util/tf_should_use.py169
-rw-r--r--tensorflow/python/util/tf_should_use_test.py76
-rw-r--r--tensorflow/python/util/util.cc1
-rw-r--r--tensorflow/python/util/util.h9
-rw-r--r--tensorflow/python/util/util.i52
-rw-r--r--tensorflow/stream_executor/BUILD2
-rw-r--r--tensorflow/stream_executor/host/host_gpu_executor.h2
-rw-r--r--tensorflow/stream_executor/host/host_stream.cc26
-rw-r--r--tensorflow/stream_executor/stream_executor_internal.h2
-rw-r--r--tensorflow/tensorflow.bzl2739
-rw-r--r--tensorflow/tools/api/golden/BUILD2
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected1-d.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected2-d.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.pbtxt16
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.strings.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.summary.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.train.-checkpoint.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v1/tensorflow.train.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.-config-proto.-experimental.pbtxt6
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.-config-proto.pbtxt6
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.data.-iterator.pbtxt1
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-classifier.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-regressor.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.estimator.-run-config.pbtxt6
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.image.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.-model.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.-sequential.pbtxt6
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.activations.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.densenet.pbtxt23
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_resnet_v2.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_v3.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.mobilenet.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.nasnet.pbtxt19
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.pbtxt87
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.resnet50.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg16.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg19.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.applications.xception.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.backend.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-lambda.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected1-d.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected2-d.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-re-l-u.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.models.-model.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.models.-sequential.pbtxt6
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-directory-iterator.pbtxt23
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-image-data-generator.pbtxt29
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-iterator.pbtxt18
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-numpy-array-iterator.pbtxt23
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.pbtxt63
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.pbtxt15
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.-timeseries-generator.pbtxt14
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.pbtxt19
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.-tokenizer.pbtxt33
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.pbtxt19
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.pbtxt16
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.strings.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.summary.pbtxt2
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.train.-checkpoint.pbtxt4
-rw-r--r--tensorflow/tools/api/golden/v2/tensorflow.train.pbtxt4
-rw-r--r--tensorflow/tools/api/tests/api_compatibility_test.py97
-rw-r--r--tensorflow/tools/ci_build/Dockerfile.gpu.ppc64le3
-rwxr-xr-xtensorflow/tools/ci_build/linux/mkl/build-dev-container.sh21
-rwxr-xr-xtensorflow/tools/ci_build/linux/ppc64le/cpu/run_py2.sh37
-rwxr-xr-xtensorflow/tools/ci_build/linux/ppc64le/cpu/run_py3.sh37
-rwxr-xr-xtensorflow/tools/ci_build/linux/ppc64le/gpu/run_py2.sh44
-rwxr-xr-xtensorflow/tools/ci_build/linux/ppc64le/gpu/run_py3.sh44
-rw-r--r--tensorflow/tools/ci_build/windows/cpu/pip/build_tf_windows.sh12
-rw-r--r--tensorflow/tools/ci_build/windows/gpu/pip/build_tf_windows.sh12
-rw-r--r--tensorflow/tools/def_file_filter/def_file_filter.py.tpl1
-rw-r--r--tensorflow/tools/def_file_filter/def_file_filter_configure.bzl42
-rw-r--r--tensorflow/tools/docker/Dockerfile2
-rw-r--r--tensorflow/tools/docker/Dockerfile.devel2
-rw-r--r--tensorflow/tools/docker/Dockerfile.devel-gpu2
-rw-r--r--tensorflow/tools/docker/Dockerfile.devel-gpu-cuda9-cudnn72
-rwxr-xr-xtensorflow/tools/docker/Dockerfile.devel-mkl27
-rwxr-xr-xtensorflow/tools/docker/Dockerfile.devel-mkl-horovod168
-rw-r--r--tensorflow/tools/docker/Dockerfile.gpu2
-rwxr-xr-xtensorflow/tools/docker/Dockerfile.mkl2
-rwxr-xr-xtensorflow/tools/docker/Dockerfile.mkl-horovod111
-rwxr-xr-xtensorflow/tools/docker/parameterized_docker_build.sh40
-rw-r--r--tensorflow/tools/docs/BUILD19
-rw-r--r--tensorflow/tools/docs/doc_controls.py319
-rw-r--r--tensorflow/tools/docs/doc_controls_test.py183
-rw-r--r--tensorflow/tools/docs/doc_generator_visitor.py1
-rw-r--r--tensorflow/tools/docs/generate.py5
-rw-r--r--tensorflow/tools/docs/generate_lib.py72
-rw-r--r--tensorflow/tools/docs/parser.py22
-rw-r--r--tensorflow/tools/docs/parser_test.py115
-rw-r--r--tensorflow/tools/pip_package/BUILD12
-rw-r--r--tensorflow/tools/pip_package/MANIFEST.in1
-rwxr-xr-xtensorflow/tools/pip_package/build_pip_package.sh2
-rw-r--r--tensorflow/tools/pip_package/pip_smoke_test.py1
-rw-r--r--tensorflow/tools/pip_package/setup.py2
-rw-r--r--tensorflow/tools/proto_text/BUILD2
-rw-r--r--tensorflow/tools/proto_text/gen_proto_text_functions.cc1
-rw-r--r--tensorflow/workspace.bzl55
-rw-r--r--third_party/curl.BUILD14
-rw-r--r--third_party/double_conversion.BUILD16
-rw-r--r--third_party/farmhash.BUILD8
-rw-r--r--third_party/fft2d/fft2d.BUILD10
-rw-r--r--third_party/flatbuffers/flatbuffers.BUILD15
-rw-r--r--third_party/gif.BUILD9
-rw-r--r--third_party/gpus/cuda_configure.bzl4
-rw-r--r--third_party/jpeg/jpeg.BUILD10
-rw-r--r--third_party/kafka/BUILD43
-rw-r--r--third_party/lmdb.BUILD6
-rw-r--r--third_party/mkl/BUILD17
-rw-r--r--third_party/mkl/build_defs.bzl83
-rw-r--r--third_party/mkl_dnn/BUILD5
-rw-r--r--third_party/nasm.BUILD9
-rw-r--r--third_party/png.BUILD18
-rw-r--r--third_party/repo.bzl229
-rw-r--r--third_party/snappy.BUILD12
-rw-r--r--third_party/sqlite.BUILD8
-rw-r--r--third_party/swig.BUILD6
-rw-r--r--third_party/systemlibs/nsync.BUILD23
-rw-r--r--third_party/systemlibs/syslibs_configure.bzl174
-rw-r--r--third_party/zlib.BUILD1
1341 files changed, 46871 insertions, 19738 deletions
diff --git a/README.md b/README.md
index 6ace2a2ed4..16d354ca7b 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,8 @@ organization for the purposes of conducting machine learning and deep neural
networks research. The system is general enough to be applicable in a wide
variety of other domains, as well.
+TensorFlow provides stable Python API and C APIs as well as without API backwards compatibility guarantee like C++, Go, Java, JavaScript and Swift.
+
Keep up to date with release announcements and security updates by
subscribing to
[announce@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/announce).
@@ -81,13 +83,13 @@ The TensorFlow project strives to abide by generally accepted best practices in
| Build Type | Status | Artifacts |
| --- | --- | --- |
-| **Linux CPU** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-cc.png) | [pypi](https://pypi.org/project/tf-nightly/) |
-| **Linux GPU** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-gpu-py3.png) | [pypi](https://pypi.org/project/tf-nightly-gpu/) |
-| **Linux XLA** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-xla.png) | TBA |
-| **MacOS** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/macos-py2-cc.png) | [pypi](https://pypi.org/project/tf-nightly/) |
-| **Windows CPU** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/windows-cpu.png) | [pypi](https://pypi.org/project/tf-nightly/) |
-| **Windows GPU** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/windows-gpu.png) | [pypi](https://pypi.org/project/tf-nightly-gpu/) |
-| **Android** | ![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/android.png) | [![Download](https://api.bintray.com/packages/google/tensorflow/tensorflow/images/download.svg)](https://bintray.com/google/tensorflow/tensorflow/_latestVersion) |
+| **Linux CPU** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-cc.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-cc.html) | [pypi](https://pypi.org/project/tf-nightly/) |
+| **Linux GPU** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-gpu-py3.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-gpu-py3.html) | [pypi](https://pypi.org/project/tf-nightly-gpu/) |
+| **Linux XLA** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-xla.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/ubuntu-xla.html) | TBA |
+| **MacOS** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/macos-py2-cc.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/macos-py2-cc.html) | [pypi](https://pypi.org/project/tf-nightly/) |
+| **Windows CPU** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/windows-cpu.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/windows-cpu.html) | [pypi](https://pypi.org/project/tf-nightly/) |
+| **Windows GPU** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/windows-gpu.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/windows-gpu.html) | [pypi](https://pypi.org/project/tf-nightly-gpu/) |
+| **Android** | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/android.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/android.html) | [![Download](https://api.bintray.com/packages/google/tensorflow/tensorflow/images/download.svg)](https://bintray.com/google/tensorflow/tensorflow/_latestVersion) |
### Community Supported Builds
@@ -102,13 +104,15 @@ The TensorFlow project strives to abide by generally accepted best practices in
## For more information
-
+* [Tensorflow Blog](https://medium.com/tensorflow)
+* [TensorFlow Course at Stanford](https://web.stanford.edu/class/cs20si)
+* [TensorFlow Model Zoo](https://github.com/tensorflow/models)
+* [TensorFlow MOOC on Udacity](https://www.udacity.com/course/deep-learning--ud730)
+* [TensorFlow Roadmap](https://www.tensorflow.org/community/roadmap)
+* [Tensorflow Twitter](https://twitter.com/tensorflow)
* [TensorFlow Website](https://www.tensorflow.org)
* [TensorFlow White Papers](https://www.tensorflow.org/about/bib)
* [TensorFlow YouTube Channel](https://www.youtube.com/channel/UC0rqucBdTuFTjJiefW5t-IQ)
-* [TensorFlow Model Zoo](https://github.com/tensorflow/models)
-* [TensorFlow MOOC on Udacity](https://www.udacity.com/course/deep-learning--ud730)
-* [TensorFlow Course at Stanford](https://web.stanford.edu/class/cs20si)
Learn more about the TensorFlow community at the [community page of tensorflow.org](https://www.tensorflow.org/community) for a few ways to participate.
diff --git a/RELEASE.md b/RELEASE.md
index 078aafd374..763ef3b279 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -3,7 +3,7 @@
## Major Features And Improvements
* The `tf.lite` runtime now supports `complex64`.
-* Initial Bigtable integration for `tf.data`.
+* Initial [Google Cloud Bigtable integration](https://github.com/tensorflow/tensorflow/tree/r1.10/tensorflow/contrib/bigtable) for `tf.data`.
* Improved local run behavior in `tf.estimator.train_and_evaluate` which does not reload checkpoints for evaluation.
* `RunConfig` now sets device_filters to restrict how workers and PS can communicate. This can speed up training and ensure clean shutdowns in some situations. But if you have jobs that require communication between workers, you will have to set custom session_options in your `RunConfig`.
* Moved Distributions and Bijectors from `tf.contrib.distributions` to [Tensorflow Probability (TFP)](https://github.com/tensorflow/probability). `tf.contrib.distributions` is now deprecated and will be removed by the end of 2018.
@@ -19,7 +19,7 @@
* `tf.data`:
* `tf.contrib.data.group_by_reducer()` is now available via the public API.
* `tf.contrib.data.choose_from_datasets()` is now available via the public API.
- * Adding `drop_remainder` argument to `tf.data.Dataset.batch()` and `tf.data.Dataset.padded_batch()`, deprecating tf.contrib.data.batch_and_drop_remainder()` and `tf.contrib.data.padded_batch_and_drop_remainder()`.
+ * Adding `drop_remainder` argument to `tf.data.Dataset.batch()` and `tf.data.Dataset.padded_batch()`, deprecating `tf.contrib.data.batch_and_drop_remainder()` and `tf.contrib.data.padded_batch_and_drop_remainder()`.
* `tf.estimator`:
* `Estimator`s now use custom savers included in `EstimatorSpec` scaffolds for saving SavedModels during export.
* `EstimatorSpec` will now add a default prediction output for export if no `export_output` is provided, eliminating the need to explicitly include a `PredictOutput` object in the `model_fn` for simple use-cases.
diff --git a/configure.py b/configure.py
index f97bf8a668..b6285cfc38 100644
--- a/configure.py
+++ b/configure.py
@@ -839,14 +839,15 @@ def set_tf_cuda_version(environ_cp):
cuda_toolkit_path = cygpath(cuda_toolkit_path)
if is_windows():
- cuda_rt_lib_path = 'lib/x64/cudart.lib'
+ cuda_rt_lib_paths = ['lib/x64/cudart.lib']
elif is_linux():
- cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
+ cuda_rt_lib_paths = ['%s/libcudart.so.%s' % (x, tf_cuda_version)
+ for x in ['lib64', 'lib/x86_64-linux-gnu']]
elif is_macos():
- cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
+ cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
- cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
- if os.path.exists(cuda_toolkit_path_full):
+ cuda_toolkit_paths_full = [os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths]
+ if any([os.path.exists(x) for x in cuda_toolkit_paths_full]):
break
# Reset and retry
@@ -1398,8 +1399,11 @@ def set_grpc_build_flags():
write_to_bazelrc('build --define grpc_no_ares=true')
-def set_build_strip_flag():
- write_to_bazelrc('build --strip=always')
+def set_system_libs_flag(environ_cp):
+ syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
+ syslibs = ','.join(sorted(syslibs.split(',')))
+ if syslibs and syslibs != '':
+ write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
def set_windows_build_flags(environ_cp):
@@ -1558,7 +1562,7 @@ def main():
set_grpc_build_flags()
set_cc_opt_flags(environ_cp)
- set_build_strip_flag()
+ set_system_libs_flag(environ_cp)
if is_windows():
set_windows_build_flags(environ_cp)
diff --git a/tensorflow/BUILD b/tensorflow/BUILD
index f8cd682024..94e059b914 100644
--- a/tensorflow/BUILD
+++ b/tensorflow/BUILD
@@ -124,12 +124,6 @@ config_setting(
)
config_setting(
- name = "windows_msvc",
- values = {"cpu": "x64_windows_msvc"},
- visibility = ["//visibility:public"],
-)
-
-config_setting(
name = "no_tensorflow_py_deps",
define_values = {"no_tensorflow_py_deps": "true"},
visibility = ["//visibility:public"],
@@ -387,6 +381,7 @@ config_setting(
define_values = {
"dynamic_loaded_kernels": "true",
},
+ visibility = ["//visibility:public"],
)
config_setting(
@@ -429,12 +424,12 @@ package_group(
load(
"//third_party/mkl:build_defs.bzl",
- "if_mkl",
+ "if_mkl_ml",
)
filegroup(
name = "intel_binary_blob",
- data = if_mkl(
+ data = if_mkl_ml(
[
"//third_party/mkl:intel_binary_blob",
],
@@ -487,7 +482,6 @@ tf_cc_shared_object(
linkopts = select({
"//tensorflow:darwin": [],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": [
"-Wl,--version-script", # This line must be directly followed by the version_script.lds file
"$(location //tensorflow:tf_framework_version_script.lds)",
@@ -529,7 +523,6 @@ tf_cc_shared_object(
"-Wl,-install_name,@rpath/libtensorflow.so",
],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": [
"-z defs",
"-Wl,--version-script", # This line must be directly followed by the version_script.lds file
@@ -554,7 +547,6 @@ tf_cc_shared_object(
"$(location //tensorflow:tf_exported_symbols.lds)",
],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": [
"-z defs",
"-Wl,--version-script", # This line must be directly followed by the version_script.lds file
diff --git a/tensorflow/__init__.py b/tensorflow/__init__.py
index 440e9f8dbd..21677512b6 100644
--- a/tensorflow/__init__.py
+++ b/tensorflow/__init__.py
@@ -28,7 +28,8 @@ contrib = LazyLoader('contrib', globals(), 'tensorflow.contrib')
del LazyLoader
from tensorflow.python.platform import flags # pylint: disable=g-import-not-at-top
-app.flags = flags # pylint: disable=undefined-variable
+from tensorflow.python.platform import app # pylint: disable=g-import-not-at-top
+app.flags = flags
del absolute_import
del division
diff --git a/tensorflow/c/c_api.cc b/tensorflow/c/c_api.cc
index 19ccb6e71d..b8adf6c127 100644
--- a/tensorflow/c/c_api.cc
+++ b/tensorflow/c/c_api.cc
@@ -202,7 +202,8 @@ TF_Tensor* TF_NewTensor(TF_DataType dtype, const int64_t* dims, int num_dims,
buf->len_ = len;
if (dtype != TF_STRING && dtype != TF_RESOURCE &&
tensorflow::DataTypeCanUseMemcpy(static_cast<DataType>(dtype)) &&
- reinterpret_cast<intptr_t>(data) % EIGEN_MAX_ALIGN_BYTES != 0) {
+ reinterpret_cast<intptr_t>(data) % std::max(1, EIGEN_MAX_ALIGN_BYTES) !=
+ 0) {
// TF_STRING and TF_RESOURCE tensors have a different representation in
// TF_Tensor than they do in tensorflow::Tensor. So a copy here is a waste
// (any alignment requirements will be taken care of by TF_TensorToTensor
diff --git a/tensorflow/c/eager/c_api_test.cc b/tensorflow/c/eager/c_api_test.cc
index 71d5f3613c..7126227cf5 100644
--- a/tensorflow/c/eager/c_api_test.cc
+++ b/tensorflow/c/eager/c_api_test.cc
@@ -1471,4 +1471,61 @@ void BM_ReadVariable(int iters) {
}
BENCHMARK(BM_ReadVariable);
+TEST(CAPI, StringAttributes) {
+ // Test that TFE_OpSetAttrString doesn't hold on to the value after it
+ // returns.
+ TF_Status* status = TF_NewStatus();
+ TFE_ContextOptions* opts = TFE_NewContextOptions();
+ TFE_Context* ctx = TFE_NewContext(opts, status);
+ ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
+ TFE_DeleteContextOptions(opts);
+
+ std::vector<int64_t> dims(4, 1);
+ TFE_Op* op = TFE_NewOp(ctx, "AvgPool", status);
+ ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
+
+ TF_Tensor* tensor =
+ TF_AllocateTensor(TF_FLOAT, dims.data(), dims.size(), sizeof(float));
+ float tensor_data[] = {1};
+ memcpy(TF_TensorData(tensor), tensor_data, TF_TensorByteSize(tensor));
+ TFE_TensorHandle* tensor_handle = TFE_NewTensorHandle(tensor, status);
+ ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
+ TFE_OpAddInput(op, tensor_handle, status);
+ TF_DeleteTensor(tensor);
+ TFE_DeleteTensorHandle(tensor_handle);
+
+ std::vector<int64_t> values(4, 1);
+ TFE_OpSetAttrIntList(op, "ksize", values.data(), values.size());
+ TFE_OpSetAttrIntList(op, "strides", values.data(), values.size());
+
+ const int BUFFER_SIZE = 10;
+ char buffer[BUFFER_SIZE];
+ std::strncpy(buffer, "VALID", BUFFER_SIZE);
+ TFE_OpSetAttrString(op, "padding", buffer, std::strlen(buffer));
+ // Overwriting value in "buffer", should be fine since TFE_Op
+ // shouldn't be holding on to it.
+ std::strncpy(buffer, "NHWC", BUFFER_SIZE);
+ TFE_OpSetAttrString(op, "data_format", buffer, std::strlen(buffer));
+
+ TFE_OpSetAttrType(op, "T", TF_FLOAT);
+
+ ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
+
+ TFE_TensorHandle* retvals[1];
+ int num_retvals = 1;
+ TFE_Execute(op, &retvals[0], &num_retvals, status);
+ ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
+ ASSERT_EQ(1, num_retvals);
+
+ tensor = TFE_TensorHandleResolve(retvals[0], status);
+ ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status);
+ EXPECT_EQ(4, TF_TensorByteSize(tensor));
+ TF_DeleteTensor(tensor);
+ TFE_DeleteTensorHandle(retvals[0]);
+
+ TFE_DeleteOp(op);
+
+ TFE_DeleteContext(ctx);
+ TF_DeleteStatus(status);
+}
} // namespace
diff --git a/tensorflow/cc/BUILD b/tensorflow/cc/BUILD
index 588a45ea43..f56521dac0 100644
--- a/tensorflow/cc/BUILD
+++ b/tensorflow/cc/BUILD
@@ -379,9 +379,11 @@ tf_cc_test(
srcs = ["gradients/math_grad_test.cc"],
deps = [
":cc_ops",
+ ":client_session",
":grad_op_registry",
":grad_testutil",
":gradient_checker",
+ ":gradients",
":math_grad",
":testutil",
"//tensorflow/core:lib_internal",
@@ -626,7 +628,6 @@ tf_cc_binary(
copts = tf_copts(),
linkopts = select({
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//tensorflow:darwin": [
"-lm",
"-lpthread",
diff --git a/tensorflow/cc/framework/cc_op_gen.cc b/tensorflow/cc/framework/cc_op_gen.cc
index dfdef88945..c20ea95a15 100644
--- a/tensorflow/cc/framework/cc_op_gen.cc
+++ b/tensorflow/cc/framework/cc_op_gen.cc
@@ -508,15 +508,6 @@ bool HasOptionalAttrs(
return false;
}
-const ApiDef::Arg* FindInputArg(StringPiece name, const ApiDef& api_def) {
- for (int i = 0; i < api_def.in_arg_size(); ++i) {
- if (api_def.in_arg(i).name() == name) {
- return &api_def.in_arg(i);
- }
- }
- return nullptr;
-}
-
struct OpInfo {
// graph_op_def: The OpDef used by the runtime, has the names that
// must be used when calling NodeBuilder.
diff --git a/tensorflow/cc/gradients/math_grad.cc b/tensorflow/cc/gradients/math_grad.cc
index 35a01e0341..1329b568ab 100644
--- a/tensorflow/cc/gradients/math_grad.cc
+++ b/tensorflow/cc/gradients/math_grad.cc
@@ -441,6 +441,21 @@ Status RealDivGrad(const Scope& scope, const Operation& op,
}
REGISTER_GRADIENT_OP("RealDiv", RealDivGrad);
+Status DivNoNanGrad(const Scope& scope, const Operation& op,
+ const std::vector<Output>& grad_inputs,
+ std::vector<Output>* grad_outputs) {
+ auto x_1 = ConjugateHelper(scope, op.input(0));
+ auto x_2 = ConjugateHelper(scope, op.input(1));
+ // y = x_1 / x_2
+ // dy/dx_1 = 1/x_2
+ // dy/dx_2 = -x_1/x_2^2
+ auto gx_1 = DivNoNan(scope, grad_inputs[0], x_2);
+ auto gx_2 = Mul(scope, grad_inputs[0],
+ DivNoNan(scope, DivNoNan(scope, Neg(scope, x_1), x_2), x_2));
+ return BinaryGradCommon(scope, op, grad_outputs, gx_1, gx_2);
+}
+REGISTER_GRADIENT_OP("DivNoNan", DivNoNanGrad);
+
Status SquaredDifferenceGrad(const Scope& scope, const Operation& op,
const std::vector<Output>& grad_inputs,
std::vector<Output>* grad_outputs) {
@@ -1007,6 +1022,26 @@ Status ProdGrad(const Scope& scope, const Operation& op,
}
REGISTER_GRADIENT_OP("Prod", ProdGrad);
+Status SegmentSumGrad(const Scope& scope, const Operation& op,
+ const std::vector<Output>& grad_inputs,
+ std::vector<Output>* grad_outputs) {
+ // The SegmentSum operation sums segments of the Tensor that have the same
+ // index in the segment_ids parameter.
+ // i.e z = [2, 3, 4, 5], segment_ids [0, 0, 0, 1]
+ // will produce [2 + 3 + 4, 5] = [9, 5]
+ // The gradient that will flow back to the gather operation will look like
+ // [x1, x2], it will have the same shape as the output of the SegmentSum
+ // operation. The differentiation step of the SegmentSum operation just
+ // broadcast the gradient in order to retrieve the z's shape.
+ // dy/dz = [x1, x1, x1, x2]
+ grad_outputs->push_back(Gather(scope, grad_inputs[0], op.input(1)));
+
+ // stop propagation along segment_ids
+ grad_outputs->push_back(NoGradient());
+ return scope.status();
+}
+REGISTER_GRADIENT_OP("SegmentSum", SegmentSumGrad);
+
// MatMulGrad helper function used to compute two MatMul operations
// based on input matrix transposition combinations.
Status MatMulGradHelper(const Scope& scope, const bool is_batch,
diff --git a/tensorflow/cc/gradients/math_grad_test.cc b/tensorflow/cc/gradients/math_grad_test.cc
index 1c9bdff5e1..c16938322c 100644
--- a/tensorflow/cc/gradients/math_grad_test.cc
+++ b/tensorflow/cc/gradients/math_grad_test.cc
@@ -13,8 +13,10 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/framework/gradient_checker.h"
+#include "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/framework/testutil.h"
#include "tensorflow/cc/gradients/grad_testutil.h"
#include "tensorflow/cc/ops/standard_ops.h"
@@ -31,6 +33,7 @@ using ops::AddN;
using ops::BatchMatMul;
using ops::Const;
using ops::Div;
+using ops::DivNoNan;
using ops::MatMul;
using ops::Max;
using ops::Maximum;
@@ -42,6 +45,7 @@ using ops::Placeholder;
using ops::Pow;
using ops::Prod;
using ops::RealDiv;
+using ops::SegmentSum;
using ops::SquaredDifference;
using ops::Sub;
using ops::Sum;
@@ -850,6 +854,36 @@ TEST_F(NaryGradTest, RealDiv) {
RunTest({x}, {x_shape}, {y}, {x_shape});
}
+TEST_F(NaryGradTest, DivNoNan) {
+ {
+ TensorShape x_shape({3, 2, 5});
+ const auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(x_shape));
+ // Test x / (1 + |x|) rather than x_1 / x_2 to avoid triggering large
+ // division errors in the numeric estimator used by the gradient checker.
+ const auto y = DivNoNan(
+ scope_, x, Add(scope_, Const<float>(scope_, 1), Abs(scope_, x)));
+ RunTest({x}, {x_shape}, {y}, {x_shape});
+ }
+ {
+ // Return 0 gradient (rather than NaN) for division by zero.
+ const auto x = Placeholder(scope_, DT_FLOAT);
+ const auto zero = Const<float>(scope_, 0.0);
+ const auto y = DivNoNan(scope_, x, zero);
+
+ std::vector<Output> grad_outputs;
+ TF_EXPECT_OK(AddSymbolicGradients(scope_, {y}, {x}, &grad_outputs));
+ ClientSession session(scope_);
+ std::vector<Tensor> grad_result;
+ TF_EXPECT_OK(
+ session.Run({{x, {-3.0f, 0.0f, 3.0f}}}, grad_outputs, &grad_result));
+ EXPECT_EQ(grad_result.size(), 1);
+ EXPECT_EQ(grad_result[0].NumElements(), 3);
+ EXPECT_EQ(grad_result[0].flat<float>()(0), 0.0f);
+ EXPECT_EQ(grad_result[0].flat<float>()(1), 0.0f);
+ EXPECT_EQ(grad_result[0].flat<float>()(2), 0.0f);
+ }
+}
+
TEST_F(NaryGradTest, SquaredDifference) {
TensorShape x1_shape({3, 2, 5});
TensorShape x2_shape({2, 5});
@@ -898,5 +932,14 @@ TEST_F(NaryGradTest, Prod) {
RunTest({x}, {x_shape}, {y}, {y_shape});
}
+TEST_F(NaryGradTest, SegmentSum) {
+ TensorShape x_shape({3, 4});
+ auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(x_shape));
+ auto y = SegmentSum(scope_, x, {0, 0, 1});
+ // the sum is always on the first dimension
+ TensorShape y_shape({2, 4});
+ RunTest({x}, {x_shape}, {y}, {y_shape});
+}
+
} // namespace
} // namespace tensorflow
diff --git a/tensorflow/compiler/aot/BUILD b/tensorflow/compiler/aot/BUILD
index d2f803bd18..1899a32e4d 100644
--- a/tensorflow/compiler/aot/BUILD
+++ b/tensorflow/compiler/aot/BUILD
@@ -48,6 +48,7 @@ cc_library(
"//tensorflow/compiler/xla/client:compile_only_client",
"//tensorflow/compiler/xla/client:xla_computation",
"//tensorflow/compiler/xla/service:compiler",
+ "//tensorflow/compiler/xla/service/cpu:buffer_info_util",
"//tensorflow/compiler/xla/service/cpu:cpu_compiler",
"//tensorflow/core:core_cpu_internal",
"//tensorflow/core:framework_internal",
diff --git a/tensorflow/compiler/aot/codegen.cc b/tensorflow/compiler/aot/codegen.cc
index 8dbe1e11b7..89fefdad54 100644
--- a/tensorflow/compiler/aot/codegen.cc
+++ b/tensorflow/compiler/aot/codegen.cc
@@ -24,6 +24,7 @@ limitations under the License.
#include "tensorflow/compiler/tf2xla/str_util.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/xla/service/compiler.h"
+#include "tensorflow/compiler/xla/service/cpu/buffer_info_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/errors.h"
@@ -36,6 +37,8 @@ namespace tfcompile {
namespace {
+using BufferInfo = cpu_function_runtime::BufferInfo;
+
bool IsAlpha(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
@@ -85,27 +88,36 @@ Status XLATypeToCpp(xla::PrimitiveType type, string* str) {
return Status::OK();
}
-// total_buffer_bytes returns the sum of each size in `sizes`, skipping -1
-// values. There are `n` entries in `sizes`.
-size_t total_buffer_bytes(const intptr_t* sizes, size_t n) {
- size_t total = 0;
- for (size_t i = 0; i < n; ++i) {
- if (sizes[i] != -1) {
- total += sizes[i];
- }
- }
- return total;
+// Returns the sum of the size of each buffer in `buffer_infos`.
+size_t TotalBufferBytes(const std::vector<BufferInfo>& buffer_infos) {
+ return std::accumulate(buffer_infos.begin(), buffer_infos.end(), size_t{0},
+ [](size_t size, const BufferInfo& buffer_info) {
+ return size + buffer_info.size();
+ });
}
-// Fills in arg_sizes with the byte size of each positional arg.
-Status ComputeArgSizes(const CompileResult& compile_result,
- std::vector<int64>* arg_sizes) {
- const xla::ProgramShape& ps = compile_result.program_shape;
- for (int i = 0; i < ps.parameters_size(); ++i) {
- arg_sizes->push_back(xla::ShapeUtil::ByteSizeOf(
- ps.parameters(i), compile_result.pointer_size));
- }
- return Status::OK();
+// Returns a vector of BufferInfo instances in `buffer_infos` that are entry
+// parameter buffers.
+std::vector<BufferInfo> ExtractEntryParamBufferInfos(
+ const std::vector<BufferInfo>& buffer_infos) {
+ std::vector<BufferInfo> result;
+ std::copy_if(buffer_infos.begin(), buffer_infos.end(),
+ std::back_inserter(result), [](const BufferInfo& buffer_info) {
+ return buffer_info.is_entry_parameter();
+ });
+ return result;
+}
+
+// Returns a vector of BufferInfo instances in `buffer_infos` that are temp
+// buffers.
+std::vector<BufferInfo> ExtractTempBufferInfos(
+ const std::vector<BufferInfo>& buffer_infos) {
+ std::vector<BufferInfo> result;
+ std::copy_if(buffer_infos.begin(), buffer_infos.end(),
+ std::back_inserter(result), [](const BufferInfo& buffer_info) {
+ return buffer_info.is_temp_buffer();
+ });
+ return result;
}
// Add (from,to) rewrite pairs based on the given shape. These rewrite pairs
@@ -278,6 +290,25 @@ Status ValidateFeedFetchCppNames(const tf2xla::Config& config) {
return Status::OK();
}
+// Returns a list of C++ expressions that, when executed, will construct the
+// BufferInfo instances in `buffer_infos`.
+std::vector<string> BufferInfosToCppExpression(
+ const std::vector<BufferInfo>& buffer_infos) {
+ std::vector<string> buffer_infos_as_strings;
+ std::transform(buffer_infos.begin(), buffer_infos.end(),
+ std::back_inserter(buffer_infos_as_strings),
+ [](const BufferInfo& buffer_info) {
+ std::pair<uint64, uint64> encoded = buffer_info.Encode();
+ string encoded_second_as_str =
+ encoded.second == ~0ULL
+ ? "~0ULL"
+ : strings::StrCat(encoded.second, "ULL");
+ return strings::StrCat(
+ "::tensorflow::cpu_function_runtime::BufferInfo({",
+ encoded.first, "ULL, ", encoded_second_as_str, "})");
+ });
+ return buffer_infos_as_strings;
+}
} // namespace
Status GenerateHeader(const CodegenOpts& opts, const tf2xla::Config& config,
@@ -286,29 +317,35 @@ Status GenerateHeader(const CodegenOpts& opts, const tf2xla::Config& config,
TF_RETURN_IF_ERROR(ValidateConfig(config));
TF_RETURN_IF_ERROR(ValidateFeedFetchCppNames(config));
const int64 result_index = compile_result.aot->result_buffer_index();
- const xla::BufferSizes& temp_sizes = compile_result.aot->buffer_sizes();
- if (result_index < 0 || result_index >= temp_sizes.size()) {
+ const std::vector<BufferInfo>& buffer_infos =
+ compile_result.aot->buffer_infos();
+ const std::vector<int32> arg_index_table =
+ ::xla::cpu::CreateArgIndexTableFromBufferInfos(buffer_infos);
+ std::vector<string> buffer_infos_as_strings =
+ BufferInfosToCppExpression(buffer_infos);
+ if (result_index < 0 || result_index >= buffer_infos.size()) {
return errors::InvalidArgument("result index: ", result_index,
" is outside the range of temp sizes: [0,",
- temp_sizes.size(), ")");
+ buffer_infos.size(), ")");
}
// Compute sizes and generate methods.
- std::vector<int64> arg_sizes;
- TF_RETURN_IF_ERROR(ComputeArgSizes(compile_result, &arg_sizes));
+ std::vector<BufferInfo> buffer_infos_for_args =
+ ExtractEntryParamBufferInfos(buffer_infos);
+ std::vector<BufferInfo> buffer_infos_for_temps =
+ ExtractTempBufferInfos(buffer_infos);
const xla::ProgramShape& ps = compile_result.program_shape;
string methods_arg, methods_result;
TF_RETURN_IF_ERROR(GenArgMethods(config, ps, compile_result, &methods_arg));
TF_RETURN_IF_ERROR(GenResultMethods(config, ps, &methods_result));
- const std::vector<intptr_t> iarg(arg_sizes.begin(), arg_sizes.end());
- const std::vector<intptr_t> itemp(temp_sizes.begin(), temp_sizes.end());
- const size_t arg_bytes_aligned =
- cpu_function_runtime::AlignedBufferBytes(iarg.data(), iarg.size());
- const size_t arg_bytes_total = total_buffer_bytes(iarg.data(), iarg.size());
- const size_t temp_bytes_aligned =
- cpu_function_runtime::AlignedBufferBytes(itemp.data(), itemp.size());
- const size_t temp_bytes_total =
- total_buffer_bytes(itemp.data(), itemp.size());
+ const size_t arg_bytes_aligned = cpu_function_runtime::AlignedBufferBytes(
+ buffer_infos_for_args.data(), buffer_infos_for_args.size(),
+ /*allocate_entry_params=*/true);
+ const size_t arg_bytes_total = TotalBufferBytes(buffer_infos_for_args);
+ const size_t temp_bytes_aligned = cpu_function_runtime::AlignedBufferBytes(
+ buffer_infos_for_temps.data(), buffer_infos_for_temps.size(),
+ /*allocate_entry_params=*/true);
+ const size_t temp_bytes_total = TotalBufferBytes(buffer_infos_for_temps);
// Create rewrite strings for namespace start and end.
string ns_start;
@@ -343,8 +380,8 @@ Status GenerateHeader(const CodegenOpts& opts, const tf2xla::Config& config,
// calling HloProfilePrinter::profile_counters_size.
const string assign_profile_counters_size =
opts.gen_hlo_profile_printer_data
- ? "data->profile_counters_size = "
- "data->hlo_profile_printer_data->profile_counters_size();"
+ ? "data->set_profile_counters_size("
+ "data->hlo_profile_printer_data()->profile_counters_size());"
: "";
// Use a poor-man's text templating mechanism; first populate the full header
@@ -414,9 +451,8 @@ class {{CLASS}} : public tensorflow::XlaCompiledCpuFunction {
static constexpr size_t kNumArgs = {{ARG_NUM}};
// Byte size of each argument buffer. There are kNumArgs entries.
- static const intptr_t* ArgSizes() {
- static constexpr intptr_t kArgSizes[kNumArgs] = {{{ARG_SIZES}}};
- return kArgSizes;
+ static const ::tensorflow::int64 ArgSize(::tensorflow::int32 index) {
+ return BufferInfos()[ArgIndexToBufferIndex()[index]].size();
}
// Returns static data used to create an XlaCompiledCpuFunction.
@@ -424,17 +460,17 @@ class {{CLASS}} : public tensorflow::XlaCompiledCpuFunction {
static XlaCompiledCpuFunction::StaticData* kStaticData = [](){
XlaCompiledCpuFunction::StaticData* data =
new XlaCompiledCpuFunction::StaticData;
- data->raw_function = {{ENTRY}};
- data->arg_sizes = ArgSizes();
- data->num_args = kNumArgs;
- data->temp_sizes = TempSizes();
- data->num_temps = kNumTemps;
- data->result_index = kResultIndex;
- data->arg_names = StaticArgNames();
- data->result_names = StaticResultNames();
- data->program_shape = StaticProgramShape();
- data->hlo_profile_printer_data = StaticHloProfilePrinterData();
- {{ASSIGN_PROFILE_COUNTERS_SIZE}}
+ data->set_raw_function({{ENTRY}});
+ data->set_buffer_infos(BufferInfos());
+ data->set_num_buffers(kNumBuffers);
+ data->set_arg_index_table(ArgIndexToBufferIndex());
+ data->set_num_args(kNumArgs);
+ data->set_result_index(kResultIndex);
+ data->set_arg_names(StaticArgNames());
+ data->set_result_names(StaticResultNames());
+ data->set_program_shape(StaticProgramShape());
+ data->set_hlo_profile_printer_data(StaticHloProfilePrinterData());
+{{ASSIGN_PROFILE_COUNTERS_SIZE}}
return data;
}();
return *kStaticData;
@@ -482,17 +518,27 @@ class {{CLASS}} : public tensorflow::XlaCompiledCpuFunction {
{{METHODS_RESULT}}
private:
- // Number of result and temporary buffers for the compiled computation.
- static constexpr size_t kNumTemps = {{TEMP_NUM}};
- // The 0-based index of the result tuple in the temporary buffers.
- static constexpr size_t kResultIndex = {{RESULT_INDEX}};
+ // Number of buffers for the compiled computation.
+ static constexpr size_t kNumBuffers = {{NUM_BUFFERS}};
- // Byte size of each result / temporary buffer. There are kNumTemps entries.
- static const intptr_t* TempSizes() {
- static constexpr intptr_t kTempSizes[kNumTemps] = {{{TEMP_SIZES}}};
- return kTempSizes;
+ static const ::tensorflow::cpu_function_runtime::BufferInfo* BufferInfos() {
+ static const ::tensorflow::cpu_function_runtime::BufferInfo
+ kBufferInfos[kNumBuffers] = {
+{{BUFFER_INFOS_AS_STRING}}
+ };
+ return kBufferInfos;
}
+ static const ::tensorflow::int32* ArgIndexToBufferIndex() {
+ static constexpr ::tensorflow::int32 kArgIndexToBufferIndex[kNumArgs] = {
+{{ARG_INDEX_TABLE}}
+ };
+ return kArgIndexToBufferIndex;
+ }
+
+ // The 0-based index of the result tuple in the temporary buffers.
+ static constexpr size_t kResultIndex = {{RESULT_INDEX}};
+
// Array of names of each positional argument, terminated by nullptr.
static const char** StaticArgNames() {{ARG_NAMES_CODE}}
@@ -523,8 +569,8 @@ class {{CLASS}} : public tensorflow::XlaCompiledCpuFunction {
{"{{ARG_BYTES_ALIGNED}}", strings::StrCat(arg_bytes_aligned)},
{"{{ARG_BYTES_TOTAL}}", strings::StrCat(arg_bytes_total)},
{"{{ARG_NAMES_CODE}}", arg_names_code},
- {"{{ARG_NUM}}", strings::StrCat(arg_sizes.size())},
- {"{{ARG_SIZES}}", str_util::Join(arg_sizes, ", ")},
+ {"{{ARG_NUM}}", strings::StrCat(arg_index_table.size())},
+ {"{{ARG_INDEX_TABLE}}", str_util::Join(arg_index_table, ", ")},
{"{{ASSIGN_PROFILE_COUNTERS_SIZE}}", assign_profile_counters_size},
{"{{CLASS}}", opts.class_name},
{"{{DECLS_FROM_OBJ_FILE}}",
@@ -546,8 +592,9 @@ class {{CLASS}} : public tensorflow::XlaCompiledCpuFunction {
{"{{RESULT_NAMES_CODE}}", result_names_code},
{"{{TEMP_BYTES_ALIGNED}}", strings::StrCat(temp_bytes_aligned)},
{"{{TEMP_BYTES_TOTAL}}", strings::StrCat(temp_bytes_total)},
- {"{{TEMP_NUM}}", strings::StrCat(temp_sizes.size())},
- {"{{TEMP_SIZES}}", str_util::Join(temp_sizes, ", ")}};
+ {"{{NUM_BUFFERS}}", strings::StrCat(buffer_infos.size())},
+ {"{{BUFFER_INFOS_AS_STRING}}",
+ str_util::Join(buffer_infos_as_strings, ",\n")}};
str_util::ReplaceAllPairs(header, rewrites);
return Status::OK();
}
diff --git a/tensorflow/compiler/aot/codegen_test.cc b/tensorflow/compiler/aot/codegen_test.cc
index 29bc9c13b8..60d59ae996 100644
--- a/tensorflow/compiler/aot/codegen_test.cc
+++ b/tensorflow/compiler/aot/codegen_test.cc
@@ -32,6 +32,8 @@ namespace tensorflow {
namespace tfcompile {
namespace {
+using ::tensorflow::cpu_function_runtime::BufferInfo;
+
void ExpectErrorContains(const Status& status, StringPiece str) {
EXPECT_NE(Status::OK(), status);
EXPECT_TRUE(str_util::StrContains(status.error_message(), str))
@@ -171,8 +173,14 @@ TEST(CodegenTest, Golden) {
fetch->mutable_id()->set_node_name("fetch0");
fetch->set_name("myfetch");
CompileResult compile_result;
- compile_result.aot.reset(
- new xla::cpu::CpuAotCompilationResult({}, {1, -1, 2, -1, 3, 120}, 5, {}));
+ compile_result.aot.reset(new xla::cpu::CpuAotCompilationResult(
+ {},
+ {BufferInfo::MakeTempBuffer(1),
+ BufferInfo::MakeEntryParameter(/*size=*/8, /*param_number=*/0),
+ BufferInfo::MakeTempBuffer(2),
+ BufferInfo::MakeEntryParameter(/*size=*/96, /*param_number=*/1),
+ BufferInfo::MakeTempBuffer(3), BufferInfo::MakeTempBuffer(120)},
+ 5, {}));
compile_result.program_shape = xla::ShapeUtil::MakeProgramShape(
{
xla::ShapeUtil::MakeShape(xla::F32, {1, 2}),
diff --git a/tensorflow/compiler/aot/codegen_test_h.golden b/tensorflow/compiler/aot/codegen_test_h.golden
index 6641d45e83..e4d8a02877 100644
--- a/tensorflow/compiler/aot/codegen_test_h.golden
+++ b/tensorflow/compiler/aot/codegen_test_h.golden
@@ -65,9 +65,8 @@ class MyClass : public tensorflow::XlaCompiledCpuFunction {
static constexpr size_t kNumArgs = 2;
// Byte size of each argument buffer. There are kNumArgs entries.
- static const intptr_t* ArgSizes() {
- static constexpr intptr_t kArgSizes[kNumArgs] = {8, 96};
- return kArgSizes;
+ static const ::tensorflow::int64 ArgSize(::tensorflow::int32 index) {
+ return BufferInfos()[ArgIndexToBufferIndex()[index]].size();
}
// Returns static data used to create an XlaCompiledCpuFunction.
@@ -75,17 +74,17 @@ class MyClass : public tensorflow::XlaCompiledCpuFunction {
static XlaCompiledCpuFunction::StaticData* kStaticData = [](){
XlaCompiledCpuFunction::StaticData* data =
new XlaCompiledCpuFunction::StaticData;
- data->raw_function = entry_point;
- data->arg_sizes = ArgSizes();
- data->num_args = kNumArgs;
- data->temp_sizes = TempSizes();
- data->num_temps = kNumTemps;
- data->result_index = kResultIndex;
- data->arg_names = StaticArgNames();
- data->result_names = StaticResultNames();
- data->program_shape = StaticProgramShape();
- data->hlo_profile_printer_data = StaticHloProfilePrinterData();
-
+ data->set_raw_function(entry_point);
+ data->set_buffer_infos(BufferInfos());
+ data->set_num_buffers(kNumBuffers);
+ data->set_arg_index_table(ArgIndexToBufferIndex());
+ data->set_num_args(kNumArgs);
+ data->set_result_index(kResultIndex);
+ data->set_arg_names(StaticArgNames());
+ data->set_result_names(StaticResultNames());
+ data->set_program_shape(StaticProgramShape());
+ data->set_hlo_profile_printer_data(StaticHloProfilePrinterData());
+
return data;
}();
return *kStaticData;
@@ -215,17 +214,32 @@ class MyClass : public tensorflow::XlaCompiledCpuFunction {
}
private:
- // Number of result and temporary buffers for the compiled computation.
- static constexpr size_t kNumTemps = 6;
- // The 0-based index of the result tuple in the temporary buffers.
- static constexpr size_t kResultIndex = 5;
+ // Number of buffers for the compiled computation.
+ static constexpr size_t kNumBuffers = 6;
+
+ static const ::tensorflow::cpu_function_runtime::BufferInfo* BufferInfos() {
+ static const ::tensorflow::cpu_function_runtime::BufferInfo
+ kBufferInfos[kNumBuffers] = {
+::tensorflow::cpu_function_runtime::BufferInfo({5ULL, ~0ULL}),
+::tensorflow::cpu_function_runtime::BufferInfo({34ULL, 0ULL}),
+::tensorflow::cpu_function_runtime::BufferInfo({9ULL, ~0ULL}),
+::tensorflow::cpu_function_runtime::BufferInfo({386ULL, 1ULL}),
+::tensorflow::cpu_function_runtime::BufferInfo({13ULL, ~0ULL}),
+::tensorflow::cpu_function_runtime::BufferInfo({481ULL, ~0ULL})
+ };
+ return kBufferInfos;
+ }
- // Byte size of each result / temporary buffer. There are kNumTemps entries.
- static const intptr_t* TempSizes() {
- static constexpr intptr_t kTempSizes[kNumTemps] = {1, -1, 2, -1, 3, 120};
- return kTempSizes;
+ static const ::tensorflow::int32* ArgIndexToBufferIndex() {
+ static constexpr ::tensorflow::int32 kArgIndexToBufferIndex[kNumArgs] = {
+1, 3
+ };
+ return kArgIndexToBufferIndex;
}
+ // The 0-based index of the result tuple in the temporary buffers.
+ static constexpr size_t kResultIndex = 5;
+
// Array of names of each positional argument, terminated by nullptr.
static const char** StaticArgNames() {
static const char* kNames[] = {"myfeed", nullptr};
diff --git a/tensorflow/compiler/aot/test.cc b/tensorflow/compiler/aot/test.cc
index 6b098049cb..5deb47d123 100644
--- a/tensorflow/compiler/aot/test.cc
+++ b/tensorflow/compiler/aot/test.cc
@@ -51,11 +51,9 @@ namespace tensorflow {
namespace tfcompile {
namespace {
-void zero_buffers(void** bufs, const intptr_t* sizes, size_t n) {
- for (int i = 0; i < n; ++i) {
- if (sizes[i] != -1) {
- memset(bufs[i], 0, sizes[i]);
- }
+void zero_buffers(XlaCompiledCpuFunction* computation) {
+ for (int i = 0; i < computation->num_args(); ++i) {
+ memset(computation->arg_data(i), 0, computation->arg_size(i));
}
}
@@ -66,7 +64,7 @@ TEST(TEST_NAME, NoCrash) {
CPP_CLASS computation;
computation.set_thread_pool(&device);
- zero_buffers(computation.args(), CPP_CLASS::ArgSizes(), CPP_CLASS::kNumArgs);
+ zero_buffers(&computation);
EXPECT_TRUE(computation.Run());
}
@@ -80,7 +78,7 @@ void BM_NAME(int iters) {
CPP_CLASS computation;
computation.set_thread_pool(&device);
- zero_buffers(computation.args(), CPP_CLASS::ArgSizes(), CPP_CLASS::kNumArgs);
+ zero_buffers(&computation);
testing::StartTiming();
while (--iters) {
diff --git a/tensorflow/compiler/aot/tests/tfcompile_test.cc b/tensorflow/compiler/aot/tests/tfcompile_test.cc
index fee46280e9..0c0c676ece 100644
--- a/tensorflow/compiler/aot/tests/tfcompile_test.cc
+++ b/tensorflow/compiler/aot/tests/tfcompile_test.cc
@@ -44,8 +44,8 @@ using ::testing::IsSupersetOf;
TEST(TFCompileTest, Add) {
AddComp add;
- EXPECT_EQ(add.arg0_data(), add.args()[0]);
- EXPECT_EQ(add.arg1_data(), add.args()[1]);
+ EXPECT_EQ(add.arg0_data(), add.arg_data(0));
+ EXPECT_EQ(add.arg1_data(), add.arg_data(1));
add.arg0() = 1;
add.arg1() = 2;
@@ -67,10 +67,10 @@ TEST(TFCompileTest, Add) {
EXPECT_EQ(add_const.error_msg(), "");
EXPECT_EQ(add_const.arg0(), 123);
EXPECT_EQ(add_const.arg0_data()[0], 123);
- EXPECT_EQ(add_const.arg0_data(), add.args()[0]);
+ EXPECT_EQ(add_const.arg0_data(), add.arg_data(0));
EXPECT_EQ(add_const.arg1(), 456);
EXPECT_EQ(add_const.arg1_data()[0], 456);
- EXPECT_EQ(add_const.arg1_data(), add.args()[1]);
+ EXPECT_EQ(add_const.arg1_data(), add.arg_data(1));
EXPECT_EQ(add_const.result0(), 579);
EXPECT_EQ(add_const.result0_data()[0], 579);
EXPECT_EQ(add_const.result0_data(), add_const.results()[0]);
@@ -85,8 +85,8 @@ TEST(TFCompileTest, Add_SetArg) {
int32 arg_y = 32;
add.set_arg0_data(&arg_x);
add.set_arg1_data(&arg_y);
- EXPECT_EQ(add.arg0_data(), add.args()[0]);
- EXPECT_EQ(add.arg1_data(), add.args()[1]);
+ EXPECT_EQ(add.arg0_data(), add.arg_data(0));
+ EXPECT_EQ(add.arg1_data(), add.arg_data(1));
EXPECT_TRUE(add.Run());
EXPECT_EQ(add.error_msg(), "");
@@ -97,7 +97,7 @@ TEST(TFCompileTest, Add_SetArg) {
TEST(TFCompileTest, AddWithCkpt) {
AddWithCkptComp add;
- EXPECT_EQ(add.arg0_data(), add.args()[0]);
+ EXPECT_EQ(add.arg0_data(), add.arg_data(0));
add.arg0() = 1;
EXPECT_TRUE(add.Run());
@@ -117,7 +117,7 @@ TEST(TFCompileTest, AddWithCkpt) {
EXPECT_EQ(add_const.error_msg(), "");
EXPECT_EQ(add_const.arg0(), 111);
EXPECT_EQ(add_const.arg0_data()[0], 111);
- EXPECT_EQ(add_const.arg0_data(), add_const.args()[0]);
+ EXPECT_EQ(add_const.arg0_data(), add_const.arg_data(0));
EXPECT_EQ(add_const.result0(), 153);
EXPECT_EQ(add_const.result0_data()[0], 153);
EXPECT_EQ(add_const.result0_data(), add_const.results()[0]);
@@ -125,7 +125,7 @@ TEST(TFCompileTest, AddWithCkpt) {
TEST(TFCompileTest, AddWithCkptSaver) {
AddWithCkptSaverComp add;
- EXPECT_EQ(add.arg0_data(), add.args()[0]);
+ EXPECT_EQ(add.arg0_data(), add.arg_data(0));
add.arg0() = 1;
EXPECT_TRUE(add.Run());
@@ -145,7 +145,7 @@ TEST(TFCompileTest, AddWithCkptSaver) {
EXPECT_EQ(add_const.error_msg(), "");
EXPECT_EQ(add_const.arg0(), 111);
EXPECT_EQ(add_const.arg0_data()[0], 111);
- EXPECT_EQ(add_const.arg0_data(), add_const.args()[0]);
+ EXPECT_EQ(add_const.arg0_data(), add_const.arg_data(0));
EXPECT_EQ(add_const.result0(), 153);
EXPECT_EQ(add_const.result0_data()[0], 153);
EXPECT_EQ(add_const.result0_data(), add_const.results()[0]);
@@ -153,9 +153,9 @@ TEST(TFCompileTest, AddWithCkptSaver) {
TEST(TFCompileTest, Cond) {
CondComp cond;
- EXPECT_EQ(cond.arg0_data(), cond.args()[0]);
- EXPECT_EQ(cond.arg1_data(), cond.args()[1]);
- EXPECT_EQ(cond.arg2_data(), cond.args()[2]);
+ EXPECT_EQ(cond.arg0_data(), cond.arg_data(0));
+ EXPECT_EQ(cond.arg1_data(), cond.arg_data(1));
+ EXPECT_EQ(cond.arg2_data(), cond.arg_data(2));
cond.arg1() = 10;
cond.arg2() = 20;
{
@@ -178,8 +178,8 @@ TEST(TFCompileTest, Cond) {
TEST(TFCompileTest, Gather) {
GatherComp gather;
- EXPECT_EQ(gather.arg0_data(), gather.args()[0]);
- EXPECT_EQ(gather.arg1_data(), gather.args()[1]);
+ EXPECT_EQ(gather.arg0_data(), gather.arg_data(0));
+ EXPECT_EQ(gather.arg1_data(), gather.arg_data(1));
// Successful gather.
{
@@ -202,12 +202,12 @@ TEST(TFCompileTest, Gather) {
EXPECT_EQ(gather_const.arg0(i), params[i]);
EXPECT_EQ(gather_const.arg0_data()[i], params[i]);
}
- EXPECT_EQ(gather_const.arg0_data(), gather_const.args()[0]);
+ EXPECT_EQ(gather_const.arg0_data(), gather_const.arg_data(0));
for (int i = 0; i < 2; ++i) {
EXPECT_EQ(gather_const.arg1(i), indices[i]);
EXPECT_EQ(gather_const.arg1_data()[i], indices[i]);
}
- EXPECT_EQ(gather_const.arg1_data(), gather_const.args()[1]);
+ EXPECT_EQ(gather_const.arg1_data(), gather_const.arg_data(1));
for (int i = 0; i < 2; ++i) {
EXPECT_EQ(gather_const.result0(i), results[i]);
EXPECT_EQ(gather_const.result0_data()[i], results[i]);
@@ -222,8 +222,8 @@ TEST(TFCompileTest, MatMul2) {
foo::bar::MatMulComp matmul;
matmul.set_thread_pool(&device);
- EXPECT_EQ(matmul.arg0_data(), matmul.args()[0]);
- EXPECT_EQ(matmul.arg1_data(), matmul.args()[1]);
+ EXPECT_EQ(matmul.arg0_data(), matmul.arg_data(0));
+ EXPECT_EQ(matmul.arg1_data(), matmul.arg_data(1));
// Test using the argN() methods.
{
@@ -271,12 +271,12 @@ TEST(TFCompileTest, MatMul2) {
EXPECT_EQ(matmul_const.arg0(i / 3, i % 3), args[i]);
EXPECT_EQ(matmul_const.arg0_data()[i], args[i]);
}
- EXPECT_EQ(matmul_const.arg0_data(), matmul.args()[0]);
+ EXPECT_EQ(matmul_const.arg0_data(), matmul.arg_data(0));
for (int i = 0; i < 6; ++i) {
EXPECT_EQ(matmul_const.arg1(i / 2, i % 2), args[i + 6]);
EXPECT_EQ(matmul_const.arg1_data()[i], args[i + 6]);
}
- EXPECT_EQ(matmul_const.arg1_data(), matmul.args()[1]);
+ EXPECT_EQ(matmul_const.arg1_data(), matmul.arg_data(1));
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(matmul_const.result0(i / 2, i % 2), results[i]);
EXPECT_EQ(matmul_const.result0_data()[i], results[i]);
@@ -300,8 +300,8 @@ TEST(TFCompileTest, MatMul2_SetArg) {
float arg1[3][2] = {{7, 8}, {9, 10}, {11, 12}};
matmul.set_arg0_data(&arg0);
matmul.set_arg1_data(&arg1);
- EXPECT_EQ(matmul.arg0_data(), matmul.args()[0]);
- EXPECT_EQ(matmul.arg1_data(), matmul.args()[1]);
+ EXPECT_EQ(matmul.arg0_data(), matmul.arg_data(0));
+ EXPECT_EQ(matmul.arg1_data(), matmul.arg_data(1));
EXPECT_TRUE(matmul.Run());
EXPECT_EQ(matmul.error_msg(), "");
@@ -319,8 +319,8 @@ TEST(TFCompileTest, MatMulAndAdd1) {
MatMulAndAddComp muladd;
muladd.set_thread_pool(&device);
- EXPECT_EQ(muladd.arg0_data(), muladd.args()[0]);
- EXPECT_EQ(muladd.arg1_data(), muladd.args()[1]);
+ EXPECT_EQ(muladd.arg0_data(), muladd.arg_data(0));
+ EXPECT_EQ(muladd.arg1_data(), muladd.arg_data(1));
// Test methods with positional args and results.
{
@@ -346,12 +346,12 @@ TEST(TFCompileTest, MatMulAndAdd1) {
EXPECT_EQ(muladd_const.arg0(i / 2, i % 2), args[i]);
EXPECT_EQ(muladd_const.arg0_data()[i], args[i]);
}
- EXPECT_EQ(muladd_const.arg0_data(), muladd.args()[0]);
+ EXPECT_EQ(muladd_const.arg0_data(), muladd.arg_data(0));
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(muladd_const.arg1(i / 2, i % 2), args[i + 4]);
EXPECT_EQ(muladd_const.arg1_data()[i], args[i + 4]);
}
- EXPECT_EQ(muladd_const.arg1_data(), muladd.args()[1]);
+ EXPECT_EQ(muladd_const.arg1_data(), muladd.arg_data(1));
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(muladd_const.result0(i / 2, i % 2), results0[i]);
EXPECT_EQ(muladd_const.result0_data()[i], results0[i]);
@@ -387,12 +387,12 @@ TEST(TFCompileTest, MatMulAndAdd1) {
EXPECT_EQ(muladd_const.arg_x(i / 2, i % 2), args[i]);
EXPECT_EQ(muladd_const.arg_x_data()[i], args[i]);
}
- EXPECT_EQ(muladd_const.arg_x_data(), muladd.args()[0]);
+ EXPECT_EQ(muladd_const.arg_x_data(), muladd.arg_data(0));
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(muladd_const.arg_y(i / 2, i % 2), args[i + 4]);
EXPECT_EQ(muladd_const.arg_y_data()[i], args[i + 4]);
}
- EXPECT_EQ(muladd_const.arg_y_data(), muladd.args()[1]);
+ EXPECT_EQ(muladd_const.arg_y_data(), muladd.arg_data(1));
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(muladd_const.result_x_y_prod(i / 2, i % 2), results0[i]);
EXPECT_EQ(muladd_const.result_x_y_prod_data()[i], results0[i]);
@@ -407,8 +407,8 @@ TEST(TFCompileTest, MatMulAndAdd1) {
TEST(TFCompileTest, Function) {
// The function is equivalent to an addition
FunctionComp add_fn;
- EXPECT_EQ(add_fn.arg0_data(), add_fn.args()[0]);
- EXPECT_EQ(add_fn.arg1_data(), add_fn.args()[1]);
+ EXPECT_EQ(add_fn.arg0_data(), add_fn.arg_data(0));
+ EXPECT_EQ(add_fn.arg1_data(), add_fn.arg_data(1));
add_fn.arg0() = 1;
add_fn.arg1() = 2;
@@ -451,8 +451,8 @@ TEST(TFCompileTest, AssertEqAndReturnDiff) {
// Assert is converted into a no-op in XLA, so there is no failure even if the
// two args are different.
AssertComp assert;
- EXPECT_EQ(assert.arg0_data(), assert.args()[0]);
- EXPECT_EQ(assert.arg1_data(), assert.args()[1]);
+ EXPECT_EQ(assert.arg0_data(), assert.arg_data(0));
+ EXPECT_EQ(assert.arg1_data(), assert.arg_data(1));
assert.arg0() = 2;
assert.arg1() = 1;
diff --git a/tensorflow/compiler/jit/BUILD b/tensorflow/compiler/jit/BUILD
index 15f9ba217f..e059f77563 100644
--- a/tensorflow/compiler/jit/BUILD
+++ b/tensorflow/compiler/jit/BUILD
@@ -160,6 +160,7 @@ cc_library(
"//tensorflow/compiler/jit/ops:xla_ops",
"//tensorflow/compiler/tf2xla:common",
"//tensorflow/compiler/tf2xla:dump_graph",
+ "//tensorflow/compiler/tf2xla:tf2xla_util",
"//tensorflow/compiler/tf2xla:xla_compiler",
"//tensorflow/compiler/tf2xla/kernels:xla_ops",
"//tensorflow/compiler/xla:util",
@@ -313,12 +314,16 @@ cc_library(
"deadness_analysis_internal.h",
"encapsulate_subgraphs_pass.cc",
"mark_for_compilation_pass.cc",
+ "mark_for_compilation_pass_test_helper.cc",
+ "partially_decluster_pass.cc",
],
hdrs = [
"build_xla_launch_ops_pass.h",
"deadness_analysis.h",
"encapsulate_subgraphs_pass.h",
"mark_for_compilation_pass.h",
+ "mark_for_compilation_pass_test_helper.h",
+ "partially_decluster_pass.h",
],
deps = [
":common",
@@ -353,6 +358,7 @@ cc_library(
"//tensorflow/compiler/jit/graphcycles",
"//tensorflow/core:framework",
"//tensorflow/core:graph",
+ "//tensorflow/core:lib",
"//tensorflow/core:protos_all_cc",
"//tensorflow/core/kernels:bounds_check",
],
@@ -417,10 +423,12 @@ tf_cc_test(
srcs = [
"encapsulate_subgraphs_pass_test.cc",
"mark_for_compilation_pass_test.cc",
+ "partially_decluster_pass_test.cc",
],
deps = [
":common",
":compilation_passes",
+ ":xla_cluster_util",
"//tensorflow/cc:cc_ops",
"//tensorflow/cc:cc_ops_internal",
"//tensorflow/cc:function_ops",
diff --git a/tensorflow/compiler/jit/deadness_analysis.cc b/tensorflow/compiler/jit/deadness_analysis.cc
index 8aff87e5e6..0ca0f949dc 100644
--- a/tensorflow/compiler/jit/deadness_analysis.cc
+++ b/tensorflow/compiler/jit/deadness_analysis.cc
@@ -21,18 +21,79 @@ limitations under the License.
#include "tensorflow/core/lib/hash/hash.h"
// ALGORITHM OVERVIEW
+// ==================
//
// We map every output produced by each node in the TensorFlow graph (including
// control dependence) into an instance of the Predicate class. Instances of
// Predicate denote logical formulas and mapping a node `n` to a predicate
-// `pred` implies that `n` is executed whenver `pred` is true. Then we can
-// deduce mismatching liveness in the inputs to node by comparing the predicate
-// those inputs are mapped to.
+// `pred` implies that `n` is live whenever `pred` is true. Then we can deduce
+// mismatching liveness in the inputs to node by comparing the predicate those
+// inputs are mapped to. The core logic of this pass resides in creating the
+// map from TensorFlow nodes to predicates.
//
-// Loops are handled pessimistically -- we map Merge nodes with backedges to
-// uninterpreted symbols (the same kind we use to represent Switch and _Recv).
-// Predicate equality has to hold over all possible assignments to these
-// uninterpreted symbols.
+//
+// MAPPING NODES TO PREDICATES, MODULO CYCLES
+// ------------------------------------------
+//
+// If we ignore cycles for a moment, computing predicates is fairly
+// straightforward. We traverse the graph in RPO, mapping each node to a
+// predicate based on the predicates its inputs are mapped to. For instance a
+// Merge(X, Y) node will be mapped to OR(PredicateFor(X), PredicateFor(Y)).
+// Roughtly speaking, we abstract interpret each node on the "liveness" domain,
+// where values in the domain represent if a tensor carries a dead signal or
+// not.
+//
+//
+// DEALING WITH CYCLES
+// -------------------
+//
+// We map Merge nodes that are the target of a backedge to AndRecurrence
+// instances. An AndRecurrence with start() = S and step() = X, printed as
+// {S,&,X}, *roughly* represents the infinite list of predicates
+// [S,S&X,S&X&X,S&X&X, ...]. So {S,&,X} can be used to represent the predicate
+// for Merge in a graph like:
+//
+// Init
+// |
+// v
+// Merge <-----------+
+// | |
+// v |
+// Incr |
+// | |
+// v |
+// Switch <- Cond |
+// | |
+// v (oidx: 1) |
+// | |
+// +---------------+
+//
+// Where S is the predicate for Init and X is the predicate that asserts that
+// Cond is true. {S,&,X} states that Merge is live on the first "iteration" iff
+// S is true, live on the second iteration iff "S&X" is true, live on the third
+// iteration iff "S&X&X" is true etc. There is a subtlety here, S&X&X would
+// normally be equivalent to S&X which isn't quite what we want to represent.
+// Instead we want {S,&,X} to denote the infinite list [S, S&X,
+// S&X&X',S&X&X'&X'', ...] where X, X', X'' are predicates that assert Cond is
+// true on iteration 0, 1, 2 respectively. This is made more precise in the
+// comment on the AndRecurrence class.
+//
+// The general algorithm that deals with cycles does two RPO (reverse post
+// order) passes over the graph. On the first pass it assigns a symbolic
+// predicate to merge nodes with backedges. On the second pass it tries to
+// pattern matche the predicates for the backedges of these merges and infer an
+// AndRecurrence for the merge.
+//
+// In other words, we do a pessimistic data flow analysis where the data-flow
+// lattice has two elements, Symbolic and NonSymbolic with Symbolic >
+// NonSymbolic. The lattice has height = 2 so two iterations are sufficient to
+// converge. We don't do an optimistic data flow analysis to make pattern
+// matching easier: if we assigned the predicate of the initial value to the
+// merge during the first pass, on the second pass the backedge may see a
+// simplified value that would be difficult to pattern match.
+//
+// We still use symbolic predicates for merges for which we can't pattern match
+// on the backedge predicate. This is conservatively correct.
namespace tensorflow {
@@ -42,14 +103,21 @@ namespace {
// above.
class Predicate {
public:
- enum class Kind { kAnd, kOr, kNot, kSymbol };
+ enum class Kind { kAnd, kOr, kNot, kAndRecurrence, kSymbol };
virtual string ToString() const = 0;
int64 hash() const { return hash_; }
+ virtual gtl::ArraySlice<Predicate*> GetOperands() const = 0;
virtual Kind kind() const = 0;
virtual ~Predicate() {}
+ // Invokes func on p and on all of its operands recursively. Does not invoke
+ // `func` on the same Predicate instance twice. Aborts the search if `func`
+ // returns true.
+ template <typename FunctionTy>
+ static void Visit(Predicate* p, const FunctionTy& func);
+
protected:
explicit Predicate(int64 hash) : hash_(hash) {}
@@ -90,7 +158,8 @@ class AndPredicate : public Predicate {
Kind kind() const override { return Kind::kAnd; }
- const gtl::ArraySlice<Predicate*> operands() const { return operands_; }
+ gtl::ArraySlice<Predicate*> GetOperands() const override { return operands_; }
+ gtl::ArraySlice<Predicate*> operands() const { return operands_; }
private:
std::vector<Predicate*> operands_;
@@ -117,7 +186,8 @@ class OrPredicate : public Predicate {
}
Kind kind() const override { return Kind::kOr; }
- const gtl::ArraySlice<Predicate*> operands() const { return operands_; }
+ gtl::ArraySlice<Predicate*> GetOperands() const override { return operands_; }
+ gtl::ArraySlice<Predicate*> operands() const { return operands_; }
private:
std::vector<Predicate*> operands_;
@@ -128,23 +198,58 @@ class NotPredicate : public Predicate {
public:
explicit NotPredicate(Predicate* operand)
: Predicate(HashPredicateSequence(Kind::kNot, {operand})),
- operand_(operand) {}
+ operands_({operand}) {}
string ToString() const override {
return strings::StrCat("~", operand()->ToString());
}
Kind kind() const override { return Kind::kNot; }
- Predicate* operand() const { return operand_; }
+ Predicate* operand() const { return operands_[0]; }
+ gtl::ArraySlice<Predicate*> GetOperands() const override { return operands_; }
+
+ private:
+ std::array<Predicate*, 1> operands_;
+};
+
+// Represents an infinite list of predicates.
+//
+// An AndRecurrence with start = S and step = X is printed as {S,&,X} and stands
+// for the list of predicates:
+//
+// S, S & GenSym(X,1), S & GenSym(X,1) & GenSym(X,2), ...
+//
+// where GenSym(<expression>, <id>) renames every SymbolPredicate in
+// <expression> by appending <id> to it, in effect creating a "fresh" symbol.
+// This means {P,&,Q} is not equal to "P on the first iteration; P&Q on
+// subsequent iterations".
+class AndRecurrencePredicate : public Predicate {
+ public:
+ explicit AndRecurrencePredicate(Predicate* start, Predicate* step)
+ : Predicate(HashPredicateSequence(Kind::kAndRecurrence, {start, step})),
+ operands_({start, step}) {}
+
+ Predicate* start() const { return operands_[0]; }
+ Predicate* step() const { return operands_[1]; }
+
+ string ToString() const override {
+ return strings::StrCat("{", start()->ToString(), ",&,", step()->ToString(),
+ "}");
+ }
+
+ Kind kind() const override { return Kind::kAndRecurrence; }
+
+ gtl::ArraySlice<Predicate*> GetOperands() const override { return operands_; }
private:
- Predicate* operand_;
+ std::array<Predicate*, 2> operands_;
};
// Represents an uninterpreted symbol in a logical predicate.
//
// Two predicates are equivalent iff they are equivalent for all assignments to
-// the symbols contained in them.
+// the symbols contained in them, i.e. predicates are forall qualified over
+// symbols.
class SymbolPredicate : public Predicate {
public:
explicit SymbolPredicate(TensorId tensor_id, bool must_be_true)
@@ -158,6 +263,7 @@ class SymbolPredicate : public Predicate {
}
Kind kind() const override { return Kind::kSymbol; }
+ gtl::ArraySlice<Predicate*> GetOperands() const override { return {}; }
// If `must_be_true()` is true this SymbolPredicate represents the proposition
// "tensor_id() is live and evaluates to true".
@@ -179,6 +285,29 @@ class SymbolPredicate : public Predicate {
}
};
+template <typename FunctionTy>
+/*static*/ void Predicate::Visit(Predicate* p, const FunctionTy& func) {
+ gtl::FlatSet<Predicate*> visited;
+ std::vector<Predicate*> stack;
+
+ stack.push_back(p);
+ visited.insert(p);
+
+ while (!stack.empty()) {
+ Predicate* current = stack.back();
+ stack.pop_back();
+ bool done = func(current);
+ if (done) {
+ return;
+ }
+ for (Predicate* op : current->GetOperands()) {
+ if (visited.insert(op).second) {
+ stack.push_back(op);
+ }
+ }
+ }
+}
+
// Creates and owns Predicate instances. Simplifies predicates as it creates
// them.
class PredicateFactory {
@@ -204,6 +333,21 @@ class PredicateFactory {
}
}
+ Predicate* MakeAndRecurrencePredicate(Predicate* start, Predicate* step) {
+ auto it = interned_and_rec_instances_.find({start, step});
+ if (it != interned_and_rec_instances_.end()) {
+ return it->second.get();
+ }
+
+ std::unique_ptr<Predicate> new_pred =
+ Make<AndRecurrencePredicate>(start, step);
+ Predicate* new_pred_ptr = new_pred.get();
+ CHECK(interned_and_rec_instances_
+ .emplace(SignatureForAndRec(start, step), std::move(new_pred))
+ .second);
+ return new_pred_ptr;
+ }
+
Predicate* MakeSymbolPredicate(TensorId tensor_id, bool must_be_true) {
SignatureForSymbol signature = {tensor_id, must_be_true};
auto it = interned_symbol_instances_.find(signature);
@@ -244,6 +388,7 @@ class PredicateFactory {
using SignatureForAndOr =
std::pair<Predicate::Kind, gtl::ArraySlice<Predicate*>>;
using SignatureForNot = Predicate*;
+ using SignatureForAndRec = std::pair<Predicate*, Predicate*>;
using SignatureForSymbol = std::pair<SafeTensorId, bool>;
struct HashSignatureForAndOr {
@@ -268,6 +413,8 @@ class PredicateFactory {
interned_and_or_instances_;
gtl::FlatMap<SignatureForNot, std::unique_ptr<Predicate>>
interned_not_instances_;
+ gtl::FlatMap<SignatureForAndRec, std::unique_ptr<Predicate>>
+ interned_and_rec_instances_;
gtl::FlatMap<SignatureForSymbol, std::unique_ptr<Predicate>,
HashSignatureForSymbol>
interned_symbol_instances_;
@@ -288,10 +435,7 @@ Predicate* PredicateFactory::MakeAndOrImpl(gtl::ArraySlice<Predicate*> operands,
if (op->kind() == pred_kind) {
// "Inline" the operands of an inner And/Or into the parent And/Or.
- gtl::ArraySlice<Predicate*> operands =
- is_and ? dynamic_cast<AndPredicate*>(op)->operands()
- : dynamic_cast<OrPredicate*>(op)->operands();
- for (Predicate* subop : operands) {
+ for (Predicate* subop : op->GetOperands()) {
if (simplified_ops_set.insert(subop).second) {
simplified_ops.push_back(subop);
}
@@ -351,6 +495,7 @@ class DeadnessAnalysisImpl : public DeadnessAnalysis {
: graph_(*graph), vlog_(VLOG_IS_ON(2)) {}
Status Populate();
+ Status PopulateWithReversePostOrder(gtl::ArraySlice<Node*> rpo);
bool HasInputsWithMismatchingDeadness(const Node& node) override;
void Print() const override;
gtl::FlatMap<TensorId, string, TensorId::Hasher> PredicateMapAsString() const;
@@ -359,20 +504,40 @@ class DeadnessAnalysisImpl : public DeadnessAnalysis {
enum class EdgeKind { kDataAndControl, kDataOnly, kControlOnly };
std::vector<Predicate*> GetIncomingPreds(Node* n, EdgeKind edge_kind);
- void SetPred(Node* n, int output_idx, Predicate* pred) {
- CHECK(
- predicate_map_.insert({TensorId(n->name(), output_idx), pred}).second);
+
+ // Sets the predicate for output `output_idx` of `n` to `pred`. Sets the i'th
+ // bit of `should_revisit` if `pred` is different from the current predicate
+ // for the `output_idx` output of `n`.
+ void SetPredicate(Node* n, int output_idx, Predicate* pred,
+ std::vector<bool>* should_revisit) {
+ auto insert_result =
+ predicate_map_.insert({TensorId(n->name(), output_idx), pred});
+ if (!insert_result.second && insert_result.first->second != pred) {
+ VLOG(4) << "For " << n->name() << ":" << output_idx << " from "
+ << insert_result.first->second->ToString() << " "
+ << insert_result.first->second << " to " << pred->ToString()
+ << " " << pred;
+ insert_result.first->second = pred;
+ if (should_revisit != nullptr) {
+ for (const Edge* e : n->out_edges()) {
+ (*should_revisit)[e->dst()->id()] = true;
+ }
+ }
+ }
}
- void SetPred(Node* n, gtl::ArraySlice<int> output_idxs, Predicate* pred) {
+
+ void SetPredicate(Node* n, gtl::ArraySlice<int> output_idxs, Predicate* pred,
+ std::vector<bool>* should_revisit) {
for (int output_idx : output_idxs) {
- SetPred(n, output_idx, pred);
+ SetPredicate(n, output_idx, pred, should_revisit);
}
}
- Status HandleSwitch(Node* n);
- Status HandleMerge(Node* n);
- Status HandleRecv(Node* n);
- Status HandleGeneric(Node* n);
+ Status HandleSwitch(Node* n, std::vector<bool>* should_revisit);
+ Status HandleMerge(Node* n, std::vector<bool>* should_revisit);
+ Status HandleRecv(Node* n, std::vector<bool>* should_revisit);
+ Status HandleGeneric(Node* n, std::vector<bool>* should_revisit);
+ Status HandleNode(Node* n, std::vector<bool>* should_revisit);
const Graph& graph_;
gtl::FlatMap<TensorId, Predicate*, TensorId::Hasher> predicate_map_;
@@ -395,14 +560,15 @@ std::vector<Predicate*> DeadnessAnalysisImpl::GetIncomingPreds(
if (should_process) {
auto it = predicate_map_.find(InputEdgeToTensorId(in_edge));
- CHECK(it != predicate_map_.end());
+ CHECK(it != predicate_map_.end()) << n->name();
incoming_preds.push_back(it->second);
}
}
return incoming_preds;
}
-Status DeadnessAnalysisImpl::HandleSwitch(Node* n) {
+Status DeadnessAnalysisImpl::HandleSwitch(Node* n,
+ std::vector<bool>* should_revisit) {
std::vector<Predicate*> input_preds =
GetIncomingPreds(n, EdgeKind::kDataAndControl);
const Edge* pred_edge;
@@ -414,84 +580,252 @@ Status DeadnessAnalysisImpl::HandleSwitch(Node* n) {
// Output 0 is alive iff all inputs are alive and the condition is false.
input_preds.push_back(false_switch);
- SetPred(n, 0, predicate_factory_.MakeAndPredicate(input_preds));
+ SetPredicate(n, 0, predicate_factory_.MakeAndPredicate(input_preds),
+ should_revisit);
input_preds.pop_back();
// Output 1 is alive iff all inputs are alive and the condition is true.
input_preds.push_back(true_switch);
- SetPred(n, 1, predicate_factory_.MakeAndPredicate(input_preds));
+ SetPredicate(n, 1, predicate_factory_.MakeAndPredicate(input_preds),
+ should_revisit);
input_preds.pop_back();
- // Control is alive iff any inputs are alive.
- SetPred(n, Graph::kControlSlot,
- predicate_factory_.MakeAndPredicate(input_preds));
+ // Control is alive iff all inputs are alive.
+ SetPredicate(n, Graph::kControlSlot,
+ predicate_factory_.MakeAndPredicate(input_preds),
+ should_revisit);
return Status::OK();
}
-Status DeadnessAnalysisImpl::HandleMerge(Node* n) {
+namespace {
+const Edge* FindUniqueBackedge(Node* merge) {
+ CHECK(merge->IsMerge());
+ const Edge* result = nullptr;
+ for (const Edge* e : merge->in_edges()) {
+ if (e->src()->IsNextIteration()) {
+ CHECK_EQ(result, nullptr)
+ << "Multiple backedges to " << merge->DebugString();
+ result = e;
+ }
+ }
+ return result;
+}
+
+// If `backedge_predicate` is equal to `symbolic_predicate` & Step where Step
+// does not contain `symbolic_predicate` as an inner (not top-level) operand
+// then returns `Step`. Otherwise returns nullptr.
+Predicate* DeduceStepPredicate(PredicateFactory* predicate_factory,
+ Predicate* symbolic_predicate,
+ Predicate* backedge_predicate) {
+ CHECK(dynamic_cast<SymbolPredicate*>(symbolic_predicate));
+ if (backedge_predicate->kind() != Predicate::Kind::kAnd) {
+ return nullptr;
+ }
+
+ std::vector<Predicate*> and_ops;
+ gtl::ArraySlice<Predicate*> recurrent_pred_ops =
+ backedge_predicate->GetOperands();
+
+ bool found_sym = false;
+ for (Predicate* and_op : recurrent_pred_ops) {
+ // We want the `symbol_predicate` to be the one of the operands of
+ // `backedge_predicate`,
+ if (and_op == symbolic_predicate) {
+ found_sym = true;
+ continue;
+ }
+
+ // but we don't want it to be present anywhere else in the formula. E.g. we
+ // don't want the recurrent predicate to be
+ // symbol_predicate&(X|symbol_predicate).
+ bool found_sym_as_inner_operand = false;
+ auto has_self_as_inner_operand = [&](Predicate* p) {
+ if (p == symbolic_predicate) {
+ found_sym_as_inner_operand = true;
+ return true; // Stop searching, we're done.
+ }
+
+ // Continue searching.
+ return false;
+ };
+
+ Predicate::Visit(and_op, has_self_as_inner_operand);
+ if (found_sym_as_inner_operand) {
+ return nullptr;
+ }
+ and_ops.push_back(and_op);
+ }
+
+ return found_sym ? predicate_factory->MakeAndPredicate(and_ops) : nullptr;
+}
+} // namespace
+
+Status DeadnessAnalysisImpl::HandleMerge(Node* n,
+ std::vector<bool>* should_revisit) {
// Merge ignores deadness of its control inputs. A merge that isn't the
- // target of a backedge has is alive iff any of its data inputs are. We treat
- // the liveness of a merge that is the target of a backedge symbolically.
+ // target of a backedge has is alive iff any of its data inputs are. The
+ // liveness of a merge that is the target of a backedge can sometimes be
+ // represented using a AndRecurrencePredicate. If neither apply, we represent
+ // the liveness of the merge symbolically.
+
+ bool has_unvisited_backedge = false;
+ for (const Edge* e : n->in_edges()) {
+ if (!e->IsControlEdge() && e->src()->IsNextIteration()) {
+ has_unvisited_backedge |= !predicate_map_.count(InputEdgeToTensorId(e));
+ }
+ }
+
+ auto it = predicate_map_.find(TensorId(n->name(), 0));
+ if (it == predicate_map_.end()) {
+ if (has_unvisited_backedge) {
+ // We're visiting this merge for the first time and it has an unvisited
+ // backedge.
+ Predicate* input_data_pred = predicate_factory_.MakeSymbolPredicate(
+ TensorId(n->name(), 0), /*must_be_true=*/false);
+ SetPredicate(n, {0, 1, Graph::kControlSlot}, input_data_pred,
+ should_revisit);
+ return Status::OK();
+ }
- bool has_backedge = std::any_of(
- n->in_edges().begin(), n->in_edges().end(), [](const Edge* e) {
- return !e->IsControlEdge() && e->src()->IsNextIteration();
- });
+ // We're visiting this merge for the first time and it is a acyclic merge.
+ Predicate* input_data_pred = predicate_factory_.MakeOrPredicate(
+ GetIncomingPreds(n, EdgeKind::kDataOnly));
+ SetPredicate(n, {0, 1, Graph::kControlSlot}, input_data_pred,
+ should_revisit);
+ return Status::OK();
+ }
- Predicate* input_data_pred =
- has_backedge ? predicate_factory_.MakeSymbolPredicate(
- TensorId(n->name(), 0), /*must_be_true=*/false)
- : predicate_factory_.MakeOrPredicate(
- GetIncomingPreds(n, EdgeKind::kDataOnly));
+ if (it->second->kind() == Predicate::Kind::kSymbol) {
+ // Last time we visited this merge we only got a symbolic predicate because
+ // of an unvisited backedge. Try to pattern match the predicate expression
+ // for that backedge (which should be visited now) into an and recurrence
+ // for the merge node.
+ if (const Edge* unique_backedge = FindUniqueBackedge(n)) {
+ if (Predicate* step = DeduceStepPredicate(
+ &predicate_factory_, it->second,
+ predicate_map_[InputEdgeToTensorId(unique_backedge)])) {
+ // If the predicate for the backedge is "Sym&X" where "Sym" is the
+ // predicate for the merge then the merge has predicate {S,&,X} where S
+ // is the predicate for the merge ignoring the backedge.
+ std::vector<Predicate*> non_recurrent_inputs;
+ for (const Edge* e : n->in_edges()) {
+ if (e != unique_backedge) {
+ non_recurrent_inputs.push_back(
+ predicate_map_[InputEdgeToTensorId(e)]);
+ }
+ }
- SetPred(n, {0, 1, Graph::kControlSlot}, input_data_pred);
+ Predicate* start =
+ predicate_factory_.MakeOrPredicate(non_recurrent_inputs);
+ Predicate* and_rec =
+ predicate_factory_.MakeAndRecurrencePredicate(start, step);
+ SetPredicate(n, {0, 1, Graph::kControlSlot}, and_rec, should_revisit);
+ return Status::OK();
+ }
+ }
+ }
return Status::OK();
}
-Status DeadnessAnalysisImpl::HandleRecv(Node* n) {
+Status DeadnessAnalysisImpl::HandleRecv(Node* n,
+ std::vector<bool>* should_revisit) {
// In addition to being alive or dead based on the inputs, a _Recv can also
// acquire a dead signal from a _Send.
std::vector<Predicate*> input_preds =
GetIncomingPreds(n, EdgeKind::kDataAndControl);
input_preds.push_back(predicate_factory_.MakeSymbolPredicate(
TensorId(n->name(), 0), /*must_be_true=*/false));
- SetPred(n, {0, Graph::kControlSlot},
- predicate_factory_.MakeAndPredicate(input_preds));
+ SetPredicate(n, {0, Graph::kControlSlot},
+ predicate_factory_.MakeAndPredicate(input_preds),
+ should_revisit);
return Status::OK();
}
-Status DeadnessAnalysisImpl::HandleGeneric(Node* n) {
+Status DeadnessAnalysisImpl::HandleGeneric(Node* n,
+ std::vector<bool>* should_revisit) {
// Generally nodes are alive iff all their inputs are alive.
Predicate* pred = predicate_factory_.MakeAndPredicate(
GetIncomingPreds(n, EdgeKind::kDataAndControl));
for (int output_idx = 0; output_idx < n->num_outputs(); output_idx++) {
- SetPred(n, output_idx, pred);
+ SetPredicate(n, output_idx, pred, should_revisit);
+ }
+ SetPredicate(n, Graph::kControlSlot, pred, should_revisit);
+ return Status::OK();
+}
+
+Status DeadnessAnalysisImpl::HandleNode(Node* n,
+ std::vector<bool>* should_revisit) {
+ if (n->IsSwitch()) {
+ TF_RETURN_IF_ERROR(HandleSwitch(n, should_revisit));
+ } else if (n->IsMerge()) {
+ TF_RETURN_IF_ERROR(HandleMerge(n, should_revisit));
+ } else if (n->IsControlTrigger()) {
+ SetPredicate(n, Graph::kControlSlot, predicate_factory_.MakeTrue(),
+ nullptr);
+ } else if (n->IsRecv() || n->IsHostRecv()) {
+ TF_RETURN_IF_ERROR(HandleRecv(n, should_revisit));
+ } else if (n->IsNextIteration()) {
+ TF_RETURN_IF_ERROR(HandleGeneric(n, should_revisit));
+ } else {
+ TF_RETURN_IF_ERROR(HandleGeneric(n, should_revisit));
}
- SetPred(n, Graph::kControlSlot, pred);
return Status::OK();
}
Status DeadnessAnalysisImpl::Populate() {
std::vector<Node*> rpo;
- GetReversePostOrder(graph_, &rpo, /*stable_comparator=*/{},
+ GetReversePostOrder(graph_, &rpo, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/[](const Edge& edge) {
return !edge.src()->IsNextIteration();
});
+ return PopulateWithReversePostOrder(rpo);
+}
+Status DeadnessAnalysisImpl::PopulateWithReversePostOrder(
+ gtl::ArraySlice<Node*> rpo) {
// This an abstract interpretation over the deadness propagation semantics of
// the graph executor.
+ //
+ // We iterate over the graph twice, each time in RPO. On the first iteration
+ // merge nodes with backedges are mapped to symbolic predicates. On the
+ // second iteration we use the predicates assigned to the backedges in the
+ // previous iteration to infer a more precise predicate for the backedge merge
+ // nodes and all the nodes that transitively use it.
+ //
+ // We don't track the output indices for should_revisit. Instead, putting a
+ // node in `should_revisit` denotes that the deadness flowing out from any
+ // output from said node may have changed. This is fine; only switches
+ // propagate different deadness along different output edges, and since the
+ // delta is solely due to the input *values* (and not input deadness), the
+ // delta should not change in the second iteration.
+ std::vector<bool> should_revisit;
+ should_revisit.resize(graph_.num_node_ids());
for (Node* n : rpo) {
- if (n->IsSwitch()) {
- TF_RETURN_IF_ERROR(HandleSwitch(n));
- } else if (n->IsMerge()) {
- TF_RETURN_IF_ERROR(HandleMerge(n));
- } else if (n->IsControlTrigger()) {
- SetPred(n, Graph::kControlSlot, predicate_factory_.MakeTrue());
- } else if (n->IsRecv() || n->IsHostRecv()) {
- TF_RETURN_IF_ERROR(HandleRecv(n));
- } else {
- TF_RETURN_IF_ERROR(HandleGeneric(n));
+ VLOG(4) << "Visiting " << n->name();
+ TF_RETURN_IF_ERROR(HandleNode(n, /*should_revisit=*/nullptr));
+ if (n->IsNextIteration()) {
+ // If this is a backedge for a merge node then remember to reprocess the
+ // merge the next time we run.
+ for (const Edge* e : n->out_edges()) {
+ if (e->dst()->IsMerge()) {
+ should_revisit[e->dst()->id()] = true;
+ }
+ }
+ }
+ }
+
+ for (Node* n : rpo) {
+ // The nodes added to should_revisit in the previous loop need to be
+ // revisited now. Reprocesing these initial nodes may add *their* consumers
+ // to should_revisit, and these newly added nodes will also be processed by
+ // this very same loop. Since we're traversing the graph in reverse post
+ // order (producers before consumers) and HandleNode(n) can only ever add
+ // n's consumers to should_revisit, we won't "miss" an addition to
+ // should_revisit.
+ if (should_revisit[n->id()]) {
+ VLOG(4) << "Revisiting " << n->name();
+ TF_RETURN_IF_ERROR(HandleNode(n, &should_revisit));
}
}
@@ -587,6 +921,15 @@ Status ComputePredicates(const Graph& graph,
*out_predicate_map = impl.PredicateMapAsString();
return Status::OK();
}
+
+Status ComputePredicates(const Graph& graph,
+ gtl::ArraySlice<Node*> reverse_post_order,
+ PredicateMapTy* out_predicate_map) {
+ DeadnessAnalysisImpl impl(&graph);
+ TF_RETURN_IF_ERROR(impl.PopulateWithReversePostOrder(reverse_post_order));
+ *out_predicate_map = impl.PredicateMapAsString();
+ return Status::OK();
+}
} // namespace deadness_analysis_internal
} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/deadness_analysis_internal.h b/tensorflow/compiler/jit/deadness_analysis_internal.h
index cdef405110..401d6e406a 100644
--- a/tensorflow/compiler/jit/deadness_analysis_internal.h
+++ b/tensorflow/compiler/jit/deadness_analysis_internal.h
@@ -26,6 +26,14 @@ namespace deadness_analysis_internal {
// testing purposes only.
using PredicateMapTy = gtl::FlatMap<TensorId, string, TensorId::Hasher>;
Status ComputePredicates(const Graph& graph, PredicateMapTy* out_predicate_map);
+
+// Returns a map describing the predicate each Tensor was mapped to. For
+// testing purposes only. Makes deadness analysis visit the graph in the order
+// specified in `reverse_post_order` which must be a valid RPO for the graph
+// minus NextIteration->Merge edges.
+Status ComputePredicates(const Graph& graph,
+ gtl::ArraySlice<Node*> reverse_post_order,
+ PredicateMapTy* out_predicate_map);
} // namespace deadness_analysis_internal
} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/deadness_analysis_test.cc b/tensorflow/compiler/jit/deadness_analysis_test.cc
index 6881095b51..cc9f102398 100644
--- a/tensorflow/compiler/jit/deadness_analysis_test.cc
+++ b/tensorflow/compiler/jit/deadness_analysis_test.cc
@@ -38,6 +38,9 @@ limitations under the License.
namespace tensorflow {
namespace {
+using deadness_analysis_internal::ComputePredicates;
+using deadness_analysis_internal::PredicateMapTy;
+
Status AnalyzeDeadness(Graph* graph,
std::unique_ptr<DeadnessAnalysis>* result) {
FixupSourceAndSinkEdges(graph);
@@ -51,13 +54,73 @@ ops::Switch CreateSwitch(const Scope& root, const string& prefix) {
return ops::Switch(root.WithOpName(prefix + "/switch"), value, predicate);
}
-Output CreateInductionVariable(const Scope& root, const string& prefix,
- const string& frame_name, int32 init) {
- Output initial_value = ops::Const(root.WithOpName(prefix + "/init"), init);
+TensorId ControlOutputFor(const Output& o) {
+ return {o.node()->name(), Graph::kControlSlot};
+}
+
+void VLogGraphIfAsked(const Graph& graph) {
+ if (VLOG_IS_ON(3)) {
+ GraphDef graph_def;
+ graph.ToGraphDef(&graph_def);
+ string serialized;
+ ::tensorflow::protobuf::TextFormat::PrintToString(graph_def, &serialized);
+ LOG(INFO) << serialized;
+ }
+}
+
+struct InductionVarInfo {
+ Output induction_var;
+ Output loop_cond;
+};
+
+// Creates an induction variable with the following structure (simplified for
+// brevity):
+//
+// +---------------+
+// | initial_value |
+// +---------------+
+// |
+// |
+// v
+// +---------------+
+// | Enter |
+// +---------------+
+// |
+// |
+// v
+// +---------------+
+// +> | Merge | -+
+// | +---------------+ |
+// | | |
+// | | |
+// | v |
+// | +---------------+ |
+// | | LessThan10 | |
+// | +---------------+ |
+// | | |
+// | | |
+// | v |
+// | +---------------+ |
+// +----+- | Switch | <+
+// | | +---------------+
+// | | |
+// | | |
+// | | v
+// | | +---------------+
+// | +- | AddOne |
+// | +---------------+
+// | +---------------+
+// +-----> | Exit |
+// +---------------+
+InductionVarInfo CreateInductionVariable(const Scope& root,
+ const string& prefix,
+ const string& frame_name,
+ const Output& initial_value) {
Output enter_initial_value = ops::internal::Enter(
root.WithOpName(prefix + "/enter"), initial_value, frame_name);
- ops::Merge iv(root.WithOpName(prefix + "/iv"), {enter_initial_value});
+ ops::Merge iv(root.WithOpName(prefix + "/iv"),
+ {enter_initial_value, enter_initial_value});
Output increment_by = ops::Const(root.WithOpName(prefix + "/incr"), 1);
Output final_value = ops::Const(root.WithOpName(prefix + "/final"), 10);
Output loop_cond_expr =
@@ -66,16 +129,84 @@ Output CreateInductionVariable(const Scope& root, const string& prefix,
ops::LoopCond(root.WithOpName(prefix + "/cond"), loop_cond_expr);
ops::Switch latch(root.WithOpName(prefix + "/latch"), iv.output, loop_cond);
ops::internal::Exit exit(root.WithOpName(prefix + "/exit"), iv.output);
- Output iv_next =
- ops::Add(root.WithOpName(prefix + "/ivnext"), iv.output, increment_by);
+ Output iv_next = ops::Add(root.WithOpName(prefix + "/ivnext"),
+ latch.output_true, increment_by);
Output next_iteration =
- ops::NextIteration(root.WithOpName(prefix + "next_iteration"), iv_next);
+ ops::NextIteration(root.WithOpName(prefix + "/next_iteration"), iv_next);
- root.graph()->AddEdge(next_iteration.node(), 0, iv.output.node(), 1);
+ CHECK(root.graph()
+ ->UpdateEdge(next_iteration.node(), 0, iv.output.node(), 1)
+ .ok());
root.graph()->AddControlEdge(iv.output.node(), increment_by.node());
root.graph()->AddControlEdge(iv.output.node(), final_value.node());
- return iv.output;
+ return {iv.output, loop_cond};
+}
+
+InductionVarInfo CreateInductionVariable(const Scope& root,
+ const string& prefix,
+ const string& frame_name, int32 init) {
+ return CreateInductionVariable(
+ root, prefix, frame_name,
+ ops::Const(root.WithOpName(prefix + "/init"), init));
+}
+
+// Creates an induction variable with the following structure:
+//
+// +---------------+
+// | initial_value |
+// +---------------+
+// |
+// |
+// v
+// +---------------+
+// | Enter |
+// +---------------+
+// |
+// |
+// v
+// +---------------+
+// | Merge | <+
+// +---------------+ |
+// | |
+// | |
+// v |
+// +-----------+ +---------------+ |
+// | loop_cond | --> | Switch | -+
+// +-----------+ +---------------+
+// |
+// |
+// v
+// +---------------+
+// | Exit |
+// +---------------+
+struct DependentInductionVar {
+ Output induction_var;
+ ops::Switch latch;
+};
+
+DependentInductionVar CreateDependentLoopInvariantValue(
+ const Scope& root, const string& prefix, const string& frame_name,
+ const Output& loop_cond, const Output& value) {
+ Output enter_value = ops::internal::Enter(root.WithOpName(prefix + "/enter"),
+ value, frame_name);
+ ops::Merge iv(root.WithOpName(prefix + "/iv"), {enter_value, enter_value});
+ ops::Switch latch(root.WithOpName(prefix + "/latch"), iv.output, loop_cond);
+ ops::internal::Exit exit(root.WithOpName(prefix + "/exit"), iv.output);
+ Output next_iteration = ops::NextIteration(
+ root.WithOpName(prefix + "/next_iteration"), latch.output_true);
+ CHECK(root.graph()
+ ->UpdateEdge(next_iteration.node(), 0, iv.output.node(), 1)
+ .ok());
+ return {iv.output, latch};
+}
+
+DependentInductionVar CreateDependentLoopInvariantValue(
+ const Scope& root, const string& prefix, const string& frame_name,
+ const Output& loop_cond, int32 value) {
+ return CreateDependentLoopInvariantValue(
+ root, prefix, frame_name, loop_cond,
+ ops::Const(root.WithOpName(prefix + "/init"), value));
}
TEST(DeadnessAnalysisTest, BasicPositive) {
@@ -337,21 +468,224 @@ TEST(DeadnessAnalysisTest, HostRecv) {
TEST(DeadnessAnalysisTest, Loop) {
Scope root = Scope::NewRootScope().ExitOnError();
- Output iv0 = CreateInductionVariable(root, "iv0", "fr0", 0);
- Output iv1 = CreateInductionVariable(root, "iv1", "fr0", 0);
- Output iv2 = CreateInductionVariable(root, "iv2", "fr0", 1);
+ Output iv0 = CreateInductionVariable(root, "iv0", "fr0", 0).induction_var;
+ Output iv1 = CreateInductionVariable(root, "iv1", "fr0", 0).induction_var;
+ Output iv2 = CreateInductionVariable(root, "iv2", "fr0", 1).induction_var;
Output add0 = ops::Add(root.WithOpName("add0"), iv0, iv1);
Output add1 = ops::Add(root.WithOpName("add1"), iv1, iv2);
- std::unique_ptr<DeadnessAnalysis> result;
- TF_ASSERT_OK(AnalyzeDeadness(root.graph(), &result));
-
// NB! iv0 and iv1 are equivalent and a smarter deadness analysis would have
// noticed that. Today we are pessimistic here because we assign an
// uninterpreted symbol to merges with backedges.
- EXPECT_TRUE(result->HasInputsWithMismatchingDeadness(*add0.node()));
- EXPECT_TRUE(result->HasInputsWithMismatchingDeadness(*add1.node()));
+ VLogGraphIfAsked(*root.graph());
+
+ {
+ std::unique_ptr<DeadnessAnalysis> result;
+ TF_ASSERT_OK(AnalyzeDeadness(root.graph(), &result));
+
+ EXPECT_TRUE(result->HasInputsWithMismatchingDeadness(*add0.node()));
+ EXPECT_TRUE(result->HasInputsWithMismatchingDeadness(*add1.node()));
+ }
+ {
+ PredicateMapTy predicate_map;
+ TF_ASSERT_OK(ComputePredicates(*root.graph(), &predicate_map));
+
+ // In theory we should be able to tell that iv0/cond:0 and iv1/cond:0
+ // produce the same deadness. But we're not that smart today.
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv0)], "{#true,&,*iv0/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv1)], "{#true,&,*iv1/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv2)], "{#true,&,*iv2/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(add0)],
+ "({#true,&,*iv1/cond:0} & {#true,&,*iv0/cond:0})");
+ EXPECT_EQ(predicate_map[ControlOutputFor(add1)],
+ "({#true,&,*iv1/cond:0} & {#true,&,*iv2/cond:0})");
+ }
+}
+
+TEST(DeadnessAnalysisTest, ControlEquivalentLoopBodies) {
+ Scope root = Scope::NewRootScope().ExitOnError();
+ InductionVarInfo iv = CreateInductionVariable(root, "iv0", "frame", 0);
+ Output dependent_iv0 =
+ CreateDependentLoopInvariantValue(root, "div0", "frame", iv.loop_cond, 0)
+ .induction_var;
+ Output dependent_iv1 =
+ CreateDependentLoopInvariantValue(root, "div1", "frame", iv.loop_cond, 0)
+ .induction_var;
+ Output add0 = ops::Add(root.WithOpName("add0"), dependent_iv0, dependent_iv1);
+
+ VLogGraphIfAsked(*root.graph());
+
+ {
+ std::unique_ptr<DeadnessAnalysis> result;
+ TF_ASSERT_OK(AnalyzeDeadness(root.graph(), &result));
+
+ EXPECT_FALSE(result->HasInputsWithMismatchingDeadness(*add0.node()));
+ }
+ {
+ PredicateMapTy predicate_map;
+ TF_ASSERT_OK(ComputePredicates(*root.graph(), &predicate_map));
+
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv.induction_var)],
+ "{#true,&,*iv0/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(dependent_iv0)],
+ "{#true,&,(*iv0/cond:0 & iv0/iv:0)}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(dependent_iv1)],
+ "{#true,&,(*iv0/cond:0 & iv0/iv:0)}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(add0)],
+ "{#true,&,(*iv0/cond:0 & iv0/iv:0)}");
+ }
+}
+
+TEST(DeadnessAnalysisTest, LoopInvariantPredicateOnBackedge) {
+ // Create a merge that "looks like" a loop but isn't really. It has a value
+ // that does not depend on the merge on its backedge.
+ Scope root = Scope::NewRootScope().ExitOnError();
+ InductionVarInfo iv = CreateInductionVariable(root, "iv0", "frame", 0);
+ DependentInductionVar dependent_iv =
+ CreateDependentLoopInvariantValue(root, "div0", "frame", iv.loop_cond, 0);
+ FixupSourceAndSinkEdges(root.graph());
+
+ // To make deadness analysis think that dependent_iv is a loop we need an RPO
+ // that visits the merge before the backedge. This is a legal RPO for
+ // deadness analysis since it ignores NextIteration->Merge edges during RPO.
+ // Right now dependent_iv has an edge from Merge to NextIteration so do the
+ // RPO with this edge in place. Then remove this edge to get our test case.
+ std::vector<Node*> rpo;
+ GetReversePostOrder(*root.graph(), &rpo, /*stable_comparator=*/{},
+ /*edge_filter=*/[](const Edge& edge) {
+ return !edge.src()->IsNextIteration();
+ });
+ TF_ASSERT_OK(root.graph()->UpdateEdge(
+ iv.induction_var.node(), 0, dependent_iv.latch.output_true.node(), 0));
+
+ VLogGraphIfAsked(*root.graph());
+
+ {
+ PredicateMapTy predicate_map;
+ TF_ASSERT_OK(ComputePredicates(*root.graph(), rpo, &predicate_map));
+
+ EXPECT_EQ(predicate_map[ControlOutputFor(dependent_iv.induction_var)],
+ "div0/iv:0");
+ }
+}
+
+TEST(DeadnessAnalysisTest, ControlEquivalentNestedLoopBodies) {
+ Scope root = Scope::NewRootScope().ExitOnError();
+ InductionVarInfo iv_outer =
+ CreateInductionVariable(root, "iv_outer", "frame", 0);
+ ops::Switch inner_value(root.WithOpName("outer_is_live"),
+ ops::Const(root.WithOpName("constant"), 5),
+ iv_outer.loop_cond);
+ InductionVarInfo iv_inner = CreateInductionVariable(
+ root, "iv_inner", "frame",
+ ops::internal::Enter(root.WithOpName("iv_inner/enter"),
+ inner_value.output_true, "frame_inner"));
+
+ Output dependent_outer_iv0 =
+ CreateDependentLoopInvariantValue(root, "dependent_outer_iv0", "frame",
+ iv_outer.loop_cond, 0)
+ .induction_var;
+ Output dependent_outer_iv1 =
+ CreateDependentLoopInvariantValue(root, "dependent_outer_iv1", "frame",
+ iv_outer.loop_cond, 0)
+ .induction_var;
+
+ Output dependent_inner_iv0 =
+ CreateDependentLoopInvariantValue(root, "dependent_inner_iv0", "frame",
+ iv_inner.loop_cond, dependent_outer_iv0)
+ .induction_var;
+ Output dependent_inner_iv1 =
+ CreateDependentLoopInvariantValue(root, "dependent_inner_iv1", "frame",
+ iv_inner.loop_cond, dependent_outer_iv1)
+ .induction_var;
+
+ Output add0 = ops::Add(root.WithOpName("add0"), dependent_inner_iv0,
+ dependent_inner_iv1);
+
+ VLogGraphIfAsked(*root.graph());
+
+ {
+ std::unique_ptr<DeadnessAnalysis> result;
+ TF_ASSERT_OK(AnalyzeDeadness(root.graph(), &result));
+
+ EXPECT_FALSE(result->HasInputsWithMismatchingDeadness(*add0.node()));
+ }
+ {
+ PredicateMapTy predicate_map;
+ TF_ASSERT_OK(ComputePredicates(*root.graph(), &predicate_map));
+
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv_outer.induction_var)],
+ "{#true,&,*iv_outer/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv_inner.induction_var)],
+ "{(*iv_outer/cond:0 & {#true,&,*iv_outer/cond:0}),&,"
+ "*iv_inner/cond:0}");
+
+ EXPECT_EQ(predicate_map[ControlOutputFor(dependent_inner_iv0)],
+ "{{#true,&,(iv_outer/iv:0 & *iv_outer/cond:0)},&,"
+ "(*iv_inner/cond:0 & iv_inner/iv:0)}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(dependent_inner_iv1)],
+ "{{#true,&,(iv_outer/iv:0 & *iv_outer/cond:0)},&,"
+ "(*iv_inner/cond:0 & iv_inner/iv:0)}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(add0)],
+ "{{#true,&,(iv_outer/iv:0 & *iv_outer/cond:0)},&,"
+ "(*iv_inner/cond:0 & iv_inner/iv:0)}");
+ }
+}
+
+TEST(DeadnessAnalysisTest, ControlNonEquivalentNestedLoopBodies) {
+ Scope root = Scope::NewRootScope().ExitOnError();
+ InductionVarInfo iv_outer_0 =
+ CreateInductionVariable(root, "iv_outer_0", "frame", 0);
+ ops::Switch inner_value_0(root.WithOpName("outer_0_is_live"),
+ ops::Const(root.WithOpName("constant"), 5),
+ iv_outer_0.loop_cond);
+ InductionVarInfo iv_inner_0 = CreateInductionVariable(
+ root, "iv_inner_0", "frame",
+ ops::internal::Enter(root.WithOpName("iv_inner_0/enter"),
+ inner_value_0.output_true, "frame_inner"));
+
+ InductionVarInfo iv_outer_1 =
+ CreateInductionVariable(root, "iv_outer_1", "frame", 1);
+ ops::Switch inner_init_value_1(root.WithOpName("outer_1_is_live"),
+ ops::Const(root.WithOpName("constant"), 5),
+ iv_outer_1.loop_cond);
+ InductionVarInfo iv_inner_1 = CreateInductionVariable(
+ root, "iv_inner_1", "frame",
+ ops::internal::Enter(root.WithOpName("iv_inner_1/enter"),
+ inner_init_value_1.output_true, "frame_inner"));
+ Output add0 = ops::Add(root.WithOpName("add0"), iv_inner_0.induction_var,
+ iv_inner_1.induction_var);
+
+ VLogGraphIfAsked(*root.graph());
+
+ {
+ std::unique_ptr<DeadnessAnalysis> result;
+ TF_ASSERT_OK(AnalyzeDeadness(root.graph(), &result));
+
+ EXPECT_TRUE(result->HasInputsWithMismatchingDeadness(*add0.node()));
+ }
+
+ {
+ PredicateMapTy predicate_map;
+ TF_ASSERT_OK(ComputePredicates(*root.graph(), &predicate_map));
+
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv_outer_0.induction_var)],
+ "{#true,&,*iv_outer_0/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv_inner_0.induction_var)],
+ "{(*iv_outer_0/cond:0 & {#true,&,*iv_outer_0/cond:0}),&,"
+ "*iv_inner_0/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv_outer_1.induction_var)],
+ "{#true,&,*iv_outer_1/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(iv_inner_1.induction_var)],
+ "{(*iv_outer_1/cond:0 & {#true,&,*iv_outer_1/cond:0}),&,"
+ "*iv_inner_1/cond:0}");
+ EXPECT_EQ(predicate_map[ControlOutputFor(add0)],
+ "({(*iv_outer_1/cond:0 & {#true,&,*iv_outer_1/cond:0}),&,"
+ "*iv_inner_1/cond:0} & "
+ "{(*iv_outer_0/cond:0 & {#true,&,*iv_outer_0/cond:0}),&,"
+ "*iv_inner_0/cond:0})");
+ }
}
TEST(DeadnessAnalysisTest, ControlInputs) {
@@ -454,9 +788,8 @@ TEST(DeadnessAnalysisTest, RecvVsSwitchText) {
std::unique_ptr<DeadnessAnalysis> result;
TF_ASSERT_OK(AnalyzeDeadness(root.graph(), &result));
- deadness_analysis_internal::PredicateMapTy predicate_map;
- TF_ASSERT_OK(deadness_analysis_internal::ComputePredicates(*root.graph(),
- &predicate_map));
+ PredicateMapTy predicate_map;
+ TF_ASSERT_OK(ComputePredicates(*root.graph(), &predicate_map));
TensorId logical_and_output_0 = {logical_and.node()->name(),
Graph::kControlSlot};
diff --git a/tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc b/tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc
index fdd71c6a58..f150bf1819 100644
--- a/tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc
+++ b/tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc
@@ -1161,8 +1161,7 @@ Status Encapsulator::Subgraph::ReplaceFunctionDef(
strings::StrCat("replace_encapsulate_fdef_", name), fdef);
}
- TF_RETURN_IF_ERROR(library->RemoveFunction(name));
- TF_RETURN_IF_ERROR(library->AddFunctionDef(fdef));
+ TF_RETURN_IF_ERROR(library->ReplaceFunction(name, fdef));
return Status::OK();
}
diff --git a/tensorflow/compiler/jit/jit_compilation_pass_registration.cc b/tensorflow/compiler/jit/jit_compilation_pass_registration.cc
index 4d49a14b24..c37b6112cc 100644
--- a/tensorflow/compiler/jit/jit_compilation_pass_registration.cc
+++ b/tensorflow/compiler/jit/jit_compilation_pass_registration.cc
@@ -16,6 +16,7 @@ limitations under the License.
#include "tensorflow/compiler/jit/build_xla_launch_ops_pass.h"
#include "tensorflow/compiler/jit/encapsulate_subgraphs_pass.h"
#include "tensorflow/compiler/jit/mark_for_compilation_pass.h"
+#include "tensorflow/compiler/jit/partially_decluster_pass.h"
#include "tensorflow/core/common_runtime/optimization_registry.h"
namespace tensorflow {
@@ -23,15 +24,18 @@ namespace tensorflow {
REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 10,
MarkForCompilationPass);
+REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 20,
+ PartiallyDeclusterPass);
+
// The EncapsulateSubgraphs pass must run after the MarkForCompilationPass. We
// also need to run it after the graph been rewritten to have _Send nodes added
// for fetches. Before the _Send nodes are added, fetch nodes are identified by
// name, and encapsulation might remove that node from the graph.
-REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 20,
+REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 30,
EncapsulateSubgraphsPass);
// Must run after EncapsulateSubgraphsPass.
-REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 30,
+REGISTER_OPTIMIZATION(OptimizationPassRegistry::POST_REWRITE_FOR_EXEC, 40,
BuildXlaLaunchOpsPass);
} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/kernels/BUILD b/tensorflow/compiler/jit/kernels/BUILD
index 00a6f4075f..8f78c110cb 100644
--- a/tensorflow/compiler/jit/kernels/BUILD
+++ b/tensorflow/compiler/jit/kernels/BUILD
@@ -16,6 +16,7 @@ cc_library(
"//tensorflow/compiler/jit:xla_device",
"//tensorflow/compiler/jit:xla_launch_util",
"//tensorflow/compiler/tf2xla:common",
+ "//tensorflow/compiler/tf2xla:tf2xla_util",
"//tensorflow/compiler/tf2xla:xla_compiler",
"//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla/client:client_library",
diff --git a/tensorflow/compiler/jit/kernels/xla_launch_op.cc b/tensorflow/compiler/jit/kernels/xla_launch_op.cc
index b313d48011..7f4370b5b0 100644
--- a/tensorflow/compiler/jit/kernels/xla_launch_op.cc
+++ b/tensorflow/compiler/jit/kernels/xla_launch_op.cc
@@ -19,6 +19,7 @@ limitations under the License.
#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_launch_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
+#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/client_library.h"
@@ -199,7 +200,7 @@ void XlaLocalLaunchBase::Compute(OpKernelContext* ctx) {
run_options.set_stream(stream);
run_options.set_allocator(xla_allocator);
run_options.set_intra_op_thread_pool(&ctx->eigen_cpu_device());
- run_options.set_rng_seed(ctx->step_id());
+ run_options.set_rng_seed(GetXLARandomSeed());
Env* env = Env::Default();
auto start_time = env->NowMicros();
@@ -209,7 +210,8 @@ void XlaLocalLaunchBase::Compute(OpKernelContext* ctx) {
auto elapsed = env->NowMicros() - start_time;
VLOG(2) << "Elapsed time: " << elapsed << "us";
- launch_context.PopulateOutputs(ctx, kernel, run_result.ConsumeValueOrDie());
+ OP_REQUIRES_OK(ctx, launch_context.PopulateOutputs(
+ ctx, kernel, run_result.ConsumeValueOrDie()));
VLOG(1) << "Done";
}
diff --git a/tensorflow/compiler/jit/mark_for_compilation_pass.cc b/tensorflow/compiler/jit/mark_for_compilation_pass.cc
index 45d422943c..f4e179dab2 100644
--- a/tensorflow/compiler/jit/mark_for_compilation_pass.cc
+++ b/tensorflow/compiler/jit/mark_for_compilation_pass.cc
@@ -39,7 +39,9 @@ limitations under the License.
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/control_flow.h"
#include "tensorflow/core/kernels/bounds_check.h"
+#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/strings/strcat.h"
+#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/public/version.h"
namespace tensorflow {
@@ -65,6 +67,7 @@ bool HasXLAKernel(const Node& node, const DeviceType& jit_device_type) {
// XLA cluster so it can't implement the forward-tensor-ref semantic. Leave
// such nodes out of XLA clusters.
if (HasForwardedRefInput(node)) {
+ VLOG(2) << "Rejecting " << node.name() << ": Identity with unsafe cast.";
return false;
}
@@ -84,14 +87,13 @@ bool IsCompilableCall(const NodeDef& call_def,
bool IsCompilableWhile(const Node& while_node,
const DeviceType& jit_device_type, int depth,
FunctionLibraryRuntime* lib_runtime) {
- VLOG(2) << "Loop marking: " << while_node.type_string();
-
const NameAttrList* name_attr;
NodeDef call;
Status status;
status = GetNodeAttr(while_node.attrs(), "cond", &name_attr);
if (!status.ok()) {
- VLOG(2) << "Missing 'cond' attribute on While node.";
+ VLOG(2) << "Rejecting While " << while_node.name()
+ << ": missing 'cond' attribute on While node.";
return false;
}
const string cond_func = name_attr->name();
@@ -99,12 +101,14 @@ bool IsCompilableWhile(const Node& while_node,
call.set_op(cond_func);
*call.mutable_attr() = name_attr->attr();
if (!IsCompilableCall(call, jit_device_type, depth + 1, lib_runtime)) {
- VLOG(2) << "Can't compile loop condition: " << cond_func;
+ VLOG(2) << "Rejecting While " << while_node.name()
+ << ": can't compile loop condition: " << cond_func;
return false;
}
status = GetNodeAttr(while_node.attrs(), "body", &name_attr);
if (!status.ok()) {
- VLOG(2) << "Missing 'body' attribute on While node.";
+ VLOG(2) << "Rejecting While " << while_node.name()
+ << ": missing 'body' attribute on While node.";
return false;
}
const string body_func = name_attr->name();
@@ -112,10 +116,10 @@ bool IsCompilableWhile(const Node& while_node,
call.set_op(body_func);
*call.mutable_attr() = name_attr->attr();
if (!IsCompilableCall(call, jit_device_type, depth + 1, lib_runtime)) {
- VLOG(2) << "Can't compile loop body: " << body_func;
+ VLOG(2) << "Rejecting While " << while_node.name()
+ << ": can't compile loop body: " << body_func;
return false;
}
- VLOG(2) << "Loop is compilable.";
return true;
}
@@ -125,10 +129,9 @@ bool IsCompilableWhile(const Node& while_node,
bool IsCompilableCall(const NodeDef& call_def,
const DeviceType& jit_device_type, int depth,
FunctionLibraryRuntime* lib_runtime) {
- VLOG(2) << "Function marking: " << call_def.op();
-
if (depth > kMaxRecursionDepth) {
- VLOG(2) << "Function depth limit exceeded";
+ VLOG(2) << "Rejecting " << call_def.op()
+ << ": function depth limit exceeded.";
return false;
}
@@ -136,9 +139,14 @@ bool IsCompilableCall(const NodeDef& call_def,
Status status =
lib_runtime->Instantiate(call_def.op(), AttrSlice(call_def), &handle);
if (!status.ok()) {
- VLOG(2) << "Could not instantiate " << call_def.op() << ": " << status;
+ VLOG(2) << "Rejecting " << call_def.op()
+ << ": could not instantiate: " << status;
return false;
}
+
+ auto release_handle_on_return = gtl::MakeCleanup(
+ [&] { TF_CHECK_OK(lib_runtime->ReleaseHandle(handle)); });
+
const FunctionBody* fbody = lib_runtime->GetFunctionBody(handle);
CHECK(fbody);
const FunctionDef& fdef = fbody->fdef;
@@ -150,7 +158,8 @@ bool IsCompilableCall(const NodeDef& call_def,
// tf2xla to translate the TF graph into XLA. So we avoid this for now.
//
// TODO(b/36139787): Create a mechanism to set inlining hints.
- VLOG(2) << "Can't compile noinline function: " << fdef.DebugString();
+ VLOG(2) << "Rejecting " << call_def.op()
+ << ": can't compile noinline function.";
return false;
}
@@ -164,23 +173,14 @@ bool IsCompilableCall(const NodeDef& call_def,
if (!HasXLAKernel(*node, jit_device_type) &&
!IsCompilableCall(node->def(), jit_device_type, depth + 1,
lib_runtime)) {
- VLOG(2) << "Function marking failed: unsupported op " << node->name()
- << ": " << node->def().ShortDebugString();
+ VLOG(2) << "Rejecting " << call_def.op() << ": unsupported op "
+ << node->name() << ": " << node->def().ShortDebugString();
return false;
}
}
- VLOG(2) << "Function is compilable: " << call_def.op();
return true;
}
-// Tests whether `node` has a DT_RESOURCE typed input or output.
-bool HasResourceInputOrOutput(const Node& node) {
- return std::find(node.input_types().begin(), node.input_types().end(),
- DT_RESOURCE) != node.input_types().end() ||
- std::find(node.output_types().begin(), node.output_types().end(),
- DT_RESOURCE) != node.output_types().end();
-}
-
// Returns true if the op can be decomposed into XLA ops for which
// there are fusable elemental implementations.
//
@@ -357,24 +357,27 @@ Status FindCompilationCandidates(
}
std::sort(sorted_nodes.begin(), sorted_nodes.end(), NodeComparatorID());
+ if (fuel >= std::numeric_limits<int64>::max() / 2) {
+ // The assumption is that if fuel started out as INT64_MAX, it will forever
+ // stay greater than INT64_MAX / 2.
+ VLOG(2) << "Starting fuel: infinity";
+ } else {
+ VLOG(2) << "Starting fuel: " << fuel;
+ }
+
for (Node* node : sorted_nodes) {
- VLOG(2) << "Fuel: " << fuel;
if (fuel <= 0) {
- VLOG(2)
+ VLOG(1)
<< "Hit fuel limit; not marking any remaining ops as clusterable.";
break;
}
- VLOG(2) << "FindCompilationCandidates(): Processing "
- << node->DebugString();
-
DeviceType device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(node->assigned_device_name(), &device_type));
if (is_compilable_fn && !is_compilable_fn(node, device_type)) {
- VLOG(2) << "Compilation rejected node: not compilable " << node->name()
- << ": " << node->type_string();
+ // is_compilable_fn has already logged the reason if it returned false.
continue;
}
@@ -384,14 +387,14 @@ Status FindCompilationCandidates(
DeviceType jit_device_type(registration->compilation_device_name);
if (!HasXLAKernel(*node, jit_device_type) &&
!IsCompilableCall(node->def(), jit_device_type, 0, lib_runtime)) {
- VLOG(2) << "Compilation rejected node: unsupported op " << node->name()
- << ": " << node->type_string();
+ VLOG(2) << "Rejecting " << node->name() << ": unsupported op "
+ << node->type_string();
continue;
}
if (!registration->compile_resource_ops &&
HasResourceInputOrOutput(*node)) {
- VLOG(2) << "Compilation rejected node: resource input/output "
- << node->name() << ": " << node->type_string();
+ VLOG(2) << "Rejecting: " << node->name() << ": resource input/output "
+ << node->type_string();
continue;
}
if (node->type_string() == "While" &&
@@ -401,15 +404,11 @@ Status FindCompilationCandidates(
// _Arg nodes in a top-level function represent feeds.
// Do not compile them.
if (node->type_string() == "_Arg") {
- VLOG(2) << "Skipping jit compilation for '_Arg'-typed node "
- << node->DebugString();
continue;
}
// _Retval nodes in a top-level function represent fetches.
// Do not compile them.
if (node->type_string() == "_Retval") {
- VLOG(2) << "Compilation rejected node: return value " << node->name()
- << ": " << node->type_string();
continue;
}
candidates->insert(node);
@@ -475,6 +474,7 @@ Status MarkForCompilationPass::Run(
const XlaOpRegistry::DeviceRegistration* registration;
if (!XlaOpRegistry::GetCompilationDevice(device_type.type(),
&registration)) {
+ VLOG(2) << "Rejecting " << node->name() << ": could not find JIT device.";
return false;
}
@@ -484,21 +484,36 @@ Status MarkForCompilationPass::Run(
// If there is a _XlaCompile annotation, use its value.
bool compile = false;
Status status = GetNodeAttr(node->attrs(), kXlaCompileAttr, &compile);
- if (status.ok()) return compile;
+ if (status.ok()) {
+ if (!compile) {
+ VLOG(2) << "Rejecting " << node->name() << ": kXlaCompileAttr("
+ << kXlaCompileAttr << ") is false.";
+ }
+ return compile;
+ }
status = fld->GetAttr(*node, kXlaCompileAttr, &compile);
- if (status.ok()) return compile;
+ if (status.ok()) {
+ if (!compile) {
+ VLOG(2) << "Rejecting " << node->name() << ": kXlaCompileAttr("
+ << kXlaCompileAttr << ") on callee is false.";
+ }
+ return compile;
+ }
// If inputs to `node` can have conflicting deadness (i.e. some are alive
// and some are dead) then don't compile it. XLA cannot represent the
// deadness semantics of these nodes correctly and auto-clustering these
// nodes can cause deadness to propagate to nodes that should be live.
if (node->IsMerge() || deadness->HasInputsWithMismatchingDeadness(*node)) {
+ VLOG(2) << "Rejecting " << node->name() << ": mismatching deadness.";
return false;
}
// Check for fusable ops only if requested.
if (global_jit_level > 0 && fusion_only && !IsXlaFusable(node->def())) {
+ VLOG(2) << "Rejecting " << node->name()
+ << ": not fusable op but fusion_only enabled.";
return false;
}
@@ -506,12 +521,75 @@ Status MarkForCompilationPass::Run(
// Ignore enable_jit_by_default if global jit compilation for CPU
// is explicitly requested via tf_xla_cpu_global_jit flag
bool ignore_registration = cpu_global_jit && device_type == DEVICE_CPU;
- return (ignore_registration || registration->enable_jit_by_default) &&
- global_jit_level > 0;
+ bool should_compile =
+ (ignore_registration || registration->enable_jit_by_default) &&
+ global_jit_level > 0;
+ if (!should_compile) {
+ if (global_jit_level <= 0) {
+ VLOG(2) << "Rejecting " << node->name() << ": global jit disabled.";
+ } else {
+ VLOG(2) << "Rejecting " << node->name() << ": JIT for device disabled.";
+ }
+ }
+ return should_compile;
};
return RunImpl(options, is_compilable);
}
+static string RatioToString(int numerator, int denominator) {
+ return strings::Printf("%d / %d (%.2f%%)", numerator, denominator,
+ (100.0 * numerator) / denominator);
+}
+
+static void VLogClusteringSummary(const Graph& g) {
+ if (!VLOG_IS_ON(2)) {
+ return;
+ }
+
+ std::map<StringPiece, int> cluster_name_to_size;
+ std::map<StringPiece, std::map<StringPiece, int>>
+ cluster_name_to_op_histogram;
+ std::map<StringPiece, int> unclustered_op_histogram;
+ int clustered_node_count = 0;
+
+ for (Node* n : g.nodes()) {
+ gtl::optional<StringPiece> cluster_name = GetXlaClusterForNode(*n);
+ if (cluster_name) {
+ clustered_node_count++;
+ cluster_name_to_size[*cluster_name]++;
+ cluster_name_to_op_histogram[*cluster_name][n->type_string()]++;
+ } else {
+ unclustered_op_histogram[n->type_string()]++;
+ }
+ }
+
+ int unclustered_node_count = g.num_nodes() - clustered_node_count;
+
+ VLOG(2) << "*** Clustering info for graph of size " << g.num_nodes();
+ VLOG(2) << " Built " << cluster_name_to_size.size() << " clusters, size "
+ << RatioToString(clustered_node_count, g.num_nodes());
+
+ for (const auto& cluster_name_size_pair : cluster_name_to_size) {
+ StringPiece cluster_name = cluster_name_size_pair.first;
+ int size = cluster_name_size_pair.second;
+ VLOG(2) << " " << cluster_name << " "
+ << RatioToString(size, g.num_nodes());
+ for (const auto& op_count_pair :
+ cluster_name_to_op_histogram[cluster_name]) {
+ VLOG(3) << " " << op_count_pair.first << ": " << op_count_pair.second
+ << " instances";
+ }
+ }
+
+ if (!unclustered_op_histogram.empty()) {
+ VLOG(2) << " Unclustered nodes: "
+ << RatioToString(unclustered_node_count, g.num_nodes());
+ for (const auto& pair : unclustered_op_histogram) {
+ VLOG(3) << " " << pair.first << ": " << pair.second << " instances";
+ }
+ }
+}
+
// Is 'node' an operator that consumes only the shape of its input, not the
// data itself?
static bool IsShapeConsumerOp(const Node& node) {
@@ -700,6 +778,9 @@ Status MarkForCompilationPass::RunImpl(
dump_graph::DumpGraphToFile("mark_for_compilation", **options.graph,
options.flib_def);
}
+
+ VLogClusteringSummary(*graph);
+
return Status::OK();
}
diff --git a/tensorflow/compiler/jit/mark_for_compilation_pass.h b/tensorflow/compiler/jit/mark_for_compilation_pass.h
index e9acbfb19e..f1137af3c1 100644
--- a/tensorflow/compiler/jit/mark_for_compilation_pass.h
+++ b/tensorflow/compiler/jit/mark_for_compilation_pass.h
@@ -40,20 +40,18 @@ class MarkForCompilationPass : public GraphOptimizationPass {
Status Run(const GraphOptimizationPassOptions& options) override;
- // Run() just calls RunImpl() if --tf_xla_auto_jit is enabled. To run the pass
- // unconditionally, call RunImpl() directly.
- // is_compilable_fn, if set, is a predicate that must be true for a node to
- // be compiled.
+ private:
Status RunImpl(const GraphOptimizationPassOptions& options,
const std::function<bool(const Node*, const DeviceType&)>&
is_compilable_fn = {});
+
+ friend class MarkForCompilationPassTestHelper;
};
// Returns true iff 'ndef' is a call to a function that is compilable. A
// function is compilable iff every operator in the function body is
// compilable.
bool IsCompilable(FunctionLibraryRuntime* flr, const NodeDef& ndef);
-
} // namespace tensorflow
#endif // TENSORFLOW_COMPILER_JIT_MARK_FOR_COMPILATION_PASS_H_
diff --git a/tensorflow/compiler/jit/mark_for_compilation_pass_test.cc b/tensorflow/compiler/jit/mark_for_compilation_pass_test.cc
index 2c5f4fb774..a780d4a936 100644
--- a/tensorflow/compiler/jit/mark_for_compilation_pass_test.cc
+++ b/tensorflow/compiler/jit/mark_for_compilation_pass_test.cc
@@ -13,7 +13,7 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#include "tensorflow/compiler/jit/mark_for_compilation_pass.h"
+#include "tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h"
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
@@ -39,27 +39,6 @@ namespace {
REGISTER_OP("UncompilableNullary").Output("o: float");
REGISTER_OP("UncompilableUnary").Input("a: float").Output("o: float");
-Status MarkForCompilation(std::unique_ptr<Graph>* graph,
- FunctionLibraryDefinition* flib_def) {
- // Assign all nodes to the CPU device.
- static const char* kCpuDevice = "/job:localhost/replica:0/task:0/cpu:0";
- for (Node* n : (*graph)->nodes()) {
- n->set_assigned_device_name(kCpuDevice);
- }
-
- GraphOptimizationPassOptions opt_options;
- opt_options.graph = graph;
- opt_options.flib_def = flib_def;
- MarkForCompilationPass pass;
- return pass.RunImpl(opt_options);
-}
-
-Status MarkForCompilation(std::unique_ptr<Graph>* graph) {
- FunctionDefLibrary flib;
- FunctionLibraryDefinition flib_def((*graph)->op_registry(), flib);
- return MarkForCompilation(graph, &flib_def);
-}
-
std::unordered_map<string, string> GetClusters(const Graph& graph) {
std::unordered_map<string, string> ids;
for (Node* node : graph.nodes()) {
@@ -88,7 +67,7 @@ TEST(XlaCompilationTest, Chains) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(4, clusters.size());
EXPECT_EQ(clusters["B"], clusters["C"]);
@@ -113,7 +92,7 @@ TEST(XlaCompilationTest, UncompilableCycles) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_TRUE(clusters.empty());
@@ -133,7 +112,7 @@ TEST(XlaCompilationTest, CompilableCycles) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(3, clusters.size());
@@ -156,7 +135,7 @@ TEST(XlaCompilationTest, Complex128Unsupported) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_TRUE(clusters.empty());
}
@@ -177,7 +156,7 @@ TEST(XlaCompilationTest, HalfSupported) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_FALSE(clusters.empty());
}
@@ -206,7 +185,7 @@ TEST(XlaCompilationTest, ConcatWithConstArg) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(3, clusters.size()); // Everything should be compiled.
}
@@ -241,7 +220,8 @@ TEST(XlaCompilationTest, FunctionCalls) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph, &flib_def));
+ TF_ASSERT_OK(
+ MarkForCompilationPassTestHelper::MarkForCompilation(&graph, &flib_def));
auto clusters = GetClusters(*graph);
EXPECT_EQ(2, clusters.size());
@@ -272,7 +252,7 @@ TEST(XlaCompilationTest, MetadataOpsDontStartClusters) {
ops::UnaryOp("Shape", d, builder.opts().WithName("E"));
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(0, clusters.size()); // Nothing should be compiled.
}
@@ -359,7 +339,7 @@ TEST(XlaCompilationTest, SymbolicGradients) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(2, clusters.size());
@@ -384,7 +364,7 @@ TEST(XlaCompilationTest, Loops) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_EXPECT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
// Nothing should be compiled. In particular, 'd' and 'c' must not be
@@ -411,7 +391,7 @@ TEST(XlaCompilationTest, CyclesWithAllDifferentScopes) {
TF_CHECK_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
// The computation is: C = A + relu(A)
@@ -442,7 +422,7 @@ TEST(XlaCompilationTest, CyclesWithSplittingScopes) {
TF_CHECK_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
// The computation is: D = relu(A) + (A @ relu(A))
@@ -472,7 +452,7 @@ TEST(XlaCompilationTest, CyclesWithDifferentScopesAndBridge) {
TF_CHECK_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
// The computation is: C = A @ relu(A)
@@ -512,7 +492,7 @@ TEST(XlaCompilationTest, Resources) {
ops::UnaryOp("Relu", d, builder.opts().WithName("E"));
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(0, clusters.size()); // Nothing should be compiled.
}
@@ -542,7 +522,7 @@ TEST(XlaCompilationTest, IllegalCycle_UsefulErrorMessage) {
TF_EXPECT_OK(root.ToGraph(graph.get()));
- Status status = MarkForCompilation(&graph);
+ Status status = MarkForCompilationPassTestHelper::MarkForCompilation(&graph);
EXPECT_FALSE(status.ok());
EXPECT_TRUE(str_util::StrContains(status.ToString(),
"Edge from c to a would create a cycle.\n"
@@ -570,7 +550,7 @@ TEST(XlaCompilationTest, Retval) {
TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
}
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_EQ(2, clusters.size());
@@ -588,7 +568,7 @@ TEST(XlaCompilationTest, DontCountIdentityOps) {
auto r = ops::_Retval(root.WithOpName("R"), c, 0);
}
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_TRUE(clusters.empty());
@@ -604,7 +584,7 @@ TEST(XlaCompilationTest, DontCountIdentityOpsWithLocalJit) {
auto r = ops::_Retval(root.WithOpName("R"), b, 0);
}
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
auto clusters = GetClusters(*graph);
EXPECT_TRUE(clusters.empty());
@@ -618,7 +598,7 @@ TEST(XlaCompilationTest, ConstOp) {
auto c = ops::Const(root.WithOpName("const"), 0.5f);
c.node()->AddAttr(kXlaCompileAttr, true);
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
EXPECT_EQ(1, GetClusters(*graph).size());
}
@@ -629,7 +609,7 @@ TEST(XlaCompilationTest, ConstOp) {
auto c = ops::Const(root.WithOpName("const"), string("string"));
c.node()->AddAttr(kXlaCompileAttr, true);
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
EXPECT_TRUE(GetClusters(*graph).empty());
}
}
@@ -644,7 +624,7 @@ TEST(XlaCompilationTest, DontClusterIdentityWithRefInput) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
std::unordered_map<string, string> clusters = GetClusters(*graph);
@@ -667,7 +647,7 @@ TEST(XlaCompilationTest, ClusterIdentityWithNonRefInput) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
std::unordered_map<string, string> clusters = GetClusters(*graph);
@@ -699,7 +679,7 @@ TEST(XlaCompilationTest, ClusterControlTrigger) {
std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
TF_ASSERT_OK(root.ToGraph(graph.get()));
- TF_ASSERT_OK(MarkForCompilation(&graph));
+ TF_ASSERT_OK(MarkForCompilationPassTestHelper::MarkForCompilation(&graph));
std::unordered_map<string, string> clusters = GetClusters(*graph);
diff --git a/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.cc b/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.cc
new file mode 100644
index 0000000000..a84b82e479
--- /dev/null
+++ b/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.cc
@@ -0,0 +1,40 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h"
+
+namespace tensorflow {
+/*static*/ Status MarkForCompilationPassTestHelper::MarkForCompilation(
+ std::unique_ptr<Graph>* graph, FunctionLibraryDefinition* flib_def) {
+ // Assign all nodes to the CPU device.
+ static const char* kCpuDevice = "/job:localhost/replica:0/task:0/cpu:0";
+ for (Node* n : (*graph)->nodes()) {
+ n->set_assigned_device_name(kCpuDevice);
+ }
+
+ GraphOptimizationPassOptions opt_options;
+ opt_options.graph = graph;
+ opt_options.flib_def = flib_def;
+ MarkForCompilationPass pass;
+ return pass.RunImpl(opt_options);
+}
+
+/*static*/ Status MarkForCompilationPassTestHelper::MarkForCompilation(
+ std::unique_ptr<Graph>* graph) {
+ FunctionDefLibrary flib;
+ FunctionLibraryDefinition flib_def((*graph)->op_registry(), flib);
+ return MarkForCompilation(graph, &flib_def);
+}
+} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h b/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h
new file mode 100644
index 0000000000..b9a0531cb0
--- /dev/null
+++ b/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h
@@ -0,0 +1,35 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_JIT_MARK_FOR_COMPILATION_PASS_TEST_HELPER_H_
+#define TENSORFLOW_COMPILER_JIT_MARK_FOR_COMPILATION_PASS_TEST_HELPER_H_
+
+#include "tensorflow/compiler/jit/mark_for_compilation_pass.h"
+
+namespace tensorflow {
+class MarkForCompilationPassTestHelper {
+ public:
+ // Runs the MarkForCompilation pass on `graph` after assigning all nodes in
+ // `graph` to the CPU device. To make testing easier, ignores device
+ // registration, _XlaCompile attributes, input deadness and global jit level.
+ static Status MarkForCompilation(std::unique_ptr<Graph>* graph,
+ FunctionLibraryDefinition* flib_def);
+
+ // Like `MarkForCompilation` but creates `flib_def` from the op registry.
+ static Status MarkForCompilation(std::unique_ptr<Graph>* graph);
+};
+} // namespace tensorflow
+
+#endif // TENSORFLOW_COMPILER_JIT_MARK_FOR_COMPILATION_PASS_TEST_HELPER_H_
diff --git a/tensorflow/compiler/jit/partially_decluster_pass.cc b/tensorflow/compiler/jit/partially_decluster_pass.cc
new file mode 100644
index 0000000000..68ead39424
--- /dev/null
+++ b/tensorflow/compiler/jit/partially_decluster_pass.cc
@@ -0,0 +1,177 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/jit/partially_decluster_pass.h"
+#include "tensorflow/compiler/jit/xla_cluster_util.h"
+#include "tensorflow/core/framework/memory_types.h"
+#include "tensorflow/core/framework/node_def.pb.h"
+#include "tensorflow/core/lib/gtl/flatset.h"
+
+namespace tensorflow {
+namespace {
+Status FindNodesToDecluster(const Graph& graph, gtl::FlatSet<Node*>* result,
+ gtl::ArraySlice<Node*> post_order) {
+ // Find nodes that have at least one user outside their cluster that expects
+ // hostmem output. These nodes should be cloned to outside the cluster to
+ // avoid the device-host copy we'd otherwise need.
+
+ MemoryTypeVector input_mtypes, output_mtypes;
+
+ for (Node* n : post_order) {
+ gtl::optional<StringPiece> from_cluster = GetXlaClusterForNode(*n);
+ if (!from_cluster) {
+ continue;
+ }
+
+ // We assume the only XLA-auto-clusterable operations with side effects are
+ // resource variable updates. We can't execute these twice.
+ if (HasResourceInputOrOutput(*n)) {
+ continue;
+ }
+
+ DeviceType device_type("");
+ TF_RETURN_IF_ERROR(
+ DeviceToDeviceType(n->assigned_device_name(), &device_type));
+ TF_RETURN_IF_ERROR(MemoryTypesForNode(graph.op_registry(), device_type,
+ n->def(), &input_mtypes,
+ &output_mtypes));
+ for (const Edge* e : n->out_edges()) {
+ Node* dst = e->dst();
+
+ if (e->IsControlEdge()) {
+ continue;
+ }
+
+ bool edge_incurs_extra_device_to_host_copy;
+ if (output_mtypes[e->src_output()] == DEVICE_MEMORY) {
+ // If the output of the *TensorFlow* operation is in DEVICE_MEMORY then
+ // keep the node clustered -- XLA will also produce the output in device
+ // memory and we will get some benefit from clustering.
+ edge_incurs_extra_device_to_host_copy = false;
+ } else {
+ MemoryTypeVector dst_input_mtypes, dst_output_mtypes;
+ DeviceType dst_device_type("");
+ TF_RETURN_IF_ERROR(
+ DeviceToDeviceType(dst->assigned_device_name(), &dst_device_type));
+ TF_RETURN_IF_ERROR(MemoryTypesForNode(graph.op_registry(), device_type,
+ dst->def(), &dst_input_mtypes,
+ &dst_output_mtypes));
+ edge_incurs_extra_device_to_host_copy =
+ dst_input_mtypes[e->dst_input()] == HOST_MEMORY;
+ }
+
+ if (!edge_incurs_extra_device_to_host_copy) {
+ continue;
+ }
+
+ // Check if `dst` is in a different cluster, unclustered, or about to be
+ // partially declustered (here we rely on the post-order traversal order).
+ // If yes, decluster `n` to avoid the device-to-host memcpy.
+ gtl::optional<StringPiece> dst_cluster =
+ result->count(dst) ? gtl::nullopt : GetXlaClusterForNode(*dst);
+ if (from_cluster != dst_cluster) {
+ CHECK(result->insert(n).second);
+ break;
+ }
+ }
+ }
+ return Status::OK();
+}
+
+Status PartiallyDeclusterNode(Graph* graph, Node* n) {
+ StringPiece cluster_name = *GetXlaClusterForNode(*n);
+ gtl::InlinedVector<const Edge*, 6> out_edges_to_clone;
+ for (const Edge* out_edge : n->out_edges()) {
+ if (out_edge->IsControlEdge()) {
+ continue;
+ }
+
+ Node* dst = out_edge->dst();
+ gtl::optional<StringPiece> dst_cluster_name = GetXlaClusterForNode(*dst);
+ if (dst_cluster_name != cluster_name) {
+ out_edges_to_clone.push_back(out_edge);
+ }
+ }
+
+ CHECK(!out_edges_to_clone.empty()) << n->DebugString();
+
+ NodeDef ndef = n->def();
+ ndef.set_name(strings::StrCat(n->name(), "/declustered"));
+ RemoveFromXlaCluster(&ndef);
+ Status s;
+ Node* cloned_node = graph->AddNode(ndef, &s);
+ cloned_node->set_assigned_device_name(n->assigned_device_name());
+ TF_RETURN_IF_ERROR(s);
+
+ for (const Edge* in_edge : n->in_edges()) {
+ graph->AddEdge(in_edge->src(), in_edge->src_output(), cloned_node,
+ in_edge->dst_input());
+ }
+
+ for (const Edge* out_edge_to_clone : out_edges_to_clone) {
+ graph->AddEdge(cloned_node, out_edge_to_clone->src_output(),
+ out_edge_to_clone->dst(), out_edge_to_clone->dst_input());
+ graph->RemoveEdge(out_edge_to_clone);
+ }
+
+ return Status::OK();
+}
+} // namespace
+
+Status PartiallyDeclusterPass::Run(
+ const GraphOptimizationPassOptions& options) {
+ // NB! In this pass we assume the only XLA-auto-clusterable operations that
+ // may have side effects are resource variable operations so we don't cluster
+ // those. The pass will have to be updated if this assumption becomes
+ // invalid.
+
+ Graph* graph = options.graph->get();
+
+ // When deciding whether to decluster a particular node, we base our decision
+ // on if we've decided that some of its consumers have to be declustered too.
+ // Iterating the graph in post-order guarantees that consumers have been
+ // visited before producers.
+ std::vector<Node*> post_order;
+ GetPostOrder(*graph, &post_order, /*stable_comparator=*/NodeComparatorName(),
+ /*edge_filter=*/[](const Edge& edge) {
+ return !edge.src()->IsNextIteration();
+ });
+
+ gtl::FlatSet<Node*> nodes_to_partially_decluster;
+ TF_RETURN_IF_ERROR(FindNodesToDecluster(
+ **options.graph, &nodes_to_partially_decluster, post_order));
+
+ if (VLOG_IS_ON(3)) {
+ for (Node* n : post_order) {
+ if (nodes_to_partially_decluster.count(n)) {
+ VLOG(3) << n->DebugString();
+ }
+ }
+ }
+
+ for (Node* n : post_order) {
+ if (nodes_to_partially_decluster.count(n)) {
+ TF_RETURN_IF_ERROR(PartiallyDeclusterNode(graph, n));
+ }
+ }
+
+ nodes_to_partially_decluster.clear();
+ TF_RETURN_IF_ERROR(FindNodesToDecluster(
+ **options.graph, &nodes_to_partially_decluster, post_order));
+ CHECK(nodes_to_partially_decluster.empty());
+
+ return Status::OK();
+}
+} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/partially_decluster_pass.h b/tensorflow/compiler/jit/partially_decluster_pass.h
new file mode 100644
index 0000000000..6949b5028e
--- /dev/null
+++ b/tensorflow/compiler/jit/partially_decluster_pass.h
@@ -0,0 +1,58 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_JIT_PARTIALLY_DECLUSTER_PASS_H_
+#define TENSORFLOW_COMPILER_JIT_PARTIALLY_DECLUSTER_PASS_H_
+
+#include "tensorflow/core/common_runtime/optimization_registry.h"
+
+namespace tensorflow {
+
+// Clones nodes from within a cluster to outside the cluster if profitable.
+//
+// Today this only clones to avoid device-to-host copies, but in the future we
+// may consider other reasons to clone. For instance, we convert this:
+//
+// .....
+// |
+// v
+// A_Clustered ====> C_Unclustered
+// |
+// v
+// B_Clustered
+//
+// to:
+//
+// .....
+// | |
+// | +-------------+
+// | |
+// v v
+// A_Clustered A_Unclustered ====> C_Unclustered
+// |
+// v
+// B_Clustered
+//
+// where the ===> arrow has a hostmem source and destination and would entail a
+// device to host copy if the source and destination were not in the same XLA
+// cluster.
+class PartiallyDeclusterPass : public GraphOptimizationPass {
+ public:
+ Status Run(const GraphOptimizationPassOptions& options) override;
+};
+
+} // namespace tensorflow
+
+#endif // TENSORFLOW_COMPILER_JIT_PARTIALLY_DECLUSTER_PASS_H_
diff --git a/tensorflow/compiler/jit/partially_decluster_pass_test.cc b/tensorflow/compiler/jit/partially_decluster_pass_test.cc
new file mode 100644
index 0000000000..08a956e4c6
--- /dev/null
+++ b/tensorflow/compiler/jit/partially_decluster_pass_test.cc
@@ -0,0 +1,284 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/jit/partially_decluster_pass.h"
+
+#include "tensorflow/cc/framework/ops.h"
+#include "tensorflow/cc/ops/array_ops.h"
+#include "tensorflow/cc/ops/control_flow_ops_internal.h"
+#include "tensorflow/cc/ops/function_ops.h"
+#include "tensorflow/cc/ops/sendrecv_ops.h"
+#include "tensorflow/cc/ops/standard_ops.h"
+#include "tensorflow/compiler/jit/defs.h"
+#include "tensorflow/compiler/jit/xla_cluster_util.h"
+#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
+#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
+#include "tensorflow/core/framework/node_def_util.h"
+#include "tensorflow/core/framework/op.h"
+#include "tensorflow/core/graph/algorithm.h"
+#include "tensorflow/core/graph/graph_constructor.h"
+#include "tensorflow/core/graph/graph_def_builder.h"
+#include "tensorflow/core/graph/graph_def_builder_util.h"
+#include "tensorflow/core/lib/core/status_test_util.h"
+#include "tensorflow/core/lib/strings/str_util.h"
+#include "tensorflow/core/platform/test.h"
+
+namespace tensorflow {
+namespace {
+REGISTER_OP("FakeNullary").Output("out: float");
+
+REGISTER_OP("FakeBinary")
+ .Input("host_in: float")
+ .Input("device_in: float")
+ .Output("host_out: float")
+ .Output("device_out: float");
+
+REGISTER_OP("FakeResourceVar").Output("out: resource");
+
+REGISTER_OP("FakeResourceUpdate")
+ .Input("in: resource")
+ .Output("out: resource")
+ .Output("something_else: float");
+
+class FakeBinaryOp : public OpKernel {
+ public:
+ explicit FakeBinaryOp(OpKernelConstruction* context) : OpKernel(context) {}
+
+ void Compute(OpKernelContext* ctx) override { CHECK(false); }
+};
+
+class FakeResourceVarUpdateOp : public OpKernel {
+ public:
+ explicit FakeResourceVarUpdateOp(OpKernelConstruction* context)
+ : OpKernel(context) {}
+
+ void Compute(OpKernelContext* ctx) override { CHECK(false); }
+};
+
+REGISTER_KERNEL_BUILDER(Name("FakeBinary")
+ .Device(DEVICE_CPU)
+ .HostMemory("host_in")
+ .HostMemory("host_out"),
+ FakeBinaryOp);
+
+REGISTER_KERNEL_BUILDER(Name("FakeResourceVarUpdate")
+ .Device(DEVICE_CPU)
+ .HostMemory("something_else"),
+ FakeResourceVarUpdateOp);
+
+Status PartiallyDecluster(std::unique_ptr<Graph>* graph) {
+ FixupSourceAndSinkEdges(graph->get());
+ // Assign all nodes to the CPU device.
+ static const char* kCpuDevice = "/job:localhost/replica:0/task:0/cpu:0";
+ for (Node* n : (*graph)->nodes()) {
+ n->set_assigned_device_name(kCpuDevice);
+ }
+
+ GraphOptimizationPassOptions opt_options;
+ opt_options.graph = graph;
+ PartiallyDeclusterPass pass;
+ return pass.Run(opt_options);
+}
+
+const Node* FindNodeByName(const Graph& graph, const string& name) {
+ for (const Node* node : graph.nodes()) {
+ if (node->name() == name) {
+ return node;
+ }
+ }
+ return nullptr;
+}
+
+bool GetInputsForNode(const Graph& graph, const string& node_name,
+ std::vector<Node*>* inputs) {
+ const Node* node = FindNodeByName(graph, node_name);
+ if (node == nullptr) {
+ return false;
+ }
+ for (const Edge* e : node->in_edges()) {
+ inputs->push_back(e->src());
+ }
+ std::sort(inputs->begin(), inputs->end(), NodeComparatorName());
+ return true;
+}
+
+TEST(PartiallyDeclusterPassTest, ClusteredAndUnclustered) {
+ std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
+ {
+ GraphDefBuilder builder(GraphDefBuilder::kFailImmediately);
+ Node* input =
+ ops::SourceOp("FakeNullary", builder.opts().WithName("Input"));
+ Node* clustered_producer =
+ ops::BinaryOp("FakeBinary", input, input,
+ builder.opts().WithName("ClusteredProducer"));
+ ops::BinaryOp("FakeBinary", clustered_producer, input,
+ builder.opts().WithName("UnclusteredConsumer"));
+ Node* clustered_consumer =
+ ops::BinaryOp("FakeBinary", {clustered_producer, 1}, input,
+ builder.opts().WithName("ClusteredConsumer"));
+ clustered_producer->AddAttr(kXlaClusterAttr, "cluster_0");
+ clustered_consumer->AddAttr(kXlaClusterAttr, "cluster_0");
+ TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
+ }
+
+ TF_ASSERT_OK(PartiallyDecluster(&graph));
+ std::vector<Node*> unclustered_consumer_inputs;
+ ASSERT_TRUE(GetInputsForNode(*graph, "UnclusteredConsumer",
+ &unclustered_consumer_inputs));
+ ASSERT_EQ(unclustered_consumer_inputs.size(), 2);
+ EXPECT_EQ(unclustered_consumer_inputs[0]->name(),
+ "ClusteredProducer/declustered");
+ EXPECT_EQ(unclustered_consumer_inputs[1]->name(), "Input");
+
+ std::vector<Node*> clustered_consumer_inputs;
+ ASSERT_TRUE(GetInputsForNode(*graph, "ClusteredConsumer",
+ &clustered_consumer_inputs));
+ ASSERT_EQ(clustered_consumer_inputs.size(), 2);
+ EXPECT_EQ(clustered_consumer_inputs[0]->name(), "ClusteredProducer");
+ EXPECT_EQ(clustered_consumer_inputs[1]->name(), "Input");
+}
+
+TEST(PartiallyDeclusterPassTest, DifferentClusters) {
+ std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
+ {
+ GraphDefBuilder builder(GraphDefBuilder::kFailImmediately);
+ Node* input =
+ ops::SourceOp("FakeNullary", builder.opts().WithName("Input"));
+ Node* clustered_producer =
+ ops::BinaryOp("FakeBinary", input, input,
+ builder.opts().WithName("ClusteredProducer"));
+ Node* consumer_in_different_cluster =
+ ops::BinaryOp("FakeBinary", clustered_producer, input,
+ builder.opts().WithName("ConsumerInDifferentCluster"));
+ Node* clustered_consumer =
+ ops::BinaryOp("FakeBinary", input, {clustered_producer, 1},
+ builder.opts().WithName("ClusteredConsumer"));
+ clustered_producer->AddAttr(kXlaClusterAttr, "cluster_0");
+ clustered_consumer->AddAttr(kXlaClusterAttr, "cluster_0");
+ consumer_in_different_cluster->AddAttr(kXlaClusterAttr, "cluster_1");
+ TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
+ }
+
+ TF_ASSERT_OK(PartiallyDecluster(&graph));
+ std::vector<Node*> inputs;
+ ASSERT_TRUE(GetInputsForNode(*graph, "ConsumerInDifferentCluster", &inputs));
+ ASSERT_EQ(inputs.size(), 2);
+ EXPECT_EQ(inputs[0]->name(), "ClusteredProducer/declustered");
+ EXPECT_EQ(inputs[1]->name(), "Input");
+}
+
+TEST(PartiallyDeclusterPassTest, DontDeclusterIfUserIsDeviceMem) {
+ std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
+ {
+ GraphDefBuilder builder(GraphDefBuilder::kFailImmediately);
+ Node* input =
+ ops::SourceOp("FakeNullary", builder.opts().WithName("Input"));
+ Node* clustered_producer =
+ ops::BinaryOp("FakeBinary", input, input,
+ builder.opts().WithName("ClusteredProducer"));
+ // The first input is hostmem and the second input is devicemem.
+ Node* consumer_in_different_cluster =
+ ops::BinaryOp("FakeBinary", input, clustered_producer,
+ builder.opts().WithName("ConsumerInDifferentCluster"));
+ Node* clustered_consumer =
+ ops::BinaryOp("FakeBinary", input, {clustered_producer, 1},
+ builder.opts().WithName("ClusteredConsumer"));
+ clustered_producer->AddAttr(kXlaClusterAttr, "cluster_0");
+ clustered_consumer->AddAttr(kXlaClusterAttr, "cluster_0");
+ consumer_in_different_cluster->AddAttr(kXlaClusterAttr, "cluster_1");
+ TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
+ }
+
+ TF_ASSERT_OK(PartiallyDecluster(&graph));
+ std::vector<Node*> inputs;
+ ASSERT_TRUE(GetInputsForNode(*graph, "ConsumerInDifferentCluster", &inputs));
+ ASSERT_EQ(inputs.size(), 2);
+ EXPECT_EQ(inputs[0]->name(), "ClusteredProducer");
+ EXPECT_EQ(inputs[1]->name(), "Input");
+}
+
+TEST(PartiallyDeclusterPassTest, DontDuplicateResourceVarOps) {
+ std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
+ {
+ GraphDefBuilder builder(GraphDefBuilder::kFailImmediately);
+ Node* input =
+ ops::SourceOp("FakeNullary", builder.opts().WithName("Input"));
+ Node* resource_var = ops::SourceOp("FakeResourceVar",
+ builder.opts().WithName("ResourceVar"));
+ Node* clustered_producer =
+ ops::UnaryOp("FakeResourceUpdate", resource_var,
+ builder.opts().WithName("ClusteredProducer"));
+ Node* consumer_in_different_cluster =
+ ops::BinaryOp("FakeBinary", {clustered_producer, 1}, input,
+ builder.opts().WithName("ConsumerInDifferentCluster"));
+ Node* clustered_consumer =
+ ops::BinaryOp("FakeBinary", input, {clustered_producer, 1},
+ builder.opts().WithName("ClusteredConsumer"));
+ clustered_producer->AddAttr(kXlaClusterAttr, "cluster_0");
+ clustered_consumer->AddAttr(kXlaClusterAttr, "cluster_0");
+ consumer_in_different_cluster->AddAttr(kXlaClusterAttr, "cluster_1");
+ TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
+ }
+
+ TF_ASSERT_OK(PartiallyDecluster(&graph));
+ std::vector<Node*> inputs;
+ ASSERT_TRUE(GetInputsForNode(*graph, "ConsumerInDifferentCluster", &inputs));
+ ASSERT_EQ(inputs.size(), 2);
+ EXPECT_EQ(inputs[0]->name(), "ClusteredProducer");
+ EXPECT_EQ(inputs[1]->name(), "Input");
+}
+
+TEST(PartiallyDeclusterPassTest, DeclusterDependentNodes) {
+ std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
+ {
+ GraphDefBuilder builder(GraphDefBuilder::kFailImmediately);
+ Node* input =
+ ops::SourceOp("FakeNullary", builder.opts().WithName("Input"));
+ Node* clustered_producer_0 =
+ ops::BinaryOp("FakeBinary", input, input,
+ builder.opts().WithName("ClusteredProducer0"));
+ Node* clustered_producer_1 =
+ ops::BinaryOp("FakeBinary", clustered_producer_0, input,
+ builder.opts().WithName("ClusteredProducer1"));
+ ops::BinaryOp("FakeBinary", clustered_producer_1, input,
+ builder.opts().WithName("UnclusteredConsumer"));
+ Node* clustered_consumer =
+ ops::BinaryOp("FakeBinary", {clustered_producer_1, 1}, input,
+ builder.opts().WithName("ClusteredConsumer"));
+ clustered_producer_0->AddAttr(kXlaClusterAttr, "cluster_0");
+ clustered_producer_1->AddAttr(kXlaClusterAttr, "cluster_0");
+ clustered_consumer->AddAttr(kXlaClusterAttr, "cluster_0");
+ TF_EXPECT_OK(GraphDefBuilderToGraph(builder, graph.get()));
+ }
+
+ TF_ASSERT_OK(PartiallyDecluster(&graph));
+ std::vector<Node*> unclustered_consumer_inputs, declustered_producer_1_inputs;
+
+ ASSERT_TRUE(GetInputsForNode(*graph, "UnclusteredConsumer",
+ &unclustered_consumer_inputs));
+ ASSERT_EQ(unclustered_consumer_inputs.size(), 2);
+ EXPECT_EQ(unclustered_consumer_inputs[0]->name(),
+ "ClusteredProducer1/declustered");
+ EXPECT_EQ(unclustered_consumer_inputs[1]->name(), "Input");
+
+ ASSERT_TRUE(GetInputsForNode(*graph, "ClusteredProducer1/declustered",
+ &declustered_producer_1_inputs));
+ ASSERT_EQ(declustered_producer_1_inputs.size(), 2);
+ EXPECT_EQ(declustered_producer_1_inputs[0]->name(),
+ "ClusteredProducer0/declustered");
+ EXPECT_EQ(declustered_producer_1_inputs[1]->name(), "Input");
+}
+} // namespace
+} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/xla_cluster_util.cc b/tensorflow/compiler/jit/xla_cluster_util.cc
index a5628b12a2..0a025a1fc0 100644
--- a/tensorflow/compiler/jit/xla_cluster_util.cc
+++ b/tensorflow/compiler/jit/xla_cluster_util.cc
@@ -185,4 +185,26 @@ Status CreateCycleDetectionGraph(const Graph* graph, GraphCycles* cycles) {
return Status::OK();
}
+gtl::optional<StringPiece> GetXlaClusterForNode(const Node& node) {
+ const AttrValue* attr_value = node.attrs().Find(kXlaClusterAttr);
+ if (attr_value == nullptr) {
+ return gtl::nullopt;
+ }
+ Status s = AttrValueHasType(*attr_value, "string");
+ if (!s.ok()) {
+ return gtl::nullopt;
+ }
+ return attr_value->s();
+}
+
+bool HasResourceInputOrOutput(const Node& node) {
+ return std::find(node.input_types().begin(), node.input_types().end(),
+ DT_RESOURCE) != node.input_types().end() ||
+ std::find(node.output_types().begin(), node.output_types().end(),
+ DT_RESOURCE) != node.output_types().end();
+}
+
+void RemoveFromXlaCluster(NodeDef* node_def) {
+ node_def->mutable_attr()->erase(kXlaClusterAttr);
+}
} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/xla_cluster_util.h b/tensorflow/compiler/jit/xla_cluster_util.h
index bcce082aaf..bff76da6f9 100644
--- a/tensorflow/compiler/jit/xla_cluster_util.h
+++ b/tensorflow/compiler/jit/xla_cluster_util.h
@@ -20,6 +20,7 @@ limitations under the License.
#include "tensorflow/compiler/jit/graphcycles/graphcycles.h"
#include "tensorflow/core/graph/algorithm.h"
+#include "tensorflow/core/lib/gtl/optional.h"
namespace tensorflow {
@@ -44,6 +45,16 @@ bool HasForwardedRefInput(const Node& node);
// the enclosing graph.
Status CreateCycleDetectionGraph(const Graph* graph, GraphCycles* cycles);
+// Returns the XLA cluster in which `node` is placed if it is in an XLA cluster,
+// otherwise returns nullopt.
+gtl::optional<StringPiece> GetXlaClusterForNode(const Node& node);
+
+// Removes `node_def` its XLA cluster (by clearing its _XlaCluster attribute).
+void RemoveFromXlaCluster(NodeDef* node_def);
+
+// Returns true if `node` has a DT_RESOURCE typed input or output.
+bool HasResourceInputOrOutput(const Node& node);
+
} // namespace tensorflow
#endif // TENSORFLOW_COMPILER_JIT_XLA_CLUSTER_UTIL_H_
diff --git a/tensorflow/compiler/jit/xla_compile_on_demand_op.cc b/tensorflow/compiler/jit/xla_compile_on_demand_op.cc
index d288d37bc7..dd84fb34c1 100644
--- a/tensorflow/compiler/jit/xla_compile_on_demand_op.cc
+++ b/tensorflow/compiler/jit/xla_compile_on_demand_op.cc
@@ -18,6 +18,7 @@ limitations under the License.
#include "tensorflow/compiler/jit/xla_compile_on_demand_op.h"
#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_launch_util.h"
+#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
@@ -71,13 +72,14 @@ Status XlaCompileOnDemandOp::Run(OpKernelContext* ctx,
run_options.set_stream(stream);
run_options.set_allocator(client->backend().memory_allocator());
run_options.set_intra_op_thread_pool(&ctx->eigen_cpu_device());
- run_options.set_rng_seed(ctx->step_id());
+ run_options.set_rng_seed(GetXLARandomSeed());
xla::StatusOr<xla::ScopedShapedBuffer> run_result =
executable->Run(launch_context.arguments(), run_options);
TF_RETURN_IF_ERROR(run_result.status());
- launch_context.PopulateOutputs(ctx, result, run_result.ConsumeValueOrDie());
+ TF_RETURN_IF_ERROR(launch_context.PopulateOutputs(
+ ctx, result, run_result.ConsumeValueOrDie()));
return Status::OK();
}
diff --git a/tensorflow/compiler/jit/xla_device.cc b/tensorflow/compiler/jit/xla_device.cc
index 4ddeaebd3e..2a2691a6a4 100644
--- a/tensorflow/compiler/jit/xla_device.cc
+++ b/tensorflow/compiler/jit/xla_device.cc
@@ -26,6 +26,7 @@ limitations under the License.
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/client_library.h"
+#include "tensorflow/compiler/xla/service/stream_pool.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
@@ -216,6 +217,8 @@ XlaDevice::XlaDevice(
transfer_as_literal_(transfer_as_literal),
shape_representation_fn_(shape_representation_fn) {
VLOG(1) << "Created XLA device " << jit_device_name << " " << this;
+ thread_pool_.reset(new thread::ThreadPool(options.env, "xla_device",
+ /*num_threads=*/1));
}
XlaDevice::~XlaDevice() {
@@ -262,10 +265,12 @@ Status XlaDevice::EnsureDeviceContextOk() {
Status XlaDevice::EnsureStreamOkLocked(xla::Backend* backend,
const string& name,
- xla::StreamPool::Ptr* stream,
+ std::shared_ptr<se::Stream>* stream,
bool* stream_was_changed) {
if (!(*stream) || !(*stream)->ok()) {
- TF_ASSIGN_OR_RETURN(*stream, backend->BorrowStream(device_ordinal_));
+ xla::StreamPool::Ptr ptr;
+ TF_ASSIGN_OR_RETURN(ptr, backend->BorrowStream(device_ordinal_));
+ *stream = std::shared_ptr<se::Stream>(std::move(ptr));
VLOG(1) << "XlaDevice " << this << " new " << name << " "
<< (*stream)->DebugStreamPointers();
*stream_was_changed = true;
@@ -281,8 +286,8 @@ xla::StatusOr<XlaDeviceContext*> XlaDevice::GetDeviceContextLocked() {
TF_RETURN_IF_ERROR(EnsureStreamOkLocked(backend, "stream", &stream_,
&need_new_device_context));
- se::Stream* host_to_device_stream = stream_.get();
- se::Stream* device_to_host_stream = stream_.get();
+ std::shared_ptr<se::Stream> host_to_device_stream = stream_;
+ std::shared_ptr<se::Stream> device_to_host_stream = stream_;
if (use_multiple_streams_) {
TF_RETURN_IF_ERROR(EnsureStreamOkLocked(backend, "host_to_device_stream",
&host_to_device_stream_,
@@ -290,8 +295,8 @@ xla::StatusOr<XlaDeviceContext*> XlaDevice::GetDeviceContextLocked() {
TF_RETURN_IF_ERROR(EnsureStreamOkLocked(backend, "device_to_host_stream",
&device_to_host_stream_,
&need_new_device_context));
- host_to_device_stream = host_to_device_stream_.get();
- device_to_host_stream = device_to_host_stream_.get();
+ host_to_device_stream = host_to_device_stream_;
+ device_to_host_stream = device_to_host_stream_;
}
if (!need_new_device_context) {
@@ -304,9 +309,13 @@ xla::StatusOr<XlaDeviceContext*> XlaDevice::GetDeviceContextLocked() {
if (device_context_) {
device_context_->Unref();
}
+ // The XlaDeviceContext keeps a reference count to the streams, and the
+ // XlaDeviceContext remains live for the duration of a Executor run. This
+ // ensures that the streams remain live for the duration of a run, even if
+ // an error is encountered and the streams are replaced with new ones.
device_context_ = new XlaDeviceContext(
- stream_.get(), host_to_device_stream, device_to_host_stream, client(),
- transfer_as_literal_, shape_representation_fn_);
+ stream_, host_to_device_stream, device_to_host_stream, client(),
+ transfer_as_literal_, shape_representation_fn_, thread_pool_.get());
VLOG(1) << "XlaDevice " << this << " new XlaDeviceContext "
<< device_context_;
@@ -371,6 +380,22 @@ void XlaDevice::ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context,
op_kernel->ComputeAsync(context, done);
}
+Status XlaDevice::Sync() {
+ VLOG(1) << "XlaDevice::Sync";
+ std::shared_ptr<se::Stream> stream;
+ {
+ mutex_lock lock(mu_);
+ stream = stream_;
+ }
+ if (!stream) return Status::OK();
+
+ if (!stream->parent()->SynchronizeAllActivity() || !stream->ok()) {
+ return errors::Internal("XlaDevice::Sync() failed.");
+ }
+ VLOG(1) << "XlaDevice::Sync completed";
+ return Status::OK();
+}
+
Status XlaDevice::MakeTensorFromProto(const TensorProto& tensor_proto,
const AllocatorAttributes alloc_attrs,
Tensor* tensor) {
diff --git a/tensorflow/compiler/jit/xla_device.h b/tensorflow/compiler/jit/xla_device.h
index d8906419b0..dbf35f349f 100644
--- a/tensorflow/compiler/jit/xla_device.h
+++ b/tensorflow/compiler/jit/xla_device.h
@@ -30,7 +30,6 @@ limitations under the License.
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/local_client.h"
-#include "tensorflow/compiler/xla/service/stream_pool.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/local_device.h"
#include "tensorflow/core/framework/allocator.h"
@@ -124,7 +123,7 @@ class XlaDevice : public LocalDevice {
void Compute(OpKernel* op_kernel, OpKernelContext* context) override;
void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context,
AsyncOpKernel::DoneCallback done) override;
- Status Sync() override { return Status::OK(); }
+ Status Sync() override;
Status FillContextMap(const Graph* graph,
DeviceContextMap* device_context_map) override
@@ -153,7 +152,7 @@ class XlaDevice : public LocalDevice {
Allocator* GetAllocatorLocked(AllocatorAttributes attr)
EXCLUSIVE_LOCKS_REQUIRED(mu_);
Status EnsureStreamOkLocked(xla::Backend* backend, const string& name,
- xla::StreamPool::Ptr* stream,
+ std::shared_ptr<se::Stream>* stream,
bool* stream_was_changed)
EXCLUSIVE_LOCKS_REQUIRED(mu_);
xla::StatusOr<XlaDeviceContext*> GetDeviceContextLocked()
@@ -174,17 +173,17 @@ class XlaDevice : public LocalDevice {
// stream are executed on the device. Operations include data
// copying back and forth between CPU and the device, and
// computations enqueued by XLA.
- xla::StreamPool::Ptr stream_ GUARDED_BY(mu_);
+ std::shared_ptr<se::Stream> stream_ GUARDED_BY(mu_);
// If false, only stream_ is valid and all computation and transfers use
// stream_. If true, computation is performed by stream_ and transfers are
// performed by host_to_device/device_to_host_stream.
const bool use_multiple_streams_;
// If use_multiple_streams_, host to device transfers are performed using this
// stream.
- xla::StreamPool::Ptr host_to_device_stream_ GUARDED_BY(mu_);
+ std::shared_ptr<se::Stream> host_to_device_stream_ GUARDED_BY(mu_);
// If use_multiple_streams_, device to host transfers are performed using this
// stream.
- xla::StreamPool::Ptr device_to_host_stream_ GUARDED_BY(mu_);
+ std::shared_ptr<se::Stream> device_to_host_stream_ GUARDED_BY(mu_);
// Must we use XLA's transfer manager for correct host<->device transfers? if
// false, we can use ThenMemcpy() instead.
const bool transfer_as_literal_;
@@ -198,6 +197,9 @@ class XlaDevice : public LocalDevice {
// Holds extra information for GPU and TPU devices, e.g. the device context.
bool use_gpu_device_info_ GUARDED_BY(mu_) = false;
std::unique_ptr<GpuDeviceInfo> gpu_device_info_ GUARDED_BY(mu_);
+
+ // Thread pool used for running closures
+ std::unique_ptr<thread::ThreadPool> thread_pool_;
};
// Builds OpKernel registrations on 'device' for the JIT operators
diff --git a/tensorflow/compiler/jit/xla_device_context.cc b/tensorflow/compiler/jit/xla_device_context.cc
index 0100bf51ed..0a0c089241 100644
--- a/tensorflow/compiler/jit/xla_device_context.cc
+++ b/tensorflow/compiler/jit/xla_device_context.cc
@@ -15,6 +15,9 @@ limitations under the License.
#include "tensorflow/compiler/jit/xla_device_context.h"
+#include <memory>
+
+#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_launch_util.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
@@ -48,17 +51,20 @@ void XlaDeviceAllocator::DeallocateRaw(void* ptr) {
void XlaDeviceAllocator::GetStats(AllocatorStats* stats) { stats->Clear(); }
XlaTransferManager::XlaTransferManager(
- se::Stream* compute_stream, se::Stream* host_to_device_stream,
- se::Stream* device_to_host_stream, xla::LocalClient* client,
+ std::shared_ptr<se::Stream> compute_stream,
+ std::shared_ptr<se::Stream> host_to_device_stream,
+ std::shared_ptr<se::Stream> device_to_host_stream, xla::LocalClient* client,
bool transfer_as_literal,
- XlaCompiler::ShapeRepresentationFn shape_representation_fn)
- : stream_(compute_stream),
- host_to_device_stream_(host_to_device_stream),
- device_to_host_stream_(device_to_host_stream),
+ XlaCompiler::ShapeRepresentationFn shape_representation_fn,
+ thread::ThreadPool* thread_pool)
+ : stream_(std::move(compute_stream)),
+ host_to_device_stream_(std::move(host_to_device_stream)),
+ device_to_host_stream_(std::move(device_to_host_stream)),
client_(client),
transfer_manager_(client->backend().transfer_manager()),
transfer_as_literal_(transfer_as_literal),
- shape_representation_fn_(std::move(shape_representation_fn)) {
+ shape_representation_fn_(std::move(shape_representation_fn)),
+ thread_pool_(thread_pool) {
CHECK(host_to_device_stream_ != nullptr);
CHECK(device_to_host_stream_ != nullptr);
CHECK(stream_ != nullptr);
@@ -88,15 +94,15 @@ Status XlaTransferManager::TransferLiteralToDevice(
if (UseMultipleStreams()) {
// Initially wait for the compute stream so that memory allocations are
// synchronized.
- host_to_device_stream_->ThenWaitFor(stream_);
+ host_to_device_stream_->ThenWaitFor(stream_.get());
}
TF_RETURN_IF_ERROR(transfer_manager_->TransferLiteralToDeviceAsync(
- host_to_device_stream_, *literal, shaped_buffer));
+ host_to_device_stream_.get(), *literal, shaped_buffer));
if (UseMultipleStreams()) {
- se::Event event(stream_->parent());
- TF_RET_CHECK(event.Init()) << "Event failed to initialize!";
- host_to_device_stream_->ThenRecordEvent(&event);
- xla_tensor->SetDefinedOn(host_to_device_stream_, std::move(event));
+ auto event = std::make_shared<se::Event>(stream_->parent());
+ TF_RET_CHECK(event->Init()) << "Event failed to initialize!";
+ host_to_device_stream_->ThenRecordEvent(event.get());
+ xla_tensor->SetDefinedOn(host_to_device_stream_.get(), std::move(event));
}
// Unref the host tensor, and capture the literal shared_ptr too so it goes
// out of scope when the lambda completes.
@@ -116,7 +122,7 @@ void XlaTransferManager::TransferLiteralFromDevice(
TensorReference ref(device_tensor);
transfer_manager_->TransferLiteralFromDevice(
- device_to_host_stream_, shaped_buffer, literal,
+ device_to_host_stream_.get(), shaped_buffer, literal,
[=, &shaped_buffer, &literal](xla::Status status) {
ref.Unref();
done([&]() -> Status {
@@ -179,8 +185,14 @@ void XlaTransferManager::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
status = TransferLiteralToDevice(reshaped_cpu_tensor, device_tensor);
if (status.ok()) {
xla_tensor->set_host_tensor(*cpu_tensor);
- host_to_device_stream_->ThenDoHostCallback(
- [done]() { done(Status::OK()); });
+ host_to_device_stream_->ThenDoHostCallback([this, done]() {
+ // We must not call the done closure directly from DoHostCallback
+ // to avoid a deadlock. If done() is the callback that ends an
+ // Executor's run, the Executor may call XlaDevice::Sync() inside the
+ // callback. This deadlocks, because XlaDevice::Sync() waits for all
+ // stream activity to complete.
+ thread_pool_->Schedule([done]() { done(Status::OK()); });
+ });
return;
}
} else {
@@ -192,7 +204,7 @@ void XlaTransferManager::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
if (!block_status.ok()) {
status = xla::InternalError(
"Failed to complete data transfer on stream %p: %s",
- host_to_device_stream_, block_status.error_message().c_str());
+ host_to_device_stream_.get(), block_status.error_message().c_str());
}
}
xla_tensor->set_host_tensor(*cpu_tensor);
@@ -225,9 +237,9 @@ void XlaTransferManager::CopyDeviceTensorToCPU(const Tensor* device_tensor,
XlaTensor* xla_tensor = XlaTensor::FromTensor(device_tensor);
if (se::Event* event =
- xla_tensor->GetDefinitionEvent(device_to_host_stream_)) {
+ xla_tensor->GetDefinitionEvent(device_to_host_stream_.get())) {
device_to_host_stream_->ThenWaitFor(event);
- xla_tensor->SetDefinedOn(device_to_host_stream_);
+ xla_tensor->SetDefinedOn(device_to_host_stream_.get());
}
Status status;
@@ -240,7 +252,7 @@ void XlaTransferManager::CopyDeviceTensorToCPU(const Tensor* device_tensor,
Status block_status = device_to_host_stream_->BlockHostUntilDone();
if (!block_status.ok()) {
status = xla::InternalError(
- "Failed to complete data transfer on stream %p: %s", stream_,
+ "Failed to complete data transfer on stream %p: %s", stream_.get(),
block_status.error_message().c_str());
}
}
@@ -278,14 +290,14 @@ void XlaTransferManager::CopyDeviceTensorToDevice(const Tensor& src_tensor,
if (stream_ != device_to_device_stream) {
// Initially wait for the compute stream so that memory allocations are
// synchronized.
- device_to_device_stream->ThenWaitFor(stream_);
+ device_to_device_stream->ThenWaitFor(stream_.get());
}
}
if (se::Event* event =
- xla_src->GetDefinitionEvent(device_to_device_stream)) {
+ xla_src->GetDefinitionEvent(device_to_device_stream.get())) {
device_to_device_stream->ThenWaitFor(event);
- xla_src->SetDefinedOn(device_to_device_stream);
+ xla_src->SetDefinedOn(device_to_device_stream.get());
}
auto from_iter = xla_src->shaped_buffer().buffers().begin();
@@ -297,28 +309,37 @@ void XlaTransferManager::CopyDeviceTensorToDevice(const Tensor& src_tensor,
}
if (UseMultipleStreams()) {
- se::Event event(stream_->parent());
- CHECK(event.Init());
- device_to_device_stream->ThenRecordEvent(&event);
- xla_dst->SetDefinedOn(device_to_device_stream, std::move(event));
+ auto event = std::make_shared<se::Event>(stream_->parent());
+ TF_RET_CHECK(event->Init()) << "Event failed to initialize";
+ device_to_device_stream->ThenRecordEvent(event.get());
+ xla_dst->SetDefinedOn(device_to_device_stream.get(), std::move(event));
}
return Status::OK();
}();
if (!status.ok()) {
return done(status);
} else {
- stream_->ThenDoHostCallback([=]() { done(Status::OK()); });
+ stream_->ThenDoHostCallback([this, done]() {
+ // We must not call the done closure directly from DoHostCallback to avoid
+ // a deadlock. If done() is the callback that ends an Executor's run, the
+ // Executor may call XlaDevice::Sync() inside the callback. This
+ // deadlocks, because XlaDevice::Sync() waits for all stream activity to
+ // complete.
+ thread_pool_->Schedule([done]() { done(Status::OK()); });
+ });
}
}
XlaDeviceContext::XlaDeviceContext(
- se::Stream* compute_stream, se::Stream* host_to_device_stream,
- se::Stream* device_to_host_stream, xla::LocalClient* client,
+ std::shared_ptr<se::Stream> compute_stream,
+ std::shared_ptr<se::Stream> host_to_device_stream,
+ std::shared_ptr<se::Stream> device_to_host_stream, xla::LocalClient* client,
bool transfer_as_literal,
- XlaCompiler::ShapeRepresentationFn shape_representation_fn)
- : manager_(compute_stream, host_to_device_stream, device_to_host_stream,
- client, transfer_as_literal,
- std::move(shape_representation_fn)) {}
+ XlaCompiler::ShapeRepresentationFn shape_representation_fn,
+ thread::ThreadPool* thread_pool)
+ : manager_(std::move(compute_stream), std::move(host_to_device_stream),
+ std::move(device_to_host_stream), client, transfer_as_literal,
+ std::move(shape_representation_fn), thread_pool) {}
void XlaDeviceContext::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
Device* device,
diff --git a/tensorflow/compiler/jit/xla_device_context.h b/tensorflow/compiler/jit/xla_device_context.h
index 912f8d779e..2e7445340c 100644
--- a/tensorflow/compiler/jit/xla_device_context.h
+++ b/tensorflow/compiler/jit/xla_device_context.h
@@ -47,10 +47,12 @@ class XlaDeviceAllocator : public Allocator {
class XlaTransferManager {
public:
explicit XlaTransferManager(
- se::Stream* compute_stream, se::Stream* host_to_device_stream,
- se::Stream* device_to_host_stream, xla::LocalClient* client,
- bool transfer_as_literal,
- XlaCompiler::ShapeRepresentationFn shape_representation_fn);
+ std::shared_ptr<se::Stream> compute_stream,
+ std::shared_ptr<se::Stream> host_to_device_stream,
+ std::shared_ptr<se::Stream> device_to_host_stream,
+ xla::LocalClient* client, bool transfer_as_literal,
+ XlaCompiler::ShapeRepresentationFn shape_representation_fn,
+ thread::ThreadPool* thread_pool);
void CopyCPUTensorToDevice(const Tensor* cpu_tensor, Device* device,
Tensor* device_tensor, StatusCallback done) const;
@@ -61,7 +63,7 @@ class XlaTransferManager {
void CopyDeviceTensorToDevice(const Tensor& src_tensor, Tensor* dst_tensor,
const StatusCallback& done);
- se::Stream* stream() const { return stream_; }
+ se::Stream* stream() const { return stream_.get(); }
private:
Status TransferLiteralToDevice(const Tensor& host_tensor,
@@ -73,13 +75,13 @@ class XlaTransferManager {
// The main compute stream of the device, used to synchronize the transfer
// streams if they are set.
- se::Stream* stream_;
+ std::shared_ptr<se::Stream> stream_;
// The stream to use for transferring data from host to device. Can be
// idential to stream_, but must not be nullptr.
- se::Stream* host_to_device_stream_;
+ std::shared_ptr<se::Stream> host_to_device_stream_;
// The stream to use for transferring data from device to host. Can be
// idential to stream_, but must not be nullptr.
- se::Stream* device_to_host_stream_;
+ std::shared_ptr<se::Stream> device_to_host_stream_;
// For the underlying memory allocator and XLA's TransferManager.
xla::LocalClient* client_;
// Transfer manager, for marshalling data to and from the device.
@@ -87,6 +89,9 @@ class XlaTransferManager {
// True if we must use XLA's TransferManager for correct device transfers.
const bool transfer_as_literal_;
XlaCompiler::ShapeRepresentationFn shape_representation_fn_;
+
+ // Thread pool used for running closures
+ thread::ThreadPool* thread_pool_;
};
// DeviceContext for operators assigned to XlaDevice devices. The
@@ -95,10 +100,12 @@ class XlaTransferManager {
class XlaDeviceContext : public DeviceContext {
public:
explicit XlaDeviceContext(
- se::Stream* compute_stream, se::Stream* host_to_device_stream,
- se::Stream* device_to_host_stream, xla::LocalClient* client,
- bool transfer_as_literal,
- XlaCompiler::ShapeRepresentationFn shape_representation_fn);
+ std::shared_ptr<se::Stream> compute_stream,
+ std::shared_ptr<se::Stream> host_to_device_stream,
+ std::shared_ptr<se::Stream> device_to_host_stream,
+ xla::LocalClient* client, bool transfer_as_literal,
+ XlaCompiler::ShapeRepresentationFn shape_representation_fn,
+ thread::ThreadPool* thread_pool);
void CopyCPUTensorToDevice(const Tensor* cpu_tensor, Device* device,
Tensor* device_tensor,
diff --git a/tensorflow/compiler/jit/xla_launch_util.cc b/tensorflow/compiler/jit/xla_launch_util.cc
index 6134b8c694..4efbb2d5d7 100644
--- a/tensorflow/compiler/jit/xla_launch_util.cc
+++ b/tensorflow/compiler/jit/xla_launch_util.cc
@@ -15,6 +15,8 @@ limitations under the License.
#include "tensorflow/compiler/jit/xla_launch_util.h"
+#include <memory>
+
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
@@ -182,7 +184,7 @@ void XlaComputationLaunchContext::PopulateInputs(
}
}
-void XlaComputationLaunchContext::PopulateOutputs(
+Status XlaComputationLaunchContext::PopulateOutputs(
OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel,
ScopedShapedBuffer output) {
se::Stream* stream =
@@ -211,6 +213,15 @@ void XlaComputationLaunchContext::PopulateOutputs(
output = ScopedShapedBuffer(std::move(buffer), output.memory_allocator());
}
+ std::shared_ptr<se::Event> definition_event;
+ if (use_multiple_streams_) {
+ definition_event = std::make_shared<se::Event>(stream->parent());
+ if (!definition_event->Init()) {
+ return errors::Internal("Failed to initialize tensor definition event.");
+ }
+ stream->ThenRecordEvent(definition_event.get());
+ }
+
// Copy XLA results to the OpOutputList.
int output_num = 0;
for (int i = 0; i < ctx->num_outputs(); ++i) {
@@ -228,12 +239,13 @@ void XlaComputationLaunchContext::PopulateOutputs(
// reallocate the device buffer later.
VLOG(1) << "Constant output tensor on device";
- OP_REQUIRES_OK(
- ctx, ctx->allocate_output(i, const_tensor.shape(), &output_tensor));
+ TF_RETURN_IF_ERROR(
+ ctx->allocate_output(i, const_tensor.shape(), &output_tensor));
Device* device = dynamic_cast<Device*>(ctx->device());
- OP_REQUIRES(ctx, device != nullptr,
- errors::Internal("DeviceBase was not a Device."));
+ if (device == nullptr) {
+ return errors::Internal("DeviceBase was not a Device.");
+ }
ctx->op_device_context()->CopyCPUTensorToDevice(
&const_tensor, device, output_tensor,
[&](Status status) { TF_CHECK_OK(status); });
@@ -263,16 +275,13 @@ void XlaComputationLaunchContext::PopulateOutputs(
se::DeviceMemoryBase buffer = output.buffer({output_num});
if (allocate_xla_tensors_) {
Tensor* output_tensor;
- OP_REQUIRES_OK(ctx, ctx->allocate_output(i, shape, &output_tensor));
+ TF_RETURN_IF_ERROR(ctx->allocate_output(i, shape, &output_tensor));
XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor);
if (xla_tensor) {
xla_tensor->set_shaped_buffer(ScopedShapedBuffer(
ExtractSubShapedBuffer(&output, output_num, xla_allocator_)));
if (use_multiple_streams_) {
- se::Event event(stream->parent());
- CHECK(event.Init());
- stream->ThenRecordEvent(&event);
- xla_tensor->SetDefinedOn(stream, std::move(event));
+ xla_tensor->SetDefinedOn(stream, definition_event);
}
} else {
// xla_tensor wasn't valid, which must mean this is a zero-element
@@ -298,41 +307,39 @@ void XlaComputationLaunchContext::PopulateOutputs(
for (int i = 0; i < kernel->resource_updates.size(); ++i) {
Allocator* allocator = ctx->device()->GetAllocator({});
const XlaCompiler::ResourceUpdate& write = kernel->resource_updates[i];
- OP_REQUIRES(ctx,
- write.input_index >= 0 && write.input_index < ctx->num_inputs(),
- errors::Internal("Invalid input index for variable write."));
+ if (write.input_index < 0 || write.input_index >= ctx->num_inputs()) {
+ return errors::Internal("Invalid input index for variable write.");
+ }
se::DeviceMemoryBase buffer = output.buffer({output_num});
Var* variable = nullptr;
// TODO(b/35625933): tensorflow::Var should contain a PersistentTensor,
// not a Tensor.
- OP_REQUIRES_OK(ctx, LookupOrCreateResource<Var>(
- ctx, HandleFromInput(ctx, write.input_index),
- &variable, [this, ctx, &write](Var** ptr) {
- *ptr = new Var(write.type);
- return Status::OK();
- }));
+ TF_RETURN_IF_ERROR(LookupOrCreateResource<Var>(
+ ctx, HandleFromInput(ctx, write.input_index), &variable,
+ [&write](Var** ptr) {
+ *ptr = new Var(write.type);
+ return Status::OK();
+ }));
core::ScopedUnref s(variable);
mutex_lock ml(*variable->mu());
- OP_REQUIRES(ctx, variable->tensor()->dtype() == write.type,
- errors::Internal("Mismatched type in variable write"));
+ if (variable->tensor()->dtype() != write.type) {
+ return errors::Internal("Mismatched type in variable write");
+ }
if (allocate_xla_tensors_) {
Tensor output_tensor;
- OP_REQUIRES_OK(
- ctx, ctx->allocate_temp(write.type, write.shape, &output_tensor));
+ TF_RETURN_IF_ERROR(
+ ctx->allocate_temp(write.type, write.shape, &output_tensor));
XlaTensor* xla_tensor = XlaTensor::FromTensor(&output_tensor);
CHECK(xla_tensor);
xla_tensor->set_shaped_buffer(
ExtractSubShapedBuffer(&output, output_num, xla_allocator_));
if (use_multiple_streams_) {
- se::Event event(stream->parent());
- CHECK(event.Init());
- stream->ThenRecordEvent(&event);
- xla_tensor->SetDefinedOn(stream, std::move(event));
+ xla_tensor->SetDefinedOn(stream, definition_event);
}
*variable->tensor() = output_tensor;
} else {
@@ -343,6 +350,7 @@ void XlaComputationLaunchContext::PopulateOutputs(
}
++output_num;
}
+ return Status::OK();
}
} // namespace tensorflow
diff --git a/tensorflow/compiler/jit/xla_launch_util.h b/tensorflow/compiler/jit/xla_launch_util.h
index 1ea3fa4cf2..4232f514b3 100644
--- a/tensorflow/compiler/jit/xla_launch_util.h
+++ b/tensorflow/compiler/jit/xla_launch_util.h
@@ -93,9 +93,9 @@ class XlaComputationLaunchContext {
const std::map<int, OptionalTensor>& variables);
// Given the XLA output in `output`, populate all outputs of `ctx`.
- void PopulateOutputs(OpKernelContext* ctx,
- const XlaCompiler::CompilationResult* kernel,
- xla::ScopedShapedBuffer output);
+ Status PopulateOutputs(OpKernelContext* ctx,
+ const XlaCompiler::CompilationResult* kernel,
+ xla::ScopedShapedBuffer output);
// Return the argument list. Only valid after PopulateInputs() has been
// called.
diff --git a/tensorflow/compiler/jit/xla_tensor.cc b/tensorflow/compiler/jit/xla_tensor.cc
index d777dfa5a3..92ba7de1b7 100644
--- a/tensorflow/compiler/jit/xla_tensor.cc
+++ b/tensorflow/compiler/jit/xla_tensor.cc
@@ -75,7 +75,7 @@ Status XlaTensor::AllocateShapedBuffer(DataType dtype, const TensorShape& shape,
se::Event* XlaTensor::GetDefinitionEvent(se::Stream* stream) {
mutex_lock lock(mu_);
- if (!definition_event_.has_value()) {
+ if (!definition_event_) {
return nullptr;
}
@@ -87,10 +87,11 @@ se::Event* XlaTensor::GetDefinitionEvent(se::Stream* stream) {
return nullptr;
}
- return &*definition_event_;
+ return definition_event_.get();
}
-void XlaTensor::SetDefinedOn(se::Stream* stream, se::Event event) {
+void XlaTensor::SetDefinedOn(se::Stream* stream,
+ std::shared_ptr<se::Event> event) {
mutex_lock lock(mu_);
definition_event_ = std::move(event);
streams_defined_on_ = {stream};
diff --git a/tensorflow/compiler/jit/xla_tensor.h b/tensorflow/compiler/jit/xla_tensor.h
index f7e401c731..8d36d0fa0a 100644
--- a/tensorflow/compiler/jit/xla_tensor.h
+++ b/tensorflow/compiler/jit/xla_tensor.h
@@ -16,6 +16,8 @@ limitations under the License.
#ifndef TENSORFLOW_COMPILER_JIT_XLA_TENSOR_H_
#define TENSORFLOW_COMPILER_JIT_XLA_TENSOR_H_
+#include <memory>
+
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/service/shaped_buffer.h"
#include "tensorflow/core/framework/allocator.h"
@@ -94,7 +96,7 @@ class XlaTensor {
// Assert that the tensor's content is defined on 'stream' by the time 'event'
// triggers.
- void SetDefinedOn(se::Stream* stream, se::Event event);
+ void SetDefinedOn(se::Stream* stream, std::shared_ptr<se::Event> event);
// Assert that the tensor's content is defined on 'stream'. This version does
// not provide an event, and must be called *after* SetDefinedOn(Stream,
@@ -116,7 +118,7 @@ class XlaTensor {
// An optional event that is triggered when the tensor's content has been
// defined. If this event is nullptr, it is assumed that the tensor's content
// is always defined.
- gtl::optional<se::Event> definition_event_;
+ std::shared_ptr<se::Event> definition_event_;
// A list of all streams for which the tensor's content is defined for any
// newly enqueued command.
gtl::InlinedVector<se::Stream*, 2> streams_defined_on_ GUARDED_BY(mu_);
diff --git a/tensorflow/compiler/tests/adam_test.py b/tensorflow/compiler/tests/adam_test.py
index 03554d6933..0d2e4d0296 100644
--- a/tensorflow/compiler/tests/adam_test.py
+++ b/tensorflow/compiler/tests/adam_test.py
@@ -52,6 +52,9 @@ class AdamOptimizerTest(xla_test.XLATestCase):
def testBasic(self):
for dtype in self.float_types:
+ # TODO: test fails for float16 due to excessive precision requirements.
+ if dtype == np.float16:
+ continue
with self.test_session(), self.test_scope():
variable_scope.get_variable_scope().set_use_resource(True)
@@ -91,6 +94,9 @@ class AdamOptimizerTest(xla_test.XLATestCase):
def testTensorLearningRate(self):
for dtype in self.float_types:
+ # TODO: test fails for float16 due to excessive precision requirements.
+ if dtype == np.float16:
+ continue
with self.test_session(), self.test_scope():
variable_scope.get_variable_scope().set_use_resource(True)
@@ -130,6 +136,9 @@ class AdamOptimizerTest(xla_test.XLATestCase):
def testSharing(self):
for dtype in self.float_types:
+ # TODO: test fails for float16 due to excessive precision requirements.
+ if dtype == np.float16:
+ continue
with self.test_session(), self.test_scope():
variable_scope.get_variable_scope().set_use_resource(True)
diff --git a/tensorflow/compiler/tests/binary_ops_test.py b/tensorflow/compiler/tests/binary_ops_test.py
index 0aafda7fb4..5b7001b5a4 100644
--- a/tensorflow/compiler/tests/binary_ops_test.py
+++ b/tensorflow/compiler/tests/binary_ops_test.py
@@ -1167,6 +1167,16 @@ class BinaryOpsTest(xla_test.XLATestCase):
for dtype in self.numeric_types:
self._testBinary(
array_ops.tile,
+ np.array([[6], [3], [4]], dtype=dtype),
+ np.array([2, 0], dtype=np.int32),
+ expected=np.empty([6, 0], dtype=dtype))
+ self._testBinary(
+ array_ops.tile,
+ np.array([[6, 3, 4]], dtype=dtype),
+ np.array([2, 0], dtype=np.int32),
+ expected=np.empty([2, 0], dtype=dtype))
+ self._testBinary(
+ array_ops.tile,
np.array([[6]], dtype=dtype),
np.array([1, 2], dtype=np.int32),
expected=np.array([[6, 6]], dtype=dtype))
diff --git a/tensorflow/compiler/tests/eager_test.py b/tensorflow/compiler/tests/eager_test.py
index 422f36d43b..3d21fb5864 100644
--- a/tensorflow/compiler/tests/eager_test.py
+++ b/tensorflow/compiler/tests/eager_test.py
@@ -32,6 +32,7 @@ from tensorflow.python.layers import convolutional
from tensorflow.python.layers import pooling
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import embedding_ops
+from tensorflow.python.ops import gen_random_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
@@ -122,6 +123,14 @@ class EagerTest(xla_test.XLATestCase):
with self.test_scope():
self.assertAllEqual(2, array_ops.identity(2))
+ def testRandomOps(self):
+ with self.test_scope():
+ tensor = gen_random_ops.random_uniform((2, 2), dtypes.float32)
+ row0 = tensor[0].numpy()
+ row1 = tensor[1].numpy()
+ # It should be very unlikely to rng to generate two equal rows.
+ self.assertFalse((row0 == row1).all())
+
def testIdentityOnVariable(self):
with self.test_scope():
v = resource_variable_ops.ResourceVariable(True)
@@ -434,7 +443,6 @@ class EagerFunctionTest(xla_test.XLATestCase):
self.assertAllEqual((2, 3, 4), dz.shape.as_list())
def testNestedDefun(self):
- self.skipTest('Nested defuns do not work on TPU at the moment')
with self.test_scope():
@function.defun
diff --git a/tensorflow/compiler/tests/random_ops_test.py b/tensorflow/compiler/tests/random_ops_test.py
index cc0e9b2f98..8c4e16e4e0 100644
--- a/tensorflow/compiler/tests/random_ops_test.py
+++ b/tensorflow/compiler/tests/random_ops_test.py
@@ -101,7 +101,7 @@ class RandomOpsTest(xla_test.XLATestCase):
for dtype in [dtypes.float32]:
with self.test_session() as sess:
with self.test_scope():
- x = random_ops.truncated_normal(shape=[count], dtype=dtype, seed=42)
+ x = random_ops.truncated_normal(shape=[count], dtype=dtype)
y = sess.run(x)
def normal_cdf(x):
@@ -130,24 +130,18 @@ class RandomOpsTest(xla_test.XLATestCase):
# Department of Scientific Computing website. Florida State University.
expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma
actual_mean = np.mean(y)
- atol = 2e-4
- if self.device in ["XLA_GPU", "XLA_CPU"]:
- atol = 2.2e-4
- self.assertAllClose(actual_mean, expected_mean, atol=atol)
+ self.assertAllClose(actual_mean, expected_mean, atol=2e-3)
expected_median = mu + probit(
(normal_cdf(alpha) + normal_cdf(beta)) / 2.) * sigma
actual_median = np.median(y)
- self.assertAllClose(actual_median, expected_median, atol=1e-3)
+ self.assertAllClose(actual_median, expected_median, atol=1e-2)
expected_variance = sigma**2 * (1 + (
(alpha * normal_pdf(alpha) - beta * normal_pdf(beta)) / z) - (
(normal_pdf(alpha) - normal_pdf(beta)) / z)**2)
actual_variance = np.var(y)
- rtol = 1e-3
- if self.device in ["XLA_GPU", "XLA_CPU"]:
- rtol = 4e-4
- self.assertAllClose(actual_variance, expected_variance, rtol=rtol)
+ self.assertAllClose(actual_variance, expected_variance, rtol=2*1e-3)
def testShuffle1d(self):
# TODO(b/26783907): this test requires the CPU backend to implement sort.
diff --git a/tensorflow/compiler/tests/reverse_ops_test.py b/tensorflow/compiler/tests/reverse_ops_test.py
index d01c676e7c..32ab5d08f0 100644
--- a/tensorflow/compiler/tests/reverse_ops_test.py
+++ b/tensorflow/compiler/tests/reverse_ops_test.py
@@ -32,14 +32,20 @@ class ReverseOpsTest(xla_test.XLATestCase):
def testReverseOneDim(self):
shape = (7, 5, 9, 11)
- for revdim in range(len(shape)):
+ for revdim in range(-len(shape), len(shape)):
self._AssertReverseEqual([revdim], shape)
def testReverseMoreThanOneDim(self):
shape = (7, 5, 9, 11)
+ # The offset is used to test various (but not all) combinations of negative
+ # and positive axis indices that are guaranteed to not collide at the same
+ # index.
for revdims in itertools.chain.from_iterable(
- itertools.combinations(range(len(shape)), k)
- for k in range(2, len(shape)+1)):
+ itertools.combinations(range(-offset,
+ len(shape) - offset), k)
+ for k in range(2,
+ len(shape) + 1)
+ for offset in range(0, len(shape))):
self._AssertReverseEqual(revdims, shape)
def _AssertReverseEqual(self, revdims, shape):
@@ -50,15 +56,16 @@ class ReverseOpsTest(xla_test.XLATestCase):
p = array_ops.placeholder(dtypes.int32, shape=shape)
axis = constant_op.constant(
np.array(revdims, dtype=np.int32),
- shape=(len(revdims),), dtype=dtypes.int32)
+ shape=(len(revdims),),
+ dtype=dtypes.int32)
rval = array_ops.reverse(p, axis).eval({p: pval})
slices = [
- slice(-1, None, -1) if d in revdims else slice(None)
- for d in range(len(shape))]
- self.assertEqual(
- pval[slices].flatten().tolist(),
- rval.flatten().tolist())
+ slice(-1, None, -1)
+ if d in revdims or d - len(shape) in revdims else slice(None)
+ for d in range(len(shape))
+ ]
+ self.assertEqual(pval[slices].flatten().tolist(), rval.flatten().tolist())
if __name__ == '__main__':
diff --git a/tensorflow/compiler/tests/unary_ops_test.py b/tensorflow/compiler/tests/unary_ops_test.py
index 73adb0d243..124cf9da81 100644
--- a/tensorflow/compiler/tests/unary_ops_test.py
+++ b/tensorflow/compiler/tests/unary_ops_test.py
@@ -398,6 +398,11 @@ class UnaryOpsTest(xla_test.XLATestCase):
self._assertOpOutputMatchesExpected(
math_ops.lgamma,
+ np.array(0.5, dtype=dtype),
+ expected=np.array(np.log(np.pi) / 2, dtype=dtype))
+
+ self._assertOpOutputMatchesExpected(
+ math_ops.lgamma,
np.array(
[[1, 2, 3], [4, 5, 6], [1 / 2, 3 / 2, 5 / 2],
[-3 / 2, -7 / 2, -11 / 2]],
@@ -420,6 +425,19 @@ class UnaryOpsTest(xla_test.XLATestCase):
],
dtype=dtype))
+ # The actual result is complex. Take the real part.
+ self._assertOpOutputMatchesExpected(
+ math_ops.lgamma,
+ np.array([-1 / 2, -5 / 2, -9 / 2], dtype=dtype),
+ expected=np.array(
+ [
+ np.log(np.pi) / 2 + np.log(2),
+ np.log(np.pi) / 2 - np.log(15) + np.log(8),
+ np.log(np.pi) / 2 - np.log(945) + np.log(32),
+ ],
+ dtype=dtype),
+ atol=1e-4)
+
self._assertOpOutputMatchesExpected(
math_ops.digamma,
np.array(
diff --git a/tensorflow/compiler/tf2xla/BUILD b/tensorflow/compiler/tf2xla/BUILD
index 61759fd276..c4fdaef940 100644
--- a/tensorflow/compiler/tf2xla/BUILD
+++ b/tensorflow/compiler/tf2xla/BUILD
@@ -95,6 +95,10 @@ cc_library(
name = "cpu_function_runtime",
srcs = ["cpu_function_runtime.cc"],
hdrs = ["cpu_function_runtime.h"],
+ visibility = [
+ "//tensorflow/compiler/aot:__pkg__",
+ "//tensorflow/compiler/xla/service/cpu:__pkg__",
+ ],
deps = [
# Keep dependencies to a minimum here; this library is used in every AOT
# binary produced by tfcompile.
@@ -144,6 +148,7 @@ cc_library(
"//tensorflow/compiler/xla/client:local_client",
"//tensorflow/compiler/xla/client:xla_computation",
"//tensorflow/compiler/xla/service:cpu_plugin",
+ "//tensorflow/compiler/xla/service/cpu:buffer_info_util",
"//tensorflow/compiler/xla/service/cpu:cpu_executable",
"//tensorflow/core:lib",
"//tensorflow/core:protos_all_cc",
@@ -438,10 +443,83 @@ cc_library(
)
cc_library(
+ name = "functionalize_control_flow_util",
+ srcs = [
+ "functionalize_control_flow_util.cc",
+ ],
+ hdrs = [
+ "functionalize_control_flow_util.h",
+ ],
+ deps = [
+ "//tensorflow/compiler/tf2xla/ops:xla_ops",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:core_cpu_internal",
+ "//tensorflow/core:graph",
+ "//tensorflow/core:protos_all_cc",
+ ],
+)
+
+cc_library(
+ name = "functionalize_cond",
+ srcs = [
+ "functionalize_cond.cc",
+ ],
+ hdrs = [
+ "functionalize_cond.h",
+ ],
+ deps = [
+ ":functionalize_control_flow_util",
+ ":tf2xla_util",
+ "//tensorflow/compiler/jit:union_find",
+ "//tensorflow/compiler/tf2xla:dump_graph",
+ "//tensorflow/compiler/tf2xla/ops:xla_ops",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/compiler/xla:util",
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:core_cpu_internal",
+ "//tensorflow/core:framework",
+ "//tensorflow/core:graph",
+ "//tensorflow/core:lib",
+ ],
+)
+
+cc_library(
name = "functionalize_control_flow",
- srcs = ["functionalize_control_flow.cc"],
- hdrs = ["functionalize_control_flow.h"],
+ srcs = [
+ "functionalize_control_flow.cc",
+ ],
+ hdrs = [
+ "functionalize_control_flow.h",
+ ],
deps = [
+ ":functionalize_cond",
+ ":functionalize_control_flow_util",
+ ":functionalize_while",
+ ":tf2xla_util",
+ "//tensorflow/compiler/jit:union_find",
+ "//tensorflow/compiler/tf2xla:dump_graph",
+ "//tensorflow/compiler/tf2xla/ops:xla_ops",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/compiler/xla:util",
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:core_cpu_internal",
+ "//tensorflow/core:framework",
+ "//tensorflow/core:graph",
+ "//tensorflow/core:lib",
+ ],
+)
+
+cc_library(
+ name = "functionalize_while",
+ srcs = [
+ "functionalize_while.cc",
+ ],
+ hdrs = [
+ "functionalize_while.h",
+ ],
+ deps = [
+ ":functionalize_control_flow_util",
":tf2xla_util",
"//tensorflow/compiler/jit:union_find",
"//tensorflow/compiler/tf2xla:dump_graph",
@@ -480,6 +558,32 @@ tf_cc_test(
],
)
+tf_cc_test(
+ name = "functionalize_cond_test",
+ srcs = ["functionalize_cond_test.cc"],
+ deps = [
+ ":functionalize_cond",
+ ":functionalize_control_flow",
+ ":test_util",
+ "//tensorflow/cc:cc_ops",
+ "//tensorflow/cc:cc_ops_internal",
+ "//tensorflow/cc:function_ops",
+ "//tensorflow/cc:ops",
+ "//tensorflow/cc:resource_variable_ops",
+ "//tensorflow/compiler/tf2xla/cc:xla_ops",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:core_cpu_internal",
+ "//tensorflow/core:framework",
+ "//tensorflow/core:framework_internal",
+ "//tensorflow/core:ops",
+ "//tensorflow/core:resource_variable_ops_op_lib",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ "//tensorflow/core:testlib",
+ ],
+)
+
cc_library(
name = "test_util",
testonly = 1,
diff --git a/tensorflow/compiler/tf2xla/cpu_function_runtime.cc b/tensorflow/compiler/tf2xla/cpu_function_runtime.cc
index 2ffad2af8c..fcc4095e39 100644
--- a/tensorflow/compiler/tf2xla/cpu_function_runtime.cc
+++ b/tensorflow/compiler/tf2xla/cpu_function_runtime.cc
@@ -55,19 +55,26 @@ size_t align_to(size_t n, size_t align) {
} // namespace
namespace cpu_function_runtime {
-size_t AlignedBufferBytes(const intptr_t* sizes, size_t n) {
+size_t AlignedBufferBytes(const BufferInfo* buffer_infos, size_t n,
+ bool allocate_entry_params) {
size_t total = 0;
for (size_t i = 0; i < n; ++i) {
- if (sizes[i] > 0) {
- total += align_to(sizes[i], kAlign);
+ bool should_allocate =
+ buffer_infos[i].is_temp_buffer() ||
+ (buffer_infos[i].is_entry_parameter() && allocate_entry_params);
+
+ if (should_allocate) {
+ total += align_to(buffer_infos[i].size(), kAlign);
}
}
return total;
}
-void* MallocContiguousBuffers(const intptr_t* sizes, size_t n, void** bufs,
+void* MallocContiguousBuffers(const BufferInfo* buffer_infos, size_t n,
+ bool allocate_entry_params, void** bufs,
bool annotate_initialized) {
- const size_t total = AlignedBufferBytes(sizes, n);
+ const size_t total =
+ AlignedBufferBytes(buffer_infos, n, allocate_entry_params);
void* contiguous = nullptr;
if (total > 0) {
contiguous = aligned_malloc(total, kAlign);
@@ -79,13 +86,14 @@ void* MallocContiguousBuffers(const intptr_t* sizes, size_t n, void** bufs,
}
uintptr_t pos = reinterpret_cast<uintptr_t>(contiguous);
for (size_t i = 0; i < n; ++i) {
- if (sizes[i] < 0) {
- // bufs[i] is either a constant, an entry parameter or a thread local
- // allocation.
- bufs[i] = nullptr;
- } else {
+ bool should_allocate =
+ buffer_infos[i].is_temp_buffer() ||
+ (buffer_infos[i].is_entry_parameter() && allocate_entry_params);
+ if (should_allocate) {
bufs[i] = reinterpret_cast<void*>(pos);
- pos += align_to(sizes[i], kAlign);
+ pos += align_to(buffer_infos[i].size(), kAlign);
+ } else {
+ bufs[i] = nullptr;
}
}
return contiguous;
diff --git a/tensorflow/compiler/tf2xla/cpu_function_runtime.h b/tensorflow/compiler/tf2xla/cpu_function_runtime.h
index c7b4559c65..dfc1e8b8ae 100644
--- a/tensorflow/compiler/tf2xla/cpu_function_runtime.h
+++ b/tensorflow/compiler/tf2xla/cpu_function_runtime.h
@@ -18,29 +18,142 @@ limitations under the License.
#include "tensorflow/core/platform/types.h"
+#include <cassert>
+
namespace tensorflow {
namespace cpu_function_runtime {
+// Stores information about one buffer used by an XLA:CPU compiled function.
+// These buffers are used for holding inputs to the computation, outputs from
+// the computation and as temporary scratch space.
+class BufferInfo {
+ public:
+ // Creates a BufferInfo from a serialized encoding generated by `Encode`.
+ explicit BufferInfo(std::pair<uint64, uint64> encoding)
+ : entry_param_number_(encoding.second) {
+ Kind kind;
+ uint64 size;
+ Unpack(encoding.first, &kind, &size);
+ kind_ = kind;
+ size_ = size;
+ }
+
+ // Returns true if this buffer stores a constant. These never need to be
+ // allocated by the runtime.
+ bool is_constant() const { return kind() == Kind::kConstant; }
+
+ // Returns true if this buffer stores an entry parameter. These may or may
+ // not need to be allocated by the runtime, depending on
+ // XlaCompiledCpuFunction::AllocMode.
+ bool is_entry_parameter() const { return kind() == Kind::kEntryParameter; }
+
+ // Returns the entry parameter number of this buffer.
+ uint64 entry_parameter_number() const {
+ assert(is_entry_parameter());
+ return entry_param_number_;
+ }
+
+ // Returns true if this buffer is temporary scratch space required by the XLA
+ // computations. These are always allocated by the runtime.
+ bool is_temp_buffer() const { return kind() == Kind::kTempBuffer; }
+
+ // Returns true if this buffer is allocated on the C stack or into registers.
+ // These buffers are never allocated by the runtime.
+ bool is_on_stack_buffer() const { return kind() == Kind::kOnStackBuffer; }
+
+ // Returns the size for this buffer.
+ uint64 size() const { return size_; }
+
+ // Encodes this BufferInfo into two 64 bit integers that can be used to
+ // reconstruct the BufferInfo later using the constructor. We need this
+ // because we use BufferInfo in places where using protocol buffers would
+ // negatively impact binary size.
+ std::pair<uint64, uint64> Encode() const {
+ static_assert(sizeof(*this) == 16, "");
+ uint64 upper = Pack(kind(), size_);
+ uint64 lower = entry_param_number_;
+ return {upper, lower};
+ }
+
+ bool operator==(const BufferInfo& buffer_info) const {
+ if (kind() != buffer_info.kind() || size() != buffer_info.size()) {
+ return false;
+ }
+ return !is_entry_parameter() ||
+ entry_parameter_number() == buffer_info.entry_parameter_number();
+ }
+
+ // Factory methods:
+
+ static BufferInfo MakeTempBuffer(uint64 size) {
+ return BufferInfo(Kind::kTempBuffer, /*size=*/size,
+ /*entry_param_number=*/-1);
+ }
+ static BufferInfo MakeConstant(uint64 size) {
+ return BufferInfo(Kind::kConstant, /*size=*/size,
+ /*entry_param_number=*/-1);
+ }
+ static BufferInfo MakeEntryParameter(uint64 size, uint64 param_number) {
+ return BufferInfo(Kind::kEntryParameter, /*size=*/size,
+ /*entry_param_number=*/param_number);
+ }
+ static BufferInfo MakeOnStackBuffer(uint64 size) {
+ return BufferInfo(Kind::kOnStackBuffer, /*size=*/size,
+ /*entry_param_number=*/-1);
+ }
+
+ private:
+ BufferInfo() = default;
+
+ enum class Kind : unsigned {
+ kConstant,
+ kTempBuffer,
+ kEntryParameter,
+ kOnStackBuffer
+ };
+
+ Kind kind() const { return static_cast<Kind>(kind_); }
+
+ explicit BufferInfo(Kind kind, uint64 size, uint64 entry_param_number)
+ : kind_(kind), size_(size), entry_param_number_(entry_param_number) {}
+
+ static uint64 Pack(Kind kind, uint64 size) {
+ return (static_cast<uint64>(size) << 2) | static_cast<uint64>(kind);
+ }
+
+ static void Unpack(uint64 packed, Kind* kind, uint64* size) {
+ *size = packed >> 2;
+ *kind = static_cast<Kind>((packed << 62) >> 62);
+ }
+
+ Kind kind_ : 2;
+ uint64 size_ : 62;
+ int64 entry_param_number_;
+};
// Align to 64-bytes, to mimic tensorflow::Allocator::kAllocatorAlignment.
constexpr size_t kAlign = 64;
-// AlignedBufferBytes returns the sum of each size in `sizes`, skipping -1
-// values. There are `n` entries in `sizes`. Each buffer is aligned to
-// kAlign byte boundaries.
-size_t AlignedBufferBytes(const intptr_t* sizes, size_t n);
+// AlignedBufferBytes returns the sum of the size of each buffer in
+// `buffer_infos`, skipping constants, on-stack buffers and, if
+// allocate_entry_params is false, entry parameters. There are `n` entries in
+// `buffer_infos`. Each buffer is aligned to kAlign byte boundaries.
+size_t AlignedBufferBytes(const BufferInfo* buffer_infos, size_t n,
+ bool allocate_entry_params);
// MallocContiguousBuffers allocates buffers for use by the entry point
-// generated by tfcompile. `sizes` is an array of byte sizes for each buffer,
-// where -1 causes the buffer pointer to be nullptr. There are `n` entries in
-// `sizes`. If `annotate_initialized` is set, the allocated memory will be
-// annotated as having been initialized - this is useful when allocating
-// temporary buffers.
+// generated by tfcompile. There are `n` entries in `buffer_infos`. If
+// `annotate_initialized` is set, the allocated memory will be annotated as
+// having been initialized - this is useful when allocating temporary buffers.
+// If allocate_entry_params is true then allocates temp buffers and entry
+// parameters, otherwise allocated only temp buffers. Slots in `bufs`
+// corresponding to unallocated buffers are set to nullptr.
//
// A single contiguous block of memory is allocated, and portions of it are
// parceled out into `bufs`, which must have space for `n` entries. Returns
// the head of the allocated contiguous block, which should be passed to
// FreeContiguous when the buffers are no longer in use.
-void* MallocContiguousBuffers(const intptr_t* sizes, size_t n, void** bufs,
+void* MallocContiguousBuffers(const BufferInfo* buffer_infos, size_t n,
+ bool allocate_entry_params, void** bufs,
bool annotate_initialized);
// FreeContiguous frees the contiguous block of memory allocated by
diff --git a/tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc b/tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc
index f4f27a1562..8ca628c4eb 100644
--- a/tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc
+++ b/tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc
@@ -21,6 +21,8 @@ limitations under the License.
namespace tensorflow {
namespace {
+using cpu_function_runtime::BufferInfo;
+
TEST(XlaCompiledCpuFunctionTest, AlignmentValue) {
// We've chosen 64 byte alignment for the tfcompile runtime to mimic the
// regular tensorflow allocator, which was chosen to play nicely with Eigen.
@@ -30,20 +32,51 @@ TEST(XlaCompiledCpuFunctionTest, AlignmentValue) {
EXPECT_EQ(cpu_function_runtime::kAlign, Allocator::kAllocatorAlignment);
}
+std::vector<BufferInfo> SizesToBufferInfos(const intptr_t* sizes, size_t n) {
+ std::vector<BufferInfo> buffer_infos;
+ std::transform(sizes, sizes + n, std::back_inserter(buffer_infos),
+ [&](intptr_t size) {
+ if (size == -1) {
+ // Use a dummy on-stack buffer allocation to indicat the
+ // the current slot does not need an allocation.
+ int64 on_stack_buffer_size = 4;
+ return BufferInfo::MakeOnStackBuffer(on_stack_buffer_size);
+ }
+ return BufferInfo::MakeTempBuffer(size);
+ });
+ return buffer_infos;
+}
+
+// Simple wrappers to make writing tests more ergonomic.
+
+size_t AlignedBufferBytesFromSizes(const intptr_t* sizes, size_t n) {
+ std::vector<BufferInfo> buffer_infos = SizesToBufferInfos(sizes, n);
+ return AlignedBufferBytes(buffer_infos.data(), n,
+ /*allocate_entry_params=*/false);
+}
+
+void* MallocContiguousBuffersFromSizes(const intptr_t* sizes, size_t n,
+ void** bufs, bool annotate_initialized) {
+ std::vector<BufferInfo> buffer_infos = SizesToBufferInfos(sizes, n);
+ return MallocContiguousBuffers(buffer_infos.data(), n,
+ /*allocate_entry_params=*/false, bufs,
+ annotate_initialized);
+}
+
TEST(XlaCompiledCpuFunctionTest, AlignedBufferBytes) {
- EXPECT_EQ(cpu_function_runtime::AlignedBufferBytes(nullptr, 0), 0);
+ EXPECT_EQ(AlignedBufferBytesFromSizes(nullptr, 0), 0);
static constexpr intptr_t sizesA[1] = {-1};
- EXPECT_EQ(cpu_function_runtime::AlignedBufferBytes(sizesA, 1), 0);
+ EXPECT_EQ(AlignedBufferBytesFromSizes(sizesA, 1), 0);
static constexpr intptr_t sizesB[1] = {3};
- EXPECT_EQ(cpu_function_runtime::AlignedBufferBytes(sizesB, 1), 64);
+ EXPECT_EQ(AlignedBufferBytesFromSizes(sizesB, 1), 64);
static constexpr intptr_t sizesC[1] = {32};
- EXPECT_EQ(cpu_function_runtime::AlignedBufferBytes(sizesC, 1), 64);
+ EXPECT_EQ(AlignedBufferBytesFromSizes(sizesC, 1), 64);
static constexpr intptr_t sizesD[7] = {1, -1, 32, -1, 64, 2, 3};
- EXPECT_EQ(cpu_function_runtime::AlignedBufferBytes(sizesD, 7), 320);
+ EXPECT_EQ(AlignedBufferBytesFromSizes(sizesD, 7), 320);
}
void* add_ptr(void* base, uintptr_t delta) {
@@ -56,15 +89,14 @@ void* add_ptr(void* base, uintptr_t delta) {
// free. We also check the contiguous property.
TEST(XlaCompiledCpuFunctionTest, MallocFreeContiguousBuffers) {
// Test empty sizes.
- void* base =
- cpu_function_runtime::MallocContiguousBuffers(nullptr, 0, nullptr, false);
+ void* base = MallocContiguousBuffersFromSizes(nullptr, 0, nullptr, false);
EXPECT_EQ(base, nullptr);
cpu_function_runtime::FreeContiguous(base);
// Test non-empty sizes with 0 sum.
static constexpr intptr_t sizesA[1] = {-1};
void* bufA[1];
- base = cpu_function_runtime::MallocContiguousBuffers(sizesA, 1, bufA, false);
+ base = MallocContiguousBuffersFromSizes(sizesA, 1, bufA, false);
EXPECT_EQ(base, nullptr);
EXPECT_EQ(bufA[0], nullptr);
cpu_function_runtime::FreeContiguous(base);
@@ -72,7 +104,7 @@ TEST(XlaCompiledCpuFunctionTest, MallocFreeContiguousBuffers) {
// Test non-empty sizes with non-0 sum.
static constexpr intptr_t sizesB[1] = {3};
void* bufB[1];
- base = cpu_function_runtime::MallocContiguousBuffers(sizesB, 1, bufB, false);
+ base = MallocContiguousBuffersFromSizes(sizesB, 1, bufB, false);
EXPECT_NE(base, nullptr);
EXPECT_EQ(bufB[0], add_ptr(base, 0));
char* bufB0_bytes = static_cast<char*>(bufB[0]);
@@ -84,7 +116,7 @@ TEST(XlaCompiledCpuFunctionTest, MallocFreeContiguousBuffers) {
// Test non-empty sizes with non-0 sum, and annotate_initialized.
static constexpr intptr_t sizesC[1] = {3};
void* bufC[1];
- base = cpu_function_runtime::MallocContiguousBuffers(sizesC, 1, bufC, true);
+ base = MallocContiguousBuffersFromSizes(sizesC, 1, bufC, true);
EXPECT_NE(base, nullptr);
EXPECT_EQ(bufC[0], add_ptr(base, 0));
char* bufC0_bytes = static_cast<char*>(bufC[0]);
@@ -96,7 +128,7 @@ TEST(XlaCompiledCpuFunctionTest, MallocFreeContiguousBuffers) {
// Test mixed sizes.
static constexpr intptr_t sizesD[7] = {1, -1, 32, -1, 64, 2, 3};
void* bufD[7];
- base = cpu_function_runtime::MallocContiguousBuffers(sizesD, 7, bufD, false);
+ base = MallocContiguousBuffersFromSizes(sizesD, 7, bufD, false);
EXPECT_NE(base, nullptr);
EXPECT_EQ(bufD[0], add_ptr(base, 0));
EXPECT_EQ(bufD[1], nullptr);
@@ -117,5 +149,23 @@ TEST(XlaCompiledCpuFunctionTest, MallocFreeContiguousBuffers) {
cpu_function_runtime::FreeContiguous(base);
}
+void CheckRoundTripIsOk(const BufferInfo& buffer_info) {
+ BufferInfo round_trip(buffer_info.Encode());
+ ASSERT_EQ(round_trip, buffer_info);
+}
+
+TEST(XlaCompiledCpuFunctionTest, BufferInfoTest) {
+ CheckRoundTripIsOk(BufferInfo::MakeTempBuffer(0));
+ CheckRoundTripIsOk(BufferInfo::MakeTempBuffer(4));
+ CheckRoundTripIsOk(BufferInfo::MakeOnStackBuffer(0));
+ CheckRoundTripIsOk(BufferInfo::MakeOnStackBuffer(4));
+ CheckRoundTripIsOk(BufferInfo::MakeConstant(0));
+ CheckRoundTripIsOk(BufferInfo::MakeConstant(4));
+ CheckRoundTripIsOk(
+ BufferInfo::MakeEntryParameter(/*size=*/0, /*param_number=*/4));
+ CheckRoundTripIsOk(
+ BufferInfo::MakeEntryParameter(/*size=*/4, /*param_number=*/0));
+}
+
} // namespace
} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_cond.cc b/tensorflow/compiler/tf2xla/functionalize_cond.cc
new file mode 100644
index 0000000000..d24b5b1bbe
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_cond.cc
@@ -0,0 +1,1379 @@
+/* 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.
+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.
+==============================================================================*/
+
+#include "tensorflow/compiler/tf2xla/functionalize_cond.h"
+
+#include <algorithm>
+#include <deque>
+#include <stack>
+#include <unordered_set>
+#include <vector>
+
+#include "tensorflow/compiler/jit/union_find.h"
+#include "tensorflow/compiler/tf2xla/dump_graph.h"
+#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h"
+#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
+#include "tensorflow/compiler/xla/ptr_util.h"
+#include "tensorflow/core/common_runtime/function.h"
+#include "tensorflow/core/framework/graph_to_functiondef.h"
+#include "tensorflow/core/framework/node_def_builder.h"
+#include "tensorflow/core/graph/algorithm.h"
+#include "tensorflow/core/graph/control_flow.h"
+#include "tensorflow/core/graph/node_builder.h"
+#include "tensorflow/core/lib/gtl/optional.h"
+
+using xla::StatusOr;
+
+namespace tensorflow {
+namespace functionalize_cond {
+
+string DebugString(const CondStateMap::CondNode& node) {
+ return node.ToString();
+}
+
+// TODO(jpienaar): Move to OutputTensor.
+string DebugString(const OutputTensor& tensor) {
+ return strings::StrCat(tensor.node->name(), ":", tensor.index);
+}
+
+string DebugString(CondStateMap::CondId cond_state) {
+ if (cond_state == nullptr || cond_state->empty()) return "[]";
+ return strings::StrCat(
+ "[",
+ tensorflow::str_util::Join(
+ *cond_state, ", ",
+ [](string* output, const CondStateMap::CondNode& node) {
+ strings::StrAppend(output, node.ToString());
+ }),
+ "]");
+}
+
+string Branch_Name(BranchType b) {
+ switch (b) {
+ case BranchType::kElseBranch:
+ return "else";
+ case BranchType::kThenBranch:
+ return "then";
+ case BranchType::kBoth:
+ return "both";
+ case BranchType::kNeither:
+ return "neither";
+ }
+}
+
+// Returns the predicate of a switch.
+Status GetSwitchPredicate(const Node& switch_node, OutputTensor* pred) {
+ const Edge* pred_edge;
+ TF_RETURN_IF_ERROR(switch_node.input_edge(1, &pred_edge));
+ // The predicate can be preceded by a identity node. Look through
+ // identity nodes to predicate.
+ while (pred_edge->src()->IsIdentity()) {
+ TF_RETURN_IF_ERROR(pred_edge->src()->input_edge(0, &pred_edge));
+ }
+ *pred = OutputTensor(pred_edge->src(), pred_edge->src_output());
+ return Status::OK();
+}
+
+CondStateMap::CondNode::CondNode(Type type, Node* switch_node,
+ BranchType branch)
+ : type(type), branch(branch) {
+ if (type == Type::kSwitch) {
+ TF_CHECK_OK(GetSwitchPredicate(*switch_node, &predicate));
+ }
+}
+
+string CondStateMap::CondNode::ToString() const {
+ switch (type) {
+ case Type::kSwitch:
+ return strings::StrCat("s(", DebugString(predicate), ",",
+ Branch_Name(branch), ")");
+ case Type::kMerge:
+ return "m";
+ case Type::kDead:
+ return "d";
+ }
+}
+
+bool CondStateMap::CondNode::operator==(const CondNode& other) const {
+ if (type != Type::kSwitch) return type == other.type;
+ return type == other.type && predicate == other.predicate &&
+ branch == other.branch;
+}
+
+bool CondStateMap::CondNode::operator!=(const CondNode& other) const {
+ return !(*this == other);
+}
+
+CondStateMap::CondStateMap(Graph* graph) {
+ node_to_condid_map_.resize(graph->num_node_ids());
+ // Initialize the dead state (empty state is designated with a nullptr).
+ dead_id_ = GetUniqueId({CondNode(CondStateMap::CondNode::Type::kDead)});
+}
+
+bool CondStateMap::IsDead(CondStateMap::CondId id) const {
+ return id == dead_id_;
+}
+
+bool CondStateMap::IsEmpty(CondStateMap::CondId id) const {
+ return id == nullptr;
+}
+
+size_t CondStateMap::CondHash::operator()(
+ const CondStateMap::CondNode& item) const {
+ return Hash64Combine(Hash64Combine(OutputTensor::Hash()(item.predicate),
+ hash<BranchType>()(item.branch)),
+ hash<CondStateMap::CondNode::Type>()(item.type));
+}
+
+size_t CondStateMap::CondHash::operator()(
+ const CondStateMap::CondState& vec) const {
+ if (vec.empty()) return 0;
+ size_t h = (*this)(vec.front());
+ auto it = vec.begin();
+ for (++it; it != vec.end(); ++it) {
+ h = Hash64Combine(h, (*this)(*it));
+ }
+ return h;
+}
+
+// CondArgNode represents a input to the conditional and its corresponding
+// switch nodes.
+struct CondArgNode {
+ explicit CondArgNode(Node* src, int src_output)
+ : src(src), src_output(src_output) {}
+
+ string ToString() const {
+ return strings::StrCat("src=", src->name(), ":", src_output,
+ " switches=", NodesToString(switches));
+ }
+
+ Node* src;
+ int src_output;
+ std::array<Node*, 2> branch_copy;
+ std::vector<Node*> switches;
+};
+using CondArgNodes = std::vector<CondArgNode>;
+
+string DebugString(const CondArgNodes& nodes) {
+ return strings::StrCat(
+ "[",
+ tensorflow::str_util::Join(nodes, ", ",
+ [](string* output, const CondArgNode& node) {
+ strings::StrAppend(output, node.ToString());
+ }),
+ "]");
+}
+
+CondStateMap::CondId CondStateMap::LookupId(const Node* node) const {
+ if (node->id() < node_to_condid_map_.size())
+ return node_to_condid_map_[node->id()];
+ return added_node_mapping_.at(node->id());
+}
+
+CondStateMap::CondId CondStateMap::GetUniqueId(
+ const CondStateMap::CondState& state) {
+ if (state.empty()) return nullptr;
+ return &*condstate_set_.insert(state).first;
+}
+
+const CondStateMap::CondState& CondStateMap::LookupState(
+ const Node* node) const {
+ return *LookupId(node);
+}
+
+void CondStateMap::ResetId(const Node* node, CondStateMap::CondId id) {
+ if (node->id() < node_to_condid_map_.size())
+ node_to_condid_map_[node->id()] = id;
+ else
+ added_node_mapping_[node->id()] = id;
+}
+
+void CondStateMap::MarkDead(const Node* node) { ResetId(node, dead_id_); }
+
+string CondStateMap::CondStateToString(const Node* node) const {
+ return CondStateToString(LookupId(node));
+}
+
+string CondStateMap::CondStateToString(CondStateMap::CondId id) const {
+ return DebugString(id);
+}
+
+FunctionalizeCond::FunctionalizeCond(Graph* graph,
+ FunctionLibraryDefinition* library)
+ : cond_state_map_(graph), library_(library), graph_(graph) {}
+
+// Class representing the merge/switch nodes that will become a conditional.
+class Conditional {
+ public:
+ Conditional(OutputTensor predicate, FunctionalizeCond* parent,
+ CondStateMap* cond_state_map);
+
+ // Adds merge node that is part of this conditional.
+ Status AddMerge(Node* m);
+
+ // Constructs an If node from the merge nodes.
+ Status BuildAndReplace(Graph* graph, FunctionLibraryDefinition* library);
+
+ private:
+ // Extracts the then/else bodies: creates new graphs with the nodes
+ // corresponding to the nodes in the then/else branches as of this conditional
+ // as function bodies.
+ Status ExtractBodies(Graph* graph);
+
+ // Builds the arguments that are the input to the If.
+ Status BuildArgumentNodes();
+
+ // Builds the If node for the extracted bodies with the given predicate.
+ Status BuildIfNode(Graph* graph, FunctionLibraryDefinition* library);
+
+ // Adds input edges to If node.
+ Status AddInputEdges(Graph* graph);
+
+ // Adds output edges from If node.
+ Status AddOutputEdges(Graph* graph);
+
+ // Adds switch node that is part of this conditional.
+ Status AddSwitch(Node* s);
+
+ // Internal name of conditional. The name is based on the first merge node
+ // added.
+ string name() const;
+
+ // The FunctionalizeCond instance that created this.
+ FunctionalizeCond* parent_;
+
+ // Mapping between nodes and their cond state.
+ CondStateMap* cond_state_map_;
+
+ // The predicate of the conditional.
+ OutputTensor predicate_;
+
+ // The predicate of the switches of the conditional. This may be different
+ // than predicate (which is initialized from the original graph) as the
+ // predicate could be the output of a newly created If node.
+ OutputTensor switch_predicate_;
+
+ // Switch nodes in graph that are part of this conditional.
+ std::set<Node*, NodeCmpByNameResourcesLast> switches_;
+
+ // Merge nodes in graph that are part of this conditional.
+ std::set<Node*, NodeCmpByNameResourcesLast> merges_;
+
+ // Vector of control inputs from outside the conditional to a node inside.
+ std::vector<Node*> external_control_inputs_;
+ std::vector<Node*> external_control_outputs_;
+
+ // Graphs corresponding to the then and else branch.
+ std::array<std::unique_ptr<Graph>, 2> bodies_;
+
+ // Maps from graph_ to the branch body's graph.
+ std::array<std::vector<Node*>, 2> node_maps_;
+
+ // The argument nodes created for the switches.
+ CondArgNodes cond_arg_nodes_;
+
+ // The constructed If node.
+ Node* if_node_ = nullptr;
+
+ // Whether the merge nodes of this conditional have been replaced.
+ bool replaced_ = false;
+};
+
+Conditional::Conditional(OutputTensor predicate, FunctionalizeCond* parent,
+ CondStateMap* cond_state_map)
+ : parent_(parent), cond_state_map_(cond_state_map), predicate_(predicate) {}
+
+Status Conditional::AddMerge(Node* m) {
+ merges_.insert(m);
+ return Status::OK();
+}
+
+Status Conditional::AddSwitch(Node* s) {
+ VLOG(5) << "Adding switch " << s->DebugString();
+ OutputTensor predicate;
+ TF_RETURN_IF_ERROR(GetSwitchPredicate(*s, &predicate));
+ if (switch_predicate_.node == nullptr) switch_predicate_ = predicate;
+ if (!(switch_predicate_ == predicate)) {
+ return errors::InvalidArgument(
+ "Merge nodes ", NodesToString(merges_),
+ " directly dominated by switch nodes with different predicates (",
+ DebugString(switch_predicate_), " vs ", DebugString(predicate), ").");
+ }
+ switches_.insert(s);
+ return Status::OK();
+}
+
+Status Conditional::BuildArgumentNodes() {
+ VLOG(1) << "Build function arguments";
+ struct Hash {
+ size_t operator()(const std::pair<Node*, int>& item) const {
+ return Hash64Combine(hash<Node*>()(item.first),
+ std::hash<int>()(item.second));
+ }
+ };
+
+ std::unordered_map<std::pair<Node*, int>, int, Hash> input_index;
+ for (Node* switch_node : switches_) {
+ const Edge* e;
+ TF_RETURN_IF_ERROR(switch_node->input_edge(0, &e));
+ std::pair<Node*, int> key = std::make_pair(e->src(), e->src_output());
+ if (input_index.find(key) == input_index.end()) {
+ input_index[key] = cond_arg_nodes_.size();
+ cond_arg_nodes_.emplace_back(key.first, key.second);
+ }
+ cond_arg_nodes_.at(input_index.at(key)).switches.push_back(switch_node);
+ }
+ VLOG(5) << "CondArg nodes created: " << DebugString(cond_arg_nodes_);
+
+ int arg_count = 0;
+ for (CondArgNode& cond_arg_node : cond_arg_nodes_) {
+ DataType dtype = cond_arg_node.src->output_type(cond_arg_node.src_output);
+ for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ int branch_index = static_cast<int>(branch);
+ TF_RETURN_IF_ERROR(
+ NodeBuilder(strings::StrCat("_Arg", arg_count),
+ FunctionLibraryDefinition::kArgOp)
+ .Attr("T", dtype)
+ .Attr("index", arg_count)
+ .Finalize(bodies_[branch_index].get(),
+ &cond_arg_node.branch_copy[branch_index]));
+ }
+ for (Node* node : cond_arg_node.switches) {
+ for (const Edge* e : node->out_edges()) {
+ if (e->IsControlEdge()) continue;
+ int branch_index = e->src_output();
+ Node* src_copy = cond_arg_node.branch_copy[branch_index];
+ Node* dst_copy = node_maps_[branch_index][e->dst()->id()];
+
+ // The graph may contain dead switch nodes,
+ if (dst_copy == nullptr) continue;
+
+ TF_RET_CHECK(dst_copy != nullptr)
+ << "Unable to find copied node for " << e->dst()->DebugString()
+ << " on branch " << Branch_Name(BranchType(branch_index));
+ // If the input goes directly to a merge then the merge has
+ // been replaced by a retval so the dst input is 0 instead of
+ // dst_input.
+ int dst_input = IsMerge(e->dst()) ? 0 : e->dst_input();
+ bodies_[branch_index]->AddEdge(src_copy, 0, dst_copy, dst_input);
+ }
+ }
+ ++arg_count;
+ }
+
+ // Verify that all retvals have an input.
+ // TODO(jpienaar): One could add a ZerosLike in the branch that doesn't have
+ // input.
+ for (Node* m : merges_) {
+ for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ bool has_input = false;
+ for (auto e : node_maps_[static_cast<int>(branch)][m->id()]->in_edges()) {
+ if (!e->IsControlEdge()) {
+ has_input = true;
+ break;
+ }
+ }
+ if (!has_input) {
+ return errors::Internal(
+ "Failed to functionalize control flow with merge '", m->name(),
+ "' that doesn't have input on ", Branch_Name(branch), " branch.");
+ }
+ }
+ }
+
+ return Status::OK();
+}
+
+Status Conditional::ExtractBodies(Graph* graph) {
+ VLOG(2) << "Extracting bodies for " << name();
+ for (auto b : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ bodies_[static_cast<int>(b)] = xla::MakeUnique<Graph>(graph->op_registry());
+ }
+
+ auto find_branch = [&](const Edge* e) {
+ const auto& id = cond_state_map_->LookupId(e->src());
+ return IsSwitch(e->src()) ? BranchType(e->src_output())
+ : cond_state_map_->FindBranchOf(id, predicate_);
+ };
+
+ std::array<std::vector<Node*>, 2> stacks;
+ VLOG(5) << "Merges: " << NodesToString(merges_);
+ for (Node* m : merges_) {
+ VLOG(5) << "For merge: " << m->DebugString() << " "
+ << cond_state_map_->CondStateToString(m);
+ for (auto e : m->in_edges()) {
+ if (e->IsControlEdge()) continue;
+ BranchType branch = find_branch(e);
+ TF_RET_CHECK(branch == BranchType::kThenBranch ||
+ branch == BranchType::kElseBranch)
+ << "Error: " << e->src()->name()
+ << " is not on either then or else branch (" << Branch_Name(branch)
+ << ").";
+ Node* src = e->src();
+ if (IsSwitch(src)) {
+ // Switch node outputs and dependencies are handled separately.
+ TF_RETURN_IF_ERROR(AddSwitch(src));
+ } else {
+ stacks[static_cast<int>(branch)].push_back(src);
+ }
+ }
+ }
+
+ for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ int branch_index = static_cast<int>(branch);
+ auto output = bodies_[branch_index].get();
+ auto& stack = stacks[branch_index];
+ VLOG(5) << "In branch: " << Branch_Name(branch) << " "
+ << NodesToString(stack);
+ std::vector<bool> visited(graph->num_node_ids(), false);
+ node_maps_[branch_index].resize(graph->num_node_ids(), nullptr);
+ auto& node_map = node_maps_[branch_index];
+
+ while (!stack.empty()) {
+ Node* n = stack.back();
+ stack.pop_back();
+
+ if (visited.at(n->id())) continue;
+ visited[n->id()] = true;
+
+ // Verify output edges and record control edges exitting scope.
+ for (const Edge* e : n->out_edges()) {
+ Node* dst = e->dst();
+ if (IsMerge(dst)) continue;
+ Node* src = e->src();
+
+ auto dst_id = cond_state_map_->LookupId(dst);
+ auto src_id = cond_state_map_->LookupId(src);
+ if (dst_id != src_id) {
+ if (e->IsControlEdge()) {
+ external_control_outputs_.push_back(e->src());
+ } else {
+ // Constants are treated specially to workaround the case of
+ // non-dominated constant nodes.
+ if (!IsConstant(src)) {
+ // TODO(b/78882471): A node that feeds into two different
+ // CondState is not necessarily an error so log a warning for now
+ // but revisit to improve the testing to enable making this an
+ // error.
+ LOG(WARNING) << errors::InvalidArgument(
+ "Graph contains node ", src->name(), " that feeds into node ",
+ dst->name(),
+ " but these nodes are in different control contexts (",
+ DebugString(src_id), " vs ", DebugString(dst_id),
+ " (detected during out edge testing)");
+ }
+ }
+ }
+ }
+
+ // Copying incomming edges to dst node.
+ for (const Edge* e : n->in_edges()) {
+ Node* src = e->src();
+ // Skip src/dst node.
+ if (!src->IsOp()) continue;
+
+ Node* dst = e->dst();
+ if (IsSwitch(src)) {
+ // Switch node outputs and dependencies are handled separately.
+ TF_RETURN_IF_ERROR(AddSwitch(src));
+ continue;
+ }
+
+ // Verify input is from the same context.
+ auto src_id = cond_state_map_->LookupId(src);
+ auto dst_id = cond_state_map_->LookupId(dst);
+ if (IsMerge(dst) || src_id == dst_id) {
+ // TODO(jpienaar): The merge case can be more strict.
+ if (node_map.at(src->id()) == nullptr) {
+ node_map.at(src->id()) = output->CopyNode(src);
+ stack.push_back(src);
+ }
+ } else if (e->IsControlEdge()) {
+ external_control_inputs_.push_back(src);
+ } else {
+ // This shouldn't happen, this means we have an external data input
+ // not entering via a switch node. Work around this for constant
+ // nodes as some constant nodes are inserted without the required
+ // control context dominance.
+ if (IsConstant(src)) {
+ node_map.at(src->id()) = output->CopyNode(src);
+ } else {
+ return errors::InvalidArgument(
+ "Graph contains node ", src->name(), " that feeds into node ",
+ dst->name(),
+ " but these nodes are in different control contexts (",
+ DebugString(src_id), " vs ", DebugString(dst_id),
+ " (detected during in edge testing)");
+ }
+ }
+
+ Node* src_copy = node_map.at(e->src()->id());
+ int src_output = e->src_output();
+ if (node_map.at(dst->id()) == nullptr) {
+ node_map.at(dst->id()) = output->CopyNode(dst);
+ }
+ Node* dst_copy = node_map.at(e->dst()->id());
+ if (e->IsControlEdge()) {
+ // Skip control inputs from external context.
+ if (src_copy != nullptr) output->AddControlEdge(src_copy, dst_copy);
+ } else {
+ output->AddEdge(src_copy, src_output, dst_copy, e->dst_input());
+ }
+ }
+ }
+ }
+
+ // Build return values from the merge nodes.
+ int index = 0;
+ for (Node* m : merges_) {
+ for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ int branch_index = static_cast<int>(branch);
+ auto& node_map = node_maps_[branch_index];
+ auto output = bodies_[branch_index].get();
+ TF_ASSIGN_OR_RETURN(node_map[m->id()],
+ BuildRetvalNode(output, m->output_type(0), index));
+ }
+ ++index;
+
+ // Connect the input to the merge_ with the retval, except if it is a
+ // Swich node, which is handled separately.
+ for (auto e : m->in_edges()) {
+ if (e->IsControlEdge()) continue;
+ int branch_index = static_cast<int>(find_branch(e));
+ auto& node_map = node_maps_[branch_index];
+ auto output = bodies_[branch_index].get();
+ Node* in = e->src();
+ if (!IsSwitch(in)) {
+ if (node_map.at(in->id()) == nullptr) {
+ node_map[in->id()] = output->CopyNode(in);
+ }
+ output->AddEdge(node_map[in->id()], e->src_output(),
+ node_map.at(m->id()), 0);
+ }
+ }
+ }
+ return Status::OK();
+}
+
+Status Conditional::BuildIfNode(Graph* graph,
+ FunctionLibraryDefinition* library) {
+ VLOG(2) << "Build cond function for " << name();
+ NodeDefBuilder builder(name(), "If");
+ const string branch_name[] = {"else_branch", "then_branch"};
+ for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ int branch_index = static_cast<int>(branch);
+ static std::atomic<int64> sequence_num(0LL);
+ int64 id = ++sequence_num;
+
+ NameAttrList body_name;
+ body_name.set_name(strings::StrCat("_functionalize_if_",
+ branch_name[branch_index], "_", id));
+
+ VLOG(3) << "FunctionalizeControlFlow (" << branch_name[branch_index]
+ << "): "
+ << dump_graph::DumpGraphToFile(
+ "functionalize_cond_body_" + branch_name[branch_index],
+ *bodies_[branch_index], nullptr);
+
+ FunctionDef body_fdef;
+ TF_RETURN_IF_ERROR(GraphToFunctionDef(*bodies_[branch_index],
+ body_name.name(), &body_fdef));
+ TF_RETURN_IF_ERROR(library->AddFunctionDef(body_fdef));
+ builder.Attr(branch_name[branch_index], body_name);
+ }
+
+ VLOG(3) << "Build input type";
+ std::vector<NodeDefBuilder::NodeOut> inputs;
+ DataTypeVector in_arg_types;
+ for (auto& kv : cond_arg_nodes_) {
+ bool inserted = false;
+ for (const Node* arg : kv.switches) {
+ const Edge* in_edge;
+ TF_RETURN_IF_ERROR(arg->input_edge(0, &in_edge));
+ if (in_edge->IsControlEdge()) {
+ builder.ControlInput(in_edge->src()->name());
+ } else {
+ if (!inserted) {
+ DataType dtype = arg->input_type(0);
+ inputs.emplace_back(NodeDefBuilder::NodeOut(
+ in_edge->src()->name(), in_edge->src_output(), dtype));
+ in_arg_types.push_back(dtype);
+ inserted = true;
+ }
+ }
+ }
+ }
+ builder.Attr("Tin", in_arg_types);
+
+ DataTypeVector out_type;
+ for (const Node* merge : merges_) {
+ DataType dtype = merge->output_type(0);
+ out_type.push_back(dtype);
+ }
+ builder.Attr("Tout", out_type);
+ VLOG(3) << "Build output type: " << DataTypeVectorString(out_type);
+
+ builder.Attr("Tcond", DT_BOOL);
+ builder.Device(predicate_.node->assigned_device_name());
+ // Conditional should be the first input ...
+ builder.Input(NodeDefBuilder::NodeOut(predicate_.node->name(),
+ predicate_.index,
+ predicate_.node->output_type(0)));
+ // ... followed by the other inputs.
+ builder.Input(inputs);
+
+ VLOG(3) << "Build If node";
+ NodeDef if_def;
+ TF_RETURN_IF_ERROR(builder.Finalize(&if_def));
+ TF_ASSIGN_OR_RETURN(if_node_, parent_->AddIfNode(if_def, *merges_.begin()));
+
+ return Status::OK();
+}
+
+Status Conditional::AddInputEdges(Graph* graph) {
+ VLOG(2) << "AddInputEdges for " << if_node_->name();
+ int index = 0;
+ // Add predicate input.
+ graph->AddEdge(const_cast<Node*>(predicate_.node), predicate_.index, if_node_,
+ index++);
+ // Add function body inputs.
+ for (auto& arg : cond_arg_nodes_) {
+ if (arg.src_output == Graph::kControlSlot) {
+ graph->AddControlEdge(arg.src, if_node_);
+ } else {
+ graph->AddEdge(arg.src, arg.src_output, if_node_, index++);
+ }
+ }
+ for (Node* n : external_control_inputs_) {
+ graph->AddControlEdge(n, if_node_);
+ }
+ return Status::OK();
+}
+
+Status Conditional::AddOutputEdges(Graph* graph) {
+ VLOG(2) << "AddOutputEdges for " << if_node_->name();
+ int i = 0;
+ for (Node* node : merges_) {
+ TF_RETURN_IF_ERROR(parent_->AddIdentityNode(node, if_node_, i));
+ std::vector<const Edge*> edges(node->out_edges().begin(),
+ node->out_edges().end());
+ for (const Edge* edge : edges) {
+ Node* dst = edge->dst();
+ int dst_input = edge->dst_input();
+ if (edge->src_output() > 0) {
+ return errors::Unimplemented("Output of index (", edge->src_output(),
+ ") of merge node ", node->name());
+ }
+
+ bool control_edge = edge->IsControlEdge();
+ graph->RemoveEdge(edge);
+ if (control_edge) {
+ graph->AddControlEdge(if_node_, dst);
+ } else {
+ graph->AddEdge(if_node_, i, dst, dst_input);
+ }
+ }
+ ++i;
+ }
+ for (Node* n : external_control_outputs_) {
+ graph->AddControlEdge(if_node_, n);
+ }
+
+ return Status::OK();
+}
+
+Status Conditional::BuildAndReplace(Graph* graph,
+ FunctionLibraryDefinition* library) {
+ VLOG(1) << "Build If and replace merge nodes " << name();
+ if (replaced_) return Status::OK();
+
+ TF_RETURN_IF_ERROR(ExtractBodies(graph));
+ TF_RETURN_IF_ERROR(BuildArgumentNodes());
+
+ if (VLOG_IS_ON(3)) {
+ LOG(INFO) << "Extracted bodies:";
+ for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) {
+ int branch_index = static_cast<int>(branch);
+ auto output = bodies_[branch_index].get();
+ LOG(INFO) << Branch_Name(branch) << ": "
+ << DebugString(output->ToGraphDefDebug());
+ }
+ }
+
+ TF_RETURN_IF_ERROR(BuildIfNode(graph, library));
+ TF_RETURN_IF_ERROR(AddInputEdges(graph));
+ TF_RETURN_IF_ERROR(AddOutputEdges(graph));
+ TF_RETURN_IF_ERROR(parent_->PropagateUpdatedState(if_node_));
+ for (Node* m : merges_) cond_state_map_->MarkDead(m);
+
+ // Check that the if_node doesn't feed into itself.
+ TF_RETURN_WITH_CONTEXT_IF_ERROR(
+ CheckNodeNotInCycle(if_node_, graph->num_node_ids()),
+ "Converting to If failed.");
+
+ replaced_ = true;
+ return Status::OK();
+}
+
+string Conditional::name() const {
+ CHECK(!merges_.empty());
+ return strings::StrCat((*merges_.begin())->name(), "_if");
+}
+
+bool CondStateMap::ScopeIn(CondStateMap::CondId id,
+ CondStateMap::CondId* scope) {
+ if (id == nullptr) {
+ *scope = nullptr;
+ return true;
+ }
+ CondState state;
+ for (const CondNode& node : *id) {
+ if (node.type == CondNode::Type::kSwitch) {
+ state.push_back(node);
+ }
+ if (node.type == CondNode::Type::kMerge) {
+ if (state.empty()) {
+ return false;
+ }
+ DCHECK(state.back().type == CondNode::Type::kSwitch &&
+ state.back().branch == BranchType::kBoth);
+ state.pop_back();
+ }
+ }
+ *scope = GetUniqueId(state);
+ return true;
+}
+
+Status FunctionalizeCond::AddIdentityNode(const Node* replacee, Node* if_node,
+ int port) {
+ Node* id;
+ TF_RETURN_IF_ERROR(NodeBuilder(replacee->name(), "Identity")
+ .Input(if_node, port)
+ .Finalize(graph_, &id));
+ cond_state_map_.ResetId(id, cond_state_map_.LookupId(if_node));
+ return Status::OK();
+}
+
+StatusOr<Node*> FunctionalizeCond::AddIfNode(const NodeDef& def,
+ const Node* replacee) {
+ Status status;
+ Node* ret = graph_->AddNode(def, &status);
+ TF_RETURN_IF_ERROR(status);
+ CondStateMap::CondState state = cond_state_map_.LookupState(replacee);
+ state.pop_back();
+ VLOG(1) << "Adding If for " << replacee->name();
+ cond_state_map_.ResetId(ret, cond_state_map_.GetUniqueId(state));
+ return ret;
+}
+
+Status FunctionalizeCond::PropagateUpdatedState(const Node* replacee) {
+ VLOG(2) << "Propagating update state for " << replacee->name() << " "
+ << cond_state_map_.CondStateToString(replacee);
+ // Redo topological sort as the order could have changed.
+ // TODO(jpienaar): The original topological order could also be updated
+ // dynamically if needed.
+ std::vector<Node*> rev_topo_order;
+ GetPostOrder(*graph_, &rev_topo_order);
+
+ // All the outputs of the new node could potentially be updated.
+ std::unordered_set<Node*> changed;
+ for (auto n : replacee->out_nodes())
+ if (n->IsOp()) changed.insert(n);
+
+ // Iterate through the changed/possible changed nodes in topological order.
+ for (auto it = rev_topo_order.rbegin();
+ it != rev_topo_order.rend() && !changed.empty(); ++it) {
+ if (changed.find(*it) != changed.end()) {
+ // Update the node state.
+ Node* n = *it;
+ CondStateMap::CondId old_state = cond_state_map_.LookupId(n);
+ cond_state_map_.ResetId(n, nullptr);
+ TF_RETURN_IF_ERROR(DetermineCondState(n));
+ if (cond_state_map_.LookupId(n) != old_state) {
+ for (auto out : n->out_nodes())
+ if (out->IsOp()) changed.insert(out);
+ }
+ changed.erase(n);
+ }
+ }
+ return Status::OK();
+}
+
+// Returns the most restrictive branch of two branches or neither. This is the
+// meet operator of the BranchType lattice.
+BranchType MeetBranch(const BranchType& lhs, const BranchType& rhs) {
+ if (lhs == rhs) return lhs;
+ if (lhs == BranchType::kNeither) return rhs;
+ if (rhs == BranchType::kNeither) return lhs;
+ if (lhs == BranchType::kBoth) return rhs;
+ if (rhs == BranchType::kBoth) return lhs;
+ return BranchType::kNeither;
+}
+
+CondStateMap::ContainsResult CondStateMap::LhsHoldsWhereverRhsHolds(
+ CondStateMap::CondId lhs, CondStateMap::CondId rhs) {
+ CondId lhs_scope;
+ CondId rhs_scope;
+ bool could_determine_scope = ScopeIn(lhs, &lhs_scope);
+ could_determine_scope = could_determine_scope && ScopeIn(rhs, &rhs_scope);
+ if (!could_determine_scope) return kIncomparable;
+
+ // Returns whether a contains b.
+ auto contains = [&](CondId a, CondId b) {
+ // Handle empty states.
+ if (a == nullptr && b != nullptr) return true;
+ if (a == nullptr && b == nullptr) return true;
+ if (a != nullptr && b == nullptr) return false;
+
+ if (a->size() > b->size()) return false;
+ auto a_it = a->begin();
+ auto b_it = b->begin();
+ while (a_it != a->end()) {
+ if (*a_it != *b_it) {
+ if (!(a_it->predicate == b_it->predicate)) return false;
+ BranchType mb = MeetBranch(a_it->branch, b_it->branch);
+ if (mb != b_it->branch) return false;
+ }
+ ++a_it;
+ ++b_it;
+ }
+ return true;
+ };
+
+ bool lhs_contains_rhs = contains(lhs_scope, rhs_scope);
+ bool rhs_contains_lhs = contains(rhs_scope, lhs_scope);
+ if (lhs_contains_rhs && rhs_contains_lhs) return kEqual;
+ if (lhs_contains_rhs) return kLhsContainsRhs;
+ if (rhs_contains_lhs) return kRhsContainsLhs;
+ return kIncomparable;
+}
+
+BranchType CondStateMap::FindBranchOf(CondId id, OutputTensor predicate) const {
+ if (IsEmpty(id)) return BranchType::kNeither;
+ gtl::optional<BranchType> b;
+ const CondState& nodes = *id;
+ for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) {
+ if (it->type == CondStateMap::CondNode::Type::kSwitch &&
+ it->predicate == predicate) {
+ if (b.has_value()) {
+ b = MeetBranch(*b, it->branch);
+ } else {
+ b = it->branch;
+ }
+ if (*b == BranchType::kNeither) {
+ LOG(FATAL) << "Inconsistent state for node: " << DebugString(id);
+ }
+ }
+ }
+ return b.has_value() ? *b : BranchType::kNeither;
+}
+
+StatusOr<CondStateMap::CondId> FunctionalizeCond::JoinCondStatesNonMerge(
+ CondStateMap::CondId src, CondStateMap::CondId dst) {
+ VLOG(4) << "Joining src=" << DebugString(src) << " [" << src
+ << "] and dst=" << DebugString(dst) << " [" << dst << "]";
+
+ if (cond_state_map_.IsEmpty(dst) || cond_state_map_.IsDead(src)) return src;
+ if (cond_state_map_.IsDead(dst)) return dst;
+
+ // Nothing to do if the CondState is the same.
+ if (src == dst) return src;
+
+ CondStateMap::CondId src_scope;
+ CondStateMap::CondId dst_scope;
+ if (!cond_state_map_.ScopeIn(src, &src_scope))
+ return errors::Unimplemented(
+ "Predicates that must hold for node to execute are invalid! ",
+ DebugString(src));
+ if (!cond_state_map_.ScopeIn(dst, &dst_scope))
+ return errors::Unimplemented(
+ "Predicates that must hold for node to execute are invalid! ",
+ DebugString(dst));
+
+ auto result = cond_state_map_.LhsHoldsWhereverRhsHolds(src_scope, dst_scope);
+ switch (result) {
+ case CondStateMap::kIncomparable:
+ return errors::InvalidArgument(
+ "Graph contains node with inputs predicated on incompatible "
+ "predicates: ",
+ DebugString(src), " and ", DebugString(dst));
+ case CondStateMap::kEqual:
+ // If both respect the same predicates, propagate the longer constraint.
+ if ((src != nullptr && dst == nullptr) ||
+ (src != nullptr && dst != nullptr && src->size() > dst->size()))
+ return src;
+ else
+ return dst;
+ case CondStateMap::kLhsContainsRhs:
+ // src contains dst, so dst is already more restrictive.
+ return dst;
+ case CondStateMap::kRhsContainsLhs:
+ // dst contains src, so src is more restrictive.
+ return src;
+ }
+}
+
+StatusOr<CondStateMap::CondState::const_iterator>
+FindThenElseSwitchForPredicate(const OutputTensor& pred,
+ CondStateMap::CondId id) {
+ for (auto it = id->begin(); it != id->end(); ++it) {
+ // Along every path one there can be only one instance of a then or else
+ // switch for a given predicate, so return once found.
+ if (it->type == CondStateMap::CondNode::Type::kSwitch &&
+ it->predicate == pred &&
+ (it->branch == BranchType::kThenBranch ||
+ it->branch == BranchType::kElseBranch))
+ return it;
+ }
+ return errors::Internal("Unable to find then/else branch with predicate ",
+ DebugString(pred), " for ", DebugString(id));
+}
+
+StatusOr<CondStateMap::CondId> FunctionalizeCond::JoinCondStatesMerge(
+ CondStateMap::CondId src, CondStateMap::CondId dst) {
+ // Determine the flow state when joining two states for a merge
+ // node. Combining the two states for a merge node is effectively performing a
+ // disjunction of the states along the different input edges. For a merge that
+ // can be transformed into a If the two inputs paths have to have a predicate
+ // on which they differ (e.g., along one edge predicate `p` has to hold while
+ // on another it should not). This function first determines this predicate
+ // and then the resultant state is the common path between the two inputs
+ // followed by s(p, both).
+ VLOG(4) << "Joining (for merge) " << DebugString(src) << " and "
+ << DebugString(dst);
+ if (cond_state_map_.IsEmpty(dst)) return src;
+
+ if (cond_state_map_.IsDead(src)) return src;
+ if (cond_state_map_.IsDead(dst)) return dst;
+
+ CondStateMap::CondId src_scope;
+ CondStateMap::CondId dst_scope;
+ if (!cond_state_map_.ScopeIn(src, &src_scope))
+ return errors::Unimplemented(
+ "Predicates that must hold for node to execute are invalid! ",
+ DebugString(src));
+ if (!cond_state_map_.ScopeIn(dst, &dst_scope))
+ return errors::Unimplemented(
+ "Predicates that must hold for node to execute are invalid! ",
+ DebugString(dst));
+
+ TF_RET_CHECK(src_scope != nullptr && dst_scope != nullptr)
+ << "Illegal merge inputs from outer scope: src=" << DebugString(src)
+ << " dst=" << DebugString(dst);
+ auto src_it = src_scope->begin();
+ auto dst_it = dst_scope->begin();
+
+ // Find branch divergent condition.
+ OutputTensor pred;
+ while (src_it != src_scope->end() && dst_it != dst_scope->end()) {
+ if (*src_it != *dst_it) {
+ VLOG(5) << "Diverges with: " << DebugString(*src_it) << " and "
+ << DebugString(*dst_it);
+ if (!(src_it->predicate == dst_it->predicate)) {
+ return errors::InvalidArgument(
+ "Unable to find common predicate which holds for one input "
+ "but not the other of the merge node.");
+ }
+ pred = src_it->predicate;
+ break;
+ }
+ ++src_it;
+ ++dst_it;
+ }
+
+ if (pred.node == nullptr)
+ return errors::InvalidArgument("Unable to determine predicate for merge.");
+
+ TF_ASSIGN_OR_RETURN(auto div_src_it,
+ FindThenElseSwitchForPredicate(pred, src));
+ TF_ASSIGN_OR_RETURN(auto div_dst_it,
+ FindThenElseSwitchForPredicate(pred, dst));
+ TF_RET_CHECK(*div_src_it != *div_dst_it);
+
+ CondStateMap::CondState result;
+ // Populate result with the longest/most restrictive path up to the divergent
+ // node. For example, if the one input is `[switch(pred:0, then)]` and the
+ // other is `[switch(pred:0, both), merge, switch(pred:0, else)]` (as created
+ // in gradient of cond test), then the resultant state here should be
+ // `[switch(pred:0, both), merge, switch(pred:0, both)]`.
+ if (std::distance(src->begin(), div_src_it) >
+ std::distance(dst->begin(), div_dst_it)) {
+ result.assign(src->begin(), std::next(div_src_it));
+ } else {
+ result.assign(dst->begin(), std::next(div_dst_it));
+ }
+ result.back().branch = BranchType::kBoth;
+ return cond_state_map_.GetUniqueId(result);
+}
+
+CondStateMap::CondId FunctionalizeCond::StateAlongEdge(const Edge* e) {
+ Node* src = e->src();
+ CondStateMap::CondId id = cond_state_map_.LookupId(e->src());
+ if (IsMerge(src)) {
+ CondStateMap::CondState state;
+ if (id != nullptr) state = *id;
+ state.emplace_back(CondStateMap::CondNode::Type::kMerge);
+ return cond_state_map_.GetUniqueId(state);
+ }
+ if (IsSwitch(src)) {
+ CondStateMap::CondState state;
+ if (id != nullptr) state = *id;
+ if (e->IsControlEdge()) {
+ state.emplace_back(CondStateMap::CondNode::Type::kSwitch, src,
+ BranchType::kBoth);
+ } else {
+ state.emplace_back(CondStateMap::CondNode::Type::kSwitch, src,
+ BranchType(e->src_output()));
+ }
+ return cond_state_map_.GetUniqueId(state);
+ }
+ return id;
+}
+
+Status FunctionalizeCond::DetermineCondStateMerge(Node* dst) {
+ // Only Merge nodes with two inputs are supported, but if this is a redundant
+ // merge, then the dead edge may already have been removed (if due to a
+ // switch) and so the input count would be incorrect.
+ if (cond_state_map_.IsDead(cond_state_map_.LookupId(dst)))
+ return Status::OK();
+
+ int data_inputs = 0;
+ for (auto e : dst->in_edges()) {
+ Node* src = e->src();
+ VLOG(5) << "Processing forward flow for merge: " << e->DebugString() << " "
+ << cond_state_map_.CondStateToString(src);
+ if (!src->IsOp()) continue;
+ if (!e->IsControlEdge()) ++data_inputs;
+
+ CondStateMap::CondId prop = StateAlongEdge(e);
+ auto id_or = JoinCondStatesMerge(prop, cond_state_map_.LookupId(dst));
+ TF_RETURN_WITH_CONTEXT_IF_ERROR(id_or.status(), "for node ", dst->name());
+ cond_state_map_.ResetId(dst, id_or.ValueOrDie());
+ }
+
+ // Incomplete Merge nodes are not supported.
+ if (data_inputs != 2) {
+ return errors::Unimplemented(
+ dst->name(), " only has ", data_inputs,
+ " inputs, while only merge nodes with two inputs supported.");
+ }
+ return Status::OK();
+}
+
+Status FunctionalizeCond::DetermineCondState(Node* dst) {
+ // The logic for the merge and non-merge case differ: for non-merge it is
+ // the most restrictive CondState, while for merge nodes the
+ // resultant state is less restrictive than either.
+ if (IsMerge(dst)) {
+ TF_RETURN_IF_ERROR(DetermineCondStateMerge(dst));
+ } else {
+ // Handle non-merge join.
+ for (auto e : dst->in_edges()) {
+ VLOG(5) << "Processing forward flow for: " << e->DebugString() << " "
+ << cond_state_map_.CondStateToString(dst);
+ Node* src = e->src();
+ if (!src->IsOp()) continue;
+
+ // Joining the state between the current and propagated state.
+ CondStateMap::CondId prop = StateAlongEdge(e);
+ auto id_or = JoinCondStatesNonMerge(prop, cond_state_map_.LookupId(dst));
+ TF_RETURN_WITH_CONTEXT_IF_ERROR(id_or.status(), "for node ", dst->name());
+ cond_state_map_.ResetId(dst, id_or.ValueOrDie());
+ }
+ }
+ return Status::OK();
+}
+
+Status FunctionalizeCond::RemoveRedundantMerge(Node* node) {
+ // Handle redundant merge nodes. A merge node is considered redundant if
+ // one input edge is dead while the other has a value.
+ if (!cond_state_map_.IsDead(cond_state_map_.LookupId(node)))
+ return Status::OK();
+
+ const Edge* non_dead_edge = nullptr;
+ for (auto e : node->in_edges()) {
+ if (e->IsControlEdge()) continue;
+ Node* src = e->src();
+
+ // Handle merge with dead state.
+ const auto& src_id = cond_state_map_.LookupId(src);
+ if (!cond_state_map_.IsDead(src_id)) {
+ non_dead_edge = e;
+ break;
+ }
+ }
+
+ if (non_dead_edge == nullptr) {
+ return errors::InvalidArgument("Merge node ", node->name(),
+ " has no non-dead inputs.");
+ }
+ cond_state_map_.MarkDead(node);
+ delete_nodes_.push_back(node->id());
+ VLOG(5) << "removing redundant merge: " << node->name();
+ while (!node->out_edges().empty()) {
+ const Edge* oe = *node->out_edges().begin();
+ Node* dst_node = oe->dst();
+ int dst_port = oe->dst_input();
+ graph_->RemoveEdge(oe);
+ graph_->AddEdge(non_dead_edge->src(),
+ dst_port == Graph::kControlSlot
+ ? Graph::kControlSlot
+ : non_dead_edge->src_output(),
+ dst_node, dst_port);
+ }
+ return Status::OK();
+}
+
+Status FunctionalizeCond::RemoveRedundantSwitch(Node* node) {
+ // Handle redundant switch nodes. A switch node is considered redundant if
+ // the predicate of the switch already holds on the current branch. E.g., if
+ // p is the predicate of the switch but p is already known to hold on this
+ // branch, then the switch can be removed and the dead state propagated
+ // along one. The checking of predicate is based on the exact predicate
+ // (rather than boolean equivalence) and aimed at redundant switches as
+ // currently generated by gradient code.
+ OutputTensor pred;
+ TF_RETURN_IF_ERROR(GetSwitchPredicate(*node, &pred));
+ auto dst_id = cond_state_map_.LookupId(node);
+ BranchType b = cond_state_map_.FindBranchOf(dst_id, pred);
+ // Determine if we are already on a branch where the switch predicate is
+ // true/false.
+ if (b != BranchType::kThenBranch && b != BranchType::kElseBranch)
+ return Status::OK();
+
+ VLOG(5) << "Redundant switch " << node->name();
+ const Edge* value_edge;
+ TF_RETURN_IF_ERROR(node->input_edge(0, &value_edge));
+ Node* val_node = value_edge->src();
+ int val_port = value_edge->src_output();
+ while (!node->out_edges().empty()) {
+ auto e = *node->out_edges().begin();
+ Node* dst_node = e->dst();
+ int dst_input = e->dst_input();
+ int switch_branch = e->src_output();
+ graph_->RemoveEdge(e);
+ if (switch_branch == Graph::kControlSlot) {
+ if (IsMerge(dst_node)) {
+ auto id_or =
+ JoinCondStatesMerge(dst_id, cond_state_map_.LookupId(dst_node));
+ TF_RETURN_IF_ERROR(id_or.status());
+ cond_state_map_.ResetId(dst_node, id_or.ValueOrDie());
+ } else {
+ auto id_or =
+ JoinCondStatesNonMerge(dst_id, cond_state_map_.LookupId(dst_node));
+ TF_RETURN_IF_ERROR(id_or.status());
+ cond_state_map_.ResetId(dst_node, id_or.ValueOrDie());
+ }
+ } else if (BranchType(switch_branch) != b) {
+ cond_state_map_.MarkDead(dst_node);
+ delete_nodes_.push_back(dst_node->id());
+ continue;
+ }
+ graph_->AddEdge(
+ val_node,
+ switch_branch == Graph::kControlSlot ? Graph::kControlSlot : val_port,
+ dst_node, dst_input);
+ }
+ return Status::OK();
+}
+
+Status FunctionalizeCond::DetermineCondStates(
+ std::vector<Node*> rev_topo_order) {
+ // The state that is propagated along the given edge.
+ for (auto it = rev_topo_order.rbegin(); it != rev_topo_order.rend(); ++it) {
+ Node* dst = *it;
+ TF_RETURN_IF_ERROR(DetermineCondState(dst));
+ if (IsSwitch(dst)) TF_RETURN_IF_ERROR(RemoveRedundantSwitch(dst));
+ if (IsMerge(dst)) TF_RETURN_IF_ERROR(RemoveRedundantMerge(dst));
+
+ VLOG(5) << dst->name() << " :: " << cond_state_map_.CondStateToString(dst);
+ }
+ return Status::OK();
+}
+
+void FunctionalizeCond::DeleteReachableNodes() {
+ // Delete all nodes that have been extracted or are reachable from
+ // deleted/dead nodes. The input and outgoing edges should have already been
+ // removed.
+ std::vector<bool> deleted(graph_->num_node_ids(), false);
+ // Don't try to delete source or sink nodes.
+ deleted[graph_->kSourceId] = true;
+ deleted[graph_->kSinkId] = true;
+ while (!delete_nodes_.empty()) {
+ int d_id = delete_nodes_.front();
+ delete_nodes_.pop_front();
+ if (deleted[d_id]) continue;
+ Node* d = graph_->FindNodeId(d_id);
+ // Switch and Merge nodes could have been deleted already.
+ if (d == nullptr) continue;
+ for (const Edge* e : d->out_edges()) {
+ delete_nodes_.push_back(e->dst()->id());
+ }
+ deleted[d_id] = true;
+ graph_->RemoveNode(d);
+ }
+}
+
+void FunctionalizeCond::SortMergeNodes(std::vector<Node*>* merge_order) {
+ // Sort merge nodes by nesting depth.
+ using sort_pair = std::pair<int, Node*>;
+ std::vector<sort_pair> inner_to_outer_merge_order;
+ inner_to_outer_merge_order.reserve(merge_order->size());
+ for (auto it = merge_order->rbegin(); it != merge_order->rend(); ++it) {
+ Node* merge = *it;
+ CondStateMap::CondId id = cond_state_map_.LookupId(merge);
+ int depth = 0;
+ for (auto cond_node_it = id->begin(); cond_node_it != id->end();
+ ++cond_node_it) {
+ if (cond_node_it->type == CondStateMap::CondNode::Type::kSwitch &&
+ (cond_node_it->branch == BranchType::kThenBranch ||
+ cond_node_it->branch == BranchType::kElseBranch)) {
+ ++depth;
+ }
+ }
+ inner_to_outer_merge_order.emplace_back(depth, merge);
+ }
+ std::stable_sort(
+ inner_to_outer_merge_order.begin(), inner_to_outer_merge_order.end(),
+ [](sort_pair lhs, sort_pair rhs) { return lhs.first > rhs.first; });
+ merge_order->clear();
+ for (sort_pair t : inner_to_outer_merge_order) {
+ merge_order->push_back(t.second);
+ }
+}
+
+Status FunctionalizeCond::FunctionalizeInternal() {
+ // The general approach for converting a tf.cond (as lowered via switch/merge
+ // nodes) to a functional if is as follows:
+ // 1. Determine the topological order and collect all the switch and merge
+ // nodes in the graph;
+ // 2. Compute the predicates and dominance structure for all the nodes in the
+ // graph - this includes which predicate must be true for a op to execute
+ // (predicate values are considered directly rather than attempting to
+ // determine deeper equivalence). We shall refer to this structure as the
+ // CondState;
+ // 3. Sort the merge nodes by nesting depth;
+ // 4. Extract merge nodes together that have the same CondState and whose
+ // input nodes have the same state from the innermost to the outermost into
+ // IfOps; Note: In the above only nodes paths that converge to a merge node
+ // will be considered for removal.
+
+ // Perform a DFS over the graph and
+ // * Determine the reverse topological order of the nodes (there should be no
+ // cycles at this point so the post-order numbering corresponds to the
+ // reverse topological sorting);
+ // * Record reverse topological for merge and switch nodes;
+ std::vector<Node*> rev_topo_order;
+ std::vector<int> switch_ids;
+ std::vector<Node*> merge_order;
+ DFS(*graph_, nullptr, [&](Node* n) {
+ if (IsSwitch(n)) {
+ switch_ids.push_back(n->id());
+ }
+ if (IsMerge(n)) {
+ merge_order.push_back(n);
+ }
+ if (n->IsOp()) {
+ rev_topo_order.push_back(n);
+ }
+ });
+
+ // No merges to functionalize.
+ if (merge_order.empty()) {
+ // No merges mean no switch values consumed (as only considering values
+ // fetchable as output of merge);
+ for (auto it = switch_ids.begin(); it != switch_ids.end(); ++it) {
+ graph_->RemoveNode(graph_->FindNodeId(*it));
+ }
+ return Status::OK();
+ }
+
+ TF_RETURN_IF_ERROR(DetermineCondStates(std::move(rev_topo_order)));
+
+ if (VLOG_IS_ON(4)) DumpGraphWithCondState("cond_id");
+
+ // Sort the merge nodes from innermost outwards.
+ SortMergeNodes(&merge_order);
+
+ // Extract from innermost out.
+ for (auto it = merge_order.begin(); it != merge_order.end(); ++it) {
+ Node* merge = *it;
+ auto id = cond_state_map_.LookupId(merge);
+ if (cond_state_map_.IsDead(id)) continue;
+
+ // Construct a Conditional with the predicate of the merge (which is the
+ // last entry of the CondState for the merge) and this as parent.
+ DCHECK(id->back().predicate.node != nullptr);
+ Conditional cond(id->back().predicate, this, &cond_state_map_);
+ TF_RETURN_IF_ERROR(cond.AddMerge(merge));
+
+ // Find all merge nodes with the same CondId. This is done repeatedly as
+ // the CondId can change due replaced conditionals. E.g., the one branch
+ // could previously have had a conditional nested in it, and so would have
+ // had CondState with sub-state [switch(p,b),m] (where p is some predicate),
+ // post removing the nested conditional that sub-state would no longer be
+ // path of the propagated state along that path.
+ auto end = merge_order.end();
+ for (auto merge_candidate_it = std::next(it); merge_candidate_it != end;
+ ++merge_candidate_it) {
+ auto merge_candidate_it_id =
+ cond_state_map_.LookupId(*merge_candidate_it);
+ if (merge_candidate_it_id != id) continue;
+ TF_RETURN_IF_ERROR(cond.AddMerge(*merge_candidate_it));
+ }
+
+ TF_RETURN_IF_ERROR(cond.BuildAndReplace(graph_, library_));
+
+ if (VLOG_IS_ON(4)) DumpGraphWithCondState("after_extract");
+ }
+
+ // All remaining Switch nodes are not reachable from a Merge node and
+ // removed. This is to account for dead Switch nodes.
+ for (int s_id : switch_ids) delete_nodes_.push_back(s_id);
+ for (Node* m : merge_order) delete_nodes_.push_back(m->id());
+ DeleteReachableNodes();
+
+ return Status::OK();
+}
+
+void FunctionalizeCond::DumpGraphWithCondState(const string& name) {
+ const char* const kCondGroupDebugAttr = "_XlaFunctionalizeCondGroup";
+
+ for (Node* n : graph_->nodes()) {
+ n->ClearAttr(kCondGroupDebugAttr);
+ n->AddAttr(kCondGroupDebugAttr, cond_state_map_.CondStateToString(n));
+ }
+ LOG(INFO) << "FunctionalizeControlFlow (" << name << "): "
+ << dump_graph::DumpGraphToFile(
+ strings::StrCat("functionalize_", name), *graph_, library_);
+}
+
+Status FunctionalizeCond::Functionalize(Graph* graph,
+ FunctionLibraryDefinition* library) {
+ VLOG(1) << "FunctionalizeCond::Functionalize";
+ FunctionalizeCond fc(graph, library);
+ return fc.FunctionalizeInternal();
+}
+
+} // namespace functionalize_cond
+
+Status FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library) {
+ // FunctionalizeControlFlow is invoked for every function, so the loops's
+ // bodies and conditionals that were extracted into functions will be handled
+ // in successive invocations.
+ return functionalize_cond::FunctionalizeCond::Functionalize(graph, library);
+}
+
+} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_cond.h b/tensorflow/compiler/tf2xla/functionalize_cond.h
new file mode 100644
index 0000000000..86436011c6
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_cond.h
@@ -0,0 +1,248 @@
+/* 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.
+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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_COND_H_
+#define TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_COND_H_
+
+#include <deque>
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/core/framework/function.h"
+#include "tensorflow/core/graph/graph.h"
+
+namespace tensorflow {
+
+// Functionalize all the switch-merge nodes of a loop-free graph into If
+// nodes. That is, attempt to transform every remaining switch and merge nodes
+// in the graph into If nodes.
+// Precondition: All while loops have been removed from graph.
+Status FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library);
+
+// Internal functions/classes exposed for testing purposes.
+namespace functionalize_cond {
+
+// All nodes are assumed to be either in no branch, then branch, else branch,
+// or both branches (such as merge nodes).
+// The code below relies on Else and Then being 0 and 1 (corresponding to the
+// switch outputs). Both and Neither are arbitrary.
+enum class BranchType {
+ kElseBranch = 0,
+ kThenBranch = 1,
+ kBoth = 2,
+ kNeither = 3,
+};
+
+// CondStateMap is responsible for mapping from each graph Node to a CondState,
+// where each CondState is the array of CondNodes (corresponding to switch,
+// merge or dead states) as described below. For efficiency, this class interns
+// the CondState, so that CondState equality comparisons are simply pointer
+// comparisons.
+class CondStateMap {
+ public:
+ explicit CondStateMap(Graph* graph);
+
+ // Represents an entry in the CondState. An entry can either be the
+ // switch (along with predicate), merge, or dead:
+ // * switch node indicates a node that is executed along a branch with the
+ // given predicate - a branch can be then, else or both;
+ // * merge node indicates that the node is executed as output of a merge;
+ // * dead indicates that this node can never be executed;
+ struct CondNode {
+ enum class Type { kSwitch = 1, kMerge = 2, kDead = 3 };
+
+ CondNode(Type type, Node* switch_node = nullptr,
+ BranchType branch = BranchType::kNeither);
+
+ string ToString() const;
+ bool operator==(const CondNode& other) const;
+ bool operator!=(const CondNode& other) const;
+
+ // Type of node.
+ Type type;
+
+ // Predicate and branch, only used when type is kSwitch.
+ OutputTensor predicate;
+ BranchType branch;
+ };
+
+ // A node in the graph is executed when multiple conditions hold. The order
+ // represents the nesting of the predicates that hold and is used when
+ // extracting the nested conditionals.
+ using CondState = std::vector<CondNode>;
+
+ // Every unique ID is mapped to a CondState.
+ using CondId = const CondState*;
+
+ // Returns the CondId for a given node.
+ CondId LookupId(const Node* node) const;
+
+ // Returns the unique CondId for CondState.
+ CondId GetUniqueId(const CondState& state);
+
+ // Returns the CondState for a Node.
+ // REQUIRES: node has a non-empty CondState.
+ const CondState& LookupState(const Node* node) const;
+
+ // Resets the CondId for a given node.
+ void ResetId(const Node* node, CondId id);
+
+ // Marks `node` as dead.
+ void MarkDead(const Node* node);
+
+ // Determine branch execution of CondState.
+ BranchType FindBranchOf(CondId id, OutputTensor predicate) const;
+
+ // Enum to represent whether one cond flow state contains another.
+ enum ContainsResult {
+ kIncomparable,
+ kEqual,
+ kLhsContainsRhs,
+ kRhsContainsLhs
+ };
+
+ // Returns whether the lhs CondState holds wherever rhs CondState hols. I.e.,
+ // [(p,t)] contains [(p,t), (r,t)].
+ ContainsResult LhsHoldsWhereverRhsHolds(CondId lhs, CondId rhs);
+
+ // Returns textual representation of node's CondState.
+ string CondStateToString(const Node* node) const;
+ string CondStateToString(CondId id) const;
+
+ // Returns whether the cond state is the dead state.
+ bool IsDead(CondId id) const;
+
+ // Returns whether the cond state is the empty state.
+ bool IsEmpty(CondId id) const;
+
+ // Computes the predicates that have to hold for a node to execute and returns
+ // whether it was possible to determine the predicates that must hold. `scope`
+ // is populated with these predicates. Scope differs from state in that it
+ // does not include merge and both nodes.
+ bool ScopeIn(CondId id, CondId* scope);
+
+ private:
+ // Hash for CondNode and CondState.
+ struct CondHash {
+ size_t operator()(const CondNode& item) const;
+ size_t operator()(const CondState& vec) const;
+ };
+
+ // Set to keep track of unique CondStates.
+ // Pointers to the entries in the unordered set are used as identifiers:
+ // unordered_set guarantees that the pointers remain the same.
+ std::unordered_set<CondState, CondHash> condstate_set_;
+
+ // Mapping from Node id to CondId.
+ std::vector<CondId> node_to_condid_map_;
+
+ // Track the CondId for newly inserted nodes. We use a vector to quickly map
+ // from Node id in the original graph to the CondId, but there will be nodes
+ // added to the original graph (such as If nodes) whose CondState needs to be
+ // tracked too.
+ std::unordered_map<int, CondId> added_node_mapping_;
+
+ // Identifier of the dead flow state. The empty flow state is represented with
+ // a nullptr.
+ CondId dead_id_;
+};
+
+// FunctionalizeCond groups all the state used by functionalizing conditionals
+// of the given graph together.
+class FunctionalizeCond {
+ public:
+ // Functionalize all the switch-merge nodes of a loop-free graph into If
+ // nodes. That is, attempt to transform every remaining switch and merge nodes
+ // in the graph into If nodes.
+ // Precondition: All while loops have been removed from graph.
+ static Status Functionalize(Graph* graph, FunctionLibraryDefinition* library);
+
+ // Build identity node with the same name as the merge that will be replaced
+ // in case the output is fetched/colocated.
+ Status AddIdentityNode(const Node* replacee, Node* if_node, int port);
+
+ // Add a If node to the graph defined by def that will, amongst other, replace
+ // replacee in the graph.
+ xla::StatusOr<Node*> AddIfNode(const NodeDef& def, const Node* replacee);
+
+ // Propagates the state of a newly inserted node.
+ Status PropagateUpdatedState(const Node* replacee);
+
+ // Dump graph with the CondState annotated.
+ void DumpGraphWithCondState(const string& name);
+
+ private:
+ FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library);
+
+ // Performs the actual cond functionalization. Iterate over groups of merge
+ // nodes (linked by common predicate & CondIds of the incomming edges),
+ // from innermost to outermost, and extract into If nodes.
+ Status FunctionalizeInternal();
+
+ // Returns the forward flow state propagated along edge `e`.
+ // This may modify cond_state_map_.
+ CondStateMap::CondId StateAlongEdge(const Edge* e);
+
+ // Determines the CondState of all the nodes in the given vector where
+ // the input is expected in reverse topological order.
+ // This populates the cond_state_map_.
+ Status DetermineCondStates(std::vector<Node*> rev_topo_order);
+
+ // Determine the CondState for a given node using the incomming edges
+ // to the node. Note: it is expected that this node's CondState is only
+ // determined once its input's CondState is.
+ Status DetermineCondState(Node* dst);
+
+ // Helper functions for DetermineCondState.
+ Status DetermineCondStateMerge(Node* dst);
+
+ // Helper functions for DetermineCondStates. Determines the dst node's
+ // CondState by joining the src and dst's CondState where either
+ // the dst node is a merge or not.
+ // These may modify cond_state_map_.
+ xla::StatusOr<CondStateMap::CondId> JoinCondStatesMerge(
+ CondStateMap::CondId src, CondStateMap::CondId dst);
+ xla::StatusOr<CondStateMap::CondId> JoinCondStatesNonMerge(
+ CondStateMap::CondId src, CondStateMap::CondId dst);
+
+ // Checks if a merge node is redundant and if so removes it from the graph.
+ Status RemoveRedundantMerge(Node* node);
+
+ // Checks if a switch node is redundant and if so removes it from the graph.
+ Status RemoveRedundantSwitch(Node* node);
+
+ // Sorts merge nodes (in reverse topological order) in order of increasing
+ // nesting depth.
+ void SortMergeNodes(std::vector<Node*>* merge_order);
+
+ // Deletes all nodes in/consumers of `delete_nodes_`.
+ void DeleteReachableNodes();
+
+ // Member used to unique the CondState to a unique CondId and keep track of
+ // CondState/CondId per Node.
+ CondStateMap cond_state_map_;
+
+ // Nodes to be deleted.
+ std::deque<int> delete_nodes_;
+
+ FunctionLibraryDefinition* library_;
+ Graph* graph_;
+
+ friend class FunctionalizeCondTest;
+};
+
+} // namespace functionalize_cond
+
+} // namespace tensorflow
+
+#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_COND_H_
diff --git a/tensorflow/compiler/tf2xla/functionalize_cond_test.cc b/tensorflow/compiler/tf2xla/functionalize_cond_test.cc
new file mode 100644
index 0000000000..548c948d09
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_cond_test.cc
@@ -0,0 +1,180 @@
+/* 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 the backward const analysis.
+
+#include "tensorflow/compiler/tf2xla/functionalize_cond.h"
+
+#include "tensorflow/cc/framework/ops.h"
+#include "tensorflow/cc/ops/function_ops.h"
+#include "tensorflow/cc/ops/standard_ops.h"
+#include "tensorflow/core/graph/testlib.h"
+#include "tensorflow/core/lib/core/status_test_util.h"
+#include "tensorflow/core/platform/test.h"
+
+namespace tensorflow {
+namespace functionalize_cond {
+
+class FunctionalizeCondTest : public ::testing::Test {
+ protected:
+ FunctionalizeCondTest() {
+ graph_.reset(new Graph(OpRegistry::Global()));
+ flib_def_.reset(
+ new FunctionLibraryDefinition(OpRegistry::Global(), fdef_lib_));
+ fc_.reset(new functionalize_cond::FunctionalizeCond(graph_.get(),
+ flib_def_.get()));
+ }
+
+ CondStateMap::CondId GetUniqueId(
+ const CondStateMap::CondStateMap::CondState& state) {
+ return fc_->cond_state_map_.GetUniqueId(state);
+ }
+
+ xla::StatusOr<CondStateMap::CondId> JoinCondStatesNonMerge(
+ CondStateMap::CondId src, CondStateMap::CondId dst) {
+ return fc_->JoinCondStatesNonMerge(src, dst);
+ }
+
+ xla::StatusOr<CondStateMap::CondId> JoinCondStatesMerge(
+ CondStateMap::CondId src, CondStateMap::CondId dst) {
+ return fc_->JoinCondStatesMerge(src, dst);
+ }
+
+ bool ScopeIn(CondStateMap::CondId ff, CondStateMap::CondId* scope) {
+ return fc_->cond_state_map_.ScopeIn(ff, scope);
+ }
+
+ CondStateMap::ContainsResult LhsHoldsWhereverRhsHolds(
+ CondStateMap::CondId lhs, CondStateMap::CondId rhs) {
+ return fc_->cond_state_map_.LhsHoldsWhereverRhsHolds(lhs, rhs);
+ }
+
+ FunctionDefLibrary fdef_lib_;
+ std::unique_ptr<functionalize_cond::FunctionalizeCond> fc_;
+ std::unique_ptr<FunctionLibraryDefinition> flib_def_;
+ std::unique_ptr<Graph> graph_;
+};
+
+namespace {
+
+TEST_F(FunctionalizeCondTest, ScopeIn) {
+ Tensor pred_tensor(DT_BOOL, TensorShape());
+ Node* pred = test::graph::Constant(graph_.get(), pred_tensor, "pred");
+ Tensor val_tensor(DT_INT32, TensorShape());
+ Node* val = test::graph::Constant(graph_.get(), val_tensor, "val");
+ Node* s = test::graph::Switch(graph_.get(), val, pred);
+
+ {
+ CondStateMap::CondStateMap::CondState ss;
+ ss.emplace_back(CondStateMap::CondNode(
+ CondStateMap::CondNode::Type::kSwitch, s, BranchType::kThenBranch));
+ CondStateMap::CondId id = GetUniqueId(ss);
+ CondStateMap::CondId scope;
+ ASSERT_TRUE(ScopeIn(id, &scope));
+ ASSERT_TRUE(id == scope);
+ }
+
+ CondStateMap::CondState empty;
+ {
+ CondStateMap::CondState ss;
+ ss.emplace_back(CondStateMap::CondNode(
+ CondStateMap::CondNode::Type::kSwitch, s, BranchType::kBoth));
+ ss.emplace_back(
+ CondStateMap::CondNode(CondStateMap::CondNode::Type::kMerge));
+ CondStateMap::CondId id = GetUniqueId(ss);
+ CondStateMap::CondId scope_1;
+ ASSERT_TRUE(ScopeIn(id, &scope_1));
+ ASSERT_TRUE(scope_1 == GetUniqueId(empty));
+ ASSERT_TRUE(id != scope_1);
+
+ ss.clear();
+ ss.emplace_back(CondStateMap::CondNode(
+ CondStateMap::CondNode::Type::kSwitch, s, BranchType::kBoth));
+ id = GetUniqueId(ss);
+ CondStateMap::CondId scope_2;
+ ASSERT_TRUE(ScopeIn(id, &scope_2));
+
+ ASSERT_TRUE(LhsHoldsWhereverRhsHolds(scope_1, scope_2) ==
+ CondStateMap::ContainsResult::kLhsContainsRhs);
+ }
+}
+
+TEST_F(FunctionalizeCondTest, JoinCondStates) {
+ Tensor pred_tensor(DT_BOOL, TensorShape());
+ Node* pred = test::graph::Constant(graph_.get(), pred_tensor, "pred");
+ Tensor val_tensor(DT_INT32, TensorShape());
+ Node* val = test::graph::Constant(graph_.get(), val_tensor, "val");
+ Node* s = test::graph::Switch(graph_.get(), val, pred);
+
+ CondStateMap::CondId empty = GetUniqueId({});
+
+ CondStateMap::CondId then_branch;
+ {
+ CondStateMap::CondState ss;
+ ss.emplace_back(CondStateMap::CondNode(
+ CondStateMap::CondNode::Type::kSwitch, s, BranchType::kThenBranch));
+ then_branch = GetUniqueId(ss);
+ }
+ CondStateMap::CondId else_branch;
+ {
+ CondStateMap::CondState ss;
+ ss.emplace_back(CondStateMap::CondNode(
+ CondStateMap::CondNode::Type::kSwitch, s, BranchType::kElseBranch));
+ else_branch = GetUniqueId(ss);
+ }
+
+ // An non-merge op with inputs from then and else branch.
+ Status status = JoinCondStatesNonMerge(then_branch, else_branch).status();
+ EXPECT_TRUE(errors::IsInvalidArgument(status));
+
+ // Merge between then and else branch.
+ auto joined_or = JoinCondStatesMerge(then_branch, else_branch);
+ TF_EXPECT_OK(joined_or.status());
+ CondStateMap::CondId joined = joined_or.ValueOrDie();
+
+ // Merge between then branch and both branch.
+ auto t = JoinCondStatesNonMerge(then_branch, joined);
+ // Note: this is OK in terms of constraint predication, but
+ TF_EXPECT_OK(t.status());
+
+ // Post merge the propagated forward flow state has an additional merge.
+ CondStateMap::CondId post_merge;
+ {
+ CondStateMap::CondState ss;
+ ss = *joined;
+ ss.emplace_back(
+ CondStateMap::CondNode(CondStateMap::CondNode::Type::kMerge));
+ post_merge = GetUniqueId(ss);
+ }
+
+ t = JoinCondStatesNonMerge(post_merge, joined);
+ TF_EXPECT_OK(t.status());
+ EXPECT_TRUE(joined == t.ValueOrDie());
+
+ // No predicate that results in two paths predicated on different conditions
+ // merge.
+ t = JoinCondStatesMerge(post_merge, joined);
+ EXPECT_FALSE(t.ok());
+
+ // Post the merge we are effectively in the root scope and merging should
+ // result in the more restrictive post merge state.
+ t = JoinCondStatesNonMerge(post_merge, empty);
+ TF_EXPECT_OK(t.status());
+ EXPECT_TRUE(post_merge == t.ValueOrDie());
+}
+
+} // namespace
+} // namespace functionalize_cond
+} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_control_flow.cc b/tensorflow/compiler/tf2xla/functionalize_control_flow.cc
index 0904778f97..2cfa3c046e 100644
--- a/tensorflow/compiler/tf2xla/functionalize_control_flow.cc
+++ b/tensorflow/compiler/tf2xla/functionalize_control_flow.cc
@@ -23,6 +23,9 @@ limitations under the License.
#include "tensorflow/compiler/jit/union_find.h"
#include "tensorflow/compiler/tf2xla/dump_graph.h"
+#include "tensorflow/compiler/tf2xla/functionalize_cond.h"
+#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h"
+#include "tensorflow/compiler/tf2xla/functionalize_while.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
@@ -31,1430 +34,11 @@ limitations under the License.
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/control_flow.h"
+#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/lib/gtl/optional.h"
namespace tensorflow {
-namespace {
-
-using xla::StatusOr;
-
-const char* const kArgOp = "_Arg";
-const char* const kRetValOp = "_Retval";
-
-// Information about a loop argument.
-struct Arg {
- // Every loop argument has an Enter node.
- Node* enter;
-
- // Is the loop argument a loop-invariant value? Taken from the `is_constant`
- // attribute on the Enter node.
- bool is_loop_invariant;
-
- // If 'is_loop_invariant' is true, the following are all nullptr. Non-constant
- // arguments must have all of the following nodes:
- Node* merge = nullptr;
- Node* switch_node = nullptr;
- Node* next_iteration = nullptr;
- Node* exit = nullptr;
-};
-
-// Information about a loop frame.
-struct Frame {
- string name;
-
- // Pointer to the parent frame. The root frame has a pointer to itself.
- Frame* parent = nullptr;
- int num_children = 0;
-
- // Arguments to this loop.
- std::vector<Arg> args;
-
- // The loop condition of the loop. There should be exactly one loop condition
- // in every loop.
- Node* loop_cond = nullptr;
-
- // Set of nodes that belong to the loop frame.
- std::unordered_set<Node*> nodes;
-};
-
-// Comparison function used for sorting nodes consistently.
-// a) resource variables are last, and
-// b) sort lexicographically by name (for deterministic output).
-struct NodeCmp {
- bool operator()(const Node* lhs, const Node* rhs) const {
- bool lhs_is_resource =
- lhs->num_inputs() > 0 ? (lhs->input_type(0) == DT_RESOURCE) : false;
- bool rhs_is_resource =
- rhs->num_inputs() > 0 ? (rhs->input_type(0) == DT_RESOURCE) : false;
- return std::tie(lhs_is_resource, lhs->name()) <
- std::tie(rhs_is_resource, rhs->name());
- }
-};
-
-// Returns a textual representation of the names of the nodes in the input.
-template <typename T>
-string NodesToString(const T& nodes) {
- return strings::StrCat("{",
- str_util::Join(nodes, ",",
- [](string* output, const Node* node) {
- strings::StrAppend(output,
- node->name());
- }),
- "}");
-}
-
-// Copies a subgraph from `graph` to `output` by performing a reverse DFS
-// starting at nodes in vector `stack`.
-// `node_map` is a vector indexed by source node ID to dest nodes.
-// Does not traverse into nodes in `node_map`, so by adding nodes to `node_map`
-// before the traversal clients can cut the graph. If a frame is provided (frame
-// != nullptr), then this functions will return an error if the
-// traversal leaves 'frame'; the client must add enough nodes to `node_map` to
-// cut the graph and prevent the traversal from escaping.
-//
-// `squash_src_outputs` contains a bool for each source node ID. If true, then
-// the source output on that node will be replaced by zero when copied. This is
-// used when replacing a Switch node with an _Arg node. The output we are
-// taking from the Switch node was not necessarily the first output, but _Arg
-// nodes only have one output. By adding the Switch node to `squash_src_outputs`
-// we rewrite the src_output of the corresponding edge to be 0.
-Status CopySubgraph(const Graph& graph, const Frame* frame,
- std::vector<Node*> stack,
- const std::vector<bool>& squash_src_outputs,
- std::vector<Node*>* node_map, Graph* output) {
- VLOG(3) << "Stack: " << NodesToString(stack);
- std::vector<bool> visited(graph.num_node_ids(), false);
- while (!stack.empty()) {
- Node* n = stack.back();
- stack.pop_back();
-
- VLOG(5) << "Copying node " << n->name();
-
- if (visited[n->id()]) continue;
- visited[n->id()] = true;
-
- for (const Edge* e : n->in_edges()) {
- Node* src = e->src();
- if (frame != nullptr && frame->nodes.find(src) == frame->nodes.end()) {
- // We traversed out of the loop frame, without encountering a cut node.
- return errors::Internal("Graph traversal of loop frame ", frame->name,
- " escaped frame at ", src->name(),
- " without encountering an argument node.");
- }
- if ((*node_map)[src->id()] == nullptr) {
- (*node_map)[src->id()] = output->CopyNode(src);
- stack.push_back(src);
- }
- Node* src_copy = (*node_map)[e->src()->id()];
- int src_output = squash_src_outputs[e->src()->id()] && !e->IsControlEdge()
- ? 0
- : e->src_output();
- Node* dst_copy = (*node_map)[e->dst()->id()];
- output->AddEdge(src_copy, src_output, dst_copy, e->dst_input());
- }
- }
- return Status::OK();
-}
-
-StatusOr<Node*> AddNode(const NodeDef& node_def, Graph* graph) {
- Status status;
- Node* inserted_node = graph->AddNode(node_def, &status);
- if (!status.ok()) {
- return status;
- }
- return inserted_node;
-}
-
-// Check that the graph has no cycle containing the given node.
-Status CheckNoCycleContains(const Node* node, const int num_nodes) {
- std::vector<const Node*> ready;
- ready.push_back(node);
- std::vector<bool> visited(num_nodes);
- while (!ready.empty()) {
- const Node* current_node = ready.back();
- ready.pop_back();
- visited[current_node->id()] = true;
- for (const Edge* out : current_node->out_edges()) {
- if (out->dst() == node) {
- return errors::Internal("Detected a cycle: ", FormatNodeForError(*node),
- "(", node->def().op(), ") feeds into itself.");
- } else if (!visited[out->dst()->id()]) {
- ready.push_back(out->dst());
- }
- }
- }
- return Status::OK();
-}
-
-StatusOr<Node*> BuildArgNode(Graph* graph, DataType type, int index) {
- NodeDef arg_def;
- NodeDefBuilder builder(strings::StrCat(kArgOp, index), kArgOp);
- builder.Attr("T", type);
- builder.Attr("index", index);
- TF_RETURN_IF_ERROR(builder.Finalize(&arg_def));
- return AddNode(arg_def, graph);
-}
-
-StatusOr<Node*> BuildRetvalNode(Graph* graph, DataType type, int index) {
- NodeDef ret_def;
- ret_def.set_op(kRetValOp);
- ret_def.set_name(strings::StrCat(kRetValOp, index));
- AddNodeAttr("T", type, &ret_def);
- AddNodeAttr("index", index, &ret_def);
- return AddNode(ret_def, graph);
-}
-
-// Builds a graph for the loop condition.
-Status BuildLoopCondition(const Graph& graph, Frame* frame,
- std::unique_ptr<Graph>* cond_output) {
- VLOG(2) << "Building loop condition for " << frame->name;
- *cond_output = xla::MakeUnique<Graph>(graph.op_registry());
- Graph* output = cond_output->get();
-
- // Map from nodes in the original graph to the condition graph.
- std::vector<Node*> node_map(graph.num_node_ids(), nullptr);
- std::vector<bool> squash_src_outputs(graph.num_node_ids(), false);
-
- // Build one _Arg node for each Enter node.
- for (int i = 0; i < frame->args.size(); ++i) {
- const Arg& arg = frame->args[i];
-
- TF_ASSIGN_OR_RETURN(Node * arg_node,
- BuildArgNode(output, arg.enter->input_type(0), i));
- if (arg.is_loop_invariant) {
- node_map[arg.enter->id()] = arg_node;
- } else {
- node_map[arg.merge->id()] = arg_node;
- }
- }
-
- // Build a Retval node for the loop condition. The LoopCond nodes are always
- // boolean because of the type constraints on the LoopCond op.
- TF_ASSIGN_OR_RETURN(node_map[frame->loop_cond->id()],
- BuildRetvalNode(output, DT_BOOL, 0));
-
- // Performs a reverse DFS, copying nodes and edges to the output graph.
- // The _Arg and _Retval nodes were added unconditionally above, so we are
- // guaranteed to get the correct function signature.
- return CopySubgraph(graph, frame, {frame->loop_cond}, squash_src_outputs,
- &node_map, output);
-}
-
-// Builds a graph for the loop body.
-Status BuildLoopBody(const Graph& graph, Frame* frame,
- DataTypeVector* arg_types,
- std::unique_ptr<Graph>* body_output) {
- VLOG(2) << "Building loop body for " << frame->name;
- *body_output = xla::MakeUnique<Graph>(graph.op_registry());
- Graph* output = body_output->get();
-
- // Map from nodes in the original graph to the condition graph.
- std::vector<Node*> node_map(graph.num_node_ids(), nullptr);
- std::vector<bool> squash_src_outputs(graph.num_node_ids(), false);
-
- // Build one _Arg node for each Enter node.
- std::vector<Node*> next_iterations;
- next_iterations.reserve(frame->args.size());
- arg_types->reserve(frame->args.size());
- for (int i = 0; i < frame->args.size(); ++i) {
- const Arg& arg = frame->args[i];
-
- DataType dtype = arg.enter->input_type(0);
- arg_types->push_back(dtype);
-
- TF_ASSIGN_OR_RETURN(Node * arg_node, BuildArgNode(output, dtype, i));
-
- if (dtype == DT_RESOURCE) {
- // The convention of the XLA bridge is that resource variable arguments
- // are only inputs to the loop body and have no corresponding output.
- // TODO(b/37741920): change the convention so that DT_RESOURCE variables
- // are both inputs and outputs, and then remove this case.
- TF_RET_CHECK(arg.is_loop_invariant);
- node_map[arg.enter->id()] = arg_node;
- } else {
- TF_ASSIGN_OR_RETURN(Node * retval_node,
- BuildRetvalNode(output, dtype, i));
-
- if (arg.is_loop_invariant) {
- // Argument is loop-invariant. Forward it from the Arg to the Retval.
- node_map[arg.enter->id()] = arg_node;
- output->AddEdge(arg_node, 0, retval_node, 0);
- } else {
- // Argument is loop-varying.
- node_map[arg.switch_node->id()] = arg_node;
- // The Switch node has two outputs, but _Arg only has one. This tells
- // the CopySubgraph function to rewrite the output number of edges from
- // the _Arg node to be 0 rather than copying the output number from the
- // Switch node.
- squash_src_outputs[arg.switch_node->id()] = true;
- node_map[arg.next_iteration->id()] = retval_node;
- next_iterations.push_back(arg.next_iteration);
- }
- }
- }
-
- // Performs a reverse DFS, copying nodes and edges to the output graph.
- // The _Arg and _Retval nodes were added unconditionally above, so we are
- // guaranteed to get the correct function signature.
- TF_RETURN_IF_ERROR(CopySubgraph(graph, frame, std::move(next_iterations),
- squash_src_outputs, &node_map, output));
-
- return Status::OK();
-}
-
-// Copy the FunctionDef of given function from lookup_library to library, if
-// it can be found in lookup_library but is missing from library.
-Status AddMissingFunctionByName(const string& function_name,
- const FunctionLibraryDefinition* lookup_library,
- FunctionLibraryDefinition* library) {
- if (!library->Find(function_name) && lookup_library->Find(function_name)) {
- return library->AddFunctionDef(*lookup_library->Find(function_name));
- }
- return Status::OK();
-}
-
-// Iterate over all functions that the given fdef refers to. Copy the missing
-// FunctionDefs from lookup_library to library.
-Status AddMissingFunctionDef(const FunctionDef& fdef,
- const FunctionLibraryDefinition* lookup_library,
- FunctionLibraryDefinition* library) {
- TF_RET_CHECK(lookup_library);
- for (const NodeDef& node : fdef.node_def()) {
- if (library->Find(node.op())) {
- continue;
- }
- // The function referred by 'SymbolicGradient' node is specified in its
- // attribute 'f'.
- if (node.op() == FunctionLibraryDefinition::kGradientOp) {
- const AttrValue* attr =
- AttrSlice(&node.attr()).Find(FunctionLibraryDefinition::kFuncAttr);
- if (!attr) {
- return errors::InvalidArgument("SymbolicGradient is missing attr: f");
- }
- const string& func_name = attr->func().name();
- TF_RETURN_IF_ERROR(
- AddMissingFunctionByName(func_name, lookup_library, library));
- // Copy the user-defined gradient function if it exists.
- const string grad_name = lookup_library->FindGradient(func_name);
- if (!grad_name.empty() && library->FindGradient(func_name).empty()) {
- TF_RETURN_IF_ERROR(
- AddMissingFunctionByName(grad_name, lookup_library, library));
- GradientDef grad_def;
- grad_def.set_function_name(func_name);
- grad_def.set_gradient_func(grad_name);
- TF_RETURN_IF_ERROR(library->AddGradientDef(grad_def));
- }
- } else if (lookup_library->Find(node.op())) {
- TF_RETURN_IF_ERROR(
- library->AddFunctionDef(*lookup_library->Find(node.op())));
- }
- }
- return Status::OK();
-}
-
-Status FunctionalizeLoop(const FunctionLibraryDefinition* lookup_library,
- Graph* graph, Frame* frame,
- FunctionLibraryDefinition* library) {
- VLOG(2) << "Frame " << frame->name << " before: "
- << dump_graph::DumpGraphToFile("functionalize_before", *graph,
- library);
-
- // Split loop-varying Enter nodes with multiple successors. If the same
- // Tensor is fed as input to multiple loop arguments, we may end up with a
- // shared Enter node. We clone Enter nodes with multiple successors to
- // maintain the invariant of a unique Enter node per argument of the final
- // loop.
- std::vector<Arg> args;
- for (const Arg& arg : frame->args) {
- if (arg.is_loop_invariant) {
- args.push_back(arg);
- } else {
- std::vector<const Edge*> edges(arg.enter->out_edges().begin(),
- arg.enter->out_edges().end());
- for (int i = 0; i < edges.size(); ++i) {
- if (edges[i]->IsControlEdge() && edges[i]->dst()->IsSink()) {
- continue;
- }
- TF_RET_CHECK(!edges[i]->IsControlEdge()) << edges[i]->src()->name();
- Arg new_arg;
- new_arg.is_loop_invariant = false;
- if (i == 0) {
- new_arg.enter = arg.enter;
- } else {
- new_arg.enter = graph->CopyNode(arg.enter);
- frame->nodes.insert(new_arg.enter);
- for (Edge const* e : arg.enter->in_edges()) {
- graph->AddEdge(e->src(), e->src_output(), new_arg.enter,
- e->IsControlEdge() ? Graph::kControlSlot : 0);
- }
- Node* dst = edges[i]->dst();
- int dst_input = edges[i]->dst_input();
- graph->RemoveEdge(edges[i]);
- graph->AddEdge(new_arg.enter, 0, dst, dst_input);
- }
- args.push_back(new_arg);
- }
- }
- }
- frame->args = std::move(args);
-
- std::sort(
- frame->args.begin(), frame->args.end(),
- [](const Arg& a, const Arg& b) { return NodeCmp()(a.enter, b.enter); });
-
- if (frame->loop_cond == nullptr) {
- return errors::InvalidArgument("Loop ", frame->name,
- " has no LoopCond node");
- }
-
- // Find the set of Switch nodes that are successors of the LoopCond.
- std::unordered_set<Node*> switches;
- for (const Edge* edge : frame->loop_cond->out_edges()) {
- if (!edge->IsControlEdge() && IsSwitch(edge->dst()) &&
- edge->dst_input() == 1) {
- switches.insert(edge->dst());
- }
- }
-
- // For each non-constant argument, looks for the following pattern of nodes:
- // Enter ----> Merge --------> Switch --> Exit
- // ^ ^
- // | |
- // NextIteration LoopCond
- // ^ ^
- // | |
- // ... ...
- for (Arg& arg : frame->args) {
- if (!arg.is_loop_invariant) {
- // Follow the edge from the Enter to Merge.
- const Edge* enter_merge = nullptr;
- for (const Edge* e : arg.enter->out_edges()) {
- // Ignore control-edges to the sink node. These are allowed by the
- // graph invariants, although probably they should have been stripped
- // off earlier.
- if (e->IsControlEdge() && e->dst()->IsSink()) {
- continue;
- }
- if (enter_merge != nullptr) {
- return errors::Internal("Enter node for loop-varying argument ",
- FormatNodeForError(*arg.enter),
- " has multiple successors: ",
- FormatNodeForError(*enter_merge->dst()),
- " and ", FormatNodeForError(*e->dst()));
- }
- enter_merge = e;
- }
- if (enter_merge == nullptr) {
- return errors::Internal("Enter node for loop-varying argument ",
- FormatNodeForError(*arg.enter),
- " has zero successors");
- }
- arg.merge = enter_merge->dst();
- if (!IsMerge(arg.merge)) {
- return errors::InvalidArgument(
- "Successor of Enter node for loop-varying argument ",
- FormatNodeForError(*arg.merge),
- " is not a Merge node; got: ", arg.merge->type_string());
- }
-
- // Find the NextIteration from the merge. There should be two inputs to
- // the Merge and the NextIteration should be the other input.
- if (arg.merge->input_types().size() != 2) {
- return errors::InvalidArgument(
- "Unexpected number of inputs to Merge node for loop-varying "
- "argument ",
- FormatNodeForError(*arg.merge), "; expected 2, got ",
- arg.merge->input_types().size());
- }
- TF_RETURN_IF_ERROR(arg.merge->input_node(1 - enter_merge->dst_input(),
- &arg.next_iteration));
- if (!IsNextIteration(arg.next_iteration)) {
- return errors::InvalidArgument(
- "Expected NextIteration node as input to Merge node; got node ",
- FormatNodeForError(*arg.next_iteration), " with kind ",
- arg.next_iteration->type_string());
- }
-
- // Find the Switch successor of the Merge. There should be exactly one
- // Switch node that is a successor of both the Merge and the LoopCond.
- for (const Edge* edge : arg.merge->out_edges()) {
- if (edge->dst_input() == 0 && IsSwitch(edge->dst()) &&
- switches.find(edge->dst()) != switches.end()) {
- if (arg.switch_node != nullptr) {
- return errors::InvalidArgument("Duplicate Switch successors to ",
- FormatNodeForError(*arg.merge));
- }
- arg.switch_node = edge->dst();
- }
- }
- if (arg.switch_node == nullptr) {
- return errors::InvalidArgument("Missing Switch successor to ",
- FormatNodeForError(*arg.merge));
- }
-
- // Update the device on the Identity outputs of the switch to match their
- // target. These Identity outputs do not
-
- // Loop over the switch node's output to:
- // - Find the Exit successor.
- // - Set the sharding on all Identity outputs of the switch. These
- // identity nodes are values used by the loop body or condition.
- // The Identity node may have the wrong device so copy the device from
- // one of its outputs instead.
- std::deque<const Edge*> possible_exit;
- for (const Edge* edge : arg.switch_node->out_edges()) {
- if (edge->src_output() == 0) {
- possible_exit.push_back(edge);
- }
- if (IsIdentity(edge->dst())) {
- TF_RETURN_IF_ERROR(
- SetNodeShardingFromNeighbors(edge->dst(), /*out_edges=*/true));
- }
- }
- // TODO(b/67425339): Allow general graph between switch and exit.
- while (!possible_exit.empty()) {
- const Edge* edge = possible_exit.front();
- possible_exit.pop_front();
- if (IsExit(edge->dst())) {
- if (arg.exit != nullptr) {
- return errors::InvalidArgument(
- "Duplicate Exit successors to ",
- FormatNodeForError(*arg.switch_node));
- }
- arg.exit = edge->dst();
- } else {
- if (!IsIdentity(edge->dst())) {
- return errors::Unimplemented("General graph between switch (",
- FormatNodeForError(*arg.switch_node),
- ") and exit node of frame ",
- frame->name, " not supported yet.");
- }
- for (const Edge* out : edge->dst()->out_edges()) {
- possible_exit.push_back(out);
- }
- }
- }
- }
- }
-
- // Builds the condition and body functions.
- std::unique_ptr<Graph> cond_graph;
- TF_RETURN_IF_ERROR(BuildLoopCondition(*graph, frame, &cond_graph));
- DataTypeVector arg_types;
- std::unique_ptr<Graph> body_graph;
- TF_RETURN_IF_ERROR(BuildLoopBody(*graph, frame, &arg_types, &body_graph));
-
- VLOG(2) << "Frame " << frame->name << " condition: "
- << dump_graph::DumpGraphToFile("loop_condition", *cond_graph, library)
- << " body: " << dump_graph::DumpGraphToFile("loop_body", *body_graph);
-
- static std::atomic<int64> sequence_num(0LL);
- int64 id = ++sequence_num;
- NameAttrList cond_name;
- cond_name.set_name(strings::StrCat("_functionalize_cond_", id));
- NameAttrList body_name;
- body_name.set_name(strings::StrCat("_functionalize_body_", id));
- FunctionDef cond_fdef;
- TF_RETURN_IF_ERROR(
- GraphToFunctionDef(*cond_graph, cond_name.name(), &cond_fdef));
- FunctionDef body_fdef;
- TF_RETURN_IF_ERROR(
- GraphToFunctionDef(*body_graph, body_name.name(), &body_fdef));
-
- TF_RETURN_IF_ERROR(library->AddFunctionDef(cond_fdef));
- TF_RETURN_IF_ERROR(library->AddFunctionDef(body_fdef));
- if (lookup_library) {
- // Copy missing FunctionDefs from lookup_library to library to make library
- // self-contained.
- TF_RETURN_IF_ERROR(
- AddMissingFunctionDef(cond_fdef, lookup_library, library));
- TF_RETURN_IF_ERROR(
- AddMissingFunctionDef(body_fdef, lookup_library, library));
- }
-
- // Builds a While operator.
- NodeDef while_def;
- NodeDefBuilder builder(frame->loop_cond->name(), "XlaWhile");
- builder.Attr("T", arg_types);
- builder.Attr("cond", cond_name);
- builder.Attr("body", body_name);
- std::vector<NodeDefBuilder::NodeOut> inputs;
- for (int i = 0; i < frame->args.size(); ++i) {
- const Arg& arg = frame->args[i];
- const Edge* in_edge;
- TF_RETURN_IF_ERROR(arg.enter->input_edge(0, &in_edge));
- if (in_edge->IsControlEdge()) {
- builder.ControlInput(in_edge->src()->name());
- } else {
- inputs.push_back(NodeDefBuilder::NodeOut(
- in_edge->src()->name(), in_edge->src_output(), arg_types[i]));
- }
- }
- builder.Input(inputs);
- TF_RETURN_IF_ERROR(builder.Finalize(&while_def));
- TF_ASSIGN_OR_RETURN(Node * while_node, AddNode(while_def, graph));
-
- // Copies edges to the Enter nodes and from the Exit nodes onto the While.
- for (int i = 0; i < frame->args.size(); ++i) {
- const Arg& arg = frame->args[i];
- const Edge* in_edge;
- TF_RETURN_IF_ERROR(arg.enter->input_edge(0, &in_edge));
- if (in_edge->IsControlEdge()) {
- graph->AddControlEdge(in_edge->src(), while_node);
- } else {
- graph->AddEdge(in_edge->src(), in_edge->src_output(), while_node, i);
- }
-
- if (!arg.is_loop_invariant) {
- // Add output edges if the output of the loop is consumed.
- if (arg.exit != nullptr) {
- std::vector<const Edge*> edges(arg.exit->out_edges().begin(),
- arg.exit->out_edges().end());
- for (const Edge* edge : edges) {
- Node* dst = edge->dst();
- int dst_input = edge->dst_input();
- graph->RemoveEdge(edge);
-
- if (dst_input == Graph::kControlSlot) {
- graph->AddControlEdge(while_node, dst);
- } else {
- graph->AddEdge(while_node, i, dst, dst_input);
- }
- }
- }
- }
- }
-
- // Remove the old nodes from the graph, and add the while node to the parent
- // frame.
- for (Node* node : frame->nodes) {
- graph->RemoveNode(node);
- }
- frame->nodes.clear();
- frame->parent->nodes.insert(while_node);
-
- VLOG(2) << "Frame " << frame->name << " after: "
- << dump_graph::DumpGraphToFile("functionalize_after", *graph,
- library);
-
- return Status::OK();
-}
-
-class FunctionalizeCond {
- public:
- // All nodes are assumed to be either in no branch, then branch, else branch,
- // or both branches (such as merge nodes).
- enum Branch {
- kElseBranch = 0,
- kThenBranch = 1,
- kBoth = 2,
- kNeither = 3,
- kNumBranchTypes = 4
- };
-
- // Returns a textual representation of the Branch b.
- static string Branch_Name(FunctionalizeCond::Branch b);
-
- // Functionalize all the switch-merge nodes of a loop-free graph into XlaIf
- // nodes. That is, attempt to transform every remaining switch and merge nodes
- // in the graph into XlaIf nodes.
- // Precondition: All while loops have been removed from graph.
- static Status Functionalize(Graph* graph, FunctionLibraryDefinition* library);
-
- private:
- // CondArgNode represents a input to the conditional and its corresponding
- // switch nodes.
- struct CondArgNode {
- explicit CondArgNode(Node* src, int src_output)
- : src(src), src_output(src_output) {}
- string ToString() const {
- return strings::StrCat("src=", src->name(), ":", src_output,
- " switches=", NodesToString(switches));
- }
-
- Node* src;
- int src_output;
- std::vector<Node*> switches;
- };
- using CondArgNodes = std::vector<CondArgNode>;
-
- struct ForwardFlowNode {
- explicit ForwardFlowNode(Branch branch = Branch::kNeither)
- : branch(branch), count(0) {}
- string ToString() const {
- return strings::StrCat("branch=", Branch_Name(branch), " count=", count);
- }
- Branch branch;
- int count;
- };
-
- // Group of switch nodes that will be part of the same XlaIf.
- struct SwitchCluster {
- explicit SwitchCluster(const Edge* predicate_edge)
- : predicate_edge(predicate_edge) {}
- string ToString() const {
- return strings::StrCat(name, " predicate=", predicate_edge->src()->name(),
- " switches=", NodesToString(switches));
- }
-
- string name;
- const Edge* predicate_edge;
- std::vector<Node*> switches;
- };
-
- FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library,
- bool dump_graphs)
- : library_(library), graph_(graph), dump_graphs_(dump_graphs) {}
-
- // Perform the actual cond functionalization. Iterate over groups of switch
- // nodes (linked by common predicate), from innermost to outermost, and
- // extract into XlaIf nodes.
- Status FunctionalizeInternal();
-
- // Determines the branch_map (mapping from node to branch of cond) and
- // frontier (the nodes where the cond ends).
- StatusOr<std::pair<std::unordered_map<Node*, ForwardFlowNode>,
- std::unordered_set<Node*>>>
- DetermineBranchMapAndFrontier(const SwitchCluster& switch_cluster);
-
- // Returns XlaIf node created from subgraph of merge and switch nodes. This
- // encapsulates the process of extracting the bodies needed for the then and
- // else branch, creates a XlaIf node, removing the nodes of the branches from
- // the graph and replacing the merge node with a XlaIf.
- StatusOr<Node*> ConvertToXlaIf(const CondArgNodes& cond_arg_nodes,
- const SwitchCluster& switch_cluster,
- const std::vector<Node*>& switches);
-
- // Builds a XlaIfOp to replace the Switch-Graph-Merge cluster with.
- StatusOr<Node*> BuildAndAddXlaIfOp(const CondArgNodes& cond_arg_nodes,
- const SwitchCluster& switch_cluster,
- const std::vector<Node*>& merge_nodes);
-
- // Extracts a function body corresponding to the given input edge of the merge
- // node.
- Status ExtractBody(const CondArgNodes& cond_arg_nodes,
- const std::vector<Node*>& switches,
- const std::vector<Node*>& merge_nodes, int input_edge,
- Graph* body);
-
- // Adds all the input edges to `if_node` corresponding to the arguments.
- Status AddInputEdges(const CondArgNodes& cond_arg_nodes,
- const Edge* predicate_edge, Node* if_node);
-
- // Adds all output edges from the `if_node`.
- Status AddOutputEdges(const std::vector<Node*>& outputs, Node* if_node);
-
- // Returns the switch clusters of graph_ in postorder. Dead switch nodes are
- // skipped and removed from the graph.
- StatusOr<std::vector<SwitchCluster>> DeterminePredicateSwitchOrder();
-
- // Update the state for destination based on the state of source and the node
- // being updated.
- Status Join(const ForwardFlowNode& src_state, const Node* dst,
- ForwardFlowNode* dst_state);
-
- // Ensure that all nodes in the branch_map are dominated by the switch
- // nodes. Returns nodes that are not dominated by the switches but are a
- // control dependency of a node in the cond, and remove such control
- // dependencies.
- StatusOr<std::vector<Node*>> EnsureDominanceAndReturnNonDominatedControlNodes(
- const std::unordered_map<Node*, ForwardFlowNode>& branch_map,
- const std::vector<Node*>& switches);
-
- // Validates that the frontier of nodes for the conditional
- // section are as expected.
- Status ValidateFrontier(
- const std::unordered_map<Node*, ForwardFlowNode>& branch_map,
- const std::unordered_set<Node*>& frontier);
-
- FunctionLibraryDefinition* library_;
- Graph* graph_;
- bool dump_graphs_;
-};
-
-bool IsDeadSwitch(const Node* node) {
- for (const Edge* e : node->out_edges()) {
- const Node* dst = e->dst();
- if (!dst->IsIdentity()) {
- return false;
- }
- for (const Edge* ee : dst->out_edges()) {
- if (!ee->IsControlEdge() || !ee->dst()->IsSink()) {
- return false;
- }
- }
- }
- return true;
-}
-
-string FunctionalizeCond::Branch_Name(FunctionalizeCond::Branch b) {
- const string branch_name[FunctionalizeCond::kNumBranchTypes + 1] = {
- "else", "then", "both", "neither", "count"};
- return branch_name[b];
-}
-
-Status FunctionalizeCond::ValidateFrontier(
- const std::unordered_map<Node*, FunctionalizeCond::ForwardFlowNode>&
- branch_map,
- const std::unordered_set<Node*>& frontier) {
- std::unordered_set<const Node*> pending[kNumBranchTypes];
- for (Node* n : frontier) {
- pending[branch_map.at(n).branch].insert(n);
- }
- TF_RET_CHECK(pending[kNeither].empty()) << NodesToString(pending[kNeither]);
- for (const Node* n : pending[kBoth]) {
- TF_RET_CHECK(IsMerge(n)) << n->DebugString();
- // Merge nodes may be in then or else branch too
- }
- int index = (pending[kThenBranch].size() <= pending[kElseBranch].size())
- ? kThenBranch
- : kElseBranch;
- int other = 1 - index;
- for (const Node* n : pending[index]) {
- if (pending[other].find(n) != pending[other].end()) {
- return errors::Internal(
- "Node (", n->DebugString().c_str(),
- ") in both Else and Then branch should be in Both.");
- }
- }
- // An empty frontier indicates a dead switch. Above we attempt to remove dead
- // switch nodes, but not all are removed so don't treat it as an error yet.
- // TODO(jpienaar): Find out why dead switch nodes remain.
- // if (pending[kBoth].empty() && pending[kThenBranch].empty() &&
- // pending[kElseBranch].empty()) {
- // return errors::Internal("Unexpected empty frontier for switch nodes");
- // }
- return Status::OK();
-}
-
-Status FunctionalizeCond::Join(const ForwardFlowNode& src_state,
- const Node* dst, ForwardFlowNode* dst_state) {
- TF_RET_CHECK(dst_state->branch != Branch::kBoth &&
- dst_state->branch != Branch::kNumBranchTypes)
- << "Unexpected/Invalid branch type: Merging "
- << Branch_Name(src_state.branch) << " with "
- << Branch_Name(dst_state->branch);
- if (dst_state->branch == Branch::kNeither) {
- dst_state->branch = src_state.branch;
- } else if (src_state.branch != dst_state->branch &&
- src_state.branch != Branch::kNeither) {
- if (IsMerge(dst)) {
- dst_state->branch = Branch::kBoth;
- } else {
- return errors::Internal("Illegal merge:\n", src_state.ToString(),
- " with ", dst_state->ToString(), " for\n",
- dst->DebugString());
- }
- }
- ++dst_state->count;
- return Status::OK();
-}
-
-StatusOr<std::vector<FunctionalizeCond::SwitchCluster>>
-FunctionalizeCond::DeterminePredicateSwitchOrder() {
- struct Cluster {
- bool operator==(const Cluster& other) const {
- return representative == other.representative;
- }
- int representative = -1;
- };
-
- // Perform a DFS over the graph and
- // * Determine the reverse topological order of the nodes (there should be no
- // cycles at this point so the post-order numbering corresponds to the
- // reverse topological sorting);
- // * Identify dead switches;
- // * Initialize the cluster's representative;
- std::vector<UnionFind<Cluster>> clusters(graph_->num_node_ids());
- std::vector<Node*> dead_switches;
- std::vector<Node*> switch_order;
- std::vector<Node*> rev_topo_sorted_nodes;
- DFS(*graph_, nullptr, [&](Node* n) {
- clusters[n->id()].Get().representative = n->id();
- if (IsSwitch(n)) {
- if (IsDeadSwitch(n)) {
- dead_switches.push_back(n);
- } else {
- rev_topo_sorted_nodes.push_back(n);
- switch_order.push_back(n);
- }
- } else if (n->IsOp()) {
- // Exclude src and sink nodes from further consideration.
- rev_topo_sorted_nodes.push_back(n);
- }
- });
-
- std::vector<SwitchCluster> switch_clusters;
- // Return early if there are no switches in the graph.
- if (switch_order.empty()) {
- return switch_clusters;
- }
-
- // Remove all dead switch nodes.
- for (Node* n : dead_switches) {
- VLOG(2) << "Removing dead switch: " << n->DebugString();
- graph_->RemoveNode(n);
- }
-
- // Identify switch nodes that are part of the same control flow context by
- // considering the operands of operations: an operation is part of the same
- // control context as its operands unless the operation is a switch. Control
- // dependencies are considered part of the same control flow context if the
- // switch depth is the same (see comment below).
-
- // entry_cluster records the input cluster to a switch node. This is used when
- // merging with a merge node where the dst's cluster is merged with the entry
- // cluster of the merge node's cluster (which corresponds to a switch cluster
- // and so has an entry cluster).
- std::unordered_map<int, UnionFind<Cluster>*> entry_cluster;
-
- // Returns the output cluster of a node. Where the output cluster is cluster
- // where the output of the node is used. For non-merge nodes this is simply
- // the cluster they are part of, while for merge nodes it is the entry cluster
- // of the cluster they are part of (this will correspond to the entry node of
- // a switch node that dominates the merge).
- auto find_output_cluster = [&](Node* n) {
- UnionFind<Cluster>* cluster = &clusters[n->id()];
- if (!IsMerge(n)) return cluster;
- auto it = entry_cluster.find(clusters[n->id()].Get().representative);
- // If the cluster is not found in the entry_cluster map then an
- // instruction not dominated by a switch node has been merged into the
- // cluster of the merge. This indicates a failure of the clustering.
- CHECK(it != entry_cluster.end())
- << "Unable to find entry for n=" << n->id() << " ("
- << cluster->Get().representative << ")";
- return it->second;
- };
-
- // TODO(jpienaar): This could be combined with DetermineBranchMapAndFrontier.
- std::vector<int> switch_depth(graph_->num_node_ids());
- for (auto it = rev_topo_sorted_nodes.rbegin();
- it != rev_topo_sorted_nodes.rend(); ++it) {
- Node* n = *it;
-
- // Compute switch depth.
- int new_switch_depth = 0;
- for (const Edge* e : n->in_edges()) {
- Node* src = e->src();
- new_switch_depth = std::max(
- new_switch_depth, switch_depth[src->id()] - (IsMerge(src) ? 1 : 0));
- }
- switch_depth[n->id()] = new_switch_depth + (IsSwitch(n) ? 1 : 0);
-
- // Only merge the input operands of a switch. The switch's clustering itself
- // is determined by the interaction of the switch's outputs.
- if (IsSwitch(n)) {
- Node* input;
- TF_CHECK_OK(n->input_node(0, &input));
- entry_cluster[n->id()] = find_output_cluster(input);
- UnionFind<Cluster>* cluster = entry_cluster[n->id()];
- int cluster_depth = switch_depth[cluster->Get().representative];
- // Merge the inputs of the switch node with one another. This results in
- // predicates and control input residing in the same cluster.
- for (const Edge* e : n->in_edges()) {
- // Only consider the data inputs to the Switch node.
- if (e->IsControlEdge()) continue;
-
- Node* src = e->src();
- UnionFind<Cluster>* src_cluster = find_output_cluster(src);
- int src_cluster_depth = switch_depth[src_cluster->Get().representative];
- if (cluster_depth != src_cluster_depth) {
- return errors::InvalidArgument(
- "Unable to functionalize control flow in graph: Switch ('",
- n->name(), "') has operands ('", input->name(), "' and '",
- src->name(), "') that have different switch depths (",
- cluster_depth, " != ", src_cluster_depth, ")");
- }
- cluster->Merge(src_cluster);
- }
- continue;
- }
-
- for (const Edge* e : n->in_edges()) {
- Node* src = e->src();
- if (!src->IsOp()) continue;
- UnionFind<Cluster>* cluster = find_output_cluster(src);
- // Merge a node with its data operands and with its control operands if
- // the src and dst are in the same ControlContext. The ControlContext is
- // not explicitly available here, and instead the switch depth is used as
- // a proxy here. Due to the invariant that control edges can only be from
- // a containing scope to an inner scope or from the inner scope to its
- // containing scope (for exit nodes), the switch depth will only match if
- // the src and dst are in the same ControlContext. Control edges between
- // ControlContexts are handled during the extraction.
- int src_id = cluster->Get().representative;
- int src_depth = switch_depth[src_id];
- if (!e->IsControlEdge() || new_switch_depth == src_depth) {
- if (src_depth != new_switch_depth) {
- // TODO(b/77601805) remove this when outside_compilation supports
- // control flow.
- if (str_util::StrContains(src->name(), "outside_compilation") ||
- str_util::StrContains(n->name(), "outside_compilation")) {
- return errors::InvalidArgument(
- "outside_compilation is not yet supported within TensorFlow "
- "control flow constructs b/77601805");
- }
- return errors::InvalidArgument(
- "Unable to functionalize control flow in graph: Operand ('",
- src->name(), "') and operator ('", n->name(),
- "') have different switch depths (", src_depth,
- " != ", new_switch_depth, ")");
- }
- cluster->Merge(&clusters[n->id()]);
- }
- }
- }
-
- if (dump_graphs_) {
- // Mark the switch cluster each node is part of.
- for (Node* n : graph_->nodes()) {
- n->ClearAttr("_XlaFunctionalizeSwitchGroup");
- n->AddAttr("_XlaFunctionalizeSwitchGroup",
- clusters[n->id()].Get().representative);
- }
- LOG(INFO) << "FunctionalizeControlFlow (with_clusters): "
- << dump_graph::DumpGraphToFile("functionalize_clustered", *graph_,
- library_);
- }
-
- // Verify all the nodes of a cluster are at the same depth.
- std::unordered_map<int, std::pair<int, Node*>> cluster_to_depth_node;
- for (Node* n : graph_->nodes()) {
- int depth = switch_depth[n->id()];
- int cluster_rep = clusters[n->id()].Get().representative;
- auto it = cluster_to_depth_node.find(cluster_rep);
- if (it == cluster_to_depth_node.end()) {
- cluster_to_depth_node[cluster_rep] = std::make_pair(depth, n);
- } else {
- if (it->second.first != depth) {
- return errors::Internal(
- "Illegal clustering created, mismatch in depths:", "\n\t",
- n->DebugString(), "(", clusters[n->id()].Get().representative,
- ") at depth=", depth, " vs\n\t", it->second.second->DebugString(),
- "(", clusters[n->id()].Get().representative, ") at depth ",
- it->second.first);
- }
- }
- }
-
- struct Hash {
- size_t operator()(const std::pair<Node*, Cluster>& item) const {
- return Hash64Combine(hash<Node*>()(item.first),
- std::hash<int>()(item.second.representative));
- }
- };
-
- // Merge Switch nodes with common predicate.
- std::unordered_map<std::pair<Node*, Cluster>, int, Hash> predicate_index;
- // The nodes in switch_order are in reverse topological order, but the
- // clustered switches need not be (i.e., when considered as a cluster one
- // element of a cluster may be later in the topological order than another
- // node whose cluster is later in the topological order of clustered
- // switches).
- for (auto it = switch_order.rbegin(); it != switch_order.rend(); ++it) {
- const Edge* pred_edge;
- TF_CHECK_OK((*it)->input_edge(1, &pred_edge));
- // The predicate can be preceded by a identity node. Look through identity
- // nodes to predicate.
- while (pred_edge->src()->IsIdentity()) {
- TF_CHECK_OK(pred_edge->src()->input_edge(0, &pred_edge));
- }
- auto repr = std::make_pair(pred_edge->src(), clusters[(*it)->id()].Get());
- if (predicate_index.find(repr) == predicate_index.end()) {
- predicate_index[repr] = switch_clusters.size();
- switch_clusters.emplace_back(pred_edge);
- // Generate a name by concatenating with the cluster representative as
- // there could be multiple switch clusters with the same predicate.
- switch_clusters[predicate_index[repr]].name = strings::StrCat(
- pred_edge->src()->name(), "_", repr.second.representative, "_If");
- }
- switch_clusters[predicate_index[repr]].switches.push_back(*it);
- }
-
- return switch_clusters;
-}
-
-StatusOr<std::vector<Node*>>
-FunctionalizeCond::EnsureDominanceAndReturnNonDominatedControlNodes(
- const std::unordered_map<Node*, ForwardFlowNode>& branch_map,
- const std::vector<Node*>& switches) {
- std::vector<Node*> old_control_nodes;
- for (const auto& kv : branch_map) {
- if (kv.second.count != kv.first->in_edges().size()) {
- std::vector<const Edge*> delete_edges;
- for (const Edge* in : kv.first->in_edges()) {
- auto it = branch_map.find(in->src());
- if (it == branch_map.end()) {
- if (in->IsControlEdge()) {
- old_control_nodes.push_back(in->src());
- delete_edges.push_back(in);
- } else {
- if (IsSwitch(in->src())) {
- if (std::find(switches.begin(), switches.end(), in->src()) ==
- switches.end()) {
- return errors::Internal(
- "Unexpected switch node found during flow forward: ",
- in->src()->DebugString());
- }
- continue;
- }
- return errors::InvalidArgument(
- "Value ", kv.first->name(), "'s input, ", in->src()->name(),
- ", is not dominated by switch nodes ", NodesToString(switches));
- }
- }
- }
- // Remove control edges from nodes that are not dominated by the switch
- // nodes. New control dependencies will be added between these nodes and
- // the XlaIf node inserted.
- for (const Edge* e : delete_edges) {
- graph_->RemoveEdge(e);
- }
- }
- }
- return old_control_nodes;
-}
-
-StatusOr<
- std::pair<std::unordered_map<Node*, FunctionalizeCond::ForwardFlowNode>,
- std::unordered_set<Node*>>>
-FunctionalizeCond::DetermineBranchMapAndFrontier(
- const SwitchCluster& switch_cluster) {
- std::unordered_map<Node*, ForwardFlowNode> branch_map;
- std::unordered_set<Node*> frontier;
- std::vector<Node*> stack = switch_cluster.switches;
- std::vector<bool> visited(graph_->num_node_ids(), false);
- while (!stack.empty()) {
- Node* n = stack.back();
- stack.pop_back();
-
- if (visited[n->id()]) {
- continue;
- }
- visited[n->id()] = true;
-
- // Propagate branch state along each edge of a switch node.
- bool sink_only = true;
- for (const Edge* e : n->out_edges()) {
- Node* out = e->dst();
- if (!out->IsOp()) {
- continue;
- }
- sink_only = false;
- // Propagate branch information.
- ForwardFlowNode& ffn = branch_map[out];
- if (IsSwitch(n)) {
- int index = e->IsControlEdge() ? Branch::kNeither : e->src_output();
- TF_RETURN_WITH_CONTEXT_IF_ERROR(
- Join(ForwardFlowNode(Branch(index)), out, &ffn), " when joining ",
- e->DebugString());
- } else {
- TF_RETURN_WITH_CONTEXT_IF_ERROR(Join(branch_map[n], out, &ffn),
- " when joining ", e->DebugString());
- }
- if (IsMerge(out)) {
- if (out->in_edges().size() == ffn.count) {
- frontier.insert(out);
- }
- } else if (!visited[out->id()]) {
- stack.push_back(out);
- }
- }
- if (sink_only) {
- if (!IsIdentity(n)) {
- VLOG(1) << "Feeding into sink: " << n->DebugString();
- }
- }
- }
-
- if (dump_graphs_) {
- for (const auto& kv : branch_map) {
- // Append attribute to the graph if running with logging to make the
- // changes clearer in the visualization.
- kv.first->AddAttr("_XlaFunctionalizeBranch",
- Branch_Name(kv.second.branch));
- }
- }
- return std::make_pair(std::move(branch_map), std::move(frontier));
-}
-
-Status FunctionalizeCond::FunctionalizeInternal() {
- TF_ASSIGN_OR_RETURN(std::vector<SwitchCluster> predicate_switch_order,
- DeterminePredicateSwitchOrder());
-
- // Iterate from innermost set of clustered switches to outermost, replacing
- // matching switch->merge subgraphs with single XlaIf nodes.
- for (auto it = predicate_switch_order.rbegin();
- it != predicate_switch_order.rend(); ++it) {
- auto& ps = *it;
- VLOG(3) << "Flow down from: " << ps.ToString();
-
- std::unordered_map<Node*, ForwardFlowNode> branch_map;
- std::unordered_set<Node*> frontier;
- TF_ASSIGN_OR_RETURN(std::tie(branch_map, frontier),
- DetermineBranchMapAndFrontier(ps));
-
- if (dump_graphs_)
- LOG(INFO) << "FunctionalizeControlFlow (before XlaIf conversion): "
- << dump_graph::DumpGraphToFile("functionalize_bc", *graph_,
- library_);
- TF_RETURN_IF_ERROR(ValidateFrontier(branch_map, frontier));
-
- struct Hash {
- size_t operator()(const std::pair<Node*, int>& item) const {
- return Hash64Combine(hash<Node*>()(item.first),
- std::hash<int>()(item.second));
- }
- };
-
- // Sort the merge and switch nodes using NodeCmp. The switch-nodes are
- // further grouped (post sorting) by input to the switch node as in the
- // functionalized form each input will be passed in only once. This grouping
- // should retain the sorted order.
- CondArgNodes cond_arg_nodes;
- std::sort(ps.switches.begin(), ps.switches.end(), NodeCmp());
- std::unordered_map<std::pair<Node*, int>, int, Hash> input_index;
- for (Node* switch_node : ps.switches) {
- const Edge* e;
- TF_RETURN_IF_ERROR(switch_node->input_edge(0, &e));
- std::pair<Node*, int> key = std::make_pair(e->src(), e->src_output());
- if (input_index.find(key) == input_index.end()) {
- input_index[key] = cond_arg_nodes.size();
- cond_arg_nodes.emplace_back(key.first, key.second);
- }
- cond_arg_nodes.at(input_index.at(key)).switches.push_back(switch_node);
- }
- std::vector<Node*> merge_nodes(frontier.begin(), frontier.end());
- std::sort(merge_nodes.begin(), merge_nodes.end(), NodeCmp());
-
- TF_ASSIGN_OR_RETURN(std::vector<Node*> old_control_nodes,
- EnsureDominanceAndReturnNonDominatedControlNodes(
- branch_map, ps.switches));
-
- TF_ASSIGN_OR_RETURN(Node * if_node,
- ConvertToXlaIf(cond_arg_nodes, ps, merge_nodes));
- for (Node* old : old_control_nodes) {
- graph_->AddControlEdge(old, if_node);
- }
-
- for (auto& del_kv : branch_map) {
- graph_->RemoveNode(del_kv.first);
- }
- for (auto& kv : cond_arg_nodes) {
- for (Node* node : kv.switches) {
- graph_->RemoveNode(node);
- }
- }
- if (dump_graphs_)
- LOG(INFO) << "FunctionalizeControlFlow (after XlaIf conversion): "
- << dump_graph::DumpGraphToFile("functionalize_ac", *graph_,
- library_);
- }
- return Status::OK();
-}
-
-StatusOr<Node*> FunctionalizeCond::BuildAndAddXlaIfOp(
- const CondArgNodes& cond_arg_nodes, const SwitchCluster& switch_cluster,
- const std::vector<Node*>& merge_nodes) {
- VLOG(2) << "Build if op for " << switch_cluster.name;
-
- NodeDef if_def;
- // Create a new If node using the name of the merge node.
- NodeDefBuilder builder(switch_cluster.name, "XlaIf");
- string branch[] = {"else_branch", "then_branch"};
- for (int i = 0; i < 2; ++i) {
- static std::atomic<int64> sequence_num(0LL);
- int64 id = ++sequence_num;
-
- NameAttrList body_name;
- body_name.set_name(
- strings::StrCat("_functionalize_if_", branch[i], "_", id));
- auto body = xla::MakeUnique<Graph>(graph_->op_registry());
- TF_RETURN_IF_ERROR(ExtractBody(cond_arg_nodes, switch_cluster.switches,
- merge_nodes, i, body.get()));
- VLOG(3) << "Body " << branch[i] << ": " << DebugString(body.get());
- FunctionDef body_fdef;
- TF_RETURN_IF_ERROR(GraphToFunctionDef(*body, body_name.name(), &body_fdef));
- TF_RETURN_IF_ERROR(library_->AddFunctionDef(body_fdef));
- builder.Attr(branch[i], body_name);
- }
-
- // Build input type.
- std::vector<NodeDefBuilder::NodeOut> inputs;
- DataTypeVector in_arg_types;
- for (auto& kv : cond_arg_nodes) {
- bool inserted = false;
- for (const Node* arg : kv.switches) {
- const Edge* in_edge;
- TF_RETURN_IF_ERROR(arg->input_edge(0, &in_edge));
- if (in_edge->IsControlEdge()) {
- builder.ControlInput(in_edge->src()->name());
- } else {
- if (!inserted) {
- DataType dtype = arg->input_type(0);
- inputs.emplace_back(NodeDefBuilder::NodeOut(
- in_edge->src()->name(), in_edge->src_output(), dtype));
- in_arg_types.push_back(dtype);
- inserted = true;
- }
- }
- }
- }
- builder.Attr("Tin", in_arg_types);
-
- // Build output type.
- DataTypeVector out_type;
- for (const Node* merge : merge_nodes) {
- DataType dtype = merge->output_type(0);
- out_type.push_back(dtype);
- }
- builder.Attr("Tout", out_type);
-
- builder.Attr("Tcond", DT_BOOL);
- builder.Device(switch_cluster.predicate_edge->src()->assigned_device_name());
- // Conditional should be the first input ...
- builder.Input(NodeDefBuilder::NodeOut(
- switch_cluster.predicate_edge->src()->name(),
- switch_cluster.predicate_edge->src_output(),
- switch_cluster.predicate_edge->src()->output_type(0)));
- // ... followed by the other inputs.
- builder.Input(inputs);
-
- TF_RETURN_IF_ERROR(builder.Finalize(&if_def));
- TF_ASSIGN_OR_RETURN(Node * if_node, AddNode(if_def, graph_));
- return if_node;
-}
-
-Status FunctionalizeCond::ExtractBody(const CondArgNodes& cond_arg_nodes,
- const std::vector<Node*>& switches,
- const std::vector<Node*>& merge_nodes,
- int input_edge, Graph* body) {
- VLOG(2) << "ExtractBody for " << NodesToString(merge_nodes) << " along edge "
- << input_edge;
- std::vector<bool> squash_src_outputs(graph_->num_node_ids(), false);
- std::vector<Node*> node_map(graph_->num_node_ids(), nullptr);
- int arg_count = 0;
- for (auto& kv : cond_arg_nodes) {
- Node* arg_node = nullptr;
- for (const auto* arg : kv.switches) {
- DataType dtype = arg->input_type(0);
- if (arg_node == nullptr) {
- TF_ASSIGN_OR_RETURN(arg_node, BuildArgNode(body, dtype, arg_count++));
- }
- node_map.at(arg->id()) = arg_node;
- squash_src_outputs.at(arg->id()) = true;
- }
- }
-
- std::vector<Node*> stack;
- stack.reserve(merge_nodes.size());
- for (int j = 0; j < merge_nodes.size(); ++j) {
- Node* node = merge_nodes[j];
- TF_ASSIGN_OR_RETURN(node_map.at(node->id()),
- BuildRetvalNode(body, node->output_type(0),
- /*index=*/j));
- const Edge* in_edge;
- TF_RETURN_IF_ERROR(node->input_edge(input_edge, &in_edge));
- Node* in = in_edge->src();
- if (node_map.at(in->id()) == nullptr) {
- node_map.at(in->id()) = body->CopyNode(in);
- }
-
- if (std::find(switches.begin(), switches.end(), in) == switches.end()) {
- body->AddEdge(node_map.at(in->id()), in_edge->src_output(),
- node_map.at(node->id()), 0);
- } else {
- body->AddEdge(node_map.at(in->id()), 0, node_map.at(node->id()), 0);
- // Don't include input nodes that are already just returned in stack.
- continue;
- }
- stack.push_back(in);
- }
-
- return CopySubgraph(*graph_, nullptr, stack, squash_src_outputs, &node_map,
- body);
-}
-
-Status FunctionalizeCond::AddInputEdges(const CondArgNodes& cond_arg_nodes,
- const Edge* predicate_edge,
- Node* if_node) {
- VLOG(3) << "AddInputEdges for " << if_node->name();
- int index = 0;
- graph_->AddEdge(predicate_edge->src(), predicate_edge->src_output(), if_node,
- index++);
- for (auto& arg : cond_arg_nodes) {
- if (arg.src_output == Graph::kControlSlot) {
- graph_->AddControlEdge(arg.src, if_node);
- } else {
- graph_->AddEdge(arg.src, arg.src_output, if_node, index++);
- }
- }
- return Status::OK();
-}
-
-Status FunctionalizeCond::AddOutputEdges(const std::vector<Node*>& outputs,
- Node* if_node) {
- VLOG(3) << "AddOutputEdges for " << if_node->name();
- for (int i = 0; i < outputs.size(); ++i) {
- Node* node = outputs[i];
- std::vector<const Edge*> edges(node->out_edges().begin(),
- node->out_edges().end());
- for (const Edge* edge : edges) {
- Node* dst = edge->dst();
- int dst_input = edge->dst_input();
-
- if (edge->src_output() > 0) {
- return errors::Unimplemented("Output of index (", edge->src_output(),
- ") of merge node ", node->name());
- }
-
- int src_output =
- dst_input == Graph::kControlSlot ? Graph::kControlSlot : i;
- graph_->RemoveEdge(edge);
- graph_->AddEdge(if_node, src_output, dst, dst_input);
- }
- }
- return Status::OK();
-}
-
-StatusOr<Node*> FunctionalizeCond::ConvertToXlaIf(
- const CondArgNodes& cond_arg_nodes, const SwitchCluster& switch_cluster,
- const std::vector<Node*>& merge_nodes) {
- VLOG(1) << "ConvertToXlaIf for " << switch_cluster.ToString() << " -> "
- << NodesToString(merge_nodes);
-
- // Extract bodies and builds a If operator.
- TF_ASSIGN_OR_RETURN(
- Node * if_node,
- BuildAndAddXlaIfOp(cond_arg_nodes, switch_cluster, merge_nodes));
- TF_RETURN_IF_ERROR(
- AddInputEdges(cond_arg_nodes, switch_cluster.predicate_edge, if_node));
- TF_RETURN_IF_ERROR(AddOutputEdges(merge_nodes, if_node));
- // Check that the if_node doesn't feed into itself.
- TF_RETURN_WITH_CONTEXT_IF_ERROR(
- CheckNoCycleContains(if_node, graph_->num_node_ids()),
- "ConvertToXlaIf failed.");
-
- return if_node;
-}
-
-Status FunctionalizeCond::Functionalize(Graph* graph,
- FunctionLibraryDefinition* library) {
- VLOG(1) << "FunctionalizeCond::Functionalize";
- FunctionalizeCond fc(graph, library, /*dump_graphs=*/VLOG_IS_ON(2));
- return fc.FunctionalizeInternal();
-}
-
-} // namespace
-
-// Transformation that converts TensorFlow's graph control flow constructs into
-// functional equivalents.
-Status FunctionalizeControlFlow(Graph* graph,
- FunctionLibraryDefinition* library) {
- return FunctionalizeControlFlow(/*lookup_library=*/nullptr, graph, library);
-}
-
Status FunctionalizeControlFlow(const FunctionLibraryDefinition* lookup_library,
Graph* graph,
FunctionLibraryDefinition* library) {
@@ -1462,98 +46,26 @@ Status FunctionalizeControlFlow(const FunctionLibraryDefinition* lookup_library,
<< dump_graph::DumpGraphToFile("functionalize_initial", *graph,
library);
- // Note: BuildControlFlowInfo() requires that the graph's source node is
- // connected to all source nodes in the graph. Many graphs violate this
- // invariant.
- std::vector<ControlFlowInfo> cf_info;
- std::vector<string> unreachable_nodes;
- TF_RETURN_WITH_CONTEXT_IF_ERROR(
- BuildControlFlowInfo(graph, &cf_info, &unreachable_nodes),
- "FunctionalizeControlFlow failed");
- if (!unreachable_nodes.empty()) {
- return errors::InvalidArgument(
- "The following nodes are unreachable from the source in the graph: ",
- errors::FormatNodeNamesForError(unreachable_nodes));
- }
-
- // Builds Frames, indexed by name.
- std::unordered_map<string, Frame> frames;
- for (Node* node : graph->op_nodes()) {
- const ControlFlowInfo& cf = cf_info[node->id()];
-
- VLOG(2) << "node: " << node->name() << " (" << node->id()
- << ") frame_name: " << cf.frame_name
- << " frame: " << (cf.frame ? cf.frame->name() : "---")
- << " parent_frame: "
- << (cf.parent_frame ? cf.parent_frame->name() : "---");
- TF_RET_CHECK(cf.frame != nullptr && cf.parent_frame != nullptr);
-
- Frame& frame = frames[cf.frame_name];
- Frame* parent = &frames[cf_info[cf.parent_frame->id()].frame_name];
- if (frame.parent == nullptr) {
- frame.parent = parent;
- frame.name = cf.frame_name;
- ++parent->num_children;
- }
-
- if (IsEnter(node)) {
- Arg arg;
- arg.enter = node;
- TF_RETURN_IF_ERROR(GetNodeAttr(arg.enter->attrs(), "is_constant",
- &arg.is_loop_invariant));
- frame.args.push_back(arg);
- } else if (IsLoopCond(node)) {
- frame.loop_cond = node;
- }
- frame.nodes.insert(node);
- }
-
- // Adds frames with no children (i.e., the innermost frames) to a worklist.
- std::deque<Frame*> worklist;
- for (auto& frame : frames) {
- if (frame.second.num_children == 0) {
- worklist.push_back(&frame.second);
- }
- }
-
- // Eliminate loops from innermost to outermost.
- while (!worklist.empty()) {
- Frame* frame = worklist.front();
- worklist.pop_front();
- if (frame->parent == frame) {
- // Skip the root frame.
- continue;
- }
-
- TF_RETURN_IF_ERROR(
- FunctionalizeLoop(lookup_library, graph, frame, library));
-
- // If the parent has no remaining children, add it to the worklist.
- --frame->parent->num_children;
- if (frame->parent->num_children == 0) {
- worklist.push_back(frame->parent);
- }
- }
- // There should be no cycle at this point, since while loops have been removed
- // from graph.
- // Check that the newly added XlaWhile nodes don't feed into themselves.
- for (const Node* node : graph->op_nodes()) {
- if (node->def().op() == "XlaWhile") {
- TF_RETURN_WITH_CONTEXT_IF_ERROR(
- CheckNoCycleContains(node, graph->num_node_ids()),
- "FunctionalizeLoop failed.");
- }
- }
+ // Functionalize and remove while loops from graph.
+ TF_RETURN_IF_ERROR(FunctionalizeWhileLoop(lookup_library, graph, library));
// FunctionalizeControlFlow is invoked for every function, so the loops's
// bodies and conditionals that were extracted into functions will be handled
// in successive invocations.
- TF_RETURN_IF_ERROR(FunctionalizeCond::Functionalize(graph, library));
+ TF_RETURN_IF_ERROR(FunctionalizeCond(graph, library));
VLOG(2) << "FunctionalizeControlFlow (final): "
<< dump_graph::DumpGraphToFile("functionalize_final", *graph,
library);
+
return Status::OK();
}
+// Transformation that converts TensorFlow's graph control flow constructs into
+// functional equivalents.
+Status FunctionalizeControlFlow(Graph* graph,
+ FunctionLibraryDefinition* library) {
+ return FunctionalizeControlFlow(/*lookup_library=*/nullptr, graph, library);
+}
+
} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_control_flow.h b/tensorflow/compiler/tf2xla/functionalize_control_flow.h
index d941041d15..55600f2a8b 100644
--- a/tensorflow/compiler/tf2xla/functionalize_control_flow.h
+++ b/tensorflow/compiler/tf2xla/functionalize_control_flow.h
@@ -16,14 +16,16 @@ limitations under the License.
#ifndef TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_H_
#define TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_H_
+#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/graph/graph.h"
namespace tensorflow {
// Transformation that converts tf.while_loop() loops into functional While
-// operators, suitable for XLA compilation. If lookup_library is provided, use
-// it to make the library for control flow self-contained.
+// operators and tf.cond() conditionals into function If operators, suitable for
+// XLA compilation. If lookup_library is provided, use it to make the library
+// for control flow self-contained.
Status FunctionalizeControlFlow(Graph* graph,
FunctionLibraryDefinition* library);
Status FunctionalizeControlFlow(const FunctionLibraryDefinition* lookup_library,
diff --git a/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc b/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc
index ccf249b35d..cc52057f21 100644
--- a/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc
+++ b/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc
@@ -37,12 +37,12 @@ limitations under the License.
namespace tensorflow {
namespace {
-// Returns the names of the "then" and "else" functions for the XlaIf node in a
+// Returns the names of the "then" and "else" functions for the If node in a
// graph.
Status FindIfThenAndElse(const GraphDef& graph, string* op_name,
NameAttrList* then_fn, NameAttrList* else_fn) {
for (const NodeDef& node : graph.node()) {
- if (node.op() == "XlaIf") {
+ if (node.op() == "If") {
*op_name = node.name();
const NameAttrList* result;
TF_RETURN_IF_ERROR(GetNodeAttr(node, "then_branch", &result));
@@ -52,7 +52,7 @@ Status FindIfThenAndElse(const GraphDef& graph, string* op_name,
return Status::OK();
}
}
- return errors::NotFound("No XlaIf node found in graph");
+ return errors::NotFound("No If node found in graph");
}
// Graph:
@@ -115,8 +115,13 @@ TEST(FunctionalizeControlFlow, Conditional) {
auto if_op = ops::XlaIf(scope.WithOpName(op_name), less,
std::initializer_list<Input>{less, y, x}, then_fn,
else_fn, {DT_INT32});
+ auto id = ops::Identity(scope.WithOpName("cond/Merge"), if_op.output[0]);
GraphDef expected;
TF_EXPECT_OK(scope.ToGraphDef(&expected));
+ // TODO(jpienaar): Create wrapper for IfOp.
+ for (NodeDef& n : *expected.mutable_node()) {
+ if (n.op() == "XlaIf") n.set_op("If");
+ }
TF_EXPECT_GRAPH_EQ(expected, graph_def);
}
@@ -1013,63 +1018,5 @@ TEST(FunctionalizeControlFlow, Complex) {
}
}
-TEST(FunctionalizeControlFlow, Cycle) {
- std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
- // -----------------------------------------------------
- // | |
- // | v
- // less -> switch_1 --> add -> merge_1 -> identity -> switch_2
- // | ^ |
- // | | v
- // --------> one -------------------------> add_2 ---> merge_2
- {
- Scope scope = Scope::NewRootScope().ExitOnError();
-
- auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32);
- auto y = ops::Placeholder(scope.WithOpName("y"), DT_INT32);
- auto less = ops::Less(scope.WithOpName("cond/Less"), y, x);
- auto switch_1 = ops::Switch(scope.WithOpName("cond/Switch"), x, less);
- auto two =
- ops::Const<int32>(scope.WithOpName("cond/two")
- .WithControlDependencies(switch_1.output_true),
- 2);
- auto mul = ops::Multiply(scope.WithOpName("cond/true/mul"),
- switch_1.output_true, two);
- auto one =
- ops::Const<int32>(scope.WithOpName("cond/one")
- .WithControlDependencies(switch_1.output_false),
- 1);
- auto add = ops::Add(scope.WithOpName("cond/false/add"),
- switch_1.output_false, one);
-
- auto merge_1 = ops::Merge(scope.WithOpName("cond/Merge"),
- std::initializer_list<Input>{add, mul});
- auto identity =
- ops::Identity(scope.WithOpName("cond/Merge/identity"), merge_1.output);
- auto switch_2 =
- ops::Switch(scope.WithOpName("grad/cond/Switch"), identity, less);
- auto add_2 = ops::Add(scope.WithOpName("cond_2/false/add"),
- switch_2.output_false, one);
- auto mul_2 = ops::Multiply(scope.WithOpName("cond_2/true/mul"),
- switch_2.output_true, two);
- auto merge_2 = ops::Merge(scope.WithOpName("cond_2/Merge"),
- std::initializer_list<Input>{add_2, mul_2});
- TF_ASSERT_OK(scope.ToGraph(graph.get()));
- }
- // No cycle before functionalize control flow.
- TF_EXPECT_OK(graph::ValidateGraphHasNoCycle(*graph));
- FunctionLibraryDefinition library(OpRegistry::Global(), {});
- // switch_1 and switch_2 have the same switch depth. They are replaced by a
- // single XlaIf node during FunctionalizeControlFlow, resulting in a cycle:
- // less -> XlaIf <--> identity.
- Status status = FunctionalizeControlFlow(graph.get(), &library);
- EXPECT_FALSE(status.ok());
- EXPECT_TRUE(str_util::StrContains(status.error_message(), "Detected a cycle"))
- << status.error_message();
- EXPECT_TRUE(
- str_util::StrContains(status.error_message(), "{{node cond/Less_5_If}}"))
- << status.error_message();
-}
-
} // namespace
} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc b/tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc
new file mode 100644
index 0000000000..924fcdd9cd
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc
@@ -0,0 +1,72 @@
+/* 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.
+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.
+==============================================================================*/
+
+#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h"
+
+#include "tensorflow/core/framework/node_def.pb.h"
+
+namespace tensorflow {
+
+bool NodeCmpByNameResourcesLast::operator()(const Node* lhs,
+ const Node* rhs) const {
+ bool lhs_is_resource =
+ lhs->num_inputs() > 0 ? (lhs->input_type(0) == DT_RESOURCE) : false;
+ bool rhs_is_resource =
+ rhs->num_inputs() > 0 ? (rhs->input_type(0) == DT_RESOURCE) : false;
+ return std::tie(lhs_is_resource, lhs->name()) <
+ std::tie(rhs_is_resource, rhs->name());
+}
+
+xla::StatusOr<Node*> AddNodeDefToGraph(const NodeDef& node_def, Graph* graph) {
+ Status status;
+ Node* inserted_node = graph->AddNode(node_def, &status);
+ if (!status.ok()) {
+ return status;
+ }
+ return inserted_node;
+}
+
+xla::StatusOr<Node*> BuildRetvalNode(Graph* graph, DataType type, int index) {
+ const char* const kRetValOp = "_Retval";
+ NodeDef ret_def;
+ ret_def.set_op(kRetValOp);
+ ret_def.set_name(strings::StrCat(kRetValOp, index));
+ AddNodeAttr("T", type, &ret_def);
+ AddNodeAttr("index", index, &ret_def);
+ return AddNodeDefToGraph(ret_def, graph);
+}
+
+// Check that the graph has no cycle containing the given node.
+Status CheckNodeNotInCycle(const Node* node, const int num_nodes) {
+ std::vector<const Node*> ready;
+ ready.push_back(node);
+ std::vector<bool> visited(num_nodes);
+ while (!ready.empty()) {
+ const Node* current_node = ready.back();
+ ready.pop_back();
+ visited[current_node->id()] = true;
+ for (const Edge* out : current_node->out_edges()) {
+ if (out->dst() == node) {
+ return errors::Internal("Detected a cycle: ", FormatNodeForError(*node),
+ " (", node->def().op(), ") feeds into itself.");
+ } else if (!visited[out->dst()->id()]) {
+ ready.push_back(out->dst());
+ }
+ }
+ }
+ return Status::OK();
+}
+
+} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h b/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h
new file mode 100644
index 0000000000..a0544b69e9
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h
@@ -0,0 +1,56 @@
+/* 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.
+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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_UTIL_H_
+#define TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_UTIL_H_
+
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/core/graph/graph.h"
+
+// Utility functions shared between functionalize cond and while.
+
+namespace tensorflow {
+
+// Check that the graph has no cycle containing the given node.
+Status CheckNodeNotInCycle(const Node* node, const int num_nodes);
+
+// Comparison function used for sorting nodes consistently.
+// a) resource variables are last, and
+// b) sort lexicographically by name (for deterministic output).
+struct NodeCmpByNameResourcesLast {
+ bool operator()(const Node* lhs, const Node* rhs) const;
+};
+
+// Returns the Node* created from the NodeDef in the Graph.
+xla::StatusOr<Node*> AddNodeDefToGraph(const NodeDef& node_def, Graph* graph);
+
+// Build a retval node of given type and index.
+xla::StatusOr<Node*> BuildRetvalNode(Graph* graph, DataType type, int index);
+
+// Returns a textual representation of the names of the nodes in the input.
+template <typename T>
+string NodesToString(const T& nodes) {
+ return strings::StrCat("{",
+ str_util::Join(nodes, ",",
+ [](string* output, const Node* node) {
+ strings::StrAppend(output,
+ node->name());
+ }),
+ "}");
+}
+
+} // namespace tensorflow
+
+#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_UTIL_H_
diff --git a/tensorflow/compiler/tf2xla/functionalize_while.cc b/tensorflow/compiler/tf2xla/functionalize_while.cc
new file mode 100644
index 0000000000..fd3e3c6e30
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_while.cc
@@ -0,0 +1,668 @@
+/* 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.
+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.
+==============================================================================*/
+
+#include "tensorflow/compiler/tf2xla/functionalize_while.h"
+
+#include <algorithm>
+#include <deque>
+#include <stack>
+#include <unordered_set>
+#include <vector>
+
+#include "tensorflow/compiler/jit/union_find.h"
+#include "tensorflow/compiler/tf2xla/dump_graph.h"
+#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h"
+#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
+#include "tensorflow/compiler/xla/ptr_util.h"
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/core/common_runtime/function.h"
+#include "tensorflow/core/framework/graph_to_functiondef.h"
+#include "tensorflow/core/framework/node_def_builder.h"
+#include "tensorflow/core/graph/algorithm.h"
+#include "tensorflow/core/graph/control_flow.h"
+#include "tensorflow/core/graph/node_builder.h"
+#include "tensorflow/core/lib/gtl/optional.h"
+
+namespace tensorflow {
+namespace {
+
+using xla::StatusOr;
+
+// Information about a loop argument.
+struct Arg {
+ // Every loop argument has an Enter node.
+ Node* enter;
+
+ // Is the loop argument a loop-invariant value? Taken from the `is_constant`
+ // attribute on the Enter node.
+ bool is_loop_invariant;
+
+ // If 'is_loop_invariant' is true, the following are all nullptr. Non-constant
+ // arguments must have all of the following nodes:
+ Node* merge = nullptr;
+ Node* switch_node = nullptr;
+ Node* next_iteration = nullptr;
+ Node* exit = nullptr;
+};
+
+// Information about a loop frame.
+struct Frame {
+ string name;
+
+ // Pointer to the parent frame. The root frame has a pointer to itself.
+ Frame* parent = nullptr;
+ int num_children = 0;
+
+ // Arguments to this loop.
+ std::vector<Arg> args;
+
+ // The loop condition of the loop. There should be exactly one loop condition
+ // in every loop.
+ Node* loop_cond = nullptr;
+
+ // Set of nodes that belong to the loop frame.
+ std::unordered_set<Node*> nodes;
+};
+
+// Copies a subgraph from `graph` to `output` by performing a reverse DFS
+// starting at nodes in vector `stack`.
+// `node_map` is a vector indexed by source node ID to dest nodes.
+// Does not traverse into nodes in `node_map`, so by adding nodes to `node_map`
+// before the traversal clients can cut the graph. If a frame is provided (frame
+// != nullptr), then this functions will return an error if the
+// traversal leaves 'frame'; the client must add enough nodes to `node_map` to
+// cut the graph and prevent the traversal from escaping.
+//
+// `squash_src_outputs` contains a bool for each source node ID. If true, then
+// the source output on that node will be replaced by zero when copied. This is
+// used when replacing a Switch node with an _Arg node. The output we are
+// taking from the Switch node was not necessarily the first output, but _Arg
+// nodes only have one output. By adding the Switch node to `squash_src_outputs`
+// we rewrite the src_output of the corresponding edge to be 0.
+Status CopySubgraph(const Graph& graph, const Frame* frame,
+ std::vector<Node*> stack,
+ const std::vector<bool>& squash_src_outputs,
+ std::vector<Node*>* node_map, Graph* output) {
+ VLOG(3) << "Stack: " << NodesToString(stack);
+ std::vector<bool> visited(graph.num_node_ids(), false);
+ while (!stack.empty()) {
+ Node* n = stack.back();
+ stack.pop_back();
+
+ VLOG(5) << "Copying node " << n->name();
+
+ if (visited[n->id()]) continue;
+ visited[n->id()] = true;
+
+ for (const Edge* e : n->in_edges()) {
+ Node* src = e->src();
+ if (frame != nullptr && frame->nodes.find(src) == frame->nodes.end()) {
+ // We traversed out of the loop frame, without encountering a cut node.
+ return errors::Internal("Graph traversal of loop frame ", frame->name,
+ " escaped frame at ", src->name(),
+ " without encountering an argument node.");
+ }
+ if ((*node_map)[src->id()] == nullptr) {
+ (*node_map)[src->id()] = output->CopyNode(src);
+ stack.push_back(src);
+ }
+ Node* src_copy = (*node_map)[e->src()->id()];
+ int src_output = squash_src_outputs[e->src()->id()] && !e->IsControlEdge()
+ ? 0
+ : e->src_output();
+ Node* dst_copy = (*node_map)[e->dst()->id()];
+ output->AddEdge(src_copy, src_output, dst_copy, e->dst_input());
+ }
+ }
+ return Status::OK();
+}
+
+StatusOr<Node*> BuildArgNode(Graph* graph, DataType type, int index) {
+ const char* const kArgOp = "_Arg";
+ NodeDef arg_def;
+ NodeDefBuilder builder(strings::StrCat(kArgOp, index), kArgOp);
+ builder.Attr("T", type);
+ builder.Attr("index", index);
+ TF_RETURN_IF_ERROR(builder.Finalize(&arg_def));
+ return AddNodeDefToGraph(arg_def, graph);
+}
+
+// Builds a graph for the loop condition.
+Status BuildLoopCondition(const Graph& graph, Frame* frame,
+ std::unique_ptr<Graph>* cond_output) {
+ VLOG(2) << "Building loop condition for " << frame->name;
+ *cond_output = xla::MakeUnique<Graph>(graph.op_registry());
+ Graph* output = cond_output->get();
+
+ // Map from nodes in the original graph to the condition graph.
+ std::vector<Node*> node_map(graph.num_node_ids(), nullptr);
+ std::vector<bool> squash_src_outputs(graph.num_node_ids(), false);
+
+ // Build one _Arg node for each Enter node.
+ for (int i = 0; i < frame->args.size(); ++i) {
+ const Arg& arg = frame->args[i];
+
+ TF_ASSIGN_OR_RETURN(Node * arg_node,
+ BuildArgNode(output, arg.enter->input_type(0), i));
+ if (arg.is_loop_invariant) {
+ node_map[arg.enter->id()] = arg_node;
+ } else {
+ node_map[arg.merge->id()] = arg_node;
+ }
+ }
+
+ // Build a Retval node for the loop condition. The LoopCond nodes are always
+ // boolean because of the type constraints on the LoopCond op.
+ TF_ASSIGN_OR_RETURN(node_map[frame->loop_cond->id()],
+ BuildRetvalNode(output, DT_BOOL, 0));
+
+ // Performs a reverse DFS, copying nodes and edges to the output graph.
+ // The _Arg and _Retval nodes were added unconditionally above, so we are
+ // guaranteed to get the correct function signature.
+ return CopySubgraph(graph, frame, {frame->loop_cond}, squash_src_outputs,
+ &node_map, output);
+}
+
+// Builds a graph for the loop body.
+Status BuildLoopBody(const Graph& graph, Frame* frame,
+ DataTypeVector* arg_types,
+ std::unique_ptr<Graph>* body_output) {
+ VLOG(2) << "Building loop body for " << frame->name;
+ *body_output = xla::MakeUnique<Graph>(graph.op_registry());
+ Graph* output = body_output->get();
+
+ // Map from nodes in the original graph to the condition graph.
+ std::vector<Node*> node_map(graph.num_node_ids(), nullptr);
+ std::vector<bool> squash_src_outputs(graph.num_node_ids(), false);
+
+ // Build one _Arg node for each Enter node.
+ std::vector<Node*> next_iterations;
+ next_iterations.reserve(frame->args.size());
+ arg_types->reserve(frame->args.size());
+ for (int i = 0; i < frame->args.size(); ++i) {
+ const Arg& arg = frame->args[i];
+
+ DataType dtype = arg.enter->input_type(0);
+ arg_types->push_back(dtype);
+
+ TF_ASSIGN_OR_RETURN(Node * arg_node, BuildArgNode(output, dtype, i));
+
+ if (dtype == DT_RESOURCE) {
+ // The convention of the XLA bridge is that resource variable arguments
+ // are only inputs to the loop body and have no corresponding output.
+ // TODO(b/37741920): change the convention so that DT_RESOURCE variables
+ // are both inputs and outputs, and then remove this case.
+ TF_RET_CHECK(arg.is_loop_invariant);
+ node_map[arg.enter->id()] = arg_node;
+ } else {
+ TF_ASSIGN_OR_RETURN(Node * retval_node,
+ BuildRetvalNode(output, dtype, i));
+
+ if (arg.is_loop_invariant) {
+ // Argument is loop-invariant. Forward it from the Arg to the Retval.
+ node_map[arg.enter->id()] = arg_node;
+ output->AddEdge(arg_node, 0, retval_node, 0);
+ } else {
+ // Argument is loop-varying.
+ node_map[arg.switch_node->id()] = arg_node;
+ // The Switch node has two outputs, but _Arg only has one. This tells
+ // the CopySubgraph function to rewrite the output number of edges from
+ // the _Arg node to be 0 rather than copying the output number from the
+ // Switch node.
+ squash_src_outputs[arg.switch_node->id()] = true;
+ node_map[arg.next_iteration->id()] = retval_node;
+ next_iterations.push_back(arg.next_iteration);
+ }
+ }
+ }
+
+ // Performs a reverse DFS, copying nodes and edges to the output graph.
+ // The _Arg and _Retval nodes were added unconditionally above, so we are
+ // guaranteed to get the correct function signature.
+ TF_RETURN_IF_ERROR(CopySubgraph(graph, frame, std::move(next_iterations),
+ squash_src_outputs, &node_map, output));
+
+ return Status::OK();
+}
+
+// Copy the FunctionDef of given function from lookup_library to library, if
+// it can be found in lookup_library but is missing from library.
+Status AddMissingFunctionByName(const string& function_name,
+ const FunctionLibraryDefinition* lookup_library,
+ FunctionLibraryDefinition* library) {
+ if (!library->Find(function_name) && lookup_library->Find(function_name)) {
+ return library->AddFunctionDef(*lookup_library->Find(function_name));
+ }
+ return Status::OK();
+}
+
+// Iterate over all functions that the given fdef refers to. Copy the missing
+// FunctionDefs from lookup_library to library.
+Status AddMissingFunctionDef(const FunctionDef& fdef,
+ const FunctionLibraryDefinition* lookup_library,
+ FunctionLibraryDefinition* library) {
+ TF_RET_CHECK(lookup_library);
+ for (const NodeDef& node : fdef.node_def()) {
+ if (library->Find(node.op())) {
+ continue;
+ }
+ // The function referred by 'SymbolicGradient' node is specified in its
+ // attribute 'f'.
+ if (node.op() == FunctionLibraryDefinition::kGradientOp) {
+ const AttrValue* attr =
+ AttrSlice(&node.attr()).Find(FunctionLibraryDefinition::kFuncAttr);
+ if (!attr) {
+ return errors::InvalidArgument("SymbolicGradient is missing attr: f");
+ }
+ const string& func_name = attr->func().name();
+ TF_RETURN_IF_ERROR(
+ AddMissingFunctionByName(func_name, lookup_library, library));
+ // Copy the user-defined gradient function if it exists.
+ const string grad_name = lookup_library->FindGradient(func_name);
+ if (!grad_name.empty() && library->FindGradient(func_name).empty()) {
+ TF_RETURN_IF_ERROR(
+ AddMissingFunctionByName(grad_name, lookup_library, library));
+ GradientDef grad_def;
+ grad_def.set_function_name(func_name);
+ grad_def.set_gradient_func(grad_name);
+ TF_RETURN_IF_ERROR(library->AddGradientDef(grad_def));
+ }
+ } else if (lookup_library->Find(node.op())) {
+ TF_RETURN_IF_ERROR(
+ library->AddFunctionDef(*lookup_library->Find(node.op())));
+ }
+ }
+ return Status::OK();
+}
+
+Status FunctionalizeLoop(const FunctionLibraryDefinition* lookup_library,
+ Graph* graph, Frame* frame,
+ FunctionLibraryDefinition* library) {
+ VLOG(2) << "Frame " << frame->name << " before: "
+ << dump_graph::DumpGraphToFile("functionalize_before", *graph,
+ library);
+
+ // Split loop-varying Enter nodes with multiple successors. If the same
+ // Tensor is fed as input to multiple loop arguments, we may end up with a
+ // shared Enter node. We clone Enter nodes with multiple successors to
+ // maintain the invariant of a unique Enter node per argument of the final
+ // loop.
+ std::vector<Arg> args;
+ for (const Arg& arg : frame->args) {
+ if (arg.is_loop_invariant) {
+ args.push_back(arg);
+ } else {
+ std::vector<const Edge*> edges(arg.enter->out_edges().begin(),
+ arg.enter->out_edges().end());
+ for (int i = 0; i < edges.size(); ++i) {
+ if (edges[i]->IsControlEdge() && edges[i]->dst()->IsSink()) {
+ continue;
+ }
+ TF_RET_CHECK(!edges[i]->IsControlEdge()) << edges[i]->src()->name();
+ Arg new_arg;
+ new_arg.is_loop_invariant = false;
+ if (i == 0) {
+ new_arg.enter = arg.enter;
+ } else {
+ new_arg.enter = graph->CopyNode(arg.enter);
+ frame->nodes.insert(new_arg.enter);
+ for (Edge const* e : arg.enter->in_edges()) {
+ graph->AddEdge(e->src(), e->src_output(), new_arg.enter,
+ e->IsControlEdge() ? Graph::kControlSlot : 0);
+ }
+ Node* dst = edges[i]->dst();
+ int dst_input = edges[i]->dst_input();
+ graph->RemoveEdge(edges[i]);
+ graph->AddEdge(new_arg.enter, 0, dst, dst_input);
+ }
+ args.push_back(new_arg);
+ }
+ }
+ }
+ frame->args = std::move(args);
+
+ std::sort(frame->args.begin(), frame->args.end(),
+ [](const Arg& a, const Arg& b) {
+ return NodeCmpByNameResourcesLast()(a.enter, b.enter);
+ });
+
+ if (frame->loop_cond == nullptr) {
+ return errors::InvalidArgument("Loop ", frame->name,
+ " has no LoopCond node");
+ }
+
+ // Find the set of Switch nodes that are successors of the LoopCond.
+ std::unordered_set<Node*> switches;
+ for (const Edge* edge : frame->loop_cond->out_edges()) {
+ if (!edge->IsControlEdge() && IsSwitch(edge->dst()) &&
+ edge->dst_input() == 1) {
+ switches.insert(edge->dst());
+ }
+ }
+
+ // For each non-constant argument, looks for the following pattern of nodes:
+ // Enter ----> Merge --------> Switch --> Exit
+ // ^ ^
+ // | |
+ // NextIteration LoopCond
+ // ^ ^
+ // | |
+ // ... ...
+ for (Arg& arg : frame->args) {
+ if (!arg.is_loop_invariant) {
+ // Follow the edge from the Enter to Merge.
+ const Edge* enter_merge = nullptr;
+ for (const Edge* e : arg.enter->out_edges()) {
+ // Ignore control-edges to the sink node. These are allowed by the
+ // graph invariants, although probably they should have been stripped
+ // off earlier.
+ if (e->IsControlEdge() && e->dst()->IsSink()) {
+ continue;
+ }
+ if (enter_merge != nullptr) {
+ return errors::Internal("Enter node for loop-varying argument ",
+ FormatNodeForError(*arg.enter),
+ " has multiple successors: ",
+ FormatNodeForError(*enter_merge->dst()),
+ " and ", FormatNodeForError(*e->dst()));
+ }
+ enter_merge = e;
+ }
+ if (enter_merge == nullptr) {
+ return errors::Internal("Enter node for loop-varying argument ",
+ FormatNodeForError(*arg.enter),
+ " has zero successors");
+ }
+ arg.merge = enter_merge->dst();
+ if (!IsMerge(arg.merge)) {
+ return errors::InvalidArgument(
+ "Successor of Enter node for loop-varying argument ",
+ FormatNodeForError(*arg.merge),
+ " is not a Merge node; got: ", arg.merge->type_string());
+ }
+
+ // Find the NextIteration from the merge. There should be two inputs to
+ // the Merge and the NextIteration should be the other input.
+ if (arg.merge->input_types().size() != 2) {
+ return errors::InvalidArgument(
+ "Unexpected number of inputs to Merge node for loop-varying "
+ "argument ",
+ FormatNodeForError(*arg.merge), "; expected 2, got ",
+ arg.merge->input_types().size());
+ }
+ TF_RETURN_IF_ERROR(arg.merge->input_node(1 - enter_merge->dst_input(),
+ &arg.next_iteration));
+ if (!IsNextIteration(arg.next_iteration)) {
+ return errors::InvalidArgument(
+ "Expected NextIteration node as input to Merge node; got node ",
+ FormatNodeForError(*arg.next_iteration), " with kind ",
+ arg.next_iteration->type_string());
+ }
+
+ // Find the Switch successor of the Merge. There should be exactly one
+ // Switch node that is a successor of both the Merge and the LoopCond.
+ for (const Edge* edge : arg.merge->out_edges()) {
+ if (edge->dst_input() == 0 && IsSwitch(edge->dst()) &&
+ switches.find(edge->dst()) != switches.end()) {
+ if (arg.switch_node != nullptr) {
+ return errors::InvalidArgument("Duplicate Switch successors to ",
+ FormatNodeForError(*arg.merge));
+ }
+ arg.switch_node = edge->dst();
+ }
+ }
+ if (arg.switch_node == nullptr) {
+ return errors::InvalidArgument("Missing Switch successor to ",
+ FormatNodeForError(*arg.merge));
+ }
+
+ // Update the device on the Identity outputs of the switch to match their
+ // target. These Identity outputs do not
+
+ // Loop over the switch node's output to:
+ // - Find the Exit successor.
+ // - Set the sharding on all Identity outputs of the switch. These
+ // identity nodes are values used by the loop body or condition.
+ // The Identity node may have the wrong device so copy the device from
+ // one of its outputs instead.
+ std::deque<const Edge*> possible_exit;
+ for (const Edge* edge : arg.switch_node->out_edges()) {
+ if (edge->src_output() == 0) {
+ possible_exit.push_back(edge);
+ }
+ if (IsIdentity(edge->dst())) {
+ TF_RETURN_IF_ERROR(
+ SetNodeShardingFromNeighbors(edge->dst(), /*out_edges=*/true));
+ }
+ }
+ // TODO(b/67425339): Allow general graph between switch and exit.
+ while (!possible_exit.empty()) {
+ const Edge* edge = possible_exit.front();
+ possible_exit.pop_front();
+ if (IsExit(edge->dst())) {
+ if (arg.exit != nullptr) {
+ return errors::InvalidArgument(
+ "Duplicate Exit successors to ",
+ FormatNodeForError(*arg.switch_node));
+ }
+ arg.exit = edge->dst();
+ } else {
+ if (!IsIdentity(edge->dst())) {
+ return errors::Unimplemented("General graph between switch (",
+ FormatNodeForError(*arg.switch_node),
+ ") and exit node of frame ",
+ frame->name, " not supported yet.");
+ }
+ for (const Edge* out : edge->dst()->out_edges()) {
+ possible_exit.push_back(out);
+ }
+ }
+ }
+ }
+ }
+
+ // Builds the condition and body functions.
+ std::unique_ptr<Graph> cond_graph;
+ TF_RETURN_IF_ERROR(BuildLoopCondition(*graph, frame, &cond_graph));
+ DataTypeVector arg_types;
+ std::unique_ptr<Graph> body_graph;
+ TF_RETURN_IF_ERROR(BuildLoopBody(*graph, frame, &arg_types, &body_graph));
+
+ VLOG(2) << "Frame " << frame->name << " condition: "
+ << dump_graph::DumpGraphToFile("loop_condition", *cond_graph, library)
+ << " body: " << dump_graph::DumpGraphToFile("loop_body", *body_graph);
+
+ static std::atomic<int64> sequence_num(0LL);
+ int64 id = ++sequence_num;
+ NameAttrList cond_name;
+ cond_name.set_name(strings::StrCat("_functionalize_cond_", id));
+ NameAttrList body_name;
+ body_name.set_name(strings::StrCat("_functionalize_body_", id));
+ FunctionDef cond_fdef;
+ TF_RETURN_IF_ERROR(
+ GraphToFunctionDef(*cond_graph, cond_name.name(), &cond_fdef));
+ FunctionDef body_fdef;
+ TF_RETURN_IF_ERROR(
+ GraphToFunctionDef(*body_graph, body_name.name(), &body_fdef));
+
+ TF_RETURN_IF_ERROR(library->AddFunctionDef(cond_fdef));
+ TF_RETURN_IF_ERROR(library->AddFunctionDef(body_fdef));
+ if (lookup_library) {
+ // Copy missing FunctionDefs from lookup_library to library to make library
+ // self-contained.
+ TF_RETURN_IF_ERROR(
+ AddMissingFunctionDef(cond_fdef, lookup_library, library));
+ TF_RETURN_IF_ERROR(
+ AddMissingFunctionDef(body_fdef, lookup_library, library));
+ }
+
+ // Builds a While operator.
+ NodeDef while_def;
+ NodeDefBuilder builder(frame->loop_cond->name(), "XlaWhile");
+ builder.Attr("T", arg_types);
+ builder.Attr("cond", cond_name);
+ builder.Attr("body", body_name);
+ std::vector<NodeDefBuilder::NodeOut> inputs;
+ for (int i = 0; i < frame->args.size(); ++i) {
+ const Arg& arg = frame->args[i];
+ const Edge* in_edge;
+ TF_RETURN_IF_ERROR(arg.enter->input_edge(0, &in_edge));
+ if (in_edge->IsControlEdge()) {
+ builder.ControlInput(in_edge->src()->name());
+ } else {
+ inputs.push_back(NodeDefBuilder::NodeOut(
+ in_edge->src()->name(), in_edge->src_output(), arg_types[i]));
+ }
+ }
+ builder.Input(inputs);
+ TF_RETURN_IF_ERROR(builder.Finalize(&while_def));
+ TF_ASSIGN_OR_RETURN(Node * while_node, AddNodeDefToGraph(while_def, graph));
+
+ // Copies edges to the Enter nodes and from the Exit nodes onto the While.
+ for (int i = 0; i < frame->args.size(); ++i) {
+ const Arg& arg = frame->args[i];
+ const Edge* in_edge;
+ TF_RETURN_IF_ERROR(arg.enter->input_edge(0, &in_edge));
+ if (in_edge->IsControlEdge()) {
+ graph->AddControlEdge(in_edge->src(), while_node);
+ } else {
+ graph->AddEdge(in_edge->src(), in_edge->src_output(), while_node, i);
+ }
+
+ if (!arg.is_loop_invariant) {
+ // Add output edges if the output of the loop is consumed.
+ if (arg.exit != nullptr) {
+ std::vector<const Edge*> edges(arg.exit->out_edges().begin(),
+ arg.exit->out_edges().end());
+ for (const Edge* edge : edges) {
+ Node* dst = edge->dst();
+ int dst_input = edge->dst_input();
+ graph->RemoveEdge(edge);
+
+ if (dst_input == Graph::kControlSlot) {
+ graph->AddControlEdge(while_node, dst);
+ } else {
+ graph->AddEdge(while_node, i, dst, dst_input);
+ }
+ }
+ }
+ }
+ }
+
+ // Remove the old nodes from the graph, and add the while node to the parent
+ // frame.
+ for (Node* node : frame->nodes) {
+ graph->RemoveNode(node);
+ }
+ frame->nodes.clear();
+ frame->parent->nodes.insert(while_node);
+
+ VLOG(2) << "Frame " << frame->name << " after: "
+ << dump_graph::DumpGraphToFile("functionalize_after", *graph,
+ library);
+
+ return Status::OK();
+}
+} // namespace
+
+Status FunctionalizeWhileLoop(const FunctionLibraryDefinition* lookup_library,
+ Graph* graph,
+ FunctionLibraryDefinition* library) {
+ // Note: BuildControlFlowInfo() requires that the graph's source node is
+ // connected to all source nodes in the graph. Many graphs violate this
+ // invariant.
+ std::vector<ControlFlowInfo> cf_info;
+ std::vector<string> unreachable_nodes;
+ TF_RETURN_IF_ERROR(BuildControlFlowInfo(graph, &cf_info, &unreachable_nodes));
+ if (!unreachable_nodes.empty()) {
+ return errors::InvalidArgument(
+ "The following nodes are unreachable from the source in the graph: ",
+ errors::FormatNodeNamesForError(unreachable_nodes));
+ }
+
+ // Builds Frames, indexed by name.
+ std::unordered_map<string, Frame> frames;
+ for (Node* node : graph->op_nodes()) {
+ const ControlFlowInfo& cf = cf_info[node->id()];
+
+ VLOG(2) << "node: " << node->name() << " (" << node->id()
+ << ") frame_name: " << cf.frame_name
+ << " frame: " << (cf.frame ? cf.frame->name() : "---")
+ << " parent_frame: "
+ << (cf.parent_frame ? cf.parent_frame->name() : "---");
+ TF_RET_CHECK(cf.frame != nullptr && cf.parent_frame != nullptr);
+
+ Frame& frame = frames[cf.frame_name];
+ Frame* parent = &frames[cf_info[cf.parent_frame->id()].frame_name];
+ if (frame.parent == nullptr) {
+ frame.parent = parent;
+ frame.name = cf.frame_name;
+ ++parent->num_children;
+ }
+
+ if (IsEnter(node)) {
+ Arg arg;
+ arg.enter = node;
+ TF_RETURN_IF_ERROR(GetNodeAttr(arg.enter->attrs(), "is_constant",
+ &arg.is_loop_invariant));
+ frame.args.push_back(arg);
+ } else if (IsLoopCond(node)) {
+ frame.loop_cond = node;
+ }
+ frame.nodes.insert(node);
+ }
+
+ // Adds frames with no children (i.e., the innermost frames) to a worklist.
+ std::deque<Frame*> worklist;
+ for (auto& frame : frames) {
+ if (frame.second.num_children == 0) {
+ worklist.push_back(&frame.second);
+ }
+ }
+
+ // Eliminate loops from innermost to outermost.
+ while (!worklist.empty()) {
+ Frame* frame = worklist.front();
+ worklist.pop_front();
+ if (frame->parent == frame) {
+ // Skip the root frame.
+ continue;
+ }
+
+ TF_RETURN_IF_ERROR(
+ FunctionalizeLoop(lookup_library, graph, frame, library));
+
+ // If the parent has no remaining children, add it to the worklist.
+ --frame->parent->num_children;
+ if (frame->parent->num_children == 0) {
+ worklist.push_back(frame->parent);
+ }
+ }
+
+ // There should be no cycle at this point, since while loops have been removed
+ // from graph.
+ // Check that the newly added XlaWhile nodes don't feed into themselves.
+ for (const Node* node : graph->op_nodes()) {
+ if (node->def().op() == "XlaWhile") {
+ TF_RETURN_WITH_CONTEXT_IF_ERROR(
+ CheckNodeNotInCycle(node, graph->num_node_ids()),
+ "Functionalizing loop failed.");
+ }
+ }
+
+ return Status::OK();
+}
+
+} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/functionalize_while.h b/tensorflow/compiler/tf2xla/functionalize_while.h
new file mode 100644
index 0000000000..a708c6e4ec
--- /dev/null
+++ b/tensorflow/compiler/tf2xla/functionalize_while.h
@@ -0,0 +1,32 @@
+/* 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.
+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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_WHILE_H_
+#define TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_WHILE_H_
+
+#include "tensorflow/core/framework/function.h"
+#include "tensorflow/core/graph/graph.h"
+
+namespace tensorflow {
+
+// Transformation that converts tf.while_loop() loops into functional While
+// operators, suitable for XLA compilation. If lookup_library is provided, use
+// it to make the library for control flow self-contained.
+Status FunctionalizeWhileLoop(const FunctionLibraryDefinition* lookup_library,
+ Graph* graph, FunctionLibraryDefinition* library);
+
+} // namespace tensorflow
+
+#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_WHILE_H_
diff --git a/tensorflow/compiler/tf2xla/kernels/BUILD b/tensorflow/compiler/tf2xla/kernels/BUILD
index 3bfe74521f..b1366e9e31 100644
--- a/tensorflow/compiler/tf2xla/kernels/BUILD
+++ b/tensorflow/compiler/tf2xla/kernels/BUILD
@@ -6,6 +6,10 @@ package(
load("//tensorflow:tensorflow.bzl", "tf_copts")
load("//tensorflow:tensorflow.bzl", "tf_kernel_library")
+load(
+ "//third_party/mkl:build_defs.bzl",
+ "if_mkl",
+)
tf_kernel_library(
name = "xla_ops",
@@ -154,8 +158,14 @@ tf_kernel_library(
"//tensorflow/core/kernels:sparse_to_dense_op",
"//tensorflow/core/kernels:stack_ops",
"//tensorflow/core/kernels:training_ops",
- "//tensorflow/core/kernels:transpose_op",
- ],
+ ] + if_mkl(
+ [
+ "//tensorflow/core/kernels:mkl_transpose_op",
+ ],
+ [
+ "//tensorflow/core/kernels:transpose_op",
+ ],
+ ),
)
tf_kernel_library(
diff --git a/tensorflow/compiler/tf2xla/kernels/conv_ops.cc b/tensorflow/compiler/tf2xla/kernels/conv_ops.cc
index 5da7972397..674720e22f 100644
--- a/tensorflow/compiler/tf2xla/kernels/conv_ops.cc
+++ b/tensorflow/compiler/tf2xla/kernels/conv_ops.cc
@@ -120,45 +120,30 @@ xla::XlaOp CreateExpandedFilterMask(const TensorShape& filter_shape,
{expanded_filter_shape.dims() - 2});
}
-// Expands a filter of shape [H, W, ..., M, N] to [H, W, ..., M, M*N] by adding
-// zeros for the cross-depth filters. Used to build a depthwise convolution.
-xla::XlaOp ExpandFilterForDepthwiseConvolution(const TensorShape& filter_shape,
- DataType dtype,
- const xla::XlaOp& filter,
- xla::XlaBuilder* builder) {
- int64 depthwise_multiplier = filter_shape.dim_size(filter_shape.dims() - 1);
- int64 input_feature = filter_shape.dim_size(filter_shape.dims() - 2);
- TensorShape expanded_filter_shape =
- ExpandedFilterShapeForDepthwiseConvolution(filter_shape);
+// Reshapes a filter of shape [H, W, ..., M, N] to [H, W, ..., 1, M*N]. Used to
+// build a depthwise convolution.
+xla::XlaOp ReshapeFilterForDepthwiseConvolution(const TensorShape& filter_shape,
+ const xla::XlaOp& filter) {
+ int64 input_feature_dim = filter_shape.dims() - 2;
+ int64 output_feature_dim = filter_shape.dims() - 1;
+ int64 depthwise_multiplier = filter_shape.dim_size(output_feature_dim);
+ int64 input_feature = filter_shape.dim_size(input_feature_dim);
// Create a [H, W, ..., 1, N*M] reshape of the filter.
- TensorShape implicit_broadcast_filter_shape = expanded_filter_shape;
- implicit_broadcast_filter_shape.set_dim(
- implicit_broadcast_filter_shape.dims() - 2, 1);
- implicit_broadcast_filter_shape.set_dim(
- implicit_broadcast_filter_shape.dims() - 1,
- depthwise_multiplier * input_feature);
- auto implicit_broadcast_filter =
- xla::Reshape(filter, implicit_broadcast_filter_shape.dim_sizes());
-
- // Broadcast the filter to [H, W, ..., M, M*N].
- auto expanded_zero = CreateExpandedZero(filter_shape, dtype, builder);
- auto expanded_filter = xla::Add(implicit_broadcast_filter, expanded_zero);
-
- // If the filter mask is set, choose the broadcasted filter, othwerwise,
- // choose zero.
- return xla::Select(CreateExpandedFilterMask(filter_shape, builder),
- expanded_filter, expanded_zero);
+ TensorShape implicit_broadcast_filter_shape = filter_shape;
+ implicit_broadcast_filter_shape.set_dim(input_feature_dim, 1);
+ implicit_broadcast_filter_shape.set_dim(output_feature_dim,
+ depthwise_multiplier * input_feature);
+ return xla::Reshape(filter, implicit_broadcast_filter_shape.dim_sizes());
}
-// Inverse of ExpandFilterForDepthwiseConvolution.
+// Reduces the results of the convolution with an expanded filter to the
+// non-expanded filter.
xla::XlaOp ContractFilterForDepthwiseBackprop(XlaOpKernelContext* ctx,
const TensorShape& filter_shape,
DataType dtype,
const xla::XlaOp& filter_backprop,
xla::XlaBuilder* builder) {
- TensorShape expanded_filter_shape =
- ExpandedFilterShapeForDepthwiseConvolution(filter_shape);
auto masked_expanded_filter = xla::Select(
CreateExpandedFilterMask(filter_shape, builder), filter_backprop,
CreateExpandedZero(filter_shape, dtype, builder));
@@ -168,8 +153,7 @@ xla::XlaOp ContractFilterForDepthwiseBackprop(XlaOpKernelContext* ctx,
// ExpandedZero guarantees that only one element is non zero, so there
// cannot be accumulated precision error.
xla::Reduce(masked_expanded_filter, XlaHelpers::Zero(builder, dtype),
- *ctx->GetOrCreateAdd(dtype),
- {expanded_filter_shape.dims() - 2}),
+ *ctx->GetOrCreateAdd(dtype), {filter_shape.dims() - 2}),
filter_shape.dim_sizes());
}
@@ -245,15 +229,9 @@ class ConvOp : public XlaOpKernel {
"input and filter must have the same depth: ", in_depth,
" vs ", input_shape.dim_size(feature_dim)));
- xla::XlaBuilder* b = ctx->builder();
-
xla::XlaOp filter = ctx->Input(1);
- TensorShape expanded_filter_shape = filter_shape;
if (depthwise_) {
- filter = ExpandFilterForDepthwiseConvolution(
- filter_shape, ctx->input_type(0), filter, b);
- expanded_filter_shape =
- ExpandedFilterShapeForDepthwiseConvolution(filter_shape);
+ filter = ReshapeFilterForDepthwiseConvolution(filter_shape, filter);
}
xla::ConvolutionDimensionNumbers dims;
@@ -280,14 +258,15 @@ class ConvOp : public XlaOpKernel {
int64 unused_output_size;
OP_REQUIRES_OK(
ctx, GetWindowedOutputSizeVerboseV2(
- input_shape.dim_size(dim), expanded_filter_shape.dim_size(i),
+ input_shape.dim_size(dim), filter_shape.dim_size(i),
rhs_dilation[i], window_strides[i], padding_,
&unused_output_size, &padding[i].first, &padding[i].second));
}
- xla::XlaOp conv =
- xla::ConvGeneralDilated(ctx->Input(0), filter, window_strides, padding,
- lhs_dilation, rhs_dilation, dims);
+ xla::XlaOp conv = xla::ConvGeneralDilated(
+ ctx->Input(0), filter, window_strides, padding, lhs_dilation,
+ rhs_dilation, dims,
+ /*feature_group_count=*/depthwise_ ? in_depth : 1);
ctx->SetOutput(0, conv);
}
@@ -388,7 +367,6 @@ class ConvBackpropInputOp : public XlaOpKernel {
expanded_filter_shape, out_backprop_shape, dilations_,
strides_, padding_, data_format_, &dims));
- xla::XlaBuilder* b = ctx->builder();
auto filter = ctx->Input(1);
auto out_backprop = ctx->Input(2);
@@ -425,12 +403,6 @@ class ConvBackpropInputOp : public XlaOpKernel {
rhs_dilation[i] = dilations_[dim];
}
- // If this is a depthwise convolution, expand the filter.
- if (depthwise_) {
- filter = ExpandFilterForDepthwiseConvolution(
- filter_shape, ctx->input_type(1), filter, b);
- }
-
// Mirror the filter in the spatial dimensions.
xla::XlaOp mirrored_weights = xla::Rev(filter, kernel_spatial_dims);
@@ -438,7 +410,11 @@ class ConvBackpropInputOp : public XlaOpKernel {
// = gradients (with padding and dilation) <conv> mirrored_weights
xla::XlaOp in_backprop = xla::ConvGeneralDilated(
out_backprop, mirrored_weights, /*window_strides=*/ones, padding,
- lhs_dilation, rhs_dilation, dnums);
+ lhs_dilation, rhs_dilation, dnums,
+ /*feature_group_count=*/
+ depthwise_ ? out_backprop_shape.dim_size(feature_dim) /
+ filter_shape.dim_size(num_spatial_dims_ + 1)
+ : 1);
ctx->SetOutput(0, in_backprop);
}
diff --git a/tensorflow/compiler/tf2xla/kernels/gather_op.cc b/tensorflow/compiler/tf2xla/kernels/gather_op.cc
index 35de96e0aa..44140304fd 100644
--- a/tensorflow/compiler/tf2xla/kernels/gather_op.cc
+++ b/tensorflow/compiler/tf2xla/kernels/gather_op.cc
@@ -95,11 +95,11 @@ Status XlaGather(const xla::XlaOp& input, const TensorShape& input_shape,
// operand = s32[3,3] parameter(0)
// indices = s32[2] parameter(1)
// gather = s32[3,2] gather(operand, indices),
- // output_window_dims={0},
- // elided_window_dims={1},
- // gather_dims_to_operand_dims={1},
+ // offset_dims={0},
+ // collapsed_slice_dims={1},
+ // start_index_map={1},
// index_vector_dim=1,
- // window_bounds={3, 1}
+ // slice_sizes={3, 1}
//
//
// Example of an N-D gather pulling out slices of shape [1,1,2] out of a
@@ -108,42 +108,42 @@ Status XlaGather(const xla::XlaOp& input, const TensorShape& input_shape,
// operand = s32[3,3,2] parameter(0)
// indices = s32[2,2] parameter(1)
// gather = s32[2,2] gather(operand, indices),
- // output_window_dims={1},
- // elided_window_dims={0,1},
- // gather_dims_to_operand_dims={0,1},
+ // offset_dims={1},
+ // collapsed_slice_dims={0,1},
+ // start_index_map={0,1},
// index_vector_dim=0,
- // window_bounds={1,1,2}
+ // slice_sizes={1,1,2}
xla::GatherDimensionNumbers dim_numbers;
- std::vector<int64> window_bounds;
- window_bounds.reserve(input_shape.dims());
+ std::vector<int64> slice_sizes;
+ slice_sizes.reserve(input_shape.dims());
for (int64 i = 0; i < input_shape.dims(); i++) {
int64 window_bound;
if (axis <= i && i < (axis + num_index_dims)) {
- dim_numbers.add_elided_window_dims(i);
+ dim_numbers.add_collapsed_slice_dims(i);
window_bound = 1;
} else {
window_bound = input_shape.dim_size(i);
}
- window_bounds.push_back(window_bound);
+ slice_sizes.push_back(window_bound);
if (i < axis) {
- dim_numbers.add_output_window_dims(i);
+ dim_numbers.add_offset_dims(i);
} else if (i >= (axis + num_index_dims)) {
int64 indices_rank =
indices_are_nd ? (indices_shape.dims() - 1) : indices_shape.dims();
- dim_numbers.add_output_window_dims(i + indices_rank - num_index_dims);
+ dim_numbers.add_offset_dims(i + indices_rank - num_index_dims);
}
}
dim_numbers.set_index_vector_dim(indices_are_nd ? (indices_shape.dims() - 1)
: indices_shape.dims());
for (int64 i = axis; i < axis + num_index_dims; i++) {
- dim_numbers.add_gather_dims_to_operand_dims(i);
+ dim_numbers.add_start_index_map(i);
}
- *gather_output = xla::Gather(input, indices, dim_numbers, window_bounds);
+ *gather_output = xla::Gather(input, indices, dim_numbers, slice_sizes);
return Status::OK();
}
diff --git a/tensorflow/compiler/tf2xla/kernels/identity_op.cc b/tensorflow/compiler/tf2xla/kernels/identity_op.cc
index e72200bfbc..19dd38c46e 100644
--- a/tensorflow/compiler/tf2xla/kernels/identity_op.cc
+++ b/tensorflow/compiler/tf2xla/kernels/identity_op.cc
@@ -25,7 +25,10 @@ class IdentityOp : public XlaOpKernel {
void Compile(XlaOpKernelContext* ctx) override {
for (int i = 0; i < ctx->num_inputs(); ++i) {
- ctx->SetOutput(i, ctx->Input(i));
+ // Forwards using the underlying op_kernel_context so both tensor and
+ // resource values are forwarded correctly.
+ ctx->op_kernel_context()->set_output(i,
+ ctx->op_kernel_context()->input(i));
}
}
@@ -35,9 +38,10 @@ class IdentityOp : public XlaOpKernel {
// XLA_* devices also register a "real" Identity operator so we suppress the
// dummy operator using CompilationOnly().
-REGISTER_XLA_OP(Name("Identity").CompilationOnly(), IdentityOp);
-
-REGISTER_XLA_OP(Name("IdentityN").CompilationOnly(), IdentityOp);
+REGISTER_XLA_OP(Name("Identity").AllowResourceTypes().CompilationOnly(),
+ IdentityOp);
+REGISTER_XLA_OP(Name("IdentityN").AllowResourceTypes().CompilationOnly(),
+ IdentityOp);
REGISTER_XLA_OP(Name("PlaceholderWithDefault"), IdentityOp);
REGISTER_XLA_OP(Name("PreventGradient"), IdentityOp);
REGISTER_XLA_OP(Name("StopGradient"), IdentityOp);
diff --git a/tensorflow/compiler/tf2xla/kernels/if_op.cc b/tensorflow/compiler/tf2xla/kernels/if_op.cc
index 462e0e4395..6e1dbf5472 100644
--- a/tensorflow/compiler/tf2xla/kernels/if_op.cc
+++ b/tensorflow/compiler/tf2xla/kernels/if_op.cc
@@ -200,25 +200,24 @@ void XlaIfOp::Compile(XlaOpKernelContext* ctx) {
}
}
- xla::XlaOp outputs = xla::Conditional(
- ctx->Input(0), xla::Tuple(b, inputs), *then_result.computation,
- xla::Tuple(b, inputs), *else_result.computation);
+ auto input_tuple = xla::Tuple(b, inputs);
+ xla::XlaOp outputs =
+ xla::Conditional(ctx->Input(0), input_tuple, *then_result.computation,
+ input_tuple, *else_result.computation);
// Sets non-variable outputs.
for (int i = 0; i < output_types_.size(); ++i) {
- if (ctx->input_type(i) != DT_RESOURCE) {
- xla::XlaOp output_handle = xla::GetTupleElement(outputs, i);
- if (VLOG_IS_ON(2)) {
- LOG(INFO) << "Setting output " << i;
- auto shape_or = b->GetShape(output_handle);
- if (shape_or.ok()) {
- LOG(INFO) << "Shape for output " << i << ": "
- << xla::ShapeUtil::HumanString(shape_or.ValueOrDie());
- } else {
- LOG(INFO) << "Shape unknown for output " << i;
- }
+ xla::XlaOp output_handle = xla::GetTupleElement(outputs, i);
+ if (VLOG_IS_ON(2)) {
+ LOG(INFO) << "Setting output " << i;
+ auto shape_or = b->GetShape(output_handle);
+ if (shape_or.ok()) {
+ LOG(INFO) << "Shape for output " << i << ": "
+ << xla::ShapeUtil::HumanString(shape_or.ValueOrDie());
+ } else {
+ LOG(INFO) << "Shape unknown for output " << i;
}
- ctx->SetOutput(i, output_handle);
}
+ ctx->SetOutput(i, output_handle);
}
// Updates the values of any resource variables modified by the conditional
diff --git a/tensorflow/compiler/tf2xla/kernels/reverse_op.cc b/tensorflow/compiler/tf2xla/kernels/reverse_op.cc
index d962ef4a5f..c0afccaa5b 100644
--- a/tensorflow/compiler/tf2xla/kernels/reverse_op.cc
+++ b/tensorflow/compiler/tf2xla/kernels/reverse_op.cc
@@ -95,10 +95,24 @@ class ReverseV2Op : public XlaOpKernel {
std::vector<int64> axes;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &axes));
+ // witnessed_axes is used to ensure that the same axis is not marked to be
+ // reversed multiple times.
+ gtl::InlinedVector<bool, 8> witnessed_axes(x_shape.dims(), false);
+
for (int d = 0; d < axes.size(); ++d) {
- OP_REQUIRES(ctx, (0 <= axes[d]) && (axes[d] < x_shape.dims()),
- errors::InvalidArgument(axes[d], " is out of range [0, ",
- x_shape.dims(), ")."));
+ OP_REQUIRES(
+ ctx, (-x_shape.dims() <= axes[d]) && (axes[d] < x_shape.dims()),
+ errors::InvalidArgument(axes[d], " is out of range [-",
+ x_shape.dims(), ", ", x_shape.dims(), ")."));
+ // Axes can be negative and are shifted to the canonical index before
+ // being lowered to HLO.
+ if (axes[d] < 0) {
+ axes[d] += x_shape.dims();
+ }
+ OP_REQUIRES(ctx, !witnessed_axes[axes[d]],
+ errors::InvalidArgument("canonicalized axis ", axes[d],
+ " was repeated."));
+ witnessed_axes[axes[d]] = true;
}
ctx->SetOutput(0, xla::Rev(ctx->Input(0), axes));
diff --git a/tensorflow/compiler/tf2xla/kernels/tile_ops.cc b/tensorflow/compiler/tf2xla/kernels/tile_ops.cc
index 1233a37565..2c7213f322 100644
--- a/tensorflow/compiler/tf2xla/kernels/tile_ops.cc
+++ b/tensorflow/compiler/tf2xla/kernels/tile_ops.cc
@@ -70,7 +70,7 @@ class TileOp : public XlaOpKernel {
bool one_dimension_is_broadcasted_without_multiple = true;
for (int i = 0; i < input_dims; ++i) {
int multiple = literal.Get<int>({i});
- OP_REQUIRES(ctx, multiple,
+ OP_REQUIRES(ctx, multiple >= 0,
errors::InvalidArgument("Expected multiples[", i,
"] >= 0, but got ", multiple));
int64 new_dim = input_shape.dim_size(i) * multiple;
diff --git a/tensorflow/compiler/tf2xla/lib/triangular_solve.cc b/tensorflow/compiler/tf2xla/lib/triangular_solve.cc
index 04fa10108c..febb638e5e 100644
--- a/tensorflow/compiler/tf2xla/lib/triangular_solve.cc
+++ b/tensorflow/compiler/tf2xla/lib/triangular_solve.cc
@@ -57,7 +57,7 @@ xla::XlaOp DiagonalBlocks(xla::XlaOp a, int64 block_size) {
// We can grab entire blocks using gather
if (n > block_size) {
// Construct the starting indices of the diagonal blocks
- auto gather_indices =
+ auto start_indices =
Transpose(Broadcast(Mul(Iota(builder, xla::S32, num_blocks),
xla::ConstantR0<int32>(builder, block_size)),
/*broadcast_sizes=*/{2}),
@@ -65,13 +65,13 @@ xla::XlaOp DiagonalBlocks(xla::XlaOp a, int64 block_size) {
// Gather the diagonal blocks
xla::GatherDimensionNumbers dim_numbers;
- dim_numbers.add_output_window_dims(ndims - 1);
- dim_numbers.add_output_window_dims(ndims);
- dim_numbers.add_gather_dims_to_operand_dims(ndims - 2);
- dim_numbers.add_gather_dims_to_operand_dims(ndims - 1);
+ dim_numbers.add_offset_dims(ndims - 1);
+ dim_numbers.add_offset_dims(ndims);
+ dim_numbers.add_start_index_map(ndims - 2);
+ dim_numbers.add_start_index_map(ndims - 1);
dim_numbers.set_index_vector_dim(1);
- diag_blocks = Gather(a, gather_indices, dim_numbers,
- /*window_bounds=*/{block_size, block_size});
+ diag_blocks = Gather(a, start_indices, dim_numbers,
+ /*slice_sizes=*/{block_size, block_size});
}
// The last block might be smaller than the block size,
diff --git a/tensorflow/compiler/tf2xla/tf2xla_util.cc b/tensorflow/compiler/tf2xla/tf2xla_util.cc
index 9203e8d9e6..0e07485d18 100644
--- a/tensorflow/compiler/tf2xla/tf2xla_util.cc
+++ b/tensorflow/compiler/tf2xla/tf2xla_util.cc
@@ -16,6 +16,7 @@ limitations under the License.
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include <queue>
+#include <random>
#include <set>
#include <unordered_map>
@@ -297,4 +298,29 @@ void AddDtypeToKernalDefConstraint(StringPiece name, DataType dtype,
}
}
+namespace {
+uint32 InitialRandomSeed() {
+ // Support plumbing the TF seed through to XLA is being worked on.
+ // If a user wants deterministic behavior, their best option
+ // is to start with a known checkpoint. This also handles issues when
+ // multiple random calls can be invoked in any order by TF executor.
+ // Another option is to use stateless random ops. They have much cleaner
+ // semantics.
+ // If a user really wants to set a deterministic seed for XLA-based
+ // devices, this is the place to do it.
+ std::random_device rd;
+ // Make the starting value odd.
+ return rd() | 1;
+}
+} // namespace
+
+uint32 GetXLARandomSeed() {
+ // We initialize counter with an odd number and increment it by two
+ // everytime. This ensures that it will never be zero, even
+ // after an overflow. When seeded with zero, some XLA backends
+ // can return all zeros instead of random numbers.
+ static std::atomic<uint32> counter(InitialRandomSeed());
+ return counter.fetch_add(2);
+}
+
} // namespace tensorflow
diff --git a/tensorflow/compiler/tf2xla/tf2xla_util.h b/tensorflow/compiler/tf2xla/tf2xla_util.h
index 745beb39c1..33620ef810 100644
--- a/tensorflow/compiler/tf2xla/tf2xla_util.h
+++ b/tensorflow/compiler/tf2xla/tf2xla_util.h
@@ -56,6 +56,9 @@ Status SetNodeShardingFromNeighbors(Node* n, bool out_edges);
void AddDtypeToKernalDefConstraint(StringPiece name, DataType dtype,
KernelDef* kdef);
+// Returns the next random seed to use for seeding xla rng.
+uint32 GetXLARandomSeed();
+
} // namespace tensorflow
#endif // TENSORFLOW_COMPILER_TF2XLA_TF2XLA_UTIL_H_
diff --git a/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc b/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc
index 334459138b..1f0f240135 100644
--- a/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc
+++ b/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc
@@ -14,7 +14,6 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h"
-#include "tensorflow/compiler/tf2xla/cpu_function_runtime.h"
#include <cassert>
@@ -22,61 +21,42 @@ namespace tensorflow {
XlaCompiledCpuFunction::XlaCompiledCpuFunction(const StaticData& static_data,
AllocMode alloc_mode)
- : raw_function_(static_data.raw_function),
- result_index_(static_data.result_index),
- args_(new void*[static_data.num_args]),
- temps_(new void*[static_data.num_temps]),
- arg_index_to_temp_index_(new int32[static_data.num_args]),
- num_args_(static_data.num_args),
- arg_names_(static_data.arg_names),
- result_names_(static_data.result_names),
- program_shape_(static_data.program_shape),
- hlo_profile_printer_data_(static_data.hlo_profile_printer_data) {
+ : raw_function_(static_data.raw_function_),
+ result_index_(static_data.result_index_),
+ buffer_table_(new void*[static_data.num_buffers_]),
+ buffer_infos_(static_data.buffer_infos_),
+ arg_index_table_(static_data.arg_index_table_),
+ num_args_(static_data.num_args_),
+ arg_names_(static_data.arg_names_),
+ result_names_(static_data.result_names_),
+ program_shape_(static_data.program_shape_),
+ hlo_profile_printer_data_(static_data.hlo_profile_printer_data_) {
+ bool allocate_entry_params =
+ alloc_mode == AllocMode::ARGS_RESULTS_PROFILES_AND_TEMPS;
// Allocate arg and temp buffers.
- if (alloc_mode == AllocMode::ARGS_RESULTS_PROFILES_AND_TEMPS) {
- alloc_args_ = cpu_function_runtime::MallocContiguousBuffers(
- static_data.arg_sizes, static_data.num_args, args_,
- /*annotate_initialized=*/false);
- }
- alloc_temps_ = cpu_function_runtime::MallocContiguousBuffers(
- static_data.temp_sizes, static_data.num_temps, temps_,
+ alloc_buffer_table_ = cpu_function_runtime::MallocContiguousBuffers(
+ static_data.buffer_infos_, static_data.num_buffers_,
+ /*allocate_entry_params=*/allocate_entry_params, buffer_table_,
/*annotate_initialized=*/true);
-
- for (int i = 0; i < static_data.num_temps; i++) {
- if (static_data.temp_sizes[i] < -1) {
- int32 param_number = -(static_data.temp_sizes[i] + 2);
- arg_index_to_temp_index_[param_number] = i;
- }
- }
-
// If Hlo profiling is enabled the generated code expects an appropriately
// sized buffer to be passed in as the last argument. If Hlo profiling is
// disabled the last function argument is still present in the function
// signature, but it is ignored by the generated code and we pass in null for
// it.
if (hlo_profiling_enabled()) {
- profile_counters_ = new int64[static_data.profile_counters_size]();
+ profile_counters_ = new int64[static_data.profile_counters_size_]();
}
}
bool XlaCompiledCpuFunction::Run() {
- // Propagate pointers to the argument buffers into the temps array. Code
- // generated by XLA discovers the incoming argument pointers from the temps
- // array.
- for (int32 i = 0; i < num_args_; i++) {
- temps_[arg_index_to_temp_index_[i]] = args_[i];
- }
- raw_function_(temps_[result_index_], &run_options_, nullptr, temps_,
- profile_counters_);
+ raw_function_(buffer_table_[result_index_], &run_options_, nullptr,
+ buffer_table_, profile_counters_);
return true;
}
XlaCompiledCpuFunction::~XlaCompiledCpuFunction() {
- cpu_function_runtime::FreeContiguous(alloc_args_);
- cpu_function_runtime::FreeContiguous(alloc_temps_);
- delete[] args_;
- delete[] temps_;
- delete[] arg_index_to_temp_index_;
+ cpu_function_runtime::FreeContiguous(alloc_buffer_table_);
+ delete[] buffer_table_;
delete[] profile_counters_;
}
diff --git a/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h b/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h
index 27cfb354bf..425e769346 100644
--- a/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h
+++ b/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h
@@ -19,6 +19,7 @@ limitations under the License.
#include <cassert>
#include <string>
+#include "tensorflow/compiler/tf2xla/cpu_function_runtime.h"
#include "tensorflow/compiler/xla/executable_run_options.h"
#include "tensorflow/core/platform/types.h"
@@ -56,46 +57,85 @@ class XlaCompiledCpuFunction {
// StaticData represents the state necessary to run an XLA-compiled
// function. For JIT this is backed by data in XlaJitCompiledCpuFunction; for
// AOT this is backed by data compiled into the object file.
- struct StaticData {
+ //
+ // The contents of StaticData are XLA-internal implementation details and
+ // should not be relied on by clients.
+ //
+ // TODO(sanjoy): Come up with a cleaner way to express the contraint we want
+ // here: generated XlaCompiledCpuFunction subclasses should be able to create
+ // instances of StaticData but only XlaCompiledCpuFunction should be able to
+ // read from StaticData instances.
+ class StaticData {
+ public:
+ void set_raw_function(RawFunction raw_function) {
+ raw_function_ = raw_function;
+ }
+ void set_buffer_infos(
+ const cpu_function_runtime::BufferInfo* buffer_infos) {
+ buffer_infos_ = buffer_infos;
+ }
+ void set_num_buffers(size_t num_buffers) { num_buffers_ = num_buffers; }
+ void set_arg_index_table(const int32* arg_index_table) {
+ arg_index_table_ = arg_index_table;
+ }
+ void set_num_args(int64 num_args) { num_args_ = num_args; }
+ void set_result_index(size_t result_index) { result_index_ = result_index; }
+ void set_arg_names(const char** arg_names) { arg_names_ = arg_names; }
+ void set_result_names(const char** result_names) {
+ result_names_ = result_names;
+ }
+ void set_program_shape(const xla::ProgramShape* program_shape) {
+ program_shape_ = program_shape;
+ }
+ const xla::HloProfilePrinterData* hlo_profile_printer_data() const {
+ return hlo_profile_printer_data_;
+ }
+ void set_hlo_profile_printer_data(
+ const xla::HloProfilePrinterData* hlo_profile_printer_data) {
+ hlo_profile_printer_data_ = hlo_profile_printer_data;
+ }
+ void set_profile_counters_size(int64 profile_counters_size) {
+ profile_counters_size_ = profile_counters_size;
+ }
+
+ private:
// The raw function to call.
- RawFunction raw_function;
-
- // Cardinality and size of arg buffers.
- const intptr_t* arg_sizes = nullptr;
- size_t num_args = 0;
-
- // Cardinality and size of temp buffers.
- //
- // If temp_sizes[i] >= 0 then the i'th temp is a regular temporary buffer.
- //
- // If temp_sizes[i] == -1 then the i'th temp is a constant buffer. The
- // corresponding entry in the temp buffer array needs to be set to null.
- //
- // If temp_sizes[i] < -1 then the i'th temp is the entry parameter
- // -(temp_sizes[i] + 2).
- const intptr_t* temp_sizes = nullptr;
- size_t num_temps = 0;
+ RawFunction raw_function_;
+
+ // Contains information about the buffers used by the XLA computation.
+ const cpu_function_runtime::BufferInfo* buffer_infos_ = nullptr;
+ size_t num_buffers_ = 0;
+
+ // Entry parameter i is described by
+ // buffer_infos[arg_index_table[i]].
+ const int32* arg_index_table_ = nullptr;
+
+ // There are num_args entry parameters.
+ int64 num_args_ = 0;
// The 0-based index of the result tuple, in the temp buffers.
- size_t result_index = 0;
+ size_t result_index_ = 0;
// [Optional] Arrays of arg and result names. These are arrays of C-style
// strings, where the array is terminated by nullptr.
- const char** arg_names = nullptr;
- const char** result_names = nullptr;
+ const char** arg_names_ = nullptr;
+ const char** result_names_ = nullptr;
// [Optional] Arg and result shapes.
- const xla::ProgramShape* program_shape = nullptr;
+ const xla::ProgramShape* program_shape_ = nullptr;
// [Optional] Profile printer data. Null if profiling is disabled.
- const xla::HloProfilePrinterData* hlo_profile_printer_data = nullptr;
+ const xla::HloProfilePrinterData* hlo_profile_printer_data_ = nullptr;
// [Optional] The number of profile counters expected in the profile counter
// buffer by the generated code and hlo_profile_printer. 0 if profiling is
// disabled. This information is already present in
// hlo_profile_printer_data but xla::HloProfilePrinterData is forward
// declared so we don't have access to that information here.
- int64 profile_counters_size = 0;
+ int64 profile_counters_size_ = 0;
+
+ // Only XlaCompiledCpuFunction is allowed to read the above fields.
+ friend class XlaCompiledCpuFunction;
};
// AllocMode controls the buffer allocation mode.
@@ -135,14 +175,25 @@ class XlaCompiledCpuFunction {
// ------------------------------
// Arg methods for managing input buffers. Buffers are in row-major order.
- // Returns the underlying array of argument buffers, where args()[I] is the
- // buffer for the positional argument at index I.
- void** args() { return args_; }
- const void* const* args() const { return args_; }
-
// Returns the buffer for the positional argument at the given `index`.
- void* arg_data(size_t index) { return args_[index]; }
- const void* arg_data(size_t index) const { return args_[index]; }
+ void* arg_data(size_t index) {
+ return buffer_table_[arg_index_table_[index]];
+ }
+ const void* arg_data(size_t index) const {
+ return buffer_table_[arg_index_table_[index]];
+ }
+
+ int num_args() const { return num_args_; }
+
+ // Returns the size of entry parameter `idx`.
+ //
+ // There is a static version of this method on tfcompile generated subclasses
+ // of XlaCompiledCpuFunction, but try to prefer this when possible since it
+ // works both for XlaJitCompiledCpuFunction and AOT compiled subclasses.
+ int arg_size(int idx) const {
+ assert(idx < num_args());
+ return buffer_infos_[arg_index_table_[idx]].size();
+ }
// Sets the buffer for the positional argument at the given `index` to `data`.
// Must be called before Run to have an effect. May be called under any
@@ -155,7 +206,9 @@ class XlaCompiledCpuFunction {
//
// Aliasing of argument and result buffers is not allowed, and results in
// undefined behavior.
- void set_arg_data(size_t index, void* data) { args_[index] = data; }
+ void set_arg_data(size_t index, void* data) {
+ buffer_table_[arg_index_table_[index]] = data;
+ }
// ------------------------------
// Result methods for managing output buffers. Buffers are in row-major order.
@@ -165,9 +218,9 @@ class XlaCompiledCpuFunction {
// Returns the underlying array of result buffers, where results()[I] is the
// buffer for the positional result at index I.
- void** results() { return static_cast<void**>(temps_[result_index_]); }
+ void** results() { return static_cast<void**>(buffer_table_[result_index_]); }
const void* const* results() const {
- return static_cast<const void* const*>(temps_[result_index_]);
+ return static_cast<const void* const*>(buffer_table_[result_index_]);
}
// Profile counters for this XLA computation.
@@ -225,25 +278,28 @@ class XlaCompiledCpuFunction {
const RawFunction raw_function_;
const size_t result_index_;
- // Arrays of argument and temp buffers; entries in args_ may be overwritten by
- // the user.
- void** args_ = nullptr;
- void** temps_ = nullptr;
+ // Array containing pointers to argument and temp buffers (slots corresponding
+ // to constant and on-stack buffers are null).
+ void** const buffer_table_;
+
+ // Describes the buffers used by the XLA computation.
+ const cpu_function_runtime::BufferInfo* const buffer_infos_;
- // Argument i needs to be placed in temps_[arg_index_to_temp_index_[i]] for
- // XLA generated code to be able to find it.
+ // Argument i needs to be placed in buffer_table_[arg_index_to_temp_index_[i]]
+ // for XLA generated code to be able to find it.
//
// For now we need to keep around the args_ array because there is code that
// depends on args() returning a void**. However, in the future we may remove
- // args_ in favor of using temps_ as the sole storage for the arguments.
- int32* arg_index_to_temp_index_;
+ // args_ in favor of using buffer_table_ as the sole storage for the
+ // arguments.
+ const int32* const arg_index_table_;
// The number of incoming arguments.
- int32 num_args_;
+ const int32 num_args_;
- // Backing memory for individual arg and temp buffers.
- void* alloc_args_ = nullptr;
- void* alloc_temps_ = nullptr;
+ // Backing memory for buffer_table_ and args_, the latter depending on
+ // AllocMode.
+ void* alloc_buffer_table_ = nullptr;
// Backing memory for profiling counters.
int64* profile_counters_ = nullptr;
diff --git a/tensorflow/compiler/tf2xla/xla_compiler_test.cc b/tensorflow/compiler/tf2xla/xla_compiler_test.cc
index be00ed8813..7227df9649 100644
--- a/tensorflow/compiler/tf2xla/xla_compiler_test.cc
+++ b/tensorflow/compiler/tf2xla/xla_compiler_test.cc
@@ -821,7 +821,10 @@ TEST_F(XlaCompilerTest, Variables) {
Scope scope = Scope::NewRootScope().ExitOnError();
auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0);
auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1);
- auto write = ops::AssignAddVariableOp(scope, var, a);
+ // Adds an identity op around the resource to make sure identity ops propagate
+ // resources correctly.
+ auto identity = ops::Identity(scope.WithOpName("VIdentity"), var);
+ auto write = ops::AssignAddVariableOp(scope, identity, a);
auto read = ops::ReadVariableOp(
scope.WithControlDependencies(std::vector<Operation>{write}), var,
DT_INT32);
diff --git a/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc b/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc
index 114a9241bd..86a78ee429 100644
--- a/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc
+++ b/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc
@@ -24,6 +24,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
+#include "tensorflow/compiler/xla/service/cpu/buffer_info_util.h"
#include "tensorflow/compiler/xla/service/cpu/cpu_executable.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
@@ -35,45 +36,6 @@ limitations under the License.
namespace tensorflow {
namespace {
-
-// Returns a vector of positional argument buffer sizes.
-xla::StatusOr<std::vector<intptr_t>> ComputeArgSizes(
- const xla::ProgramShape& program_shape) {
- std::vector<intptr_t> arg_sizes;
- const size_t num_args = program_shape.parameters_size();
- arg_sizes.reserve(num_args);
- for (int i = 0; i < num_args; ++i) {
- const xla::Shape& arg_shape = program_shape.parameters(i);
- constexpr size_t kPointerSize = sizeof(void*);
- arg_sizes.push_back(xla::ShapeUtil::ByteSizeOf(arg_shape, kPointerSize));
- }
- return std::move(arg_sizes);
-}
-
-// Returns a vector of positional temporary buffer sizes.
-xla::StatusOr<std::vector<intptr_t>> ComputeTempSizes(
- const xla::BufferAssignment& buffer_assignment) {
- const std::vector<xla::BufferAllocation>& allocations =
- buffer_assignment.Allocations();
- std::vector<intptr_t> temp_sizes;
- temp_sizes.reserve(allocations.size());
- for (const xla::BufferAllocation& allocation : allocations) {
- if (allocation.is_constant() || allocation.is_thread_local()) {
- // Constants are lowered to globals. Thread locals are lowered to
- // allocas.
- temp_sizes.push_back(-1);
- } else if (allocation.is_entry_computation_parameter()) {
- // Entry computation parameters need some preprocessing in
- // XlaCompiledCpuFunction::Run. See the comment on
- // XlaCompiledCpuFunction::StaticData::temp_sizes.
- temp_sizes.push_back(-allocation.parameter_number() - 2);
- } else {
- temp_sizes.push_back(allocation.size());
- }
- }
- return std::move(temp_sizes);
-}
-
// Returns the index of the result in the temp buffers.
xla::StatusOr<size_t> ComputeResultIndex(
const xla::BufferAssignment& buffer_assignment) {
@@ -157,11 +119,11 @@ XlaJitCompiledCpuFunction::Compile(
const xla::BufferAssignment& buffer_assignment =
cpu_executable->buffer_assignment();
- // Compute buffer sizes and the result index, needed to run the raw function.
- TF_ASSIGN_OR_RETURN(std::vector<intptr_t> arg_sizes,
- ComputeArgSizes(*program_shape));
- TF_ASSIGN_OR_RETURN(std::vector<intptr_t> temp_sizes,
- ComputeTempSizes(buffer_assignment));
+ // Compute buffer infos and the result index, needed to run the raw function.
+ std::vector<cpu_function_runtime::BufferInfo> buffer_infos =
+ xla::cpu::CreateBufferInfosFromBufferAssignment(buffer_assignment);
+ std::vector<int32> arg_index_table =
+ xla::cpu::CreateArgIndexTableFromBufferInfos(buffer_infos);
TF_ASSIGN_OR_RETURN(size_t result_index,
ComputeResultIndex(buffer_assignment));
@@ -169,28 +131,28 @@ XlaJitCompiledCpuFunction::Compile(
new XlaJitCompiledCpuFunction);
XlaJitCompiledCpuFunction* jit = jit_unique_ptr.get();
jit->executable_ = std::move(executable);
- jit->arg_sizes_ = std::move(arg_sizes);
- jit->temp_sizes_ = std::move(temp_sizes);
+ jit->buffer_infos_ = std::move(buffer_infos);
+ jit->arg_index_table_ = std::move(arg_index_table);
jit->program_shape_ = std::move(program_shape);
- jit->static_data_.raw_function = std::move(raw_function);
- jit->static_data_.arg_sizes = jit->arg_sizes_.data();
- jit->static_data_.num_args = jit->arg_sizes_.size();
- jit->static_data_.temp_sizes = jit->temp_sizes_.data();
- jit->static_data_.num_temps = jit->temp_sizes_.size();
- jit->static_data_.result_index = result_index;
+ jit->static_data_.set_raw_function(raw_function);
+ jit->static_data_.set_buffer_infos(jit->buffer_infos_.data());
+ jit->static_data_.set_num_buffers(jit->buffer_infos_.size());
+ jit->static_data_.set_arg_index_table(jit->arg_index_table_.data());
+ jit->static_data_.set_num_args(jit->arg_index_table_.size());
+ jit->static_data_.set_result_index(result_index);
// Optional metadata is collected and set below.
CollectNames(config.feed(), &jit->nonempty_arg_names_, &jit->arg_names_);
CollectNames(config.fetch(), &jit->nonempty_result_names_,
&jit->result_names_);
- jit->static_data_.arg_names = jit->arg_names_.data();
- jit->static_data_.result_names = jit->result_names_.data();
- jit->static_data_.program_shape = jit->program_shape_.get();
+ jit->static_data_.set_arg_names(jit->arg_names_.data());
+ jit->static_data_.set_result_names(jit->result_names_.data());
+ jit->static_data_.set_program_shape(jit->program_shape_.get());
if (cpu_executable->hlo_profiling_enabled()) {
- jit->static_data_.hlo_profile_printer_data =
- &cpu_executable->hlo_profile_printer_data();
- jit->static_data_.profile_counters_size =
- cpu_executable->hlo_profile_printer_data().profile_counters_size();
+ jit->static_data_.set_hlo_profile_printer_data(
+ &cpu_executable->hlo_profile_printer_data());
+ jit->static_data_.set_profile_counters_size(
+ cpu_executable->hlo_profile_printer_data().profile_counters_size());
}
return std::move(jit_unique_ptr);
diff --git a/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h b/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h
index af307ae4ef..d3c8f22a80 100644
--- a/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h
+++ b/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h
@@ -66,9 +66,11 @@ class XlaJitCompiledCpuFunction {
// The static data is backed by the rest of the state in this class.
XlaCompiledCpuFunction::StaticData static_data_;
- // The backing arrays of arg and temp buffer sizes.
- std::vector<intptr_t> arg_sizes_;
- std::vector<intptr_t> temp_sizes_;
+ // The backing array for buffer infos.
+ std::vector<cpu_function_runtime::BufferInfo> buffer_infos_;
+
+ // The backing array for the arg index table.
+ std::vector<int32> arg_index_table_;
// The backing arrays of arg and result names. We hold the actual strings in
// nonempty_*_names_, and hold arrays of pointers in *_names_ for the static
diff --git a/tensorflow/compiler/xla/BUILD b/tensorflow/compiler/xla/BUILD
index fdf13bb18c..e36429f62d 100644
--- a/tensorflow/compiler/xla/BUILD
+++ b/tensorflow/compiler/xla/BUILD
@@ -173,6 +173,7 @@ cc_library(
":xla_data_proto",
"//tensorflow/core:lib",
"//tensorflow/core:ptr_util",
+ "@com_google_absl//absl/algorithm:container",
],
)
diff --git a/tensorflow/compiler/xla/client/BUILD b/tensorflow/compiler/xla/client/BUILD
index ad3fcee05b..0ecf26e772 100644
--- a/tensorflow/compiler/xla/client/BUILD
+++ b/tensorflow/compiler/xla/client/BUILD
@@ -211,6 +211,7 @@ cc_library(
"//tensorflow/compiler/xla/service:hlo_proto",
"//tensorflow/compiler/xla/service:shape_inference",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
diff --git a/tensorflow/compiler/xla/client/lib/math.cc b/tensorflow/compiler/xla/client/lib/math.cc
index 0221de7672..e569610b85 100644
--- a/tensorflow/compiler/xla/client/lib/math.cc
+++ b/tensorflow/compiler/xla/client/lib/math.cc
@@ -207,7 +207,11 @@ XlaOp Lgamma(XlaOp input) {
XlaOp log_y = log_sqrt_two_pi + (z + one_half) * log_t - t + Log(x);
- XlaOp reflection = log_pi - Log(Sin(pi * input)) - log_y;
+ // If z = a + 0j, the analytic continuation of log reduces to taking the
+ // absolute value of the real part.
+ // Re(log(z)) = Re(log|z| + arg(z)j)
+ // = log|a|
+ XlaOp reflection = log_pi - Log(Abs(Sin(pi * input))) - log_y;
XlaOp result = Select(need_to_reflect, reflection, log_y);
return result;
}
diff --git a/tensorflow/compiler/xla/client/local_client.cc b/tensorflow/compiler/xla/client/local_client.cc
index 4d96316d3b..cffb24e29b 100644
--- a/tensorflow/compiler/xla/client/local_client.cc
+++ b/tensorflow/compiler/xla/client/local_client.cc
@@ -303,7 +303,7 @@ StatusOr<std::unique_ptr<Literal>> LocalClient::TransferFromOutfeedLocal(
const Shape& shape, int device_ordinal) {
TF_ASSIGN_OR_RETURN(se::StreamExecutor * executor,
backend().stream_executor(device_ordinal));
- auto literal = MakeUnique<Literal>(shape);
+ auto literal = Literal::CreateFromShape(shape);
TF_RETURN_IF_ERROR(backend().transfer_manager()->TransferLiteralFromOutfeed(
executor, shape, literal.get()));
return std::move(literal);
diff --git a/tensorflow/compiler/xla/client/xla_builder.cc b/tensorflow/compiler/xla/client/xla_builder.cc
index b3b00e2fff..e65dd5cbb4 100644
--- a/tensorflow/compiler/xla/client/xla_builder.cc
+++ b/tensorflow/compiler/xla/client/xla_builder.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include <string>
#include <utility>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/client/sharding_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/execution_options_util.h"
@@ -469,8 +470,8 @@ XlaOp XlaBuilder::Call(const XlaComputation& computation,
HloInstructionProto instr;
std::vector<const Shape*> operand_shape_ptrs;
TF_ASSIGN_OR_RETURN(const auto& operand_shapes, GetOperandShapes(operands));
- c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
- [](const Shape& shape) { return &shape; });
+ absl::c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
+ [](const Shape& shape) { return &shape; });
TF_ASSIGN_OR_RETURN(const ProgramShape& called_program_shape,
computation.GetProgramShape());
TF_ASSIGN_OR_RETURN(
@@ -622,8 +623,8 @@ XlaOp XlaBuilder::ConcatInDim(tensorflow::gtl::ArraySlice<XlaOp> operands,
std::vector<const Shape*> operand_shape_ptrs;
TF_ASSIGN_OR_RETURN(const auto& operand_shapes, GetOperandShapes(operands));
- c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
- [](const Shape& shape) { return &shape; });
+ absl::c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
+ [](const Shape& shape) { return &shape; });
TF_ASSIGN_OR_RETURN(
*instr.mutable_shape(),
ShapeInference::InferConcatOpShape(operand_shape_ptrs, dimension));
@@ -749,8 +750,8 @@ XlaOp XlaBuilder::Tuple(tensorflow::gtl::ArraySlice<XlaOp> elements) {
HloInstructionProto instr;
std::vector<const Shape*> operand_shape_ptrs;
TF_ASSIGN_OR_RETURN(const auto& operand_shapes, GetOperandShapes(elements));
- c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
- [](const Shape& shape) { return &shape; });
+ absl::c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
+ [](const Shape& shape) { return &shape; });
TF_ASSIGN_OR_RETURN(*instr.mutable_shape(),
ShapeInference::InferVariadicOpShape(
HloOpcode::kTuple, operand_shape_ptrs));
@@ -882,24 +883,28 @@ Status XlaBuilder::VerifyConvolution(
XlaOp XlaBuilder::Conv(const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- Padding padding) {
+ Padding padding, int64 feature_group_count) {
return ConvWithGeneralDimensions(
lhs, rhs, window_strides, padding,
- CreateDefaultConvDimensionNumbers(window_strides.size()));
+ CreateDefaultConvDimensionNumbers(window_strides.size()),
+ feature_group_count);
}
XlaOp XlaBuilder::ConvWithGeneralPadding(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding) {
+ tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
+ int64 feature_group_count) {
return ConvGeneral(lhs, rhs, window_strides, padding,
- CreateDefaultConvDimensionNumbers(window_strides.size()));
+ CreateDefaultConvDimensionNumbers(window_strides.size()),
+ feature_group_count);
}
XlaOp XlaBuilder::ConvWithGeneralDimensions(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
- const ConvolutionDimensionNumbers& dimension_numbers) {
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
return ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(const Shape& lhs_shape, GetShape(lhs));
TF_ASSIGN_OR_RETURN(const Shape& rhs_shape, GetShape(rhs));
@@ -926,7 +931,7 @@ XlaOp XlaBuilder::ConvWithGeneralDimensions(
return ConvGeneral(lhs, rhs, window_strides,
MakePadding(base_area_dimensions, window_dimensions,
window_strides, padding),
- dimension_numbers);
+ dimension_numbers, feature_group_count);
});
}
@@ -934,9 +939,10 @@ XlaOp XlaBuilder::ConvGeneral(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
- const ConvolutionDimensionNumbers& dimension_numbers) {
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
return ConvGeneralDilated(lhs, rhs, window_strides, padding, {}, {},
- dimension_numbers);
+ dimension_numbers, feature_group_count);
}
XlaOp XlaBuilder::ConvGeneralDilated(
@@ -945,7 +951,8 @@ XlaOp XlaBuilder::ConvGeneralDilated(
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation,
- const ConvolutionDimensionNumbers& dimension_numbers) {
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
return ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
HloInstructionProto instr;
TF_ASSIGN_OR_RETURN(const Shape& lhs_shape, GetShape(lhs));
@@ -964,12 +971,13 @@ XlaOp XlaBuilder::ConvGeneralDilated(
MakeWindow(window_dimensions, window_strides, padding,
lhs_dilation, rhs_dilation));
- TF_ASSIGN_OR_RETURN(
- *instr.mutable_shape(),
- ShapeInference::InferConvolveShape(lhs_shape, rhs_shape, instr.window(),
- dimension_numbers));
+ TF_ASSIGN_OR_RETURN(*instr.mutable_shape(),
+ ShapeInference::InferConvolveShape(
+ lhs_shape, rhs_shape, instr.window(),
+ dimension_numbers, feature_group_count));
*instr.mutable_convolution_dimension_numbers() = dimension_numbers;
+ instr.set_feature_group_count(feature_group_count);
return AddInstruction(std::move(instr), HloOpcode::kConvolution,
{lhs, rhs});
@@ -1073,6 +1081,23 @@ XlaOp XlaBuilder::Infeed(const Shape& shape, const string& config) {
"Replicated sharding is not yet supported for infeeds");
}
+ // Infeed takes a single token operand. Generate the token to pass to the
+ // infeed.
+ XlaOp token;
+ auto make_token = [&]() {
+ HloInstructionProto token_instr;
+ *token_instr.mutable_shape() = ShapeUtil::MakeTokenShape();
+ return AddInstruction(std::move(token_instr), HloOpcode::kAfterAll, {});
+ };
+ if (sharding()) {
+ // Arbitrarily assign token to device 0.
+ OpSharding sharding = sharding_builder::AssignDevice(0);
+ XlaScopedShardingAssignment scoped_sharding(this, sharding);
+ TF_ASSIGN_OR_RETURN(token, make_token());
+ } else {
+ TF_ASSIGN_OR_RETURN(token, make_token());
+ }
+
// The sharding is set by the client according to the data tuple shape.
// However, the shape of the infeed instruction is a tuple containing the
// data and a token. For tuple sharding type, the sharding must be changed
@@ -1088,11 +1113,11 @@ XlaOp XlaBuilder::Infeed(const Shape& shape, const string& config) {
sharding_builder::AssignDevice(0);
XlaScopedShardingAssignment scoped_sharding(this,
infeed_instruction_sharding);
- TF_ASSIGN_OR_RETURN(
- infeed, AddInstruction(std::move(instr), HloOpcode::kInfeed, {}));
+ TF_ASSIGN_OR_RETURN(infeed, AddInstruction(std::move(instr),
+ HloOpcode::kInfeed, {token}));
} else {
- TF_ASSIGN_OR_RETURN(
- infeed, AddInstruction(std::move(instr), HloOpcode::kInfeed, {}));
+ TF_ASSIGN_OR_RETURN(infeed, AddInstruction(std::move(instr),
+ HloOpcode::kInfeed, {token}));
}
// The infeed instruction produces a tuple of the infed data and a token
@@ -1158,8 +1183,15 @@ void XlaBuilder::Outfeed(const XlaOp& operand, const Shape& shape_with_layout,
instr.set_outfeed_config(outfeed_config);
+ // Outfeed takes a token as its second operand. Generate the token to pass
+ // to the outfeed.
+ HloInstructionProto token_instr;
+ *token_instr.mutable_shape() = ShapeUtil::MakeTokenShape();
+ TF_ASSIGN_OR_RETURN(XlaOp token, AddInstruction(std::move(token_instr),
+ HloOpcode::kAfterAll, {}));
+
TF_RETURN_IF_ERROR(
- AddInstruction(std::move(instr), HloOpcode::kOutfeed, {operand})
+ AddInstruction(std::move(instr), HloOpcode::kOutfeed, {operand, token})
.status());
// The outfeed instruction produces a token. However, existing users expect
@@ -1509,8 +1541,8 @@ XlaOp XlaBuilder::Map(tensorflow::gtl::ArraySlice<XlaOp> operands,
HloInstructionProto instr;
std::vector<const Shape*> operand_shape_ptrs;
TF_ASSIGN_OR_RETURN(const auto& operand_shapes, GetOperandShapes(operands));
- c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
- [](const Shape& shape) { return &shape; });
+ absl::c_transform(operand_shapes, std::back_inserter(operand_shape_ptrs),
+ [](const Shape& shape) { return &shape; });
TF_ASSIGN_OR_RETURN(const ProgramShape& called_program_shape,
computation.GetProgramShape());
TF_ASSIGN_OR_RETURN(
@@ -1600,27 +1632,27 @@ XlaOp XlaBuilder::While(const XlaComputation& condition,
});
}
-XlaOp XlaBuilder::Gather(const XlaOp& input, const XlaOp& gather_indices,
+XlaOp XlaBuilder::Gather(const XlaOp& input, const XlaOp& start_indices,
const GatherDimensionNumbers& dimension_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds) {
+ tensorflow::gtl::ArraySlice<int64> slice_sizes) {
return ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
HloInstructionProto instr;
TF_ASSIGN_OR_RETURN(const Shape& input_shape, GetShape(input));
- TF_ASSIGN_OR_RETURN(const Shape& gather_indices_shape,
- GetShape(gather_indices));
+ TF_ASSIGN_OR_RETURN(const Shape& start_indices_shape,
+ GetShape(start_indices));
TF_ASSIGN_OR_RETURN(
*instr.mutable_shape(),
- ShapeInference::InferGatherShape(input_shape, gather_indices_shape,
- dimension_numbers, window_bounds));
+ ShapeInference::InferGatherShape(input_shape, start_indices_shape,
+ dimension_numbers, slice_sizes));
*instr.mutable_gather_dimension_numbers() = dimension_numbers;
- for (int64 bound : window_bounds) {
- instr.add_gather_window_bounds(bound);
+ for (int64 bound : slice_sizes) {
+ instr.add_gather_slice_sizes(bound);
}
return AddInstruction(std::move(instr), HloOpcode::kGather,
- {input, gather_indices});
+ {input, start_indices});
});
}
@@ -1914,8 +1946,8 @@ XlaOp XlaBuilder::AllToAll(const XlaOp& operand, int64 split_dimension,
HloInstructionProto instr;
TF_ASSIGN_OR_RETURN(auto slice_shapes, this->GetOperandShapes(slices));
std::vector<const Shape*> slice_shape_ptrs;
- c_transform(slice_shapes, std::back_inserter(slice_shape_ptrs),
- [](const Shape& shape) { return &shape; });
+ absl::c_transform(slice_shapes, std::back_inserter(slice_shape_ptrs),
+ [](const Shape& shape) { return &shape; });
TF_ASSIGN_OR_RETURN(
*instr.mutable_shape(),
ShapeInference::InferAllToAllTupleShape(slice_shape_ptrs));
@@ -2538,32 +2570,38 @@ XlaOp DotGeneral(const XlaOp& lhs, const XlaOp& rhs,
}
XlaOp Conv(const XlaOp& lhs, const XlaOp& rhs,
- tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding) {
- return lhs.builder()->Conv(lhs, rhs, window_strides, padding);
+ tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
+ int64 feature_group_count) {
+ return lhs.builder()->Conv(lhs, rhs, window_strides, padding,
+ feature_group_count);
}
XlaOp ConvWithGeneralPadding(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding) {
+ tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
+ int64 feature_group_count) {
return lhs.builder()->ConvWithGeneralPadding(lhs, rhs, window_strides,
- padding);
+ padding, feature_group_count);
}
XlaOp ConvWithGeneralDimensions(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
- const ConvolutionDimensionNumbers& dimension_numbers) {
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
return lhs.builder()->ConvWithGeneralDimensions(lhs, rhs, window_strides,
- padding, dimension_numbers);
+ padding, dimension_numbers,
+ feature_group_count);
}
XlaOp ConvGeneral(const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
- const ConvolutionDimensionNumbers& dimension_numbers) {
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
return lhs.builder()->ConvGeneral(lhs, rhs, window_strides, padding,
- dimension_numbers);
+ dimension_numbers, feature_group_count);
}
XlaOp ConvGeneralDilated(
@@ -2572,10 +2610,11 @@ XlaOp ConvGeneralDilated(
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation,
- const ConvolutionDimensionNumbers& dimension_numbers) {
- return lhs.builder()->ConvGeneralDilated(lhs, rhs, window_strides, padding,
- lhs_dilation, rhs_dilation,
- dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
+ return lhs.builder()->ConvGeneralDilated(
+ lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,
+ dimension_numbers, feature_group_count);
}
XlaOp Fft(const XlaOp& operand, FftType fft_type,
@@ -2868,11 +2907,11 @@ XlaOp ReducePrecision(const XlaOp& operand, const int exponent_bits,
mantissa_bits);
}
-XlaOp Gather(const XlaOp& input, const XlaOp& gather_indices,
+XlaOp Gather(const XlaOp& input, const XlaOp& start_indices,
const GatherDimensionNumbers& dimension_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds) {
- return input.builder()->Gather(input, gather_indices, dimension_numbers,
- window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes) {
+ return input.builder()->Gather(input, start_indices, dimension_numbers,
+ slice_sizes);
}
XlaOp Scatter(const XlaOp& input, const XlaOp& scatter_indices,
diff --git a/tensorflow/compiler/xla/client/xla_builder.h b/tensorflow/compiler/xla/client/xla_builder.h
index 9403d7ca8d..469d5048b2 100644
--- a/tensorflow/compiler/xla/client/xla_builder.h
+++ b/tensorflow/compiler/xla/client/xla_builder.h
@@ -512,22 +512,24 @@ class XlaBuilder {
// Enqueues a convolution instruction onto the computation, which uses the
// default convolution dimension numbers.
XlaOp Conv(const XlaOp& lhs, const XlaOp& rhs,
- tensorflow::gtl::ArraySlice<int64> window_strides,
- Padding padding);
+ tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided padding configuration in the format returned by MakePadding().
XlaOp ConvWithGeneralPadding(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding);
+ tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided dimension numbers configuration.
XlaOp ConvWithGeneralDimensions(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided padding configuration as well as the dimension numbers.
@@ -535,7 +537,8 @@ class XlaBuilder {
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided padding configuration, dilation factors and dimension numbers.
@@ -545,7 +548,8 @@ class XlaBuilder {
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Enqueues an FFT instruction onto the computation, of the given type and
// with the given FFT length.
@@ -873,9 +877,9 @@ class XlaBuilder {
const int mantissa_bits);
// Enqueues a Gather node onto the computation.
- XlaOp Gather(const XlaOp& input, const XlaOp& gather_indices,
+ XlaOp Gather(const XlaOp& input, const XlaOp& start_indices,
const GatherDimensionNumbers& dimension_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes);
// Enqueues a Scatter node onto the computation.
XlaOp Scatter(const XlaOp& input, const XlaOp& scatter_indices,
@@ -1161,27 +1165,31 @@ class XlaBuilder {
const DotDimensionNumbers& dimension_numbers);
friend XlaOp Conv(const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- Padding padding);
+ Padding padding, int64 feature_group_count);
friend XlaOp ConvWithGeneralPadding(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding);
+ tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
+ int64 feature_group_count);
friend XlaOp ConvWithGeneralDimensions(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count);
friend XlaOp ConvGeneral(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count);
friend XlaOp ConvGeneralDilated(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count);
friend XlaOp Fft(const XlaOp& operand, FftType fft_type,
tensorflow::gtl::ArraySlice<int64> fft_length);
friend XlaOp Infeed(XlaBuilder* builder, const Shape& shape,
@@ -1320,9 +1328,9 @@ class XlaBuilder {
const XlaComputation& false_computation);
friend XlaOp ReducePrecision(const XlaOp& operand, const int exponent_bits,
const int mantissa_bits);
- friend XlaOp Gather(const XlaOp& input, const XlaOp& gather_indices,
+ friend XlaOp Gather(const XlaOp& input, const XlaOp& start_indices,
const GatherDimensionNumbers& dimension_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes);
friend XlaOp Scatter(const XlaOp& input, const XlaOp& scatter_indices,
const XlaOp& updates,
const XlaComputation& update_computation,
@@ -1646,28 +1654,32 @@ XlaOp DotGeneral(const XlaOp& lhs, const XlaOp& rhs,
// Enqueues a convolution instruction onto the computation, which uses the
// default convolution dimension numbers.
XlaOp Conv(const XlaOp& lhs, const XlaOp& rhs,
- tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding);
+ tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided padding configuration in the format returned by MakePadding().
XlaOp ConvWithGeneralPadding(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
- tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding);
+ tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided dimension numbers configuration.
XlaOp ConvWithGeneralDimensions(
const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided padding configuration as well as the dimension numbers.
XlaOp ConvGeneral(const XlaOp& lhs, const XlaOp& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Enqueues a convolution instruction onto the computation, with the caller
// provided padding configuration, dilation factors and dimension numbers.
@@ -1677,7 +1689,8 @@ XlaOp ConvGeneralDilated(
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Enqueues an FFT instruction onto the computation, of the given type and
// with the given FFT length.
@@ -2011,9 +2024,9 @@ XlaOp ReducePrecision(const XlaOp& operand, const int exponent_bits,
const int mantissa_bits);
// Enqueues a Gather node onto the computation.
-XlaOp Gather(const XlaOp& input, const XlaOp& gather_indices,
+XlaOp Gather(const XlaOp& input, const XlaOp& start_indices,
const GatherDimensionNumbers& dimension_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes);
// Enqueues a Scatter node onto the computation.
XlaOp Scatter(const XlaOp& input, const XlaOp& scatter_indices,
diff --git a/tensorflow/compiler/xla/legacy_flags/debug_options_flags.cc b/tensorflow/compiler/xla/legacy_flags/debug_options_flags.cc
index f42fb92359..5d27e4a46b 100644
--- a/tensorflow/compiler/xla/legacy_flags/debug_options_flags.cc
+++ b/tensorflow/compiler/xla/legacy_flags/debug_options_flags.cc
@@ -31,7 +31,6 @@ std::vector<tensorflow::Flag>* flag_objects;
std::once_flag flags_init;
void SetDebugOptionsDefaults(DebugOptions* flags) {
- flags->set_xla_enable_fast_math(true);
flags->set_xla_llvm_enable_alias_scope_metadata(true);
flags->set_xla_llvm_enable_noalias_metadata(true);
flags->set_xla_llvm_enable_invariant_load_metadata(true);
@@ -53,6 +52,11 @@ void SetDebugOptionsDefaults(DebugOptions* flags) {
// the heuristics needed to decide when to run on multiple streams. See
// b/77879207.
flags->set_xla_gpu_disable_multi_streaming(true);
+
+ // TODO(jlebar): Disable fastmath once doing so is not a performance
+ // regression.
+ flags->set_xla_cpu_enable_fast_math(true);
+ flags->set_xla_gpu_enable_fast_math(true);
}
// Allocates flag_values and flag_objects; this function must not be called more
@@ -150,10 +154,16 @@ void AllocateFlags() {
flag_values->mutable_xla_generate_hlo_text_to(),
"Dump all HLO modules as text into the provided directory path."),
tensorflow::Flag(
- "xla_enable_fast_math",
- bool_setter_for(&DebugOptions::set_xla_enable_fast_math),
- flag_values->xla_enable_fast_math(),
- "Enable unsafe fast-math optimizations in the compiler; "
+ "xla_cpu_enable_fast_math",
+ bool_setter_for(&DebugOptions::set_xla_cpu_enable_fast_math),
+ flag_values->xla_cpu_enable_fast_math(),
+ "Enable unsafe fast-math optimizations in the CPU compiler; "
+ "this may produce faster code at the expense of some accuracy."),
+ tensorflow::Flag(
+ "xla_gpu_enable_fast_math",
+ bool_setter_for(&DebugOptions::set_xla_cpu_enable_fast_math),
+ flag_values->xla_cpu_enable_fast_math(),
+ "Enable unsafe fast-math optimizations in the GPU compiler; "
"this may produce faster code at the expense of some accuracy."),
tensorflow::Flag(
"xla_llvm_enable_alias_scope_metadata",
@@ -306,6 +316,13 @@ void AllocateFlags() {
bool_setter_for(&DebugOptions::set_xla_cpu_use_mkl_dnn),
flag_values->xla_cpu_use_mkl_dnn(),
"Generate calls to MKL-DNN in the CPU backend."),
+ tensorflow::Flag(
+ "xla_gpu_crash_on_verification_failures",
+ bool_setter_for(
+ &DebugOptions::set_xla_gpu_crash_on_verification_failures),
+ flag_values->xla_gpu_crash_on_verification_failures(),
+ "Crashes the program on extra verification failures, e.g. cuDNN "
+ "cross checking failures"),
});
ParseFlagsFromEnv(*flag_objects);
}
diff --git a/tensorflow/compiler/xla/literal_comparison.cc b/tensorflow/compiler/xla/literal_comparison.cc
index 94993cc874..6883a6bbab 100644
--- a/tensorflow/compiler/xla/literal_comparison.cc
+++ b/tensorflow/compiler/xla/literal_comparison.cc
@@ -38,7 +38,8 @@ namespace {
// between the left-hand-side and right-hand-side, by bit-casting to UnsignedT
// -- on miscompare, a nice error message is given in the AssertionFailure.
template <typename FloatT, typename UnsignedT>
-Status CompareFloatsBitwiseEqual(FloatT lhs, FloatT rhs) {
+Status CompareFloatsBitwiseEqual(
+ FloatT lhs, FloatT rhs, tensorflow::gtl::ArraySlice<int64> multi_index) {
auto ulhs = tensorflow::bit_cast<UnsignedT>(lhs);
auto urhs = tensorflow::bit_cast<UnsignedT>(rhs);
auto lhs_double = static_cast<double>(lhs);
@@ -46,9 +47,10 @@ Status CompareFloatsBitwiseEqual(FloatT lhs, FloatT rhs) {
if (ulhs != urhs) {
return InvalidArgument(
"floating values are not bitwise-equal; and equality testing "
- "was requested: %s=%g=%a vs %s=%g=%a",
+ "was requested: %s=%g=%a vs %s=%g=%a at index %s",
StrCat(tensorflow::strings::Hex(ulhs)).c_str(), lhs_double, lhs_double,
- StrCat(tensorflow::strings::Hex(urhs)).c_str(), rhs_double, rhs_double);
+ StrCat(tensorflow::strings::Hex(urhs)).c_str(), rhs_double, rhs_double,
+ LiteralUtil::MultiIndexAsString(multi_index).c_str());
}
return Status::OK();
}
@@ -57,39 +59,48 @@ Status CompareFloatsBitwiseEqual(FloatT lhs, FloatT rhs) {
// bitwise helper above (this is the un-specialized fallback, to just use the
// default gunit implementation).
template <typename NativeT>
-Status CompareEqual(NativeT lhs, NativeT rhs) {
+Status CompareEqual(NativeT lhs, NativeT rhs,
+ tensorflow::gtl::ArraySlice<int64> multi_index) {
if (lhs == rhs) {
return Status::OK();
}
- return InvalidArgument("Expected equality of these values:\n %s\n %s",
- StrCat(lhs).c_str(), StrCat(rhs).c_str());
+ return InvalidArgument(
+ "Expected equality of these values:\n %s\n %s\nat index %s",
+ StrCat(lhs).c_str(), StrCat(rhs).c_str(),
+ LiteralUtil::MultiIndexAsString(multi_index).c_str());
}
// Specializations for floating types that do bitwise comparisons when equality
// comparison is requested.
template <>
-Status CompareEqual<bfloat16>(bfloat16 lhs, bfloat16 rhs) {
- return CompareFloatsBitwiseEqual<bfloat16, uint16>(lhs, rhs);
+Status CompareEqual<bfloat16>(bfloat16 lhs, bfloat16 rhs,
+ tensorflow::gtl::ArraySlice<int64> multi_index) {
+ return CompareFloatsBitwiseEqual<bfloat16, uint16>(lhs, rhs, multi_index);
}
template <>
-Status CompareEqual<Eigen::half>(Eigen::half lhs, Eigen::half rhs) {
- return CompareFloatsBitwiseEqual<Eigen::half, uint16>(lhs, rhs);
+Status CompareEqual<Eigen::half>(
+ Eigen::half lhs, Eigen::half rhs,
+ tensorflow::gtl::ArraySlice<int64> multi_index) {
+ return CompareFloatsBitwiseEqual<Eigen::half, uint16>(lhs, rhs, multi_index);
}
template <>
-Status CompareEqual<float>(float lhs, float rhs) {
- return CompareFloatsBitwiseEqual<float, uint32>(lhs, rhs);
+Status CompareEqual<float>(float lhs, float rhs,
+ tensorflow::gtl::ArraySlice<int64> multi_index) {
+ return CompareFloatsBitwiseEqual<float, uint32>(lhs, rhs, multi_index);
}
template <>
-Status CompareEqual<double>(double lhs, double rhs) {
- return CompareFloatsBitwiseEqual<double, uint64>(lhs, rhs);
+Status CompareEqual<double>(double lhs, double rhs,
+ tensorflow::gtl::ArraySlice<int64> multi_index) {
+ return CompareFloatsBitwiseEqual<double, uint64>(lhs, rhs, multi_index);
}
template <>
-Status CompareEqual<complex64>(complex64 lhs, complex64 rhs) {
- auto res = CompareEqual<float>(lhs.real(), rhs.real());
+Status CompareEqual<complex64>(complex64 lhs, complex64 rhs,
+ tensorflow::gtl::ArraySlice<int64> multi_index) {
+ auto res = CompareEqual<float>(lhs.real(), rhs.real(), multi_index);
if (!res.ok()) {
return res;
}
- return CompareEqual<float>(lhs.imag(), rhs.imag());
+ return CompareEqual<float>(lhs.imag(), rhs.imag(), multi_index);
}
// A recursive function which iterates through every index of expected and
@@ -102,7 +113,7 @@ Status Equal(LiteralSlice expected, LiteralSlice actual,
if (dimension == expected.shape().dimensions_size()) {
NativeT expected_value = expected.Get<NativeT>(multi_index);
NativeT actual_value = actual.Get<NativeT>(multi_index);
- return CompareEqual<NativeT>(expected_value, actual_value);
+ return CompareEqual<NativeT>(expected_value, actual_value, multi_index);
}
Status result;
@@ -720,12 +731,10 @@ Status Equal(const LiteralSlice& expected, const LiteralSlice& actual) {
return Status::OK();
}
- return AppendStatus(result,
- tensorflow::strings::Printf(
- "\nat index: %s\nexpected: %s\nactual: %s",
- LiteralUtil::MultiIndexAsString(multi_index).c_str(),
- ToStringTruncated(expected).c_str(),
- ToStringTruncated(actual).c_str()));
+ return AppendStatus(
+ result, tensorflow::strings::Printf("\nexpected: %s\nactual: %s",
+ ToStringTruncated(expected).c_str(),
+ ToStringTruncated(actual).c_str()));
}
Status Near(const LiteralSlice& expected, const LiteralSlice& actual,
diff --git a/tensorflow/compiler/xla/python/local_computation_builder.cc b/tensorflow/compiler/xla/python/local_computation_builder.cc
index 8246f76d34..212439dec8 100644
--- a/tensorflow/compiler/xla/python/local_computation_builder.cc
+++ b/tensorflow/compiler/xla/python/local_computation_builder.cc
@@ -575,6 +575,16 @@ StatusOr<bool> LocalComputationBuilder::IsConstant(const LocalOp& operand) {
return builder_.IsConstant(operand.op());
}
+LocalOp LocalComputationBuilder::Sort(const LocalOp& operand, int64 dimension) {
+ return xla::Sort(operand.op(), tensorflow::gtl::nullopt, dimension);
+}
+
+LocalOp LocalComputationBuilder::SortKeyVal(const LocalOp& keys,
+ const LocalOp& values,
+ int64 dimension) {
+ return xla::Sort(keys.op(), values.op(), dimension);
+}
+
StatusOr<LocalComputation*> LocalComputationBuilder::BuildConstantSubGraph(
const LocalOp& operand) {
TF_ASSIGN_OR_RETURN(XlaComputation computation,
@@ -640,7 +650,6 @@ _FORWARD_UNOP(Sin)
_FORWARD_UNOP(Tanh)
_FORWARD_UNOP(IsFinite)
_FORWARD_UNOP(Neg)
-_FORWARD_UNOP(Sort)
_FORWARD_UNOP(Sqrt)
_FORWARD_UNOP(Rsqrt)
_FORWARD_UNOP(Square)
diff --git a/tensorflow/compiler/xla/python/local_computation_builder.h b/tensorflow/compiler/xla/python/local_computation_builder.h
index a568c24c63..5f9078ab84 100644
--- a/tensorflow/compiler/xla/python/local_computation_builder.h
+++ b/tensorflow/compiler/xla/python/local_computation_builder.h
@@ -301,6 +301,11 @@ class LocalComputationBuilder {
StatusOr<bool> IsConstant(const LocalOp& operand);
+ LocalOp Sort(const LocalOp& operand, int64 dimension);
+
+ LocalOp SortKeyVal(const LocalOp& keys, const LocalOp& values,
+ int64 dimension);
+
StatusOr<LocalComputation*> BuildConstantSubGraph(const LocalOp& operand);
#define _FORWARD(method_name, return_sig, args_sig) \
@@ -357,7 +362,6 @@ class LocalComputationBuilder {
_FORWARD_UNOP(Tanh)
_FORWARD_UNOP(IsFinite)
_FORWARD_UNOP(Neg)
- _FORWARD_UNOP(Sort)
_FORWARD_UNOP(Sqrt)
_FORWARD_UNOP(Rsqrt)
_FORWARD_UNOP(Square)
diff --git a/tensorflow/compiler/xla/python/local_computation_builder.i b/tensorflow/compiler/xla/python/local_computation_builder.i
index 5d5a955bfe..fa5d75908f 100644
--- a/tensorflow/compiler/xla/python/local_computation_builder.i
+++ b/tensorflow/compiler/xla/python/local_computation_builder.i
@@ -1011,6 +1011,7 @@ tensorflow::ImportNumpy();
%unignore xla::swig::LocalComputationBuilder::Pow;
%unignore xla::swig::LocalComputationBuilder::Neg;
%unignore xla::swig::LocalComputationBuilder::Sort;
+%unignore xla::swig::LocalComputationBuilder::SortKeyVal;
%unignore xla::swig::LocalComputationBuilder::Sqrt;
%unignore xla::swig::LocalComputationBuilder::Rsqrt;
%unignore xla::swig::LocalComputationBuilder::Square;
diff --git a/tensorflow/compiler/xla/python/xla_client.py b/tensorflow/compiler/xla/python/xla_client.py
index a2c6fc344d..fa4366ff07 100644
--- a/tensorflow/compiler/xla/python/xla_client.py
+++ b/tensorflow/compiler/xla/python/xla_client.py
@@ -105,7 +105,6 @@ _UNARY_OPS = [
'Square',
'Reciprocal',
'Neg',
- 'Sort',
'Erf',
'Erfc',
'ErfInv',
@@ -1218,6 +1217,14 @@ class ComputationBuilder(object):
lhs_dilation, rhs_dilation,
dimension_numbers)
+ def Sort(self, operand, dimension=-1):
+ """Enqueues a sort operation onto the computation."""
+ return self._client.Sort(operand, dimension)
+
+ def SortKeyVal(self, keys, values, dimension=-1):
+ """Enqueues a key-value sort operation onto the computation."""
+ return self._client.SortKeyVal(keys, values, dimension)
+
def _forward_methods_to_local_builder():
"""Forward remaining ComputationBuilder methods to the C API.
diff --git a/tensorflow/compiler/xla/service/BUILD b/tensorflow/compiler/xla/service/BUILD
index 1b93d72a3e..12ec38736e 100644
--- a/tensorflow/compiler/xla/service/BUILD
+++ b/tensorflow/compiler/xla/service/BUILD
@@ -175,6 +175,7 @@ cc_library(
"//tensorflow/compiler/xla:window_util",
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -237,6 +238,7 @@ cc_library(
"//tensorflow/compiler/xla:window_util",
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -311,6 +313,7 @@ cc_library(
"//tensorflow/core:human_readable_json",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -570,7 +573,7 @@ cc_library(
"//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla:types",
"//tensorflow/compiler/xla:util",
- "//tensorflow/core:core_cpu_internal",
+ "//tensorflow/core:core_cpu_lib",
"//tensorflow/core:lib",
"//tensorflow/core:stream_executor_no_cuda",
"//third_party/eigen3",
@@ -613,6 +616,7 @@ cc_library(
"//tensorflow/compiler/xla:xla_proto",
"//tensorflow/compiler/xla/legacy_flags:debug_options_flags",
"//tensorflow/core:lib",
+ "//tensorflow/core:ptr_util",
"//tensorflow/core:stream_executor_no_cuda",
],
alwayslink = 1,
@@ -1141,6 +1145,7 @@ cc_library(
":hlo_pass",
"//tensorflow/compiler/xla:util",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -1180,6 +1185,7 @@ cc_library(
"//tensorflow/compiler/xla:literal_util",
"//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla:util",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -1230,6 +1236,22 @@ cc_library(
"//tensorflow/compiler/xla:literal_util",
"//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla:util",
+ "@com_google_absl//absl/algorithm:container",
+ ],
+)
+
+cc_library(
+ name = "scatter_expander",
+ srcs = ["scatter_expander.cc"],
+ hdrs = ["scatter_expander.h"],
+ deps = [
+ ":hlo",
+ ":hlo_creation_utils",
+ ":hlo_pass",
+ ":while_util",
+ "//tensorflow/compiler/xla:literal_util",
+ "//tensorflow/compiler/xla:statusor",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -1274,6 +1296,7 @@ cc_library(
"//tensorflow/compiler/xla:window_util",
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -1308,8 +1331,7 @@ cc_library(
":hlo",
":hlo_creation_utils",
":hlo_pass",
- "//tensorflow/compiler/xla:xla_data_proto",
- "//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -1385,6 +1407,39 @@ tf_cc_test(
)
cc_library(
+ name = "convolution_feature_group_converter",
+ srcs = ["convolution_feature_group_converter.cc"],
+ hdrs = ["convolution_feature_group_converter.h"],
+ deps = [
+ ":hlo",
+ ":hlo_pass",
+ "//tensorflow/compiler/xla:literal",
+ "//tensorflow/compiler/xla:literal_util",
+ "//tensorflow/compiler/xla:shape_util",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/compiler/xla:types",
+ "//tensorflow/compiler/xla:util",
+ "//tensorflow/compiler/xla:xla_data_proto",
+ "//tensorflow/core:lib",
+ ],
+)
+
+tf_cc_test(
+ name = "convolution_feature_group_converter_test",
+ size = "small",
+ srcs = ["convolution_feature_group_converter_test.cc"],
+ deps = [
+ ":convolution_feature_group_converter",
+ ":hlo",
+ ":hlo_matchers",
+ ":hlo_parser",
+ "//tensorflow/compiler/xla:test",
+ "//tensorflow/compiler/xla:types",
+ "//tensorflow/compiler/xla/tests:hlo_test_base",
+ ],
+)
+
+cc_library(
name = "while_loop_analysis",
srcs = ["while_loop_analysis.cc"],
hdrs = ["while_loop_analysis.h"],
@@ -1534,6 +1589,7 @@ cc_library(
"//tensorflow/compiler/xla:status_macros",
"//tensorflow/compiler/xla:util",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -1696,6 +1752,7 @@ cc_library(
"//tensorflow/compiler/xla:util",
"//tensorflow/core:lib",
"//tensorflow/core:stream_executor_no_cuda",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -2517,6 +2574,7 @@ cc_library(
"//tensorflow/compiler/xla/service/llvm_ir:loop_emitter",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
+ "@com_google_absl//absl/algorithm:container",
"@llvm//:core",
"@llvm//:transform_utils",
],
@@ -2879,6 +2937,7 @@ cc_library(
":tuple_util",
"//tensorflow/compiler/xla:literal_util",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -2892,6 +2951,7 @@ tf_cc_test(
"//tensorflow/compiler/xla/service:hlo_matchers",
"//tensorflow/compiler/xla/service:hlo_parser",
"//tensorflow/compiler/xla/tests:xla_internal_test_main",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -2907,6 +2967,7 @@ cc_library(
"//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla:util",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -2934,6 +2995,7 @@ cc_library(
"//tensorflow/compiler/xla:statusor",
"//tensorflow/compiler/xla:util",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -2988,6 +3050,7 @@ cc_library(
"//tensorflow/compiler/xla:util",
"//tensorflow/core:lib",
"//tensorflow/core:ptr_util",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -3021,6 +3084,7 @@ cc_library(
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
+ "@com_google_absl//absl/algorithm:container",
],
)
diff --git a/tensorflow/compiler/xla/service/algebraic_simplifier.cc b/tensorflow/compiler/xla/service/algebraic_simplifier.cc
index 946ef6f0d6..2c539eb99a 100644
--- a/tensorflow/compiler/xla/service/algebraic_simplifier.cc
+++ b/tensorflow/compiler/xla/service/algebraic_simplifier.cc
@@ -22,6 +22,7 @@ limitations under the License.
#include <utility>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/literal_util.h"
@@ -1705,6 +1706,10 @@ Status AlgebraicSimplifierVisitor::HandleReshape(HloInstruction* reshape) {
reshape, HloInstruction::CreateReshape(reshape->shape(),
operand->mutable_operand(0)));
}
+ if (operand->opcode() == HloOpcode::kRng && operand->user_count() == 1) {
+ *operand->mutable_shape() = reshape->shape();
+ return ReplaceInstruction(reshape, operand);
+ }
if (HloOpcode::kBroadcast == reshape->operand(0)->opcode()) {
auto opt_dims = ReshapeLeavesDimensionsUnmodified(
@@ -1748,8 +1753,8 @@ Status AlgebraicSimplifierVisitor::HandleSlice(HloInstruction* slice) {
}
auto is_unstrided_slice = [](const HloInstruction* hlo) {
- return c_all_of(hlo->slice_strides(),
- [](int64 stride) { return stride == 1; });
+ return absl::c_all_of(hlo->slice_strides(),
+ [](int64 stride) { return stride == 1; });
};
if (slice->operand(0)->opcode() == HloOpcode::kSlice &&
is_unstrided_slice(slice) && is_unstrided_slice(slice->operand(0))) {
@@ -1803,6 +1808,12 @@ Status AlgebraicSimplifierVisitor::HandleDynamicUpdateSlice(
}
Status AlgebraicSimplifierVisitor::HandleReduce(HloInstruction* reduce) {
+ // TODO(b/112040122): Most of those optimizations can be done for multi-output
+ // reduces.
+ if (ShapeUtil::IsTuple(reduce->shape())) {
+ return Status::OK();
+ }
+
auto arg = reduce->mutable_operand(0);
auto init_value = reduce->mutable_operand(1);
tensorflow::gtl::ArraySlice<int64> dimensions(reduce->dimensions());
@@ -1920,7 +1931,8 @@ Status AlgebraicSimplifierVisitor::HandleReduce(HloInstruction* reduce) {
// This should make fusion easier or use less memory bandwidth in the unfused
// case.
if (arg->opcode() == HloOpcode::kConcatenate &&
- c_linear_search(reduce->dimensions(), arg->concatenate_dimension())) {
+ absl::c_linear_search(reduce->dimensions(),
+ arg->concatenate_dimension())) {
HloInstruction* old_reduce = nullptr;
for (HloInstruction* operand : arg->operands()) {
HloInstruction* new_reduce = computation_->AddInstruction(
@@ -2138,6 +2150,11 @@ Status AlgebraicSimplifierVisitor::HandleTranspose(HloInstruction* transpose) {
transpose->dimensions())));
}
+ if (operand->opcode() == HloOpcode::kRng && operand->user_count() == 1) {
+ *operand->mutable_shape() = transpose->shape();
+ return ReplaceInstruction(transpose, operand);
+ }
+
if (is_layout_sensitive_ && TransposeIsBitcast(transpose)) {
ReplaceWithBitcast(transpose);
return Status::OK();
diff --git a/tensorflow/compiler/xla/service/algebraic_simplifier_test.cc b/tensorflow/compiler/xla/service/algebraic_simplifier_test.cc
index 862cbeeba6..d3785006d5 100644
--- a/tensorflow/compiler/xla/service/algebraic_simplifier_test.cc
+++ b/tensorflow/compiler/xla/service/algebraic_simplifier_test.cc
@@ -1428,6 +1428,37 @@ TEST_F(AlgebraicSimplifierTest, NoBitcastAdded) {
EXPECT_THAT(computation->root_instruction(), op::Reshape(param0));
}
+// Test transforming reshapes and transposes of rng.
+TEST_F(AlgebraicSimplifierTest, ReshapeOfTransposeOfRngToRng) {
+ HloComputation::Builder builder(TestName());
+ HloInstruction* zero = builder.AddInstruction(
+ HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f)));
+ HloInstruction* one = builder.AddInstruction(
+ HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(1.0f)));
+ HloInstruction* rng0 = builder.AddInstruction(
+ HloInstruction::CreateRng(ShapeUtil::MakeShape(F32, {2, 2}),
+ RandomDistribution::RNG_UNIFORM, {zero, one}));
+
+ HloInstruction* transpose = builder.AddInstruction(
+ HloInstruction::CreateTranspose(rng0->shape(), rng0, {1, 0}));
+ Shape reshape_shape = builder
+ .AddInstruction(HloInstruction::CreateReshape(
+ ShapeUtil::MakeShape(F32, {4}), transpose))
+ ->shape();
+
+ auto computation = module().AddEntryComputation(builder.Build());
+
+ AlgebraicSimplifier simplifier(/*is_layout_sensitive=*/false,
+ bitcasting_callback());
+ EXPECT_TRUE(simplifier.Run(&module()).ValueOrDie());
+
+ // Verify that that reshape(transpose(rng)) is replace by a single rng of the
+ // same shape as the reshape.
+ EXPECT_THAT(computation->root_instruction(), op::Rng());
+ EXPECT_TRUE(ShapeUtil::Equal(computation->root_instruction()->shape(),
+ reshape_shape));
+}
+
// Test transforming reshapes to bitcasts under various conditions.
TEST_F(AlgebraicSimplifierTest, ReshapeReplacedWithBitcast) {
HloComputation::Builder builder(TestName());
@@ -2006,7 +2037,7 @@ TEST_F(AlgebraicSimplifierTest, ConvertConvToMatmul) {
// Builds a convolution from <options> and runs algebraic simplification on
// the computation. Returns a string description of the result of
// simplification.
- auto build_and_simplify = [&options]() -> string {
+ auto build_and_simplify = [&]() -> string {
HloComputation::Builder b(TestName());
Window window;
diff --git a/tensorflow/compiler/xla/service/batch_dot_simplification.cc b/tensorflow/compiler/xla/service/batch_dot_simplification.cc
index 2099916509..b226e7ecb0 100644
--- a/tensorflow/compiler/xla/service/batch_dot_simplification.cc
+++ b/tensorflow/compiler/xla/service/batch_dot_simplification.cc
@@ -15,6 +15,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/batch_dot_simplification.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
@@ -84,10 +85,10 @@ StatusOr<bool> BatchDotSimplification::Run(HloModule* module) {
bool changed = false;
std::vector<HloInstruction*> dot_instrs;
for (HloComputation* computation : module->MakeNonfusionComputations()) {
- c_copy_if(computation->instructions(), std::back_inserter(dot_instrs),
- [](HloInstruction* instr) {
- return instr->opcode() == HloOpcode::kDot;
- });
+ absl::c_copy_if(computation->instructions(), std::back_inserter(dot_instrs),
+ [](HloInstruction* instr) {
+ return instr->opcode() == HloOpcode::kDot;
+ });
}
for (HloInstruction* dot_instr : dot_instrs) {
TF_ASSIGN_OR_RETURN(bool elided_batch_dim_from_one,
diff --git a/tensorflow/compiler/xla/service/buffer_assignment.cc b/tensorflow/compiler/xla/service/buffer_assignment.cc
index 118a11c8de..cfd26fc778 100644
--- a/tensorflow/compiler/xla/service/buffer_assignment.cc
+++ b/tensorflow/compiler/xla/service/buffer_assignment.cc
@@ -139,6 +139,7 @@ Status GatherComputationsByAllocationType(
case HloOpcode::kMap:
case HloOpcode::kReduce:
case HloOpcode::kReduceWindow:
+ case HloOpcode::kScatter:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kFusion:
// Map/reduce etc computations are always thread-local.
diff --git a/tensorflow/compiler/xla/service/call_graph.cc b/tensorflow/compiler/xla/service/call_graph.cc
index a23427f00c..985ff30e80 100644
--- a/tensorflow/compiler/xla/service/call_graph.cc
+++ b/tensorflow/compiler/xla/service/call_graph.cc
@@ -61,6 +61,7 @@ CallContext GetInstructionCallContext(HloOpcode opcode) {
case HloOpcode::kMap:
case HloOpcode::kReduce:
case HloOpcode::kReduceWindow:
+ case HloOpcode::kScatter:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kFusion:
return CallContext::kParallel;
diff --git a/tensorflow/compiler/xla/service/compiler.h b/tensorflow/compiler/xla/service/compiler.h
index 99abb9bae3..34f7fe12ca 100644
--- a/tensorflow/compiler/xla/service/compiler.h
+++ b/tensorflow/compiler/xla/service/compiler.h
@@ -48,11 +48,6 @@ namespace xla {
// compuation.
using ObjectFileData = std::vector<char>;
-// Contains the buffer sizes information needed to allocate buffers to execute
-// an ahead-of-time computation. Entries which contain -1 designate a parameter
-// which should be skipped over during allocation.
-using BufferSizes = std::vector<int64>;
-
// Abstract superclass describing the result of an ahead-of-time compilation.
class AotCompilationResult {
public:
diff --git a/tensorflow/compiler/xla/service/convolution_feature_group_converter.cc b/tensorflow/compiler/xla/service/convolution_feature_group_converter.cc
new file mode 100644
index 0000000000..45252fc1ee
--- /dev/null
+++ b/tensorflow/compiler/xla/service/convolution_feature_group_converter.cc
@@ -0,0 +1,248 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/convolution_feature_group_converter.h"
+
+#include <memory>
+#include <vector>
+
+#include "tensorflow/compiler/xla/literal.h"
+#include "tensorflow/compiler/xla/literal_util.h"
+#include "tensorflow/compiler/xla/ptr_util.h"
+#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
+#include "tensorflow/compiler/xla/service/hlo_computation.h"
+#include "tensorflow/compiler/xla/service/hlo_instruction.h"
+#include "tensorflow/compiler/xla/service/hlo_opcode.h"
+#include "tensorflow/compiler/xla/shape_util.h"
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/compiler/xla/types.h"
+#include "tensorflow/compiler/xla/util.h"
+#include "tensorflow/compiler/xla/xla_data.pb.h"
+#include "tensorflow/core/lib/core/errors.h"
+#include "tensorflow/core/lib/core/status.h"
+#include "tensorflow/core/platform/logging.h"
+
+namespace xla {
+
+namespace {
+
+// ConvolutionVisitor traverses the HLO computation and rewrites Convolution
+// operations with feature_group_count > 1 into convolutions with
+// feature_group_count = 1.
+class ConvolutionVisitor : public DfsHloVisitorWithDefault {
+ public:
+ // Default visitor action is to do nothing and return OK.
+ Status DefaultAction(HloInstruction* /*hlo_instruction*/) override {
+ return Status::OK();
+ }
+
+ Status HandleConvolution(HloInstruction* convolution) override;
+
+ // Runs the visitor on a computation.
+ static bool Run(HloComputation* computation);
+
+ // Returns whether any convolution ops were rewritten.
+ const bool changed() const { return changed_; }
+
+ ~ConvolutionVisitor() override = default;
+
+ private:
+ explicit ConvolutionVisitor(HloComputation* computation)
+ : computation_(computation) {}
+
+ // Current HloComputation instance the ConvolutionVisitor is traversing.
+ HloComputation* computation_;
+
+ // Whether rewrite has occurred.
+ bool changed_ = false;
+};
+
+bool ConvolutionVisitor::Run(HloComputation* computation) {
+ ConvolutionVisitor visitor(computation);
+ TF_CHECK_OK(computation->Accept(&visitor));
+ return visitor.changed_;
+}
+
+Shape ExpandedFilterShape(const Shape& shape, int64 group_count,
+ int64 input_feature_dim) {
+ int64 num_dims = shape.dimensions_size();
+ CHECK_GE(num_dims, 2);
+ Shape expanded_shape = shape;
+ expanded_shape.set_dimensions(
+ input_feature_dim, shape.dimensions(input_feature_dim) * group_count);
+ return expanded_shape;
+}
+
+// Returns a vector with 'group_count' many groups, where the i-th group
+// consists of 'group_size' times the value i.
+std::vector<int32> GetMaskIds(int64 group_size, int64 group_count) {
+ std::vector<int32> values;
+ for (int i = 0; i < group_count; ++i) {
+ for (int j = 0; j < group_size; ++j) {
+ values.push_back(i);
+ }
+ }
+ return values;
+}
+
+// Create a mask for grouped convolution that will make a normal convolution
+// produce the same results as a grouped convolution. For a [2, 1, 6]
+// filter this returns a [2, 3, 6] mask
+// 1 1 0 0 0 0
+// 0 0 1 1 0 0
+// 0 0 0 0 1 1
+//
+// 1 1 0 0 0 0
+// 0 0 1 1 0 0
+// 0 0 0 0 1 1
+//
+// The first step is to create a rank 1 constant:
+// 0 1 2
+//
+// This is broadcasted to
+// 0 0 0 0 0 0
+// 1 1 1 1 1 1
+// 2 2 2 2 2 2
+//
+// 0 0 0 0 0 0
+// 1 1 1 1 1 1
+// 2 2 2 2 2 2
+//
+// Then we create another rank 1 constant
+// 0 0 1 1 2 2
+//
+// This is broadcasted to
+// 0 0 1 1 2 2
+// 0 0 1 1 2 2
+// 0 0 1 1 2 2
+//
+// 0 0 1 1 2 2
+// 0 0 1 1 2 2
+// 0 0 1 1 2 2
+//
+// Finally we use the Eq op of these two broadcasted constants and get the
+// desired mask.
+HloInstruction* GetExpandedFilterMask(
+ const Shape& filter_shape, int64 input_feature_dim,
+ int64 output_feature_dim, int64 group_count,
+ const std::function<HloInstruction*(std::unique_ptr<HloInstruction>)>&
+ add_instruction) {
+ Shape expanded_filter_shape =
+ ExpandedFilterShape(filter_shape, group_count, input_feature_dim);
+ Shape mask_shape = ShapeUtil::MakeShape(
+ S32, AsInt64Slice(expanded_filter_shape.dimensions()));
+ int64 output_feature = filter_shape.dimensions(output_feature_dim);
+ int64 group_size = filter_shape.dimensions(input_feature_dim);
+
+ // Create a 'input_feature' sized linspace and 'output_feature' sized linspace
+ // that will be broadcasted into perpendicular dimensions and compared.
+ const std::vector<int32> input_feature_filter_mask =
+ GetMaskIds(group_size, group_count);
+ const std::vector<int32> output_feature_filter_mask =
+ GetMaskIds(output_feature / group_count, group_count);
+
+ auto mask1 = add_instruction(HloInstruction::CreateConstant(
+ LiteralUtil::CreateR1<int32>(input_feature_filter_mask)));
+ auto broadcasted_mask1 = add_instruction(
+ HloInstruction::CreateBroadcast(mask_shape, mask1, {input_feature_dim}));
+ auto mask2 = add_instruction(HloInstruction::CreateConstant(
+ LiteralUtil::CreateR1<int32>(output_feature_filter_mask)));
+ auto broadcasted_mask2 = add_instruction(
+ HloInstruction::CreateBroadcast(mask_shape, mask2, {output_feature_dim}));
+
+ // Compare the broadcasted output feature linspace to the input feature
+ // linspace to create a diagonal predicate.
+ Shape predicate_shape = ShapeUtil::MakeShape(
+ PRED, AsInt64Slice(expanded_filter_shape.dimensions()));
+ return add_instruction(HloInstruction::CreateBinary(
+ predicate_shape, HloOpcode::kEq, broadcasted_mask1, broadcasted_mask2));
+}
+
+Status ConvolutionVisitor::HandleConvolution(HloInstruction* convolution) {
+ int64 group_count = convolution->feature_group_count();
+ if (group_count == 1) {
+ return Status::OK();
+ }
+ auto filter = convolution->mutable_operand(1);
+ changed_ = true;
+ auto add = [&](std::unique_ptr<HloInstruction> inst) {
+ return computation_->AddInstruction(std::move(inst));
+ };
+
+ auto dim_numbers = convolution->convolution_dimension_numbers();
+ int64 input_feature_dim = dim_numbers.kernel_input_feature_dimension();
+ int64 group_size = filter->shape().dimensions(input_feature_dim);
+ int64 output_feature_dim = dim_numbers.kernel_output_feature_dimension();
+ auto expanded_filter_shape =
+ ExpandedFilterShape(filter->shape(), group_count, input_feature_dim);
+ HloInstruction* filter_mask = GetExpandedFilterMask(
+ filter->shape(), input_feature_dim, output_feature_dim, group_count, add);
+ HloInstruction* expanded_filter;
+ // We want to repeat 'filter' in the 'input_feature_dim' dimension
+ // 'group_count' times.
+ if (group_size == 1) {
+ Shape reshaped_filter_shape =
+ ShapeUtil::DeleteDimension(input_feature_dim, filter->shape());
+ auto reshaped_filter =
+ add(HloInstruction::CreateReshape(reshaped_filter_shape, filter));
+ std::vector<int64> broadcast_dims;
+ for (int64 i = 0; i < filter->shape().dimensions_size(); ++i) {
+ if (i == input_feature_dim) {
+ continue;
+ }
+ broadcast_dims.push_back(i);
+ }
+ expanded_filter = add(HloInstruction::CreateBroadcast(
+ expanded_filter_shape, reshaped_filter, broadcast_dims));
+ } else {
+ // We could possibly also use reshape, broadcast, reshape instead of concat
+ // here, but it would require more complex code, and for depthwise
+ // convolution we would never end up in this branch.
+ std::vector<HloInstruction*> concat_operands(group_count, filter);
+ expanded_filter = add(HloInstruction::CreateConcatenate(
+ expanded_filter_shape, concat_operands, input_feature_dim));
+ }
+ auto zero = add(HloInstruction::CreateConstant(MakeUnique<Literal>(
+ LiteralUtil::Zero(expanded_filter_shape.element_type()))));
+ auto zero_filter =
+ add(HloInstruction::CreateBroadcast(expanded_filter_shape, zero, {}));
+ auto new_filter = add(
+ HloInstruction::CreateTernary(expanded_filter_shape, HloOpcode::kSelect,
+ filter_mask, expanded_filter, zero_filter));
+ auto new_convolution = HloInstruction::CreateConvolve(
+ convolution->shape(), convolution->mutable_operand(0), new_filter,
+ convolution->window(), dim_numbers, /*feature_group_count=*/1);
+ TF_RETURN_IF_ERROR(computation_->ReplaceWithNewInstruction(
+ convolution, std::move(new_convolution)));
+ return Status::OK();
+}
+
+} // namespace
+
+StatusOr<bool> ConvolutionFeatureGroupConverter::Run(HloModule* module) {
+ XLA_VLOG_LINES(2, "ConvolutionFeatureGroupConverter::Run(), before:\n" +
+ module->ToString());
+ bool changed = false;
+ for (auto* comp : module->MakeNonfusionComputations()) {
+ if (ConvolutionVisitor::Run(comp)) {
+ changed = true;
+ }
+ }
+ XLA_VLOG_LINES(2, "ConvolutionFeatureGroupConverter::Run(), after:\n" +
+ module->ToString());
+ return changed;
+}
+
+} // namespace xla
diff --git a/tensorflow/compiler/xla/service/convolution_feature_group_converter.h b/tensorflow/compiler/xla/service/convolution_feature_group_converter.h
new file mode 100644
index 0000000000..f213cc8709
--- /dev/null
+++ b/tensorflow/compiler/xla/service/convolution_feature_group_converter.h
@@ -0,0 +1,43 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CONVOLUTION_FEATURE_GROUP_CONVERTER_H_
+#define TENSORFLOW_COMPILER_XLA_SERVICE_CONVOLUTION_FEATURE_GROUP_CONVERTER_H_
+
+#include "tensorflow/compiler/xla/service/hlo_module.h"
+#include "tensorflow/compiler/xla/service/hlo_pass_interface.h"
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/core/lib/core/stringpiece.h"
+
+namespace xla {
+
+// A pass which rewrites convolutions with feature_group_count > 1 into
+// convolutions with feature_group_count = 1.
+class ConvolutionFeatureGroupConverter : public HloPassInterface {
+ public:
+ ConvolutionFeatureGroupConverter() {}
+
+ tensorflow::StringPiece name() const override {
+ return "convolution-feature-group-converter";
+ }
+
+ // Run convolution rewriting on the given computation. Returns whether the
+ // computation was changed.
+ StatusOr<bool> Run(HloModule* module) override;
+};
+
+} // namespace xla
+
+#endif // TENSORFLOW_COMPILER_XLA_SERVICE_CONVOLUTION_FEATURE_GROUP_CONVERTER_H_
diff --git a/tensorflow/compiler/xla/service/convolution_feature_group_converter_test.cc b/tensorflow/compiler/xla/service/convolution_feature_group_converter_test.cc
new file mode 100644
index 0000000000..28373ebf63
--- /dev/null
+++ b/tensorflow/compiler/xla/service/convolution_feature_group_converter_test.cc
@@ -0,0 +1,100 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/convolution_feature_group_converter.h"
+
+#include <memory>
+#include <string>
+
+#include "tensorflow/compiler/xla/service/hlo_computation.h"
+#include "tensorflow/compiler/xla/service/hlo_instruction.h"
+#include "tensorflow/compiler/xla/service/hlo_matchers.h"
+#include "tensorflow/compiler/xla/service/hlo_opcode.h"
+#include "tensorflow/compiler/xla/service/hlo_parser.h"
+#include "tensorflow/compiler/xla/test.h"
+#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
+#include "tensorflow/compiler/xla/types.h"
+
+namespace xla {
+namespace {
+
+using ConvolutionFeatureGroupConverterTest = HloTestBase;
+namespace op = testing::opcode_matchers;
+
+TEST_F(ConvolutionFeatureGroupConverterTest,
+ ConvertFeatureGroupCountEqualToInputFeatureDim) {
+ string hlo_string = R"(HloModule Convolve1D1Window_0_module
+
+ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,2], filter: f32[1,1,2]) -> f32[1,2,2] {
+ %input = f32[1,2,2]{2,1,0} parameter(0)
+ %copy = f32[1,2,2]{2,0,1} copy(f32[1,2,2]{2,1,0} %input)
+ %filter = f32[1,1,2]{2,1,0} parameter(1)
+ ROOT %convolution = f32[1,2,2]{2,0,1} convolution(f32[1,2,2]{2,0,1} %copy, f32[1,1,2]{2,1,0} %filter), window={size=1}, dim_labels=b0f_0io->b0f, feature_group_count=2
+})";
+ TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
+ ParseHloString(hlo_string));
+
+ auto computation = module->entry_computation();
+ HloInstruction* root = computation->root_instruction();
+ EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
+ ConvolutionFeatureGroupConverter converter;
+ ASSERT_TRUE(converter.Run(module.get()).ValueOrDie());
+ root = computation->root_instruction();
+ // Make sure the convolution is converted to one with feature_group_count = 1.
+ EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
+ EXPECT_EQ(root->feature_group_count(), 1);
+ // Verify that the filter operand has been replaced.
+ EXPECT_THAT(root->operand(1),
+ op::Select(op::Eq(op::Broadcast(op::Constant()),
+ op::Broadcast(op::Constant())),
+ op::Broadcast(op::Reshape(op::Parameter())),
+ op::Broadcast(op::Constant())));
+}
+
+TEST_F(ConvolutionFeatureGroupConverterTest,
+ ConvertFeatureGroupCountDivisorOfInputFeatureDim) {
+ string hlo_string = R"(HloModule Convolve1D1Window_0_module
+
+ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,4], filter: f32[1,2,2]) -> f32[1,2,2] {
+ %input = f32[1,2,4]{2,1,0} parameter(0)
+ %copy = f32[1,2,4]{2,0,1} copy(f32[1,2,4]{2,1,0} %input)
+ %filter = f32[1,2,2]{2,1,0} parameter(1)
+ ROOT %convolution = f32[1,2,2]{2,0,1} convolution(f32[1,2,4]{2,0,1} %copy, f32[1,2,2]{2,1,0} %filter), window={size=1}, dim_labels=b0f_0io->b0f, feature_group_count=2
+})";
+ TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
+ ParseHloString(hlo_string));
+
+ auto computation = module->entry_computation();
+ HloInstruction* root = computation->root_instruction();
+ EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
+ ConvolutionFeatureGroupConverter converter;
+ ASSERT_TRUE(converter.Run(module.get()).ValueOrDie());
+ root = computation->root_instruction();
+ // Make sure the convolution is converted to one with feature_group_count = 1.
+ EXPECT_EQ(root->opcode(), HloOpcode::kConvolution);
+ EXPECT_EQ(root->feature_group_count(), 1);
+ // Verify that the filter operand has been replaced.
+ EXPECT_THAT(root->operand(1),
+ op::Select(op::Eq(op::Broadcast(op::Constant()),
+ op::Broadcast(op::Constant())),
+ // We expect to see Concatenate here instead of
+ // Broadcast, because feature_group_count < input
+ // feature dimension.
+ op::Concatenate(op::Parameter(), op::Parameter()),
+ op::Broadcast(op::Constant())));
+}
+
+} // namespace
+} // namespace xla
diff --git a/tensorflow/compiler/xla/service/copy_insertion.cc b/tensorflow/compiler/xla/service/copy_insertion.cc
index 36fb9b43aa..3e39c1bab1 100644
--- a/tensorflow/compiler/xla/service/copy_insertion.cc
+++ b/tensorflow/compiler/xla/service/copy_insertion.cc
@@ -312,7 +312,7 @@ Status AddCopiesForWhile(const HloAliasAnalysis& alias_analysis,
return Status::OK();
}
-// We add copies for all the indices of the true and false computaiton roots,
+// We add copies for all the indices of the true and false computation roots,
// in order to resolve interference. We later rely on the CopyRemover to drop
// the unnecessary ones.
Status AddCopiesForConditional(const HloAliasAnalysis& alias_analysis,
@@ -648,7 +648,12 @@ class CopyRemover {
// We can only perform copy elision if the resulting merged values have
// totally ordered live ranges; otherwise the merged buffer would have
// live range interference.
- if (IsHead(*dest)) {
+ if (src->next == dest) {
+ // In the process of eliding copies, its possible for a copy to have the
+ // same source and destination buffer. In this case, the copy can be
+ // safely removed.
+ VLOG(2) << copy->name() << " source and destination buffers are same.";
+ } else if (IsHead(*dest)) {
// The copy copies an arbitrary value in the source buffer (call it s_x)
// and defines d_0, the first value in the destination buffer. After
// merging, the values in the combined buffer must be strictly ordered
diff --git a/tensorflow/compiler/xla/service/copy_insertion_test.cc b/tensorflow/compiler/xla/service/copy_insertion_test.cc
index cd735256b8..892d0d7b54 100644
--- a/tensorflow/compiler/xla/service/copy_insertion_test.cc
+++ b/tensorflow/compiler/xla/service/copy_insertion_test.cc
@@ -2007,5 +2007,46 @@ ENTRY TestComputation {
InsertCopies(module.get());
}
+TEST_F(CopyInsertionTest, NestedWhiles) {
+ // Verify that only no unnecessary copies remain after copy insertion for
+ // trivial nested whiles (b/112472605).
+ const string& hlo_string = R"(
+HloModule TestModule
+
+cond.inner {
+ ROOT param.cond.inner = pred[] parameter(0)
+}
+
+body.inner {
+ param.body.inner = pred[] parameter(0)
+ ROOT neg = pred[] negate(param.body.inner)
+}
+
+cond.outer {
+ ROOT param.cond.outer = pred[] parameter(0)
+}
+
+body.outer {
+ param.cond.outer = pred[] parameter(0)
+ ROOT while = pred[] while(param.cond.outer), condition=cond.inner, body=body.inner
+}
+
+ENTRY TestComputation {
+ entry_param = pred[] parameter(0)
+ ROOT while = pred[] while(entry_param), condition=cond.outer, body=body.outer
+}
+)";
+ TF_ASSERT_OK_AND_ASSIGN(
+ std::unique_ptr<HloModule> module,
+ HloRunner::CreateModuleFromString(hlo_string, GetDebugOptionsForTest()));
+ InsertCopies(module.get());
+
+ // There should only be a single copy inserted, and it's in the entry
+ // computation.
+ EXPECT_EQ(CountCopies(*module), 1);
+ EXPECT_THAT(module->entry_computation()->root_instruction(),
+ op::While(op::Copy(op::Parameter())));
+}
+
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/service/cpu/BUILD b/tensorflow/compiler/xla/service/cpu/BUILD
index 504b61d134..9cad674934 100644
--- a/tensorflow/compiler/xla/service/cpu/BUILD
+++ b/tensorflow/compiler/xla/service/cpu/BUILD
@@ -20,7 +20,7 @@ load("//tensorflow:tensorflow.bzl", "tf_cc_binary")
load("//tensorflow/compiler/xla:xla.bzl", "ORC_JIT_MEMORY_MAPPER_TARGETS")
load(
"//third_party/mkl:build_defs.bzl",
- "if_mkl",
+ "mkl_deps",
)
# Filegroup used to collect source files for dependency checking.
@@ -55,11 +55,23 @@ cc_library(
)
cc_library(
+ name = "buffer_info_util",
+ srcs = ["buffer_info_util.cc"],
+ hdrs = ["buffer_info_util.h"],
+ deps = [
+ "//tensorflow/compiler/tf2xla:cpu_function_runtime",
+ "//tensorflow/compiler/xla/service:buffer_assignment",
+ "//tensorflow/core:lib",
+ ],
+)
+
+cc_library(
name = "cpu_compiler",
srcs = ["cpu_compiler.cc"],
hdrs = ["cpu_compiler.h"],
deps = [
":compiler_functor",
+ ":buffer_info_util",
":conv_canonicalization",
":cpu_copy_insertion",
":cpu_executable",
@@ -73,6 +85,8 @@ cc_library(
":ir_emitter",
":parallel_task_assignment",
":simple_orc_jit",
+ "//tensorflow/compiler/tf2xla:cpu_function_runtime",
+ "//tensorflow/compiler/xla/service:scatter_expander",
"//tensorflow/compiler/xla:literal",
"//tensorflow/compiler/xla:protobuf_util",
"//tensorflow/compiler/xla:status_macros",
@@ -87,6 +101,7 @@ cc_library(
"//tensorflow/compiler/xla/service:buffer_liveness",
"//tensorflow/compiler/xla/service:call_inliner",
"//tensorflow/compiler/xla/service:conditional_simplifier",
+ "//tensorflow/compiler/xla/service:convolution_feature_group_converter",
"//tensorflow/compiler/xla/service:dot_decomposer",
"//tensorflow/compiler/xla/service:executable",
"//tensorflow/compiler/xla/service:flatten_call_graph",
@@ -484,10 +499,7 @@ cc_library(
"//tensorflow/core:framework_lite",
"//tensorflow/core/kernels:eigen_helpers",
"//third_party/eigen3",
- ] + if_mkl([
- "@mkl_dnn",
- "//third_party/mkl:intel_binary_blob",
- ]),
+ ] + mkl_deps(),
)
cc_library(
@@ -541,10 +553,7 @@ cc_library(
"//tensorflow/compiler/xla:executable_run_options",
"//tensorflow/core:framework_lite",
"//third_party/eigen3",
- ] + if_mkl([
- "//third_party/mkl:intel_binary_blob",
- "@mkl_dnn",
- ]),
+ ] + mkl_deps(),
)
cc_library(
@@ -884,6 +893,7 @@ cc_library(
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/compiler/xla/service/llvm_ir:llvm_util",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
"@llvm//:core",
"@llvm//:support",
],
diff --git a/tensorflow/compiler/xla/service/cpu/buffer_info_util.cc b/tensorflow/compiler/xla/service/cpu/buffer_info_util.cc
new file mode 100644
index 0000000000..408fe0f5bf
--- /dev/null
+++ b/tensorflow/compiler/xla/service/cpu/buffer_info_util.cc
@@ -0,0 +1,57 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/cpu/buffer_info_util.h"
+
+namespace xla {
+namespace cpu {
+
+using BufferInfo = ::tensorflow::cpu_function_runtime::BufferInfo;
+
+std::vector<BufferInfo> CreateBufferInfosFromBufferAssignment(
+ const BufferAssignment& buffer_assignment) {
+ std::vector<BufferInfo> buffer_infos;
+ for (const BufferAllocation& allocation : buffer_assignment.Allocations()) {
+ if (allocation.is_thread_local()) {
+ buffer_infos.push_back(BufferInfo::MakeOnStackBuffer(allocation.size()));
+ } else if (allocation.is_constant()) {
+ buffer_infos.push_back(BufferInfo::MakeConstant(allocation.size()));
+ } else if (allocation.is_entry_computation_parameter()) {
+ buffer_infos.push_back(BufferInfo::MakeEntryParameter(
+ /*size=*/allocation.size(),
+ /*param_number=*/allocation.parameter_number()));
+ } else {
+ buffer_infos.push_back(BufferInfo::MakeTempBuffer(allocation.size()));
+ }
+ }
+ return buffer_infos;
+}
+
+std::vector<int32> CreateArgIndexTableFromBufferInfos(
+ tensorflow::gtl::ArraySlice<BufferInfo> buffer_infos) {
+ std::vector<int32> result;
+ for (int64 i = 0; i < buffer_infos.size(); i++) {
+ if (buffer_infos[i].is_entry_parameter()) {
+ if (buffer_infos[i].entry_parameter_number() >= result.size()) {
+ result.resize(buffer_infos[i].entry_parameter_number() + 1);
+ }
+ result[buffer_infos[i].entry_parameter_number()] = i;
+ }
+ }
+ return result;
+}
+
+} // namespace cpu
+} // namespace xla
diff --git a/tensorflow/compiler/xla/service/cpu/buffer_info_util.h b/tensorflow/compiler/xla/service/cpu/buffer_info_util.h
new file mode 100644
index 0000000000..05de70c726
--- /dev/null
+++ b/tensorflow/compiler/xla/service/cpu/buffer_info_util.h
@@ -0,0 +1,42 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CPU_BUFFER_INFO_UTIL_H_
+#define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_BUFFER_INFO_UTIL_H_
+
+#include "tensorflow/compiler/tf2xla/cpu_function_runtime.h"
+#include "tensorflow/compiler/xla/service/buffer_assignment.h"
+#include "tensorflow/core/lib/gtl/array_slice.h"
+
+namespace xla {
+namespace cpu {
+// Creates and returns a list of BufferInfo instances containing relevant
+// information from `buffer_assignment`.
+std::vector<::tensorflow::cpu_function_runtime::BufferInfo>
+CreateBufferInfosFromBufferAssignment(
+ const BufferAssignment& buffer_assignment);
+
+// Creates and returns a table containing the mapping from entry computation
+// parameters to buffer allocation indices.
+//
+// If this function returns V then entry parameter i has buffer allocation index
+// V[i].
+std::vector<int32> CreateArgIndexTableFromBufferInfos(
+ tensorflow::gtl::ArraySlice<::tensorflow::cpu_function_runtime::BufferInfo>
+ buffer_infos);
+} // namespace cpu
+} // namespace xla
+
+#endif // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_BUFFER_INFO_UTIL_H_
diff --git a/tensorflow/compiler/xla/service/cpu/cpu_compiler.cc b/tensorflow/compiler/xla/service/cpu/cpu_compiler.cc
index 8cbe9a1b0d..fde8fbd486 100644
--- a/tensorflow/compiler/xla/service/cpu/cpu_compiler.cc
+++ b/tensorflow/compiler/xla/service/cpu/cpu_compiler.cc
@@ -50,6 +50,8 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/buffer_liveness.h"
#include "tensorflow/compiler/xla/service/call_inliner.h"
#include "tensorflow/compiler/xla/service/conditional_simplifier.h"
+#include "tensorflow/compiler/xla/service/convolution_feature_group_converter.h"
+#include "tensorflow/compiler/xla/service/cpu/buffer_info_util.h"
#include "tensorflow/compiler/xla/service/cpu/compiler_functor.h"
#include "tensorflow/compiler/xla/service/cpu/conv_canonicalization.h"
#include "tensorflow/compiler/xla/service/cpu/cpu_copy_insertion.h"
@@ -87,6 +89,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
#include "tensorflow/compiler/xla/service/reduce_precision_insertion.h"
#include "tensorflow/compiler/xla/service/reshape_mover.h"
+#include "tensorflow/compiler/xla/service/scatter_expander.h"
#include "tensorflow/compiler/xla/service/transpose_folding.h"
#include "tensorflow/compiler/xla/service/tuple_simplifier.h"
#include "tensorflow/compiler/xla/service/while_loop_constant_sinking.h"
@@ -103,6 +106,7 @@ limitations under the License.
namespace xla {
namespace cpu {
+using BufferInfo = ::tensorflow::cpu_function_runtime::BufferInfo;
CpuAotCompilationOptions::CpuAotCompilationOptions(
string triple, string cpu_name, string features, string entry_point_name,
@@ -120,11 +124,11 @@ se::Platform::Id CpuAotCompilationOptions::PlatformId() const {
}
CpuAotCompilationResult::CpuAotCompilationResult(
- ObjectFileData object_file_data, BufferSizes buffer_sizes,
+ ObjectFileData object_file_data, std::vector<BufferInfo> buffer_infos,
int64 result_buffer_index,
std::unique_ptr<HloProfilePrinterData> hlo_profile_printer_data)
: object_file_data_(std::move(object_file_data)),
- buffer_sizes_(std::move(buffer_sizes)),
+ buffer_infos_(std::move(buffer_infos)),
result_buffer_index_(result_buffer_index),
hlo_profile_printer_data_(std::move(hlo_profile_printer_data)) {}
@@ -255,6 +259,7 @@ Status CpuCompiler::RunHloPasses(HloModule* module, bool is_aot_compile,
pipeline.AddPass<CallInliner>();
pipeline.AddPass<BatchDotSimplification>();
pipeline.AddPass<DotDecomposer>();
+ pipeline.AddPass<ConvolutionFeatureGroupConverter>();
pipeline.AddPass<ConvCanonicalization>(&target_machine_features);
{
auto& pass =
@@ -273,7 +278,7 @@ Status CpuCompiler::RunHloPasses(HloModule* module, bool is_aot_compile,
// BatchNormExpander can create zero-sized ops, so zero-sized HLO
// elimination has to come after that pass.
- pipeline.AddPass<ZeroSizedHloElimination>();
+ pass.AddPass<ZeroSizedHloElimination>();
pass.AddPass<WhileLoopInvariantCodeMotion>();
pass.AddPass<TupleSimplifier>();
@@ -297,6 +302,8 @@ Status CpuCompiler::RunHloPasses(HloModule* module, bool is_aot_compile,
pipeline.AddPass<HloCSE>(/*is_layout_sensitive=*/false);
pipeline.AddPass<CpuInstructionFusion>();
+ pipeline.AddPass<ScatterExpander>();
+
ReducePrecisionInsertion::AddPasses(
&pipeline, module->config().debug_options(),
ReducePrecisionInsertion::PassTiming::AFTER_FUSION);
@@ -354,7 +361,7 @@ llvm::TargetOptions CompilerTargetOptions(
llvm::TargetOptions target_options;
llvm_ir::SetTargetOptions(
/*fast_math_enabled=*/module_config.debug_options()
- .xla_enable_fast_math(),
+ .xla_cpu_enable_fast_math(),
&target_options);
return target_options;
}
@@ -521,7 +528,7 @@ StatusOr<std::unique_ptr<Executable>> CpuCompiler::RunBackend(
CompilerTargetOptions(module->config()),
CodeGenOptLevel(module->config()),
options::OptimizeForSizeRequested(module->config()),
- module->config().debug_options().xla_enable_fast_math(),
+ module->config().debug_options().xla_cpu_enable_fast_math(),
module->config().debug_options().xla_llvm_disable_expensive_passes(),
pre_optimization_ir_hook, post_optimization_ir_hook);
llvm_module->setDataLayout(jit->data_layout());
@@ -651,9 +658,9 @@ CpuCompiler::CompileAheadOfTime(std::vector<std::unique_ptr<HloModule>> modules,
// so we bail if the configs have conflicting flags. At the moment, the only
// flag that needs to be consistent is fast-math.
const bool fast_math_enabled =
- modules[0]->config().debug_options().xla_enable_fast_math();
+ modules[0]->config().debug_options().xla_cpu_enable_fast_math();
for (const auto& module : modules) {
- if (module->config().debug_options().xla_enable_fast_math() !=
+ if (module->config().debug_options().xla_cpu_enable_fast_math() !=
fast_math_enabled) {
return InvalidArgument(
"All HLO module configs must have the same value for "
@@ -830,7 +837,7 @@ CpuCompiler::CompileAheadOfTime(std::vector<std::unique_ptr<HloModule>> modules,
CompilerFunctor compiler_functor(
target_machine.get(), &disassembler, opt_level,
options::OptimizeForSizeRequested(module->config()),
- module->config().debug_options().xla_enable_fast_math(),
+ module->config().debug_options().xla_cpu_enable_fast_math(),
module->config().debug_options().xla_llvm_disable_expensive_passes(),
pre_optimization_ir_dump_hook, post_optimization_ir_dump_hook);
std::unique_ptr<llvm::MemoryBuffer> object_file =
@@ -838,39 +845,14 @@ CpuCompiler::CompileAheadOfTime(std::vector<std::unique_ptr<HloModule>> modules,
ObjectFileData object_file_data(object_file->getBufferStart(),
object_file->getBufferEnd());
- BufferSizes buffer_sizes;
- for (const BufferAllocation& allocation : assignment->Allocations()) {
- // Callers don't need to allocate anything for thread-local temporary
- // buffers. They are lowered to allocas.
- if (allocation.is_thread_local()) {
- buffer_sizes.push_back(-1);
- continue;
- }
-
- // Callers don't need to allocate anything for constant buffers. They are
- // lowered to globals.
- if (allocation.is_constant()) {
- buffer_sizes.push_back(-1);
- continue;
- }
-
- // Callers don't need to allocate anything for entry computation buffers,
- // but they do need to stash the pointer to the entry computation buffer
- // in the temp buffer table. See the comment on
- // XlaCompiledCpuFunction::StaticData::temp_sizes.
- if (allocation.is_entry_computation_parameter()) {
- buffer_sizes.push_back(-allocation.parameter_number() - 2);
- continue;
- }
-
- buffer_sizes.push_back(allocation.size());
- }
+ std::vector<BufferInfo> buffer_infos =
+ CreateBufferInfosFromBufferAssignment(*assignment);
TF_ASSIGN_OR_RETURN(const BufferAllocation::Slice result_slice,
assignment->GetUniqueTopLevelOutputSlice());
results.emplace_back(MakeUnique<CpuAotCompilationResult>(
- std::move(object_file_data), std::move(buffer_sizes),
+ std::move(object_file_data), std::move(buffer_infos),
result_slice.index(), std::move(hlo_profile_printer_data)));
}
diff --git a/tensorflow/compiler/xla/service/cpu/cpu_compiler.h b/tensorflow/compiler/xla/service/cpu/cpu_compiler.h
index e56f9f0113..04e1c48872 100644
--- a/tensorflow/compiler/xla/service/cpu/cpu_compiler.h
+++ b/tensorflow/compiler/xla/service/cpu/cpu_compiler.h
@@ -19,6 +19,7 @@ limitations under the License.
#include <memory>
#include "llvm/Target/TargetMachine.h"
+#include "tensorflow/compiler/tf2xla/cpu_function_runtime.h"
#include "tensorflow/compiler/xla/service/executable.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/llvm_compiler.h"
@@ -78,7 +79,8 @@ class CpuAotCompilationOptions : public AotCompilationOptions {
class CpuAotCompilationResult : public AotCompilationResult {
public:
CpuAotCompilationResult(
- ObjectFileData object_file_data, BufferSizes buffer_sizes,
+ ObjectFileData object_file_data,
+ std::vector<::tensorflow::cpu_function_runtime::BufferInfo> buffer_infos,
int64 result_buffer_index,
std::unique_ptr<HloProfilePrinterData> hlo_profile_printer_data);
~CpuAotCompilationResult();
@@ -88,17 +90,20 @@ class CpuAotCompilationResult : public AotCompilationResult {
}
const ObjectFileData& object_file_data() const { return object_file_data_; }
- const BufferSizes& buffer_sizes() const { return buffer_sizes_; }
+ const std::vector<::tensorflow::cpu_function_runtime::BufferInfo>&
+ buffer_infos() const {
+ return buffer_infos_;
+ }
int64 result_buffer_index() const { return result_buffer_index_; }
private:
// Contains the compiled computation: an object file.
const ObjectFileData object_file_data_;
- // The list of buffer sizes which should be allocated in order to execute the
- // compiled computation. These buffers are used for temporary buffers used
- // ephemerally during computation as well as the output result.
- const BufferSizes buffer_sizes_;
+ // A list of BufferInfo objects describing the buffers used by the XLA
+ // computation.
+ const std::vector<::tensorflow::cpu_function_runtime::BufferInfo>
+ buffer_infos_;
// Contains which buffer index into |buffer_sizes| was designated to the
// result of the computation. This buffer should be passed into the output
diff --git a/tensorflow/compiler/xla/service/cpu/cpu_executable.cc b/tensorflow/compiler/xla/service/cpu/cpu_executable.cc
index 946f5124b8..c376864c3e 100644
--- a/tensorflow/compiler/xla/service/cpu/cpu_executable.cc
+++ b/tensorflow/compiler/xla/service/cpu/cpu_executable.cc
@@ -249,24 +249,11 @@ StatusOr<ScopedShapedBuffer> CpuExecutable::ExecuteOnStream(
const ServiceExecutableRunOptions* run_options,
tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
HloExecutionProfile* hlo_execution_profile) {
- if (GetRootPointsToSet().IsAmbiguous()) {
- return Unimplemented("Points-to set of root instruction is ambiguous");
- }
-
- se::Stream* stream = run_options->stream();
- DeviceMemoryAllocator* memory_allocator = run_options->allocator();
-
- std::vector<OwningDeviceMemory> owning_buffers;
- std::vector<se::DeviceMemoryBase> unowning_buffers;
TF_ASSIGN_OR_RETURN(
- std::tie(unowning_buffers, owning_buffers),
- CreateTempArray(memory_allocator, stream->parent()->device_ordinal(),
- arguments));
-
- TF_RETURN_IF_ERROR(ExecuteComputeFunction(
- &run_options->run_options(), unowning_buffers, hlo_execution_profile));
-
- return CreateResultShapedBuffer(run_options, &owning_buffers);
+ auto result,
+ ExecuteAsyncOnStreamImpl(run_options, arguments, hlo_execution_profile));
+ TF_RETURN_IF_ERROR(run_options->stream()->BlockHostUntilDone());
+ return std::move(result);
}
StatusOr<ScopedShapedBuffer> CpuExecutable::ExecuteAsyncOnStream(
@@ -277,6 +264,16 @@ StatusOr<ScopedShapedBuffer> CpuExecutable::ExecuteAsyncOnStream(
"Asynchronous execution on stream with hlo profiling is not yet "
"supported on CPU.");
}
+ return ExecuteAsyncOnStreamImpl(run_options, arguments, nullptr);
+}
+
+StatusOr<ScopedShapedBuffer> CpuExecutable::ExecuteAsyncOnStreamImpl(
+ const ServiceExecutableRunOptions* run_options,
+ tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
+ HloExecutionProfile* hlo_execution_profile) {
+ if (GetRootPointsToSet().IsAmbiguous()) {
+ return Unimplemented("Points-to set of root instruction is ambiguous");
+ }
auto* host_stream = dynamic_cast<se::host::HostStream*>(
run_options->stream()->implementation());
@@ -310,19 +307,20 @@ StatusOr<ScopedShapedBuffer> CpuExecutable::ExecuteAsyncOnStream(
ServiceExecutableRunOptions run_options;
std::vector<se::DeviceMemoryBase> unowning_buffers;
std::shared_ptr<std::vector<OwningDeviceMemory>> buffers;
+ HloExecutionProfile* hlo_execution_profile;
void operator()() {
// Failing a CHECK here is not great, but I don't see an obvious way to
// return a failed Status asynchronously.
TF_CHECK_OK(executable->ExecuteComputeFunction(
- &run_options.run_options(), unowning_buffers,
- /*hlo_execution_profile=*/nullptr));
+ &run_options.run_options(), unowning_buffers, hlo_execution_profile));
}
};
host_stream->EnqueueTask(
AsyncRunTask{this, *run_options, std::move(unowning_buffers),
std::make_shared<std::vector<OwningDeviceMemory>>(
- std::move(owning_buffers))});
+ std::move(owning_buffers)),
+ hlo_execution_profile});
return std::move(result);
}
diff --git a/tensorflow/compiler/xla/service/cpu/cpu_executable.h b/tensorflow/compiler/xla/service/cpu/cpu_executable.h
index 8af8a5dfec..96e53de57e 100644
--- a/tensorflow/compiler/xla/service/cpu/cpu_executable.h
+++ b/tensorflow/compiler/xla/service/cpu/cpu_executable.h
@@ -85,6 +85,16 @@ class CpuExecutable : public Executable {
const BufferAssignment& buffer_assignment() const { return *assignment_; }
private:
+ // This is for sharing the code between ExecuteOnStream and
+ // ExecuteAsyncOnStream.
+ //
+ // Notice that it's tricky to use correctly, as the profile object (when it
+ // exists) must out-live the task.
+ StatusOr<ScopedShapedBuffer> ExecuteAsyncOnStreamImpl(
+ const ServiceExecutableRunOptions* run_options,
+ tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
+ HloExecutionProfile* hlo_execution_profile);
+
// Creates an array suitable for passing as the "temps" argument to the JIT
// compiled function pointer.
//
diff --git a/tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion_test.cc b/tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion_test.cc
index 991b14f17d..e6130c7d76 100644
--- a/tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion_test.cc
+++ b/tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion_test.cc
@@ -697,8 +697,9 @@ void CreateComputationForDotAddOutputFusionTest(const string& test_name,
HloInstruction::CreateBinary(dot_shape, HloOpcode::kAdd, dot, addend));
if (add_extra_use_for_dot) {
+ auto* token = builder.AddInstruction(HloInstruction::CreateToken());
builder.AddInstruction(
- HloInstruction::CreateOutfeed(dot_shape, dot, "no_config"));
+ HloInstruction::CreateOutfeed(dot_shape, dot, token, "no_config"));
}
module->AddEntryComputation(builder.Build());
@@ -791,11 +792,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
gather = s32[3,2] gather(operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
one = s32[] constant(1)
one_broadcasted = s32[3,2] broadcast(one), dimensions={}
ROOT result = s32[3,2]{1,0} add(gather, one_broadcasted)
@@ -807,11 +808,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,3,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
one = s32[] constant(1)
one_broadcasted = s32[2,3,2] broadcast(one), dimensions={}
ROOT result = s32[2,3,2]{2,1,0} add(gather, one_broadcasted)
@@ -823,11 +824,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2,2] parameter(1)
gather = s32[2,2] gather(operand, indices),
- output_window_dims={},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=2,
- window_bounds={1, 1}
+ slice_sizes={1, 1}
one = s32[] constant(1)
one_broadcasted = s32[2,2] broadcast(one), dimensions={}
ROOT result = s32[2,2]{1,0} add(gather, one_broadcasted)
@@ -839,11 +840,11 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
one = s32[] constant(1)
one_broadcasted = s32[2,2] broadcast(one), dimensions={}
ROOT result = s32[2,2]{1,0} add(gather, one_broadcasted)
@@ -855,11 +856,11 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
one = s32[] constant(1)
one_broadcasted = s32[2,2] broadcast(one), dimensions={}
ROOT result = s32[2,2]{1,0} add(gather, one_broadcasted)
@@ -871,11 +872,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
gather = s32[1,1] gather(operand, indices),
- output_window_dims={0,1},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={0,1},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
one = s32[] constant(1)
one_broadcasted = s32[1,1] broadcast(one), dimensions={}
ROOT result = s32[1,1]{1,0} add(gather, one_broadcasted)
@@ -887,11 +888,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,1,1] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
one = s32[] constant(1)
one_broadcasted = s32[2,1,1] broadcast(one), dimensions={}
ROOT result = s32[2,1,1]{2,1,0} add(gather, one_broadcasted)
diff --git a/tensorflow/compiler/xla/service/cpu/dot_op_emitter.cc b/tensorflow/compiler/xla/service/cpu/dot_op_emitter.cc
index 645888de78..f2ac742b6e 100644
--- a/tensorflow/compiler/xla/service/cpu/dot_op_emitter.cc
+++ b/tensorflow/compiler/xla/service/cpu/dot_op_emitter.cc
@@ -1066,7 +1066,7 @@ bool DotOpEmitter::EmitExperimentalGebpDotIfEnabled(
<< config.GetCacheKey();
const bool enable_fast_math =
- hlo_module_config_.debug_options().xla_enable_fast_math();
+ hlo_module_config_.debug_options().xla_cpu_enable_fast_math();
const bool optimize_for_size =
options::OptimizeForSizeRequested(hlo_module_config_);
@@ -1149,7 +1149,7 @@ bool DotOpEmitter::EmitLlvmIrDotIfProfitable() {
swap_operands ? lhs_array_.GetBasePointer() : rhs_array_.GetBasePointer();
const bool enable_fast_math =
- hlo_module_config_.debug_options().xla_enable_fast_math();
+ hlo_module_config_.debug_options().xla_cpu_enable_fast_math();
const bool optimize_for_size =
options::OptimizeForSizeRequested(hlo_module_config_);
diff --git a/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.cc b/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.cc
index c13d36776f..db54454707 100644
--- a/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.cc
+++ b/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.cc
@@ -30,47 +30,6 @@ limitations under the License.
namespace xla {
namespace cpu {
-StatusOr<llvm::Value*> CpuElementalIrEmitter::EmitFloatUnaryOp(
- const HloInstruction* op, llvm::Value* operand_value) const {
- switch (op->opcode()) {
- case HloOpcode::kTanh: {
- PrimitiveType element_type = op->shape().element_type();
- bool cast_result_to_fp16 = false;
- string function_name;
- switch (element_type) {
- case F16:
- cast_result_to_fp16 = true;
- operand_value = b_->CreateFPCast(operand_value, b_->getFloatTy());
- TF_FALLTHROUGH_INTENDED;
- case F32:
- function_name = "tanhf";
- break;
- case F64:
- function_name = "tanh";
- break;
- default:
- return Unimplemented("tanh");
- }
- // Create a function declaration.
- llvm::Function* function =
- llvm::cast<llvm::Function>(module_->getOrInsertFunction(
- llvm_ir::AsStringRef(function_name), operand_value->getType(),
- operand_value->getType()));
- function->setCallingConv(llvm::CallingConv::C);
- function->setDoesNotThrow();
- function->setDoesNotAccessMemory();
- // Create an instruction to call the function.
- llvm::Value* result = b_->CreateCall(function, operand_value);
- if (cast_result_to_fp16) {
- result = b_->CreateFPCast(result, b_->getHalfTy());
- }
- return result;
- }
- default:
- return ElementalIrEmitter::EmitFloatUnaryOp(op, operand_value);
- }
-}
-
StatusOr<llvm::Value*> CpuElementalIrEmitter::EmitAtan2(
PrimitiveType prim_type, llvm::Value* lhs, llvm::Value* rhs) const {
string function_name;
@@ -106,6 +65,39 @@ StatusOr<llvm::Value*> CpuElementalIrEmitter::EmitAtan2(
return result;
}
+StatusOr<llvm::Value*> CpuElementalIrEmitter::EmitTanh(
+ PrimitiveType prim_type, llvm::Value* value) const {
+ bool cast_result_to_fp16 = false;
+ string function_name;
+ switch (prim_type) {
+ case F16:
+ cast_result_to_fp16 = true;
+ value = b_->CreateFPCast(value, b_->getFloatTy());
+ TF_FALLTHROUGH_INTENDED;
+ case F32:
+ function_name = "tanhf";
+ break;
+ case F64:
+ function_name = "tanh";
+ break;
+ default:
+ return Unimplemented("tanh");
+ }
+ // Create a function declaration.
+ llvm::Function* function = llvm::cast<llvm::Function>(
+ module_->getOrInsertFunction(llvm_ir::AsStringRef(function_name),
+ value->getType(), value->getType()));
+ function->setCallingConv(llvm::CallingConv::C);
+ function->setDoesNotThrow();
+ function->setDoesNotAccessMemory();
+ // Create an instruction to call the function.
+ llvm::Value* result = b_->CreateCall(function, value);
+ if (cast_result_to_fp16) {
+ result = b_->CreateFPCast(result, b_->getHalfTy());
+ }
+ return result;
+}
+
llvm_ir::ElementGenerator CpuElementalIrEmitter::MakeElementGenerator(
const HloInstruction* hlo,
const HloToElementGeneratorMap& operand_to_generator) const {
diff --git a/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h b/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h
index 9598a886ab..76833e765d 100644
--- a/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h
+++ b/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h
@@ -39,10 +39,10 @@ class CpuElementalIrEmitter : public ElementalIrEmitter {
const HloToElementGeneratorMap& operand_to_generator) const override;
protected:
- StatusOr<llvm::Value*> EmitFloatUnaryOp(
- const HloInstruction* op, llvm::Value* operand_value) const override;
StatusOr<llvm::Value*> EmitAtan2(PrimitiveType prim_type, llvm::Value* lhs,
llvm::Value* rhs) const override;
+ StatusOr<llvm::Value*> EmitTanh(PrimitiveType prim_type,
+ llvm::Value* value) const override;
IrEmitter* ir_emitter_;
};
diff --git a/tensorflow/compiler/xla/service/cpu/ir_emitter.cc b/tensorflow/compiler/xla/service/cpu/ir_emitter.cc
index ca645d3f1d..6f433b4f30 100644
--- a/tensorflow/compiler/xla/service/cpu/ir_emitter.cc
+++ b/tensorflow/compiler/xla/service/cpu/ir_emitter.cc
@@ -99,7 +99,7 @@ IrEmitter::IrEmitter(
target_machine_features_(*target_machine_features) {
b_.setFastMathFlags(llvm_ir::GetFastMathFlags(
/*fast_math_enabled=*/hlo_module_config_.debug_options()
- .xla_enable_fast_math()));
+ .xla_cpu_enable_fast_math()));
}
StatusOr<llvm::Function*> IrEmitter::EmitComputation(
@@ -158,11 +158,11 @@ void IrEmitter::InitializeIrFunction(const string& function_name) {
is_top_level_computation_ ? llvm::GlobalValue::ExternalLinkage
: llvm::GlobalValue::InternalLinkage;
// Create and initialize new IrFunction.
- compute_function_.reset(
- new IrFunction(function_name, linkage,
- options::OptimizeForSizeRequested(hlo_module_config_),
- hlo_module_config_.debug_options().xla_enable_fast_math(),
- module_, &b_, num_dynamic_loop_bounds_));
+ compute_function_.reset(new IrFunction(
+ function_name, linkage,
+ options::OptimizeForSizeRequested(hlo_module_config_),
+ hlo_module_config_.debug_options().xla_cpu_enable_fast_math(), module_,
+ &b_, num_dynamic_loop_bounds_));
}
IrEmitter::~IrEmitter() {}
@@ -577,7 +577,7 @@ Status IrEmitter::HandleReduceWindow(HloInstruction* reduce_window) {
TF_RETURN_IF_ERROR(ElementTypesSameAndSupported(
/*instruction=*/*reduce_window,
/*operands=*/{reduce_window->operand(0)},
- /*supported_types=*/{F32, BF16, S32}));
+ /*supported_types=*/{F32, BF16, S32, F16}));
// TODO(b/31410564): Implement dilation for reduce-window.
if (window_util::HasDilation(reduce_window->window())) {
@@ -1756,6 +1756,10 @@ StatusOr<llvm::Value*> IrEmitter::EmitTargetElementLoopBodyForReduce(
}
Status IrEmitter::HandleReduce(HloInstruction* reduce) {
+ // TODO(b/112040122): Support variadic reduce.
+ if (!ShapeUtil::IsArray(reduce->shape())) {
+ return Unimplemented("Variadic reduce is not supported on CPU");
+ }
auto arg = reduce->mutable_operand(0);
auto init_value = reduce->mutable_operand(1);
gtl::ArraySlice<int64> dimensions(reduce->dimensions());
diff --git a/tensorflow/compiler/xla/service/cpu/parallel_task_assignment_test.cc b/tensorflow/compiler/xla/service/cpu/parallel_task_assignment_test.cc
index 36c9f74385..ee272b5f4f 100644
--- a/tensorflow/compiler/xla/service/cpu/parallel_task_assignment_test.cc
+++ b/tensorflow/compiler/xla/service/cpu/parallel_task_assignment_test.cc
@@ -110,9 +110,10 @@ TEST_F(ParallelTaskAssignmentTest, InfeedOutfeedOperationNotParallelized) {
const string hlo_string = R"(
HloModule TestTaskParallel_infeed_outfeed
ENTRY InfeedOutfeed {
- infeed0 = (u32[12345678,2]{1,0}, token[]) infeed()
+ token = token[] after-all()
+ infeed0 = (u32[12345678,2]{1,0}, token[]) infeed(token)
infeed0.data = u32[12345678,2]{1,0} get-tuple-element((u32[12345678,2]{1,0}, token[]) infeed0), index=0
- ROOT outfeed0 = token[] outfeed(infeed0.data)
+ ROOT outfeed0 = token[] outfeed(infeed0.data, token)
}
)";
diff --git a/tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.cc b/tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.cc
index 997fdd2ab3..8dc5f3c93b 100644
--- a/tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.cc
+++ b/tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.cc
@@ -13,7 +13,7 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#if defined(INTEL_MKL) && !defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL) && !defined(INTEL_MKL_DNN_ONLY)
#include "tensorflow/compiler/xla/service/cpu/runtime_matmul_mkl.h"
#include "third_party/intel_mkl_ml/include/mkl_cblas.h"
#include "third_party/intel_mkl_ml/include/mkl_service.h"
diff --git a/tensorflow/compiler/xla/service/cpu/tests/cpu_literal_caching_test.cc b/tensorflow/compiler/xla/service/cpu/tests/cpu_literal_caching_test.cc
index 90b99c828e..3b87683fff 100644
--- a/tensorflow/compiler/xla/service/cpu/tests/cpu_literal_caching_test.cc
+++ b/tensorflow/compiler/xla/service/cpu/tests/cpu_literal_caching_test.cc
@@ -38,7 +38,8 @@ while_body {
while_cond {
arg_cond = f32[2,3,2] parameter(0)
- infeed = (pred[], token[]) infeed()
+ token = token[] after-all()
+ infeed = (pred[], token[]) infeed(token)
ROOT unknown = pred[] get-tuple-element((pred[], token[]) infeed), index=0
}
@@ -50,8 +51,9 @@ ENTRY main {
{{2, 1}, {2001, 3002}, {2001, 2002}}})
const_b = f32[2,3,2] while(f32[2,3,2] const_a), condition=while_cond, body=while_body
- out0 = token[] outfeed(f32[2,3,2] const_a)
- ROOT out1 = token[] outfeed(f32[2,3,2] const_b)
+ token = token[] after-all()
+ out0 = token[] outfeed(f32[2,3,2] const_a, token[] token)
+ ROOT out1 = token[] outfeed(f32[2,3,2] const_b, token[] token)
}
)";
@@ -85,7 +87,8 @@ while_body {
while_cond {
arg_cond = (f32[2,1]{1,0}, f32[1]{0}) parameter(0)
- infeed = (pred[], token[]) infeed()
+ token = token[] after-all()
+ infeed = (pred[], token[]) infeed(token)
ROOT unknown = pred[] get-tuple-element((pred[], token[]) infeed), index=0
}
@@ -94,8 +97,9 @@ ENTRY main {
const_a = (f32[2,1]{1,0}, f32[1]{0}) constant((f32[2,1], f32[1]) ( f32[2,1] { { 1 }, { 2 } }, {2} ))
const_b = (f32[2,1]{1,0}, f32[1]{0}) while((f32[2,1]{1,0}, f32[1]{0}) const_a), condition=while_cond, body=while_body
- out0 = () outfeed((f32[2,1]{1,0}, f32[1]{0}) const_a)
- ROOT out1 = () outfeed((f32[2,1]{1,0}, f32[1]{0}) const_b)
+ token = token[] after-all()
+ out0 = () outfeed((f32[2,1]{1,0}, f32[1]{0}) const_a, token[] token)
+ ROOT out1 = () outfeed((f32[2,1]{1,0}, f32[1]{0}) const_b, token[] token)
}
)";
diff --git a/tensorflow/compiler/xla/service/cpu/tests/cpu_outfeed_test.cc b/tensorflow/compiler/xla/service/cpu/tests/cpu_outfeed_test.cc
index dac416e1c7..780c07f819 100644
--- a/tensorflow/compiler/xla/service/cpu/tests/cpu_outfeed_test.cc
+++ b/tensorflow/compiler/xla/service/cpu/tests/cpu_outfeed_test.cc
@@ -32,7 +32,8 @@ ENTRY main {
{{{1, 2}, {1001, 1002}, {2001, 2002}},
{{2, 1}, {2001, 3002}, {2001, 2002}}})
- outfeed = token[] outfeed(f32[2,3,2] const_a)
+ token = token[] after-all()
+ outfeed = token[] outfeed(f32[2,3,2] const_a, token)
ROOT root = () tuple()
}
)";
diff --git a/tensorflow/compiler/xla/service/cpu/vector_support_library.cc b/tensorflow/compiler/xla/service/cpu/vector_support_library.cc
index 3274be8d9d..962ea69c09 100644
--- a/tensorflow/compiler/xla/service/cpu/vector_support_library.cc
+++ b/tensorflow/compiler/xla/service/cpu/vector_support_library.cc
@@ -15,6 +15,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/cpu/vector_support_library.h"
+#include "absl/algorithm/container.h"
#include "llvm/Support/raw_ostream.h"
#include "tensorflow/compiler/xla/service/cpu/target_machine_features.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
@@ -422,8 +423,8 @@ TileVariable::TileVariable(VectorSupportLibrary* vector_support,
std::vector<llvm::Value*> TileVariable::Get() const {
std::vector<llvm::Value*> result;
- c_transform(storage_, std::back_inserter(result),
- [&](VectorVariable vect_var) { return vect_var.Get(); });
+ absl::c_transform(storage_, std::back_inserter(result),
+ [&](VectorVariable vect_var) { return vect_var.Get(); });
return result;
}
diff --git a/tensorflow/compiler/xla/service/despecializer.cc b/tensorflow/compiler/xla/service/despecializer.cc
index d938f3a2c4..48e4471499 100644
--- a/tensorflow/compiler/xla/service/despecializer.cc
+++ b/tensorflow/compiler/xla/service/despecializer.cc
@@ -21,8 +21,33 @@ limitations under the License.
namespace xla {
+namespace {
+
+// Pass which strips control dependencies from all instructions in the module.
+class ControlDepRemover : public HloPassInterface {
+ public:
+ ControlDepRemover() = default;
+ tensorflow::StringPiece name() const override {
+ return "control-dep-remover";
+ }
+
+ StatusOr<bool> Run(HloModule* module) override {
+ bool changed = false;
+ for (HloComputation* computation : module->computations()) {
+ for (HloInstruction* instruction : computation->instructions()) {
+ changed = changed || !instruction->control_predecessors().empty();
+ TF_RETURN_IF_ERROR(instruction->DropAllControlDeps());
+ }
+ }
+ return changed;
+ }
+};
+
+} // namespace
+
Despecializer::Despecializer() : pipeline_("despecializer") {
// TODO(b/70588125): Also deal with window reversal in a fast way.
+ pipeline_.AddPass<ControlDepRemover>();
pipeline_.AddPass<Defuser>();
pipeline_.AddPass<ImplicitBroadcastRemover>();
pipeline_.AddPass<BFloat16MixedPrecisionRemoval>();
diff --git a/tensorflow/compiler/xla/service/elemental_ir_emitter.cc b/tensorflow/compiler/xla/service/elemental_ir_emitter.cc
index 6aab317ca5..4b19aa5df9 100644
--- a/tensorflow/compiler/xla/service/elemental_ir_emitter.cc
+++ b/tensorflow/compiler/xla/service/elemental_ir_emitter.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include <vector>
// IWYU pragma: no_include "llvm/IR/Intrinsics.gen.inc"
+#include "absl/algorithm/container.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
@@ -431,6 +432,8 @@ StatusOr<llvm::Value*> ElementalIrEmitter::EmitFloatUnaryOp(
return EmitCos(op->shape().element_type(), operand_value);
case HloOpcode::kSin:
return EmitSin(op->shape().element_type(), operand_value);
+ case HloOpcode::kTanh:
+ return EmitTanh(op->shape().element_type(), operand_value);
case HloOpcode::kFloor:
return llvm_ir::EmitCallToIntrinsic(llvm::Intrinsic::floor,
{operand_value},
@@ -1060,6 +1063,11 @@ StatusOr<llvm::Value*> ElementalIrEmitter::EmitAtan2(PrimitiveType prim_type,
return Unimplemented("atan2");
}
+StatusOr<llvm::Value*> ElementalIrEmitter::EmitTanh(PrimitiveType prim_type,
+ llvm::Value* value) const {
+ return Unimplemented("tanh");
+}
+
StatusOr<llvm::Value*> ElementalIrEmitter::EmitReducePrecision(
const HloInstruction* hlo, llvm::Value* x) const {
if (hlo->operand(0)->shape().element_type() != F32) {
@@ -1665,22 +1673,21 @@ StatusOr<llvm::Value*> ElementalIrEmitter::EmitElementalGather(
std::vector<int64> operand_to_output_dim(operand_shape.dimensions_size(), -1);
for (int64 i = 0, e = operand_shape.dimensions_size(), operand_index_dim = 0;
i < e; i++) {
- if (c_binary_search(dim_numbers.elided_window_dims(), i)) {
+ if (absl::c_binary_search(dim_numbers.collapsed_slice_dims(), i)) {
operand_index.push_back(index.GetConstantWithIndexType(0));
} else {
- int64 output_window_dim =
- dim_numbers.output_window_dims(operand_index_dim++);
+ int64 output_window_dim = dim_numbers.offset_dims(operand_index_dim++);
operand_to_output_dim[i] = output_window_dim;
operand_index.push_back(index[output_window_dim]);
}
}
- // This is the index of the index vector in the gather_indices tensor.
+ // This is the index of the index vector in the start_indices tensor.
IrArray::Index gather_index_index(index_type);
{
std::vector<llvm::Value*> gather_index_index_components;
for (int64 i = 0, e = output_shape.dimensions_size(); i < e; i++) {
- if (!c_binary_search(dim_numbers.output_window_dims(), i)) {
+ if (!absl::c_binary_search(dim_numbers.offset_dims(), i)) {
gather_index_index.push_back(index[i]);
}
}
@@ -1693,7 +1700,7 @@ StatusOr<llvm::Value*> ElementalIrEmitter::EmitElementalGather(
auto add_to_operand_index = [&](llvm::Value* index_component, int64 dim) {
llvm::Value* gather_dim_component_extended =
b_->CreateSExtOrTrunc(index_component, index_type);
- int64 operand_dim = dim_numbers.gather_dims_to_operand_dims(dim);
+ int64 operand_dim = dim_numbers.start_index_map(dim);
int64 output_dim = operand_to_output_dim[operand_dim];
// If 'output_dim' is -1, it means 'operand_dim' is an elided window dim.
// This means we set the iteration index to 0, so for the purpose of the
diff --git a/tensorflow/compiler/xla/service/elemental_ir_emitter.h b/tensorflow/compiler/xla/service/elemental_ir_emitter.h
index fcb34557a5..1598a4dd85 100644
--- a/tensorflow/compiler/xla/service/elemental_ir_emitter.h
+++ b/tensorflow/compiler/xla/service/elemental_ir_emitter.h
@@ -122,6 +122,9 @@ class ElementalIrEmitter {
llvm::Value* lhs,
llvm::Value* rhs) const;
+ virtual StatusOr<llvm::Value*> EmitTanh(PrimitiveType prim_type,
+ llvm::Value* value) const;
+
virtual StatusOr<llvm::Value*> EmitReducePrecision(const HloInstruction* hlo,
llvm::Value* x) const;
diff --git a/tensorflow/compiler/xla/service/gather_expander.cc b/tensorflow/compiler/xla/service/gather_expander.cc
index e3a42d0d06..d889fd8e88 100644
--- a/tensorflow/compiler/xla/service/gather_expander.cc
+++ b/tensorflow/compiler/xla/service/gather_expander.cc
@@ -15,6 +15,7 @@ limitations under the License.
#include <utility>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/gather_expander.h"
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
@@ -27,85 +28,85 @@ namespace xla {
using tensorflow::gtl::ArraySlice;
static StatusOr<HloInstruction*> TransposeIndexVectorDimToLast(
- HloInstruction* gather_indices, int64 index_vector_dim) {
- const Shape& gather_indices_shape = gather_indices->shape();
+ HloInstruction* start_indices, int64 index_vector_dim) {
+ const Shape& start_indices_shape = start_indices->shape();
- if (gather_indices_shape.dimensions_size() == index_vector_dim) {
- return gather_indices;
+ if (start_indices_shape.dimensions_size() == index_vector_dim) {
+ return start_indices;
}
- if (index_vector_dim == (gather_indices_shape.dimensions_size() - 1)) {
- return gather_indices;
+ if (index_vector_dim == (start_indices_shape.dimensions_size() - 1)) {
+ return start_indices;
}
std::vector<int64> permutation;
- permutation.reserve(gather_indices_shape.dimensions_size());
- for (int64 i = 0, e = gather_indices_shape.dimensions_size(); i < e; i++) {
+ permutation.reserve(start_indices_shape.dimensions_size());
+ for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) {
if (i != index_vector_dim) {
permutation.push_back(i);
}
}
permutation.push_back(index_vector_dim);
- return MakeTransposeHlo(gather_indices, permutation);
+ return MakeTransposeHlo(start_indices, permutation);
}
-// Canonicalizes the gather_indices tensors so that we only have deal with some
+// Canonicalizes the start_indices tensors so that we only have deal with some
// specific cases in the while loop that does the heavy lifting.
//
// See the "High Level Algorithm" section for a broader picture.
static StatusOr<HloInstruction*> CanonicalizeGatherIndices(
- HloInstruction* gather_indices, int64 index_vector_dim) {
+ HloInstruction* start_indices, int64 index_vector_dim) {
// Transpose the non-index-vector dimensions to the front.
TF_ASSIGN_OR_RETURN(
- HloInstruction * transposed_gather_indices,
- TransposeIndexVectorDimToLast(gather_indices, index_vector_dim));
+ HloInstruction * transposed_start_indices,
+ TransposeIndexVectorDimToLast(start_indices, index_vector_dim));
bool indices_are_scalar =
- index_vector_dim == gather_indices->shape().dimensions_size();
+ index_vector_dim == start_indices->shape().dimensions_size();
- // The number of dimensions in gather_indices that are index dimensions.
- const int64 index_dims_in_gather_indices = indices_are_scalar ? 0 : 1;
+ // The number of dimensions in start_indices that are index dimensions.
+ const int64 index_dims_in_start_indices = indices_are_scalar ? 0 : 1;
- // If there is only one index (i.e. gather_indices has rank 1 and this gather
+ // If there is only one index (i.e. start_indices has rank 1 and this gather
// is really just a dynamic slice) add a leading degenerate dimension for
// uniformity. Otherwise create a "collapsed" leading dimension that subsumes
// all of the non-index-vector dimensions.
- const Shape& shape = transposed_gather_indices->shape();
- if (shape.dimensions_size() == index_dims_in_gather_indices) {
- return PrependDegenerateDims(transposed_gather_indices, 1);
+ const Shape& shape = transposed_start_indices->shape();
+ if (shape.dimensions_size() == index_dims_in_start_indices) {
+ return PrependDegenerateDims(transposed_start_indices, 1);
} else {
- // Collapse all but the dimensions (0 or 1) in gather_indices containing the
+ // Collapse all but the dimensions (0 or 1) in start_indices containing the
// index vectors.
return CollapseFirstNDims(
- transposed_gather_indices,
- shape.dimensions_size() - index_dims_in_gather_indices);
+ transposed_start_indices,
+ shape.dimensions_size() - index_dims_in_start_indices);
}
}
// Expands out or contracts away the gather dimensions in the accumulator
// produced by the while loop.
-static StatusOr<HloInstruction*> AdjustGatherDimsInAccumulator(
- const Shape& gather_indices_shape, HloInstruction* accumulator,
+static StatusOr<HloInstruction*> AdjustBatchDimsInAccumulator(
+ const Shape& start_indices_shape, HloInstruction* accumulator,
int64 index_vector_dim) {
- std::vector<int64> output_gather_dim_bounds;
- output_gather_dim_bounds.reserve(gather_indices_shape.dimensions_size());
- for (int64 i = 0, e = gather_indices_shape.dimensions_size(); i < e; i++) {
+ std::vector<int64> batch_dim_bounds;
+ batch_dim_bounds.reserve(start_indices_shape.dimensions_size());
+ for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) {
if (i != index_vector_dim) {
- output_gather_dim_bounds.push_back(gather_indices_shape.dimensions(i));
+ batch_dim_bounds.push_back(start_indices_shape.dimensions(i));
}
}
- if (output_gather_dim_bounds.empty()) {
- // If output_gather_dim_bounds is empty we must be lowering a (effectively)
+ if (batch_dim_bounds.empty()) {
+ // If batch_dim_bounds is empty we must be lowering a (effectively)
// dynamic-slice. In that case, there is a leading degenerate gather
// dimension that we added to make this special case play well with the
// general while loop which we need to remove now.
return ElideDegenerateDims(accumulator, {0});
}
- return ExpandFirstDimIntoNDims(accumulator, output_gather_dim_bounds);
+ return ExpandFirstDimIntoNDims(accumulator, batch_dim_bounds);
}
-// Expand an index vector from the gather_indices tensor into a vector that can
+// Expand an index vector from the start_indices tensor into a vector that can
// be used to dynamic-slice out of the gather operand.
static StatusOr<HloInstruction*> ExpandIndexVectorIntoOperandSpace(
HloInstruction* index_vector, const GatherDimensionNumbers& dim_numbers,
@@ -121,10 +122,8 @@ static StatusOr<HloInstruction*> ExpandIndexVectorIntoOperandSpace(
std::vector<HloInstruction*> expanded_index_components;
for (int i = 0; i < operand_rank; i++) {
- int64 index_vector_dim_index =
- FindIndex(dim_numbers.gather_dims_to_operand_dims(), i);
- if (index_vector_dim_index !=
- dim_numbers.gather_dims_to_operand_dims_size()) {
+ int64 index_vector_dim_index = FindIndex(dim_numbers.start_index_map(), i);
+ if (index_vector_dim_index != dim_numbers.start_index_map_size()) {
TF_ASSIGN_OR_RETURN(
HloInstruction * component_to_concat,
MakeSliceHlo(index_vector, /*start_indices=*/{index_vector_dim_index},
@@ -147,10 +146,10 @@ static StatusOr<std::vector<HloInstruction*>> GatherLoopBody(
const GatherDimensionNumbers& dim_numbers = gather.gather_dimension_numbers();
CHECK_EQ(incoming_loop_state.size(), 3);
HloInstruction* const operand = incoming_loop_state[0];
- HloInstruction* const gather_indices = incoming_loop_state[1];
+ HloInstruction* const start_indices = incoming_loop_state[1];
HloInstruction* const output_accumulator = incoming_loop_state[2];
- bool has_scalar_indices = gather_indices->shape().dimensions_size() == 1;
+ bool has_scalar_indices = start_indices->shape().dimensions_size() == 1;
CHECK_EQ(has_scalar_indices,
dim_numbers.index_vector_dim() ==
gather.operand(1)->shape().dimensions_size());
@@ -163,24 +162,24 @@ static StatusOr<std::vector<HloInstruction*>> GatherLoopBody(
HloInstruction* index_vector;
if (has_scalar_indices) {
- // In this case gather_indices has rank 1 and induction_var_as_vector (of
+ // In this case start_indices has rank 1 and induction_var_as_vector (of
// shape {1}) is an index into this rank 1 tensor.
TF_ASSIGN_OR_RETURN(
index_vector,
- MakeDynamicSliceHlo(gather_indices, induction_var_as_vector, {1}));
+ MakeDynamicSliceHlo(start_indices, induction_var_as_vector, {1}));
} else {
- // In this case gather_indices has rank 2 and induction_var_as_vector (of
+ // In this case start_indices has rank 2 and induction_var_as_vector (of
// shape {1}) is an index into just the first dimension of this rank 2
// tensor.
TF_ASSIGN_OR_RETURN(
- HloInstruction * index_into_gather_indices,
+ HloInstruction * index_into_start_indices,
PadVectorWithZeros(induction_var_as_vector,
/*zeros_to_prepend=*/0, /*zeros_to_append=*/1));
- int64 index_vector_size = gather_indices->shape().dimensions(1);
+ int64 index_vector_size = start_indices->shape().dimensions(1);
TF_ASSIGN_OR_RETURN(
HloInstruction * index_vector_2d,
- MakeDynamicSliceHlo(gather_indices, index_into_gather_indices,
+ MakeDynamicSliceHlo(start_indices, index_into_start_indices,
{1, index_vector_size}));
TF_ASSIGN_OR_RETURN(index_vector,
@@ -194,26 +193,26 @@ static StatusOr<std::vector<HloInstruction*>> GatherLoopBody(
TF_ASSIGN_OR_RETURN(HloInstruction * gathered_slice,
MakeDynamicSliceHlo(operand, gathered_slice_start,
- gather.gather_window_bounds()));
+ gather.gather_slice_sizes()));
TF_ASSIGN_OR_RETURN(
- HloInstruction * gathered_slice_with_dims_elided,
+ HloInstruction* const gathered_slice_with_dims_collapsed,
ElideDegenerateDims(gathered_slice,
- AsInt64Slice(dim_numbers.elided_window_dims())));
+ AsInt64Slice(dim_numbers.collapsed_slice_dims())));
TF_ASSIGN_OR_RETURN(
- HloInstruction * gathered_slice_for_update,
- PrependDegenerateDims(gathered_slice_with_dims_elided, 1));
+ HloInstruction* const gathered_slice_for_update,
+ PrependDegenerateDims(gathered_slice_with_dims_collapsed, 1));
TF_ASSIGN_OR_RETURN(
- HloInstruction * index_vector_into_accumulator,
+ HloInstruction* const index_vector_into_accumulator,
PadVectorWithZeros(
induction_var_as_vector, /*zeros_to_prepend=*/0,
/*zeros_to_append=*/
- gathered_slice_with_dims_elided->shape().dimensions_size()));
+ gathered_slice_with_dims_collapsed->shape().dimensions_size()));
TF_ASSIGN_OR_RETURN(
- HloInstruction * updated_accumulator,
+ HloInstruction* const updated_accumulator,
MakeDynamicUpdateSliceHlo(output_accumulator, gathered_slice_for_update,
index_vector_into_accumulator));
@@ -221,19 +220,19 @@ static StatusOr<std::vector<HloInstruction*>> GatherLoopBody(
// WhileUtil::MakeCountedLoop functions takes care of the induction variable
// and the while loop exit condition.
return StatusOr<std::vector<HloInstruction*>>{
- {operand, gather_indices, updated_accumulator}};
+ {operand, start_indices, updated_accumulator}};
}
static StatusOr<HloInstruction*> CreateGatherLoopAccumulatorInitValue(
HloComputation* computation, PrimitiveType element_type,
- ArraySlice<int64> window_bounds, int64 gather_loop_trip_count,
+ ArraySlice<int64> slice_sizes, int64 gather_loop_trip_count,
const GatherDimensionNumbers& dim_numbers) {
std::vector<int64> accumulator_state_shape_dims;
- accumulator_state_shape_dims.reserve(1 + window_bounds.size());
+ accumulator_state_shape_dims.reserve(1 + slice_sizes.size());
accumulator_state_shape_dims.push_back(gather_loop_trip_count);
- for (int64 i = 0; i < window_bounds.size(); i++) {
- if (!c_binary_search(dim_numbers.elided_window_dims(), i)) {
- accumulator_state_shape_dims.push_back(window_bounds[i]);
+ for (int64 i = 0; i < slice_sizes.size(); i++) {
+ if (!absl::c_binary_search(dim_numbers.collapsed_slice_dims(), i)) {
+ accumulator_state_shape_dims.push_back(slice_sizes[i]);
}
}
return BroadcastZeros(computation, element_type,
@@ -241,23 +240,23 @@ static StatusOr<HloInstruction*> CreateGatherLoopAccumulatorInitValue(
}
// `accumulator` is almost the tensor the gather operation would have produced,
-// except that it has the dimensions in the wrong order -- the gather dimensions
-// are the major dimensions and the window dimensions are the minor dimensions.
+// except that it has the dimensions in the wrong order -- the batch dimensions
+// are the major dimensions and the offset dimensions are the minor dimensions.
// Fix this up with a transpose.
-static StatusOr<HloInstruction*> PermuteGatherAndWindowDims(
- HloInstruction* accumulator, ArraySlice<int64> output_window_dims,
+static StatusOr<HloInstruction*> PermuteBatchAndOffsetDims(
+ HloInstruction* accumulator, ArraySlice<int64> offset_dims,
int64 output_rank) {
std::vector<int64> permutation;
permutation.reserve(output_rank);
- int64 gather_idx_counter = 0;
- int64 window_idx_counter = output_rank - output_window_dims.size();
+ int64 batch_idx_counter = 0;
+ int64 offset_idx_counter = output_rank - offset_dims.size();
for (int64 i = 0; i < output_rank; i++) {
- bool is_window_dim = c_binary_search(output_window_dims, i);
- if (is_window_dim) {
- permutation.push_back(window_idx_counter++);
+ bool is_offset_dim = absl::c_binary_search(offset_dims, i);
+ if (is_offset_dim) {
+ permutation.push_back(offset_idx_counter++);
} else {
- permutation.push_back(gather_idx_counter++);
+ permutation.push_back(batch_idx_counter++);
}
}
@@ -268,11 +267,11 @@ static StatusOr<HloInstruction*> PermuteGatherAndWindowDims(
//
// We follow the following steps in sequence:
//
-// 1. We canonicalize the gather_indices tensor such that it has rank
+// 1. We canonicalize the start_indices tensor such that it has rank
// 2 (i.e. is a matrix) where each row is an index vector into the
// operand.
// 2. We iterate over the set of indices in the canonicalized
-// gather_indices tensor using a while loop, accumulating slices
+// start_indices tensor using a while loop, accumulating slices
// of the operand tensor into an accumulator using
// DynamicUpdateSlice.
// 3. The accumulator result from the while loop from (2) is then
@@ -287,11 +286,11 @@ static StatusOr<HloInstruction*> PermuteGatherAndWindowDims(
// operand = s32[3,3] parameter(0)
// indices = s32[2,2] parameter(1)
// ROOT gather = s32[2,3,2] gather(operand, indices),
-// output_window_dims={1},
-// elided_window_dims={1},
-// gather_dims_to_operand_dims={1},
+// offset_dims={1},
+// collapsed_slice_dims={1},
+// start_index_map={1},
// index_vector_dim=2,
-// window_bounds={3, 1}
+// slice_sizes={3, 1}
// }
//
// We'd first reshape indices to s32[4,1], where each row is an index
@@ -305,8 +304,8 @@ StatusOr<HloInstruction*> GatherExpander::ExpandGather(
HloComputation* computation = gather_instr->parent();
HloInstruction* operand = gather_instr->mutable_operand(0);
- HloInstruction* gather_indices = gather_instr->mutable_operand(1);
- const Shape& gather_indices_shape = gather_indices->shape();
+ HloInstruction* start_indices = gather_instr->mutable_operand(1);
+ const Shape& start_indices_shape = start_indices->shape();
const Shape& output_shape = gather_instr->shape();
int64 output_rank = output_shape.dimensions_size();
@@ -314,9 +313,9 @@ StatusOr<HloInstruction*> GatherExpander::ExpandGather(
gather_instr->gather_dimension_numbers();
int64 gather_loop_trip_count = 1;
- for (int64 i = 0, e = gather_indices_shape.dimensions_size(); i < e; i++) {
+ for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) {
if (i != dim_numbers.index_vector_dim()) {
- gather_loop_trip_count *= gather_indices_shape.dimensions(i);
+ gather_loop_trip_count *= start_indices_shape.dimensions(i);
}
}
@@ -327,24 +326,24 @@ StatusOr<HloInstruction*> GatherExpander::ExpandGather(
gather_instr->ToString().c_str());
}
- TF_ASSIGN_OR_RETURN(HloInstruction * canonical_gather_indices,
- CanonicalizeGatherIndices(
- gather_indices, dim_numbers.index_vector_dim()));
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * canonical_start_indices,
+ CanonicalizeGatherIndices(start_indices, dim_numbers.index_vector_dim()));
CHECK_EQ(gather_loop_trip_count,
- canonical_gather_indices->shape().dimensions(0));
+ canonical_start_indices->shape().dimensions(0));
TF_ASSIGN_OR_RETURN(
HloInstruction * accumulator_init,
CreateGatherLoopAccumulatorInitValue(
computation, output_shape.element_type(),
- gather_instr->gather_window_bounds(), gather_loop_trip_count,
+ gather_instr->gather_slice_sizes(), gather_loop_trip_count,
gather_instr->gather_dimension_numbers()));
StatusOr<std::vector<HloInstruction*>> gather_loop_result_or_error =
WhileUtil::MakeCountedLoop(
computation, gather_loop_trip_count,
- {operand, canonical_gather_indices, accumulator_init},
+ {operand, canonical_start_indices, accumulator_init},
[&](HloInstruction* indvar,
const std::vector<HloInstruction*>& loop_state) {
return GatherLoopBody(*gather_instr, indvar, loop_state);
@@ -356,13 +355,13 @@ StatusOr<HloInstruction*> GatherExpander::ExpandGather(
HloInstruction* accumulator_result = gather_loop_result.back();
TF_ASSIGN_OR_RETURN(
- HloInstruction * accumulator_with_output_gather_dims_decanonicalized,
- AdjustGatherDimsInAccumulator(gather_indices->shape(), accumulator_result,
- dim_numbers.index_vector_dim()));
+ HloInstruction* const accumulator_with_batch_dims_decanonicalized,
+ AdjustBatchDimsInAccumulator(start_indices->shape(), accumulator_result,
+ dim_numbers.index_vector_dim()));
- return PermuteGatherAndWindowDims(
- accumulator_with_output_gather_dims_decanonicalized,
- AsInt64Slice(dim_numbers.output_window_dims()), output_rank);
+ return PermuteBatchAndOffsetDims(accumulator_with_batch_dims_decanonicalized,
+ AsInt64Slice(dim_numbers.offset_dims()),
+ output_rank);
}
StatusOr<bool> GatherExpander::Run(HloModule* module) {
@@ -375,8 +374,8 @@ StatusOr<bool> GatherExpander::Run(HloModule* module) {
std::vector<HloInstruction*> gather_instrs;
for (HloComputation* computation : module->MakeNonfusionComputations()) {
- c_copy_if(computation->instructions(), std::back_inserter(gather_instrs),
- is_nontrivial_gather);
+ absl::c_copy_if(computation->instructions(),
+ std::back_inserter(gather_instrs), is_nontrivial_gather);
}
for (HloInstruction* inst : gather_instrs) {
diff --git a/tensorflow/compiler/xla/service/gather_expander_test.cc b/tensorflow/compiler/xla/service/gather_expander_test.cc
index 020ffcd106..141dd4d6f1 100644
--- a/tensorflow/compiler/xla/service/gather_expander_test.cc
+++ b/tensorflow/compiler/xla/service/gather_expander_test.cc
@@ -28,11 +28,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2147483647,5] parameter(1)
ROOT gather = s32[2147483647,3,5] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
@@ -55,11 +55,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[3,2] gather(operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
}
)";
TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
diff --git a/tensorflow/compiler/xla/service/gpu/BUILD b/tensorflow/compiler/xla/service/gpu/BUILD
index a3f6e8d989..fd1e34a547 100644
--- a/tensorflow/compiler/xla/service/gpu/BUILD
+++ b/tensorflow/compiler/xla/service/gpu/BUILD
@@ -1,6 +1,7 @@
# Description:
# GPU-specific components in XLA service implementation.
+load("//tensorflow/compiler/xla/tests:build_defs.bzl", "xla_test")
load("//tensorflow/compiler/xla:xla.bzl", "xla_proto_library")
licenses(["notice"]) # Apache 2.0
@@ -179,6 +180,7 @@ cc_library(
"//tensorflow/compiler/xla/service/llvm_ir:tuple_ops",
"//tensorflow/core:lib",
"//tensorflow/core:stream_executor_no_cuda",
+ "@com_google_absl//absl/algorithm:container",
"@llvm//:core",
"@llvm//:support",
],
@@ -361,10 +363,12 @@ cc_library(
hdrs = ["cudnn_convolution_algorithm_picker.h"],
deps = [
":backend_configs",
+ ":buffer_comparator",
":cudnn_convolution_runner",
":gpu_executable",
":ir_emission_utils",
"//tensorflow/compiler/xla:literal_util",
+ "//tensorflow/compiler/xla/service:compiler",
"//tensorflow/compiler/xla/service:device_memory_allocator",
"//tensorflow/compiler/xla/service:hlo",
"//tensorflow/compiler/xla/service:hlo_pass",
@@ -463,6 +467,7 @@ cc_library(
"//tensorflow/compiler/xla/service:hlo",
"//tensorflow/compiler/xla/service:multi_output_fusion",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -510,6 +515,7 @@ cc_library(
"//tensorflow/compiler/xla/service:hlo_cost_analysis",
"//tensorflow/compiler/xla/service:hlo_pass",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -636,6 +642,7 @@ cc_library(
"//tensorflow/compiler/xla/service:buffer_liveness",
"//tensorflow/compiler/xla/service:call_inliner",
"//tensorflow/compiler/xla/service:conditional_simplifier",
+ "//tensorflow/compiler/xla/service:convolution_feature_group_converter",
"//tensorflow/compiler/xla/service:executable",
"//tensorflow/compiler/xla/service:flatten_call_graph",
"//tensorflow/compiler/xla/service:hlo",
@@ -652,6 +659,7 @@ cc_library(
"//tensorflow/compiler/xla/service:llvm_compiler",
"//tensorflow/compiler/xla/service:reduce_precision_insertion",
"//tensorflow/compiler/xla/service:reshape_mover",
+ "//tensorflow/compiler/xla/service:scatter_expander",
"//tensorflow/compiler/xla/service:transpose_folding",
"//tensorflow/compiler/xla/service:tuple_simplifier",
"//tensorflow/compiler/xla/service:while_loop_constant_sinking",
@@ -852,3 +860,35 @@ tf_cc_test(
"//tensorflow/core:test",
],
)
+
+cc_library(
+ name = "buffer_comparator",
+ srcs = ["buffer_comparator.cc"],
+ hdrs = ["buffer_comparator.h"],
+ deps = [
+ ":gpu_executable",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/compiler/xla/service:compiler",
+ "//tensorflow/compiler/xla/service:device_memory_allocator",
+ "//tensorflow/compiler/xla/service:hlo_parser",
+ "//tensorflow/compiler/xla/service:hlo_runner",
+ "//tensorflow/core:lib",
+ "//tensorflow/core:stream_executor_no_cuda",
+ ],
+)
+
+xla_test(
+ name = "buffer_comparator_test",
+ srcs = ["buffer_comparator_test.cc"],
+ backends = [
+ "cpu",
+ "gpu",
+ ],
+ deps = [
+ ":buffer_comparator",
+ "//tensorflow/compiler/xla:types",
+ "//tensorflow/compiler/xla/service:backend",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ ],
+)
diff --git a/tensorflow/compiler/xla/service/gpu/buffer_comparator.cc b/tensorflow/compiler/xla/service/gpu/buffer_comparator.cc
new file mode 100644
index 0000000000..6a285a6b98
--- /dev/null
+++ b/tensorflow/compiler/xla/service/gpu/buffer_comparator.cc
@@ -0,0 +1,205 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/gpu/buffer_comparator.h"
+
+#include <cmath>
+#include "tensorflow/compiler/xla/service/hlo_parser.h"
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/core/lib/strings/str_util.h"
+
+namespace xla {
+namespace gpu {
+
+static constexpr float kTolerance = 0.1f;
+
+static string GetCompHloText(size_t num_elements) {
+ // Implements the textual format of the comparison routine, as it's more
+ // readable.
+ static constexpr char kF16CompHloText[] = R"(
+HloModule CompareF16
+
+MaxF32 {
+ %lhs = f32[] parameter(0)
+ %rhs = f32[] parameter(1)
+ ROOT %max = f32[] maximum(%lhs, %rhs)
+}
+
+Canonicalize (aparam: f16[SIZE]) -> f32[SIZE] {
+ %min_constant = f32[] constant(-65505)
+ %max_constant = f32[] constant(65505)
+ %large_constant = f32[] constant(1048576)
+ %min_values = f32[SIZE] broadcast(%min_constant), dimensions={}
+ %max_values = f32[SIZE] broadcast(%max_constant), dimensions={}
+ %large_values = f32[SIZE] broadcast(%large_constant), dimensions={}
+
+ %a = f16[SIZE] parameter(0)
+ %converted = f32[SIZE] convert(%a)
+ %clamped = f32[SIZE] clamp(%min_values, %converted, %max_values)
+
+ // Since the clamp() above already took care of infs, only NaNs will cause
+ // is-finite() to return false.
+ %is_finite = pred[SIZE] is-finite(%clamped)
+ ROOT %result = f32[SIZE] select(%is_finite, %clamped, %large_values)
+}
+
+ENTRY MaxDifference {
+ %one_constant = f32[] constant(1.0)
+ %zero_constant = f32[] constant(0.0)
+
+ %ones = f32[SIZE] broadcast(%one_constant), dimensions={}
+
+ %lhs = f16[SIZE] parameter(0)
+ %rhs = f16[SIZE] parameter(1)
+ %lhs_canonical = f32[SIZE] call(%lhs), to_apply=Canonicalize
+ %rhs_canonical = f32[SIZE] call(%rhs), to_apply=Canonicalize
+ %sub = f32[SIZE] subtract(%lhs_canonical, %rhs_canonical)
+ %sub_abs = f32[SIZE] abs(%sub)
+ %lhs_abs = f32[SIZE] abs(%lhs_canonical)
+ %rhs_abs = f32[SIZE] abs(%rhs_canonical)
+ %max = f32[SIZE] maximum(%lhs_abs, %rhs_abs)
+ %denominator = f32[SIZE] add(%max, %ones)
+ %error = f32[SIZE] divide(%sub_abs, %denominator)
+ ROOT %max_diff = f32[] reduce(%error, %zero_constant), dimensions={0}, to_apply=MaxF32
+})";
+ auto size_string = std::to_string(num_elements);
+ return tensorflow::str_util::StringReplace(
+ kF16CompHloText, "SIZE", {size_string.data(), size_string.size()}, true);
+}
+
+StatusOr<F16BufferComparator> F16BufferComparator::Create(
+ se::DeviceMemory<Eigen::half> ref_buffer, Compiler* compiler,
+ DeviceMemoryAllocator* allocator, se::Stream* stream) {
+ auto stream_exec = stream->parent();
+ int64 num_elements = ref_buffer.ElementCount();
+
+ // One may consider using hlo_runner to do all the compilation and execution.
+ // However, as of the time hlo_runner doesn't support injection for Compiler*,
+ // Stream*, or even the allocator. We may revisit this in the future if it
+ // proves to be a maintenance burden.
+ TF_ASSIGN_OR_RETURN(
+ auto exec, ([&]() -> StatusOr<std::unique_ptr<Executable>> {
+ HloModuleConfig config;
+ DebugOptions debug_options;
+ debug_options.set_xla_backend_optimization_level(2);
+ config.set_debug_options(debug_options);
+ TF_ASSIGN_OR_RETURN(
+ auto module, ParseHloString(GetCompHloText(num_elements), config));
+ TF_ASSIGN_OR_RETURN(
+ module,
+ compiler->RunHloPasses(std::move(module), stream_exec, nullptr));
+ return compiler->RunBackend(std::move(module), stream_exec, nullptr);
+ }()));
+
+ TF_ASSIGN_OR_RETURN(
+ auto shaped_buffer, ([&]() -> StatusOr<ScopedShapedBuffer> {
+ auto device_ordinal = stream_exec->device_ordinal();
+ TF_ASSIGN_OR_RETURN(
+ auto owning_buffer,
+ allocator->Allocate(device_ordinal, ref_buffer.size()));
+ se::DeviceMemory<Eigen::half> buffer(
+ owning_buffer.AsDeviceMemoryBase());
+ stream->ThenMemcpy(&buffer, ref_buffer, ref_buffer.size());
+ Shape shape = ShapeUtil::MakeShape(xla::F16, {num_elements});
+ ScopedShapedBuffer ret(shape, shape, allocator, device_ordinal);
+ ret.set_buffer(std::move(owning_buffer), {});
+ return std::move(ret);
+ }()));
+
+ return F16BufferComparator(stream, allocator, std::move(exec),
+ std::move(shaped_buffer));
+}
+
+StatusOr<bool> F16BufferComparator::CompareEqualImpl(
+ se::DeviceMemory<Eigen::half> test_buffer) {
+ if (ref_buffer_.root_buffer().size() != test_buffer.size()) {
+ return InternalError("Mismatched buffer size: %lld vs %lld",
+ ref_buffer_.root_buffer().size(), test_buffer.size());
+ }
+
+ int64 num_elements = test_buffer.ElementCount();
+
+ TF_ASSIGN_OR_RETURN(
+ auto result_buffer, ([&]() -> StatusOr<ScopedShapedBuffer> {
+ auto stream_exec = stream_->parent();
+ Shape shape = ShapeUtil::MakeShape(xla::F16, {num_elements});
+ auto device_ordinal = stream_exec->device_ordinal();
+ ShapedBuffer shaped_test_buffer(shape, shape, stream_exec->platform(),
+ device_ordinal);
+ shaped_test_buffer.set_buffer(test_buffer, {});
+ ExecutableRunOptions run_options;
+ run_options.set_device_ordinal(stream_exec->device_ordinal());
+ run_options.set_stream(stream_);
+ run_options.set_allocator(allocator_);
+ ServiceExecutableRunOptions service_run_options(run_options);
+ return exec_->ExecuteOnStream(
+ &service_run_options, {&ref_buffer_, &shaped_test_buffer}, nullptr);
+ }()));
+
+ float result;
+ CHECK(result_buffer.root_buffer().size() == sizeof(result));
+ stream_->ThenMemcpy(&result, result_buffer.root_buffer(), sizeof(result));
+ TF_RETURN_IF_ERROR(stream_->BlockHostUntilDone());
+ return result < kTolerance;
+}
+
+StatusOr<bool> F16BufferComparator::CompareEqual(
+ se::DeviceMemory<Eigen::half> test_buffer) {
+ TF_ASSIGN_OR_RETURN(auto result, CompareEqualImpl(test_buffer));
+ if (result) {
+ return true;
+ }
+ // Host side code that does the same thing, but report some of the
+ // differences as well.
+ int64 n = test_buffer.ElementCount();
+ std::vector<half> host_ref_buffer(n), host_test_buffer(n);
+ stream_->ThenMemcpy(host_ref_buffer.data(), ref_buffer_.root_buffer(),
+ ref_buffer_.root_buffer().size());
+ stream_->ThenMemcpy(host_test_buffer.data(), test_buffer, test_buffer.size());
+ TF_RETURN_IF_ERROR(stream_->BlockHostUntilDone());
+
+ const auto canonicalize = [](float a) -> float {
+ constexpr float kBigNumer = 1048576.;
+ constexpr float kMaxFp16Value = 65504.;
+ if (std::isnan(a)) {
+ return kBigNumer;
+ }
+ if (std::isinf(a)) {
+ if (a < 0) {
+ return -(kMaxFp16Value + 1);
+ }
+ return kMaxFp16Value + 1;
+ }
+ return a;
+ };
+ int differences_seen = 0;
+ for (int64 i = 0; i < n && differences_seen < 10; i++) {
+ float original_ref = static_cast<float>(host_ref_buffer[i]);
+ float original_test = static_cast<float>(host_test_buffer[i]);
+ float ref = canonicalize(original_ref);
+ float test = canonicalize(original_test);
+ if (!(std::abs(ref - test) / (std::max(std::abs(ref), std::abs(test)) + 1) <
+ kTolerance)) {
+ differences_seen++;
+ LOG(ERROR) << "Difference at " << i << ": " << original_ref << " vs "
+ << original_test;
+ }
+ }
+
+ return false;
+}
+
+} // namespace gpu
+} // namespace xla
diff --git a/tensorflow/compiler/xla/service/gpu/buffer_comparator.h b/tensorflow/compiler/xla/service/gpu/buffer_comparator.h
new file mode 100644
index 0000000000..bf2ba78cea
--- /dev/null
+++ b/tensorflow/compiler/xla/service/gpu/buffer_comparator.h
@@ -0,0 +1,71 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_BUFFER_COMPARATOR_H_
+#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_BUFFER_COMPARATOR_H_
+
+#include "tensorflow/compiler/xla/service/compiler.h"
+#include "tensorflow/compiler/xla/service/device_memory_allocator.h"
+#include "tensorflow/compiler/xla/service/gpu/gpu_executable.h"
+#include "tensorflow/core/platform/stream_executor_no_cuda.h"
+
+namespace xla {
+namespace gpu {
+
+// A fp16 comparator that internally keeps a reference buffer, and compares it
+// against other test buffers.
+class F16BufferComparator {
+ public:
+ F16BufferComparator(const F16BufferComparator&) = delete;
+ F16BufferComparator(F16BufferComparator&&) = default;
+
+ // Creates a new comparator. It internally allocates a buffer initialized by
+ // ref_buffer.
+ static StatusOr<F16BufferComparator> Create(
+ se::DeviceMemory<Eigen::half> ref_buffer, Compiler* compiler,
+ DeviceMemoryAllocator* allocator, se::Stream* stream);
+
+ // Returns true if the internally allocated buffer "compares equal" to
+ // test_buffer. The definition of "equal" is:
+ // * All NaNs equal.
+ // * All infs are treated as 65505 or -65505, so that this checker is tolerant
+ // to fp16 overflows.
+ // * With NaNs and infs taken care of, a and b compare equal iff:
+ // abs(a - b) / (max(abs(a), abs(b)) + 1) < tolerance
+ //
+ // See the implementation for the tolerance value.
+ StatusOr<bool> CompareEqual(se::DeviceMemory<Eigen::half> test_buffer);
+
+ private:
+ F16BufferComparator(se::Stream* stream, DeviceMemoryAllocator* allocator,
+ std::unique_ptr<Executable> exec,
+ ScopedShapedBuffer ref_buffer)
+ : stream_(stream),
+ allocator_(allocator),
+ exec_(std::move(exec)),
+ ref_buffer_(std::move(ref_buffer)) {}
+
+ StatusOr<bool> CompareEqualImpl(se::DeviceMemory<Eigen::half> test_buffer);
+
+ se::Stream* stream_;
+ DeviceMemoryAllocator* allocator_;
+ std::unique_ptr<Executable> exec_;
+ ScopedShapedBuffer ref_buffer_;
+};
+
+} // namespace gpu
+} // namespace xla
+
+#endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_BUFFER_COMPARATOR_H_
diff --git a/tensorflow/compiler/xla/service/gpu/buffer_comparator_test.cc b/tensorflow/compiler/xla/service/gpu/buffer_comparator_test.cc
new file mode 100644
index 0000000000..33761d1bd8
--- /dev/null
+++ b/tensorflow/compiler/xla/service/gpu/buffer_comparator_test.cc
@@ -0,0 +1,126 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/gpu/buffer_comparator.h"
+
+#include <limits>
+#include "tensorflow/compiler/xla/service/backend.h"
+#include "tensorflow/compiler/xla/types.h"
+#include "tensorflow/core/platform/test.h"
+
+namespace xla {
+namespace gpu {
+namespace {
+
+class BufferComparatorTest : public testing::Test {
+ protected:
+ BufferComparatorTest()
+ : backend_(Backend::CreateDefaultBackend().ConsumeValueOrDie()),
+ stream_exec_(backend_->default_stream_executor()),
+ allocator_(stream_exec_->platform(), {stream_exec_}),
+ compiler_(Compiler::GetForPlatform(stream_exec_->platform())
+ .ConsumeValueOrDie()) {}
+
+ // Take floats only for convenience. Still uses half internally.
+ bool CompareEqualFloatBuffers(const std::vector<float>& lhs_float,
+ const std::vector<float>& rhs_float) {
+ std::vector<half> lhs(lhs_float.begin(), lhs_float.end());
+ std::vector<half> rhs(rhs_float.begin(), rhs_float.end());
+ se::Stream stream(stream_exec_);
+ stream.Init();
+
+ auto owning_lhs_buffer =
+ allocator_
+ .Allocate(stream_exec_->device_ordinal(), lhs.size() * sizeof(half))
+ .ConsumeValueOrDie();
+
+ auto owning_rhs_buffer =
+ allocator_
+ .Allocate(stream_exec_->device_ordinal(), rhs.size() * sizeof(half))
+ .ConsumeValueOrDie();
+
+ auto lhs_buffer =
+ se::DeviceMemory<Eigen::half>(owning_lhs_buffer.AsDeviceMemoryBase());
+ auto rhs_buffer =
+ se::DeviceMemory<Eigen::half>(owning_rhs_buffer.AsDeviceMemoryBase());
+
+ stream.ThenMemcpy(&lhs_buffer, lhs.data(), lhs_buffer.size());
+ stream.ThenMemcpy(&rhs_buffer, rhs.data(), rhs_buffer.size());
+
+ TF_CHECK_OK(stream.BlockHostUntilDone());
+
+ return F16BufferComparator::Create(lhs_buffer, compiler_, &allocator_,
+ &stream)
+ .ConsumeValueOrDie()
+ .CompareEqual(rhs_buffer)
+ .ConsumeValueOrDie();
+ }
+
+ std::unique_ptr<Backend> backend_;
+ se::StreamExecutor* stream_exec_;
+ StreamExecutorMemoryAllocator allocator_;
+ Compiler* compiler_;
+};
+
+TEST_F(BufferComparatorTest, TestNaNs) {
+ EXPECT_TRUE(CompareEqualFloatBuffers({std::nanf("")}, {std::nanf("")}));
+ // NaN values with different bit patterns should compare equal.
+ EXPECT_TRUE(CompareEqualFloatBuffers({std::nanf("")}, {std::nanf("1234")}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({std::nanf("")}, {1.}));
+}
+
+TEST_F(BufferComparatorTest, TestInfs) {
+ const auto inf = std::numeric_limits<float>::infinity();
+ EXPECT_FALSE(CompareEqualFloatBuffers({inf}, {std::nanf("")}));
+ EXPECT_TRUE(CompareEqualFloatBuffers({inf}, {inf}));
+ EXPECT_TRUE(CompareEqualFloatBuffers({inf}, {65504}));
+ EXPECT_TRUE(CompareEqualFloatBuffers({-inf}, {-65504}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({inf}, {-65504}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({-inf}, {65504}));
+
+ EXPECT_FALSE(CompareEqualFloatBuffers({inf}, {20}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({inf}, {-20}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({-inf}, {20}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({-inf}, {-20}));
+}
+
+TEST_F(BufferComparatorTest, TestNumbers) {
+ EXPECT_TRUE(CompareEqualFloatBuffers({20}, {20.1}));
+ EXPECT_FALSE(CompareEqualFloatBuffers({0}, {1}));
+ EXPECT_TRUE(CompareEqualFloatBuffers({0.9}, {1}));
+ EXPECT_TRUE(CompareEqualFloatBuffers({9}, {10}));
+ EXPECT_TRUE(CompareEqualFloatBuffers({10}, {9}));
+}
+
+TEST_F(BufferComparatorTest, TestMultiple) {
+ EXPECT_TRUE(CompareEqualFloatBuffers({20, 30, 40, 50, 60},
+ {20.1, 30.1, 40.1, 50.1, 60.1}));
+ std::vector<float> lhs(200);
+ std::vector<float> rhs(200);
+ for (int i = 0; i < 200; i++) {
+ EXPECT_TRUE(CompareEqualFloatBuffers(lhs, rhs))
+ << "should be the same at index " << i;
+ lhs[i] = 3;
+ rhs[i] = 5;
+ EXPECT_FALSE(CompareEqualFloatBuffers(lhs, rhs))
+ << "should be the different at index " << i;
+ lhs[i] = 0;
+ rhs[i] = 0;
+ }
+}
+
+} // namespace
+} // namespace gpu
+} // namespace xla
diff --git a/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.cc b/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.cc
index 7348307ec8..caeb89d78e 100644
--- a/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.cc
+++ b/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.cc
@@ -16,6 +16,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/gpu/backend_configs.pb.h"
+#include "tensorflow/compiler/xla/service/gpu/buffer_comparator.h"
#include "tensorflow/compiler/xla/service/gpu/convolution_thunk.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/core/lib/gtl/optional.h"
@@ -30,7 +31,6 @@ namespace {
using se::DeviceMemoryBase;
using se::dnn::AlgorithmConfig;
using se::dnn::AlgorithmDesc;
-using tensorflow::gtl::nullopt;
using tensorflow::gtl::optional;
class ScratchAllocator : public se::ScratchAllocator {
@@ -173,11 +173,17 @@ tensorflow::mutex_lock LockGpu(const se::StreamExecutor* stream_exec) {
// cache misses and doing extra work. Overall, caching doesn't seem worth the
// trouble, but we may want to revisit this if we ever find a model where
// caching would speed up compilation a lot.
-optional<std::tuple<int64, bool, int64>>
+StatusOr<std::tuple<int64, bool, int64>>
CudnnConvolutionAlgorithmPicker::PickBestAlgorithm(
CudnnConvKind kind, const Shape& input_shape, const Shape& filter_shape,
const Shape& output_shape, const Window& window,
const ConvolutionDimensionNumbers& dnums, HloInstruction* instr) {
+ CHECK_EQ(input_shape.element_type(), filter_shape.element_type());
+ CHECK_EQ(input_shape.element_type(), output_shape.element_type());
+ // TODO(timshen): for now only check fp16. It can be expanded to other types,
+ // with some work on the HLO routines.
+ const bool cross_check_enabled = input_shape.element_type() == xla::F16;
+
// Don't run this function concurrently on the same GPU.
//
// This is a bit of a hack and doesn't protect us against arbitrary concurrent
@@ -206,51 +212,75 @@ CudnnConvolutionAlgorithmPicker::PickBestAlgorithm(
// Allocate space for the input, filter, and output of the convolution. We
// use a ScratchAllocator for this instead of calling allocator_ directly so
// that our allocations don't leak.
- //
- // We don't put any data in these buffers, because (in theory, anyway) the
- // speed of a conv isn't affected by the data being convolved.
ScratchAllocator input_output_allocator(device_ordinal, allocator);
- StatusOr<DeviceMemoryBase> maybe_input_buf =
- input_output_allocator.AllocateBytes(&stream,
- ShapeUtil::ByteSizeOf(input_shape));
- StatusOr<DeviceMemoryBase> maybe_filter_buf =
- input_output_allocator.AllocateBytes(&stream,
- ShapeUtil::ByteSizeOf(filter_shape));
- StatusOr<DeviceMemoryBase> maybe_output_buf =
- input_output_allocator.AllocateBytes(&stream,
- ShapeUtil::ByteSizeOf(output_shape));
- if (!maybe_input_buf.ok() || !maybe_filter_buf.ok() ||
- !maybe_output_buf.ok()) {
- LOG(WARNING)
- << "Couldn't allocate space for input/filter/output of convolution "
- << instr->ToString() << ". Falling back to default algorithm.";
- return nullopt;
- }
-
- DeviceMemoryBase input_buf = maybe_input_buf.ValueOrDie();
- DeviceMemoryBase filter_buf = maybe_filter_buf.ValueOrDie();
- DeviceMemoryBase output_buf = maybe_output_buf.ValueOrDie();
-
- // Although we don't have evidence this matters, zero out the buffers before
- // autotuning. It's conceivable that using uninitialized memory as the inputs
- // might affect performance if e.g. the inputs contain denormals, and this is
- // easy enough.
- if (!stream.ThenMemZero(&input_buf, input_buf.size())
- .ThenMemZero(&filter_buf, filter_buf.size())
- .ThenMemZero(&output_buf, output_buf.size())
- .BlockHostUntilDone()
- .ok()) {
- LOG(WARNING)
- << "Couldn't zero out input/filter/output buffer for convolution "
- << instr->ToString() << ". Falling back to default algorithm.";
- return nullopt;
+ TF_ASSIGN_OR_RETURN(DeviceMemoryBase input_buf,
+ input_output_allocator.AllocateBytes(
+ &stream, ShapeUtil::ByteSizeOf(input_shape)));
+ TF_ASSIGN_OR_RETURN(DeviceMemoryBase filter_buf,
+ input_output_allocator.AllocateBytes(
+ &stream, ShapeUtil::ByteSizeOf(filter_shape)));
+ TF_ASSIGN_OR_RETURN(DeviceMemoryBase output_buf,
+ input_output_allocator.AllocateBytes(
+ &stream, ShapeUtil::ByteSizeOf(output_shape)));
+
+ if (cross_check_enabled) {
+ // Broadcast a constant to the buffer, instead of zeroing the buffer. A
+ // non-zero constant is useful for the cross checking, because zero-inputs
+ // may not always reveal the bugs.
+ const auto initialize_f16 = [&stream](DeviceMemoryBase buffer) {
+ CHECK_EQ(0, (uintptr_t)buffer.opaque() % 4);
+ size_t left_over_bytes = buffer.size() % 4;
+ CHECK_EQ(0, left_over_bytes % 2);
+
+ constexpr float kBroadcastedConstant = 0.1f;
+ Eigen::half halfs[2] = {Eigen::half(kBroadcastedConstant),
+ Eigen::half(kBroadcastedConstant)};
+ uint32 bits;
+ static_assert(sizeof(bits) == sizeof(halfs), "");
+ memcpy(&bits, halfs, sizeof(bits));
+
+ size_t aligned_size = buffer.size() / 4 * 4;
+ stream.ThenMemset32(&buffer, bits, aligned_size);
+
+ DeviceMemoryBase left_over(
+ static_cast<char*>(buffer.opaque()) + aligned_size, left_over_bytes);
+ stream.ThenMemcpy(&left_over, halfs, left_over_bytes);
+ };
+ initialize_f16(input_buf);
+ initialize_f16(filter_buf);
+ initialize_f16(output_buf);
+ } else {
+ // Although we don't have evidence this matters, zero out the buffers before
+ // autotuning. It's conceivable that using uninitialized memory as the
+ // inputs might affect performance if e.g. the inputs contain denormals, and
+ // this is easy enough.
+ stream.ThenMemZero(&input_buf, input_buf.size())
+ .ThenMemZero(&filter_buf, filter_buf.size())
+ .ThenMemZero(&output_buf, output_buf.size());
}
+ TF_RETURN_IF_ERROR(stream.BlockHostUntilDone());
+
+ DeviceMemoryBase* result_buf = [&] {
+ switch (kind) {
+ case CudnnConvKind::kBackwardFilter:
+ return &filter_buf;
+ case CudnnConvKind::kBackwardInput:
+ return &input_buf;
+ case CudnnConvKind::kForward:
+ return &output_buf;
+ }
+ }();
const bool use_winograd_nonfused = ShouldIncludeWinogradNonfusedAlgo(
input_shape, output_shape, dnums, stream_exec_);
se::dnn::ProfileResult best_result;
int64 best_result_bytes_used = 0;
+ optional<F16BufferComparator> comparator;
+ // Use the first algorithm that's supported as reference. There isn't a
+ // particular reason to use it, as any algorithm sufficies. It doesn't make
+ // this algorithm considered correct, though.
+ optional<AlgorithmDesc> first_algorithm;
for (const AlgorithmDesc& alg :
GetAlgorithms(kind, use_winograd_nonfused, stream_exec_)) {
ScratchAllocator scratch_allocator(device_ordinal, allocator);
@@ -266,6 +296,42 @@ CudnnConvolutionAlgorithmPicker::PickBestAlgorithm(
.ok();
if (launch_ok && profile_result.is_valid()) {
+ const bool crash_on_checking_failure =
+ instr->GetModule()
+ ->config()
+ .debug_options()
+ .xla_gpu_crash_on_verification_failures();
+ if (comparator.has_value()) {
+ StatusOr<bool> result = comparator->CompareEqual(
+ se::DeviceMemory<Eigen::half>(*result_buf));
+ if (!result.ok()) {
+ LOG(ERROR) << "Unable to compare "
+ << AlgorithmToString(*first_algorithm) << " against "
+ << AlgorithmToString(alg) << " for " << instr->ToString()
+ << ": " << result.status();
+ CHECK(!crash_on_checking_failure);
+ } else if (!result.ValueOrDie()) {
+ LOG(ERROR) << "Results mismatch between different convolution "
+ "algorithms. This is likely a bug in convolution, or "
+ "an excessive loss of precision in convolution. "
+ << instr->ToString() << " for "
+ << AlgorithmToString(*first_algorithm) << " vs "
+ << AlgorithmToString(alg);
+ CHECK(!crash_on_checking_failure);
+ }
+ } else if (cross_check_enabled) {
+ auto comp = F16BufferComparator::Create(
+ se::DeviceMemory<Eigen::half>(*result_buf), compiler_, allocator,
+ &stream);
+ if (comp.ok()) {
+ comparator.emplace(comp.ConsumeValueOrDie());
+ first_algorithm.emplace(alg);
+ } else {
+ LOG(ERROR) << "Fail to initialize buffer comparator: "
+ << comp.status() << ", instruction: " << instr->ToString();
+ CHECK(!crash_on_checking_failure);
+ }
+ }
int64 scratch_bytes_used = scratch_allocator.TotalAllocatedBytes();
VLOG(3) << "Run of algorithm " << AlgorithmToString(alg)
<< " succeeded, taking " << profile_result.elapsed_time_in_ms()
@@ -292,9 +358,10 @@ CudnnConvolutionAlgorithmPicker::PickBestAlgorithm(
best_result_bytes_used);
}
- LOG(WARNING) << "All algorithms tried for convolution " << instr->ToString()
- << " failed. Falling back to default algorithm.";
- return nullopt;
+ return InternalError(
+ "All algorithms tried for convolution %s failed. Falling back to "
+ "default algorithm.",
+ instr->ToString().c_str());
}
StatusOr<bool> CudnnConvolutionAlgorithmPicker::RunOnInstruction(
@@ -305,12 +372,13 @@ StatusOr<bool> CudnnConvolutionAlgorithmPicker::RunOnInstruction(
const auto& lhs_shape = instr->operand(0)->shape();
const auto& rhs_shape = instr->operand(1)->shape();
const auto& conv_result_shape = instr->shape().tuple_shapes(0);
- optional<std::tuple<int64, bool, int64>> alg_scratch_and_tc;
+ StatusOr<std::tuple<int64, bool, int64>> alg_scratch_and_tc;
if (call_target == kCudnnConvForwardCallTarget) {
- alg_scratch_and_tc = PickBestAlgorithm(
- CudnnConvKind::kForward, /*input_shape=*/lhs_shape,
- /*filter_shape=*/rhs_shape, /*output_shape=*/conv_result_shape,
- instr->window(), instr->convolution_dimension_numbers(), instr);
+ alg_scratch_and_tc =
+ PickBestAlgorithm(CudnnConvKind::kForward, /*input_shape=*/lhs_shape,
+ /*filter_shape=*/rhs_shape,
+ /*output_shape=*/conv_result_shape, instr->window(),
+ instr->convolution_dimension_numbers(), instr);
} else if (call_target == kCudnnConvBackwardInputCallTarget) {
alg_scratch_and_tc = PickBestAlgorithm(
CudnnConvKind::kBackwardInput, /*input_shape=*/conv_result_shape,
@@ -326,7 +394,8 @@ StatusOr<bool> CudnnConvolutionAlgorithmPicker::RunOnInstruction(
<< instr->ToString();
}
- if (!alg_scratch_and_tc.has_value()) {
+ if (!alg_scratch_and_tc.ok()) {
+ LOG(ERROR) << alg_scratch_and_tc.status();
return false;
}
@@ -334,7 +403,8 @@ StatusOr<bool> CudnnConvolutionAlgorithmPicker::RunOnInstruction(
bool tensor_ops_enabled;
int64 scratch_bytes;
- std::tie(algorithm, tensor_ops_enabled, scratch_bytes) = *alg_scratch_and_tc;
+ std::tie(algorithm, tensor_ops_enabled, scratch_bytes) =
+ alg_scratch_and_tc.ConsumeValueOrDie();
VLOG(1) << "Setting cudnn conv to use algorithm " << algorithm << " and "
<< NumBytesToString(scratch_bytes)
diff --git a/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h b/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h
index bc5d1ce94a..8b7749628a 100644
--- a/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h
+++ b/tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h
@@ -16,6 +16,7 @@ limitations under the License.
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUDNN_CONVOLUTION_ALGORITHM_PICKER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUDNN_CONVOLUTION_ALGORITHM_PICKER_H_
+#include "tensorflow/compiler/xla/service/compiler.h"
#include "tensorflow/compiler/xla/service/device_memory_allocator.h"
#include "tensorflow/compiler/xla/service/gpu/cudnn_convolution_runner.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
@@ -34,8 +35,9 @@ class CudnnConvolutionAlgorithmPicker : public HloPassInterface {
// memory while timing the various convolution algorithms. If it's null,
// we'll use the default allocator on the StreamExecutor.
CudnnConvolutionAlgorithmPicker(se::StreamExecutor* stream_exec,
- DeviceMemoryAllocator* allocator)
- : stream_exec_(stream_exec), allocator_(allocator) {}
+ DeviceMemoryAllocator* allocator,
+ Compiler* compiler)
+ : stream_exec_(stream_exec), allocator_(allocator), compiler_(compiler) {}
tensorflow::StringPiece name() const override {
return "cudnn-convolution-algorithm-picker";
@@ -46,13 +48,14 @@ class CudnnConvolutionAlgorithmPicker : public HloPassInterface {
private:
StatusOr<bool> RunOnComputation(HloComputation* computation);
StatusOr<bool> RunOnInstruction(HloInstruction* instr);
- tensorflow::gtl::optional<std::tuple<int64, bool, int64>> PickBestAlgorithm(
+ StatusOr<std::tuple<int64, bool, int64>> PickBestAlgorithm(
CudnnConvKind kind, const Shape& input_shape, const Shape& filter_shape,
const Shape& output_shape, const Window& window,
const ConvolutionDimensionNumbers& dnums, HloInstruction* instr);
se::StreamExecutor* stream_exec_; // never null
DeviceMemoryAllocator* allocator_; // may be null
+ Compiler* compiler_;
};
} // namespace gpu
diff --git a/tensorflow/compiler/xla/service/gpu/cudnn_convolution_runner.cc b/tensorflow/compiler/xla/service/gpu/cudnn_convolution_runner.cc
index 0645fbb3ad..7b0d9e53d6 100644
--- a/tensorflow/compiler/xla/service/gpu/cudnn_convolution_runner.cc
+++ b/tensorflow/compiler/xla/service/gpu/cudnn_convolution_runner.cc
@@ -96,15 +96,9 @@ Status RunCudnnConvolution(
// tensorflow/python/ops/nn_ops.py).
const int effective_num_dimensions = std::max(2, num_dimensions);
- if (std::is_same<T, float>::value) {
- CHECK_EQ(F32, output_shape.element_type())
- << ShapeUtil::HumanString(output_shape);
- } else if (std::is_same<T, Eigen::half>::value) {
- CHECK_EQ(F16, output_shape.element_type())
- << ShapeUtil::HumanString(output_shape);
- } else {
- LOG(FATAL) << ShapeUtil::HumanString(output_shape);
- }
+ CHECK_EQ(primitive_util::NativeToPrimitiveType<T>(),
+ output_shape.element_type())
+ << ShapeUtil::HumanString(output_shape);
CHECK_EQ(num_dimensions, dnums.input_spatial_dimensions_size());
CHECK_EQ(num_dimensions, dnums.kernel_spatial_dimensions_size());
@@ -246,21 +240,31 @@ Status RunCudnnConvolution(
se::dnn::AlgorithmConfig algorithm, se::Stream* stream,
se::dnn::ProfileResult* profile_result) {
PrimitiveType output_primitive_type = output_shape.element_type();
- CHECK(output_primitive_type == F32 || output_primitive_type == F16)
- << ShapeUtil::HumanString(output_shape);
- if (output_primitive_type == F32) {
- return RunCudnnConvolution(
- kind, input_shape, filter_shape, output_shape,
- se::DeviceMemory<float>(input_buf), se::DeviceMemory<float>(filter_buf),
- se::DeviceMemory<float>(output_buf), scratch_allocator, window, dnums,
- algorithm, stream, profile_result);
+ switch (output_primitive_type) {
+ case F16:
+ return RunCudnnConvolution(kind, input_shape, filter_shape, output_shape,
+ se::DeviceMemory<Eigen::half>(input_buf),
+ se::DeviceMemory<Eigen::half>(filter_buf),
+ se::DeviceMemory<Eigen::half>(output_buf),
+ scratch_allocator, window, dnums, algorithm,
+ stream, profile_result);
+ case F32:
+ return RunCudnnConvolution(kind, input_shape, filter_shape, output_shape,
+ se::DeviceMemory<float>(input_buf),
+ se::DeviceMemory<float>(filter_buf),
+ se::DeviceMemory<float>(output_buf),
+ scratch_allocator, window, dnums, algorithm,
+ stream, profile_result);
+ case F64:
+ return RunCudnnConvolution(kind, input_shape, filter_shape, output_shape,
+ se::DeviceMemory<double>(input_buf),
+ se::DeviceMemory<double>(filter_buf),
+ se::DeviceMemory<double>(output_buf),
+ scratch_allocator, window, dnums, algorithm,
+ stream, profile_result);
+ default:
+ LOG(FATAL) << ShapeUtil::HumanString(output_shape);
}
- return RunCudnnConvolution(kind, input_shape, filter_shape, output_shape,
- se::DeviceMemory<Eigen::half>(input_buf),
- se::DeviceMemory<Eigen::half>(filter_buf),
- se::DeviceMemory<Eigen::half>(output_buf),
- scratch_allocator, window, dnums, algorithm,
- stream, profile_result);
}
} // namespace gpu
diff --git a/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.cc b/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.cc
index cc38db27e2..9b6de115ad 100644
--- a/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.cc
+++ b/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.cc
@@ -210,11 +210,13 @@ StatusOr<llvm::Value*> GpuElementalIrEmitter::EmitPowerOp(
return make_sqrt();
}
- if (hlo_module_config_.debug_options().xla_enable_fast_math() &&
- IsFPLiteralWithValue(rhs, -.5)) {
+ if (IsFPLiteralWithValue(rhs, -.5)) {
VLOG(10) << "emitting pow(A, -.5) as 1/sqrt(A): " << op->ToString();
// LLVM's NVPTX backend knows how to transform 1/sqrt(A) into the NVPTX
// rsqrt.approx instruction.
+ //
+ // TODO(jlebar): Does this happen with fastmath disabled? If not, should
+ // we force-enable it?
TF_ASSIGN_OR_RETURN(auto* sqrt, make_sqrt());
return b_->CreateFDiv(llvm::ConstantFP::get(llvm_ty, 1), sqrt);
}
@@ -272,27 +274,20 @@ StatusOr<llvm::Value*> GpuElementalIrEmitter::EmitAtan2(
prim_type);
}
-StatusOr<llvm::Value*> GpuElementalIrEmitter::EmitFloatUnaryOp(
- const HloInstruction* op, llvm::Value* operand_value) const {
- PrimitiveType input_type = op->operand(0)->shape().element_type();
- PrimitiveType output_type = op->shape().element_type();
- switch (op->opcode()) {
- case HloOpcode::kTanh:
- // If we don't care much about precision, emit a fast approximation of
- // tanh.
- if (hlo_module_config_.debug_options().xla_enable_fast_math()) {
- // Upcast F16 to F32 if necessary.
- llvm::Type* type =
- input_type == F16 ? b_->getFloatTy() : operand_value->getType();
- llvm::Value* input = b_->CreateFPCast(operand_value, type);
- llvm::Value* fast_tanh = llvm_ir::EmitFastTanh(b_, input);
- return b_->CreateFPCast(fast_tanh, operand_value->getType());
- }
- return EmitLibdeviceMathCall("__nv_tanh", {operand_value}, {input_type},
- output_type);
- default:
- return ElementalIrEmitter::EmitFloatUnaryOp(op, operand_value);
- }
+StatusOr<llvm::Value*> GpuElementalIrEmitter::EmitTanh(
+ PrimitiveType prim_type, llvm::Value* value) const {
+ // Emit a fast approximation of tanh instead of calling __nv_tanh.
+ // __nv_tanh is particularly bad because it contains branches, thus
+ // preventing LLVM's load-store vectorizer from working its magic across a
+ // function which contains tanh calls.
+ //
+ // This routine isn't numerically precise, but it's good enough for ML.
+
+ // Upcast F16 to F32 if necessary.
+ llvm::Type* type = prim_type == F16 ? b_->getFloatTy() : value->getType();
+ llvm::Value* input = b_->CreateFPCast(value, type);
+ llvm::Value* fast_tanh = llvm_ir::EmitFastTanh(b_, input);
+ return b_->CreateFPCast(fast_tanh, value->getType());
}
llvm::Value* GpuElementalIrEmitter::EmitDeviceFunctionCall(
@@ -445,6 +440,8 @@ llvm_ir::ElementGenerator GpuElementalIrEmitter::MakeElementGenerator(
return b_->CreateLoad(accum_ptr);
};
case HloOpcode::kReduce:
+ // TODO(b/112040122): This should be supported.
+ CHECK_EQ(hlo->operand_count(), 2) << "Did not expect variadic reduce";
return [=, &operand_to_generator](
const IrArray::Index& output_index) -> StatusOr<llvm::Value*> {
const HloInstruction* operand = hlo->operand(0);
diff --git a/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h b/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h
index e3eacef133..84454d31bb 100644
--- a/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h
+++ b/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h
@@ -51,9 +51,6 @@ class GpuElementalIrEmitter : public ElementalIrEmitter {
const HloToElementGeneratorMap& operand_to_generator) const override;
protected:
- StatusOr<llvm::Value*> EmitFloatUnaryOp(
- const HloInstruction* op, llvm::Value* operand_value) const override;
-
StatusOr<llvm::Value*> EmitFloatBinaryOp(
const HloInstruction* op, llvm::Value* lhs_value,
llvm::Value* rhs_value) const override;
@@ -85,6 +82,9 @@ class GpuElementalIrEmitter : public ElementalIrEmitter {
StatusOr<llvm::Value*> EmitAtan2(PrimitiveType prim_type, llvm::Value* lhs,
llvm::Value* rhs) const override;
+ StatusOr<llvm::Value*> EmitTanh(PrimitiveType prim_type,
+ llvm::Value* value) const override;
+
llvm::Value* EmitThreadId() const override;
private:
diff --git a/tensorflow/compiler/xla/service/gpu/fusion_merger.cc b/tensorflow/compiler/xla/service/gpu/fusion_merger.cc
index 3cd30b754c..9b86e5315b 100644
--- a/tensorflow/compiler/xla/service/gpu/fusion_merger.cc
+++ b/tensorflow/compiler/xla/service/gpu/fusion_merger.cc
@@ -18,6 +18,7 @@ limitations under the License.
#include <algorithm>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/service/gpu/instruction_fusion.h"
#include "tensorflow/compiler/xla/service/hlo_cost_analysis.h"
#include "tensorflow/compiler/xla/shape_util.h"
@@ -64,10 +65,11 @@ double CalculateBytesReadByFusionParameter(HloInstruction* param) {
// Slice for a more accurate estimate of bytes read.
double bytes = 0.0;
for (auto& instruction : instructions) {
- if (c_all_of(instruction->users(), [](const HloInstruction* instruction) {
- return instruction->opcode() == HloOpcode::kSlice ||
- instruction->opcode() == HloOpcode::kDynamicSlice;
- })) {
+ if (absl::c_all_of(
+ instruction->users(), [](const HloInstruction* instruction) {
+ return instruction->opcode() == HloOpcode::kSlice ||
+ instruction->opcode() == HloOpcode::kDynamicSlice;
+ })) {
// All users are slice: accumulate bytes of all user slice instructions.
for (auto& user : instruction->users()) {
bytes += ShapeUtil::ByteSizeOf(user->shape());
@@ -223,7 +225,7 @@ Status FusionInstructionMerger::HandleFusion(HloInstruction* fusion) {
// Skip 'fusion' instruction if we cannot merge into all of its users.
// Merging into all users enables the removal of 'fusion' from the
// computation.
- if (!c_all_of(fusion->users(), [](const HloInstruction* user) {
+ if (!absl::c_all_of(fusion->users(), [](const HloInstruction* user) {
return user->opcode() == HloOpcode::kFusion &&
(user->fusion_kind() == HloInstruction::FusionKind::kLoop ||
user->fusion_kind() == HloInstruction::FusionKind::kInput);
@@ -241,11 +243,11 @@ Status FusionInstructionMerger::HandleFusion(HloInstruction* fusion) {
// If 'fusion' has just one user, then an earlier fusion pass chose not to
// fuse this producer/comsumer pair (likely because of expensive instruction
// re-use by the consumer), and so we honor that choice here as well.
- if (c_any_of(fusion->fused_instructions(),
- [](const HloInstruction* instruction) {
- return instruction->opcode() != HloOpcode::kParameter &&
- GpuInstructionFusion::IsExpensive(*instruction);
- })) {
+ if (absl::c_any_of(fusion->fused_instructions(),
+ [](const HloInstruction* instruction) {
+ return instruction->opcode() != HloOpcode::kParameter &&
+ GpuInstructionFusion::IsExpensive(*instruction);
+ })) {
VLOG(3) << "Not merging " << fusion->name()
<< ": Contains one or more expensive instructions.";
++num_fail_expensive_fused_instruction_;
diff --git a/tensorflow/compiler/xla/service/gpu/gemm_thunk.h b/tensorflow/compiler/xla/service/gpu/gemm_thunk.h
index 939c7f85e3..12c81f9bfc 100644
--- a/tensorflow/compiler/xla/service/gpu/gemm_thunk.h
+++ b/tensorflow/compiler/xla/service/gpu/gemm_thunk.h
@@ -52,12 +52,12 @@ class GemmThunk : public Thunk {
se::Stream* stream,
HloExecutionProfiler* profiler) override;
- // Returns true if we'll perform autotuning if run on the given stream. If
- // so, we want the GPU to be quiescent during autotuning, so as not to
- // introduce noise in our results.
- bool ShouldHaltAllActivityBeforeRunning(se::Stream* stream) override {
- return autotune_results_.count(
- stream->parent()->GetDeviceDescription().name()) != 0;
+ bool WillAutotuneKernel(se::Stream* stream) override {
+ // We will autotune this kernel if we don't already have a autotune result
+ // for the stream device.
+ return autotune_results_.find(
+ stream->parent()->GetDeviceDescription().name()) ==
+ autotune_results_.end();
}
private:
@@ -75,6 +75,8 @@ class GemmThunk : public Thunk {
// results. The map's value is the best algorithm we've found for this thunk
// on this device, or an error if none of the algorithms worked and we should
// use the regular gemm without an algorithm.
+ //
+ // TODO(b/112415150): Make this thread safe.
std::unordered_map<string, StatusOr<se::blas::AlgorithmType>>
autotune_results_;
};
diff --git a/tensorflow/compiler/xla/service/gpu/gpu_executable.cc b/tensorflow/compiler/xla/service/gpu/gpu_executable.cc
index bb7736efa6..7060837904 100644
--- a/tensorflow/compiler/xla/service/gpu/gpu_executable.cc
+++ b/tensorflow/compiler/xla/service/gpu/gpu_executable.cc
@@ -131,9 +131,10 @@ Status GpuExecutable::ExecuteThunks(
stream->ThenWaitFor(FindOrDie(thunk_to_finish_event, dependency).get());
}
- // If this thunk requests it, wait for all currently-executing thunks to
- // finish. This is useful e.g. if the thunk is about to perform autotuning.
- if (thunk->ShouldHaltAllActivityBeforeRunning(stream)) {
+ // If this thunk is about to autotune then wait for all currently executing
+ // thunks to finish. This reduces noise and thus the probability of
+ // choosing a suboptimal algorithm.
+ if (thunk->WillAutotuneKernel(stream)) {
TF_RETURN_IF_ERROR(main_stream->BlockHostUntilDone());
}
diff --git a/tensorflow/compiler/xla/service/gpu/ir_emitter.cc b/tensorflow/compiler/xla/service/gpu/ir_emitter.cc
index 541cacf697..7111b53944 100644
--- a/tensorflow/compiler/xla/service/gpu/ir_emitter.cc
+++ b/tensorflow/compiler/xla/service/gpu/ir_emitter.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include "tensorflow/core/platform/logging.h"
// IWYU pragma: no_include "llvm/IR/Intrinsics.gen.inc"
+#include "absl/algorithm/container.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
@@ -64,7 +65,7 @@ IrEmitter::IrEmitter(const HloModuleConfig& hlo_module_config,
hlo_module_config_(hlo_module_config) {
b_.setFastMathFlags(llvm_ir::GetFastMathFlags(
/*fast_math_enabled=*/hlo_module_config.debug_options()
- .xla_enable_fast_math()));
+ .xla_gpu_enable_fast_math()));
}
Status IrEmitter::DefaultAction(HloInstruction* hlo) {
@@ -518,7 +519,7 @@ Status IrEmitter::HandleDot(HloInstruction* dot) {
// We don't have to iterate over the batch dimensions in both arrays, simplify
// the loop nest of the rhs.
for (int i = 0; i != dnums.lhs_batch_dimensions_size(); ++i) {
- DCHECK(c_linear_search(dnums.lhs_batch_dimensions(), i));
+ DCHECK(absl::c_linear_search(dnums.lhs_batch_dimensions(), i));
rhs_index[i] = lhs_index[i];
}
@@ -632,6 +633,10 @@ Status IrEmitter::HandleParameter(HloInstruction* parameter) {
}
Status IrEmitter::HandleReduce(HloInstruction* reduce) {
+ // TODO(b/112040122): Support variadic reduce.
+ if (!ShapeUtil::IsArray(reduce->shape())) {
+ return Unimplemented("Variadic reduce is not supported on GPU");
+ }
auto arg = reduce->operand(0);
auto init_value = reduce->operand(1);
tensorflow::gtl::ArraySlice<int64> dimensions(reduce->dimensions());
diff --git a/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.cc b/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.cc
index a093ffc7c1..71c30e19a2 100644
--- a/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.cc
+++ b/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.h"
+#include "absl/algorithm/container.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
@@ -314,13 +315,13 @@ llvm::Type* GetIndexTypeForKernel(const HloInstruction* hlo, int64 launch_size,
};
// Check the size of input tensors
- if (!c_all_of(unnested_hlo->operands(), hlo_shape_in_range)) {
+ if (!absl::c_all_of(unnested_hlo->operands(), hlo_shape_in_range)) {
return i64_ty;
}
// Check the size of the internal result tensors
if (unnested_hlo->opcode() == HloOpcode::kFusion) {
- if (!c_all_of(
+ if (!absl::c_all_of(
unnested_hlo->fused_instructions_computation()->instructions(),
hlo_shape_in_range)) {
return i64_ty;
@@ -545,6 +546,11 @@ Status IrEmitterUnnested::HandleFusion(HloInstruction* fusion) {
switch (root->opcode()) {
case HloOpcode::kTuple:
case HloOpcode::kReduce: {
+ if (root->opcode() == HloOpcode::kReduce &&
+ ShapeUtil::IsTuple(root->shape())) {
+ // TODO(b/112040122): Support variadic reduce.
+ return Unimplemented("Variadic reduce is not supported on GPU");
+ }
VLOG(3) << "Emitting fused reduction to vector: " << fusion->ToString();
std::vector<std::unique_ptr<Thunk>> thunks;
ArraySlice<HloInstruction*> output_instructions =
@@ -1694,6 +1700,10 @@ Status IrEmitterUnnested::EmitReductionToVector(
}
Status IrEmitterUnnested::HandleReduce(HloInstruction* reduce) {
+ // TODO(b/112040122): Support multi-output reduce.
+ if (!ShapeUtil::IsArray(reduce->shape())) {
+ return Unimplemented("Multi-output reduce is not supported on GPU");
+ }
auto input = reduce->operand(0);
auto init_value = reduce->operand(1);
tensorflow::gtl::ArraySlice<int64> dimensions_to_reduce(reduce->dimensions());
@@ -1729,7 +1739,7 @@ Status IrEmitterUnnested::HandleReduce(HloInstruction* reduce) {
Status IrEmitterUnnested::HandleTuple(HloInstruction* tuple) {
bool all_tuple_elements_have_buffer =
- c_all_of(tuple->operands(), [&](HloInstruction* tuple_element) {
+ absl::c_all_of(tuple->operands(), [&](HloInstruction* tuple_element) {
return ir_emitter_context_->buffer_assignment()
.GetUniqueTopLevelSlice(tuple_element)
.ok();
@@ -2313,10 +2323,10 @@ std::unique_ptr<KernelThunk> IrEmitterUnnested::BuildKernelThunk(
// We'll pass a pointer to each of the elements of `buffers` to our kernel, in
// this order.
std::vector<const BufferAllocation*> non_constant_buffers;
- c_copy_if(buffers_needed, std::back_inserter(non_constant_buffers),
- [](const BufferAllocation* allocation) {
- return !allocation->is_constant();
- });
+ absl::c_copy_if(buffers_needed, std::back_inserter(non_constant_buffers),
+ [](const BufferAllocation* allocation) {
+ return !allocation->is_constant();
+ });
std::sort(non_constant_buffers.begin(), non_constant_buffers.end(),
[](const BufferAllocation* a, const BufferAllocation* b) {
@@ -2573,7 +2583,7 @@ StatusOr<std::unique_ptr<Thunk>> IrEmitterUnnested::BuildInitializerThunk(
// MemzeroThunk.
ArraySlice<uint8> literal_bytes(
reinterpret_cast<const uint8*>(literal.untyped_data()), num_bytes);
- if (c_all_of(literal_bytes, [](uint8 byte) { return byte == 0; })) {
+ if (absl::c_all_of(literal_bytes, [](uint8 byte) { return byte == 0; })) {
return {
MakeUnique<MemzeroThunk>(GetAllocationSlice(*hlo, index), nullptr)};
}
@@ -3096,7 +3106,7 @@ LaunchDimensions IrEmitterUnnested::EmitHlo021Tile(
CeilOfRatio<int64>(output_dims_in_tiles[i], kTileSize);
}
const int64 num_tiles =
- c_accumulate(output_dims_in_tiles, 1, std::multiplies<int64>());
+ absl::c_accumulate(output_dims_in_tiles, 1, std::multiplies<int64>());
LaunchDimensions launch_dimensions(num_tiles, kThreadsPerTile);
llvm::Type* index_ty =
diff --git a/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/nvptx_backend_lib.cc b/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/nvptx_backend_lib.cc
index cf44458a2e..ff4ae1f9ef 100644
--- a/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/nvptx_backend_lib.cc
+++ b/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/nvptx_backend_lib.cc
@@ -180,7 +180,7 @@ std::unique_ptr<llvm::TargetMachine> GetTargetMachine(
TargetOptions target_options = InitTargetOptionsFromCodeGenFlags();
llvm_ir::SetTargetOptions(
/*fast_math_enabled=*/hlo_module_config.debug_options()
- .xla_enable_fast_math(),
+ .xla_gpu_enable_fast_math(),
&target_options);
// Enable FMA synthesis.
diff --git a/tensorflow/compiler/xla/service/gpu/multi_output_fusion.cc b/tensorflow/compiler/xla/service/gpu/multi_output_fusion.cc
index c62bae0628..34a479b289 100644
--- a/tensorflow/compiler/xla/service/gpu/multi_output_fusion.cc
+++ b/tensorflow/compiler/xla/service/gpu/multi_output_fusion.cc
@@ -23,6 +23,7 @@ limitations under the License.
#include <string>
#include <utility>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/service/gpu/instruction_fusion.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
@@ -131,7 +132,7 @@ bool ReduceFriendlyInputLayouts(HloInstruction* instr) {
max_rank_layout = &param->shape().layout();
}
}
- return c_all_of(params, [&](HloInstruction* param) {
+ return absl::c_all_of(params, [&](HloInstruction* param) {
return (ShapeUtil::Rank(param->shape()) < max_rank) ||
(LayoutUtil::Equal(param->shape().layout(), *max_rank_layout));
});
@@ -248,7 +249,7 @@ bool GpuMultiOutputFusion::DoProducerConsumerMultiOutputFusion() {
}
// Do not fuse a producer if the other operands of the fusion are
// reachable from the producer, this would create a cycle.
- if (c_any_of(consumer_operands, [&](HloInstruction* operand) {
+ if (absl::c_any_of(consumer_operands, [&](HloInstruction* operand) {
return producer != operand &&
reachability()->IsReachable(producer, operand);
})) {
@@ -268,7 +269,7 @@ bool GpuMultiOutputFusion::DoProducerConsumerMultiOutputFusion() {
for (auto& fusion_pair : potential_fusion_list) {
HloInstruction* producer = fusion_pair.first;
HloInstruction* consumer = fusion_pair.second;
- if (!c_any_of(consumer->operands(), [&](HloInstruction* operand) {
+ if (!absl::c_any_of(consumer->operands(), [&](HloInstruction* operand) {
return producer != operand &&
reachability()->IsReachable(producer, operand);
})) {
diff --git a/tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc b/tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc
index 76c9b6ab33..6c1eab4f8c 100644
--- a/tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc
+++ b/tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc
@@ -34,6 +34,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/buffer_liveness.h"
#include "tensorflow/compiler/xla/service/call_inliner.h"
#include "tensorflow/compiler/xla/service/conditional_simplifier.h"
+#include "tensorflow/compiler/xla/service/convolution_feature_group_converter.h"
#include "tensorflow/compiler/xla/service/flatten_call_graph.h"
#include "tensorflow/compiler/xla/service/gpu/cudnn_batchnorm_rewriter.h"
#include "tensorflow/compiler/xla/service/gpu/cudnn_convolution_algorithm_picker.h"
@@ -72,6 +73,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
#include "tensorflow/compiler/xla/service/reduce_precision_insertion.h"
#include "tensorflow/compiler/xla/service/reshape_mover.h"
+#include "tensorflow/compiler/xla/service/scatter_expander.h"
#include "tensorflow/compiler/xla/service/transpose_folding.h"
#include "tensorflow/compiler/xla/service/tuple_simplifier.h"
#include "tensorflow/compiler/xla/service/while_loop_constant_sinking.h"
@@ -130,8 +132,12 @@ string GetLibdeviceDir(const string& config_cuda_data_dir) {
}
// Runs optimization passes on the given HLO module.
+//
+// It takes a compiler pointer, as passes may compile and execute HLOs on the
+// fly for cuDNN verification or other purposes.
Status OptimizeHloModule(HloModule* hlo_module, se::StreamExecutor* stream_exec,
- DeviceMemoryAllocator* device_allocator) {
+ DeviceMemoryAllocator* device_allocator,
+ Compiler* compiler) {
{
HloPassPipeline pipeline("optimization");
pipeline.AddInvariantChecker<HloVerifier>();
@@ -167,6 +173,8 @@ Status OptimizeHloModule(HloModule* hlo_module, se::StreamExecutor* stream_exec,
// elimination has to come after that pass.
pipeline.AddPass<ZeroSizedHloElimination>();
+ pipeline.AddPass<ScatterExpander>();
+
pass.AddPass<AlgebraicSimplifier>(
/*is_layout_sensitive=*/false,
[](const Shape&, const Shape&) { return false; });
@@ -196,6 +204,8 @@ Status OptimizeHloModule(HloModule* hlo_module, se::StreamExecutor* stream_exec,
// (PadInsertion).
HloPassPipeline pipeline("conv_canonicalization");
pipeline.AddInvariantChecker<HloVerifier>();
+ // TODO(b/31709653): Directly use the grouped convolution support of Cudnn.
+ pipeline.AddPass<ConvolutionFeatureGroupConverter>();
pipeline.AddPass<CudnnConvolutionRewriter>();
pipeline.AddPass<PadInsertion>();
if (IsVoltaOrLater(*stream_exec)) {
@@ -245,8 +255,8 @@ Status OptimizeHloModule(HloModule* hlo_module, se::StreamExecutor* stream_exec,
// the gte(customcall, 0) would probably already be into a fusion node. We
// can't simplify across HloComputation boundaries, so in this case we
// wouldn't be able to simplify away the new_tuple bits.
- pipeline.AddPass<CudnnConvolutionAlgorithmPicker>(stream_exec,
- device_allocator);
+ pipeline.AddPass<CudnnConvolutionAlgorithmPicker>(
+ stream_exec, device_allocator, compiler);
// Clean up new_tuple described above.
pipeline.AddPass<TupleSimplifier>();
@@ -492,11 +502,15 @@ NVPTXCompiler::NVPTXCompiler()
StatusOr<std::unique_ptr<HloModule>> NVPTXCompiler::RunHloPasses(
std::unique_ptr<HloModule> module, se::StreamExecutor* stream_exec,
DeviceMemoryAllocator* device_allocator) {
+ // We dump the post-optimization HLO in RunBackend so no need to dump it here.
+ VLOG(2) << "*** HLO Before Optimization";
+ XLA_VLOG_LINES(2, module->ToString());
+
XLA_SCOPED_LOGGING_TIMER("NVPTXCompiler::RunHloPasses");
tracing::ScopedActivity activity("HLO Transforms", module->name(),
/*is_expensive=*/true);
TF_RETURN_IF_ERROR(
- OptimizeHloModule(module.get(), stream_exec, device_allocator));
+ OptimizeHloModule(module.get(), stream_exec, device_allocator, this));
return std::move(module);
}
@@ -548,6 +562,7 @@ StatusOr<std::unique_ptr<Executable>> NVPTXCompiler::RunBackend(
// include headers, so no need for us to print them ourselves.
XLA_VLOG_LINES(1, buffer_assignment->GetStats().ToString());
XLA_VLOG_LINES(2, buffer_assignment->ToString());
+ VLOG(2) << "*** HLO After Optimization";
XLA_VLOG_LINES(2, module->ToString());
const string xla_dump_optimized_hlo_proto_to =
module->config().debug_options().xla_dump_optimized_hlo_proto_to();
diff --git a/tensorflow/compiler/xla/service/gpu/thunk.h b/tensorflow/compiler/xla/service/gpu/thunk.h
index 4df0bb005b..e68bee035a 100644
--- a/tensorflow/compiler/xla/service/gpu/thunk.h
+++ b/tensorflow/compiler/xla/service/gpu/thunk.h
@@ -82,17 +82,9 @@ class Thunk {
return Status::OK();
}
- // Users of Thunk should call ShouldHaltAllActivityBeforeRunning(stream)
- // before calling ExecuteOnStream(stream). If it returns true, it's the
- // user's responsibility to wait for all activity on the GPU to finish before
- // calling ExecuteOnStream.
- //
- // This value is not required to be constant for a given Thunk. For example,
- // a Thunk that performs autotuning may return true for its first run and
- // false thereafter.
- virtual bool ShouldHaltAllActivityBeforeRunning(se::Stream* /*stream*/) {
- return false;
- }
+ // Returns true if this kernel will autotune for the stream device the next
+ // time it is run.
+ virtual bool WillAutotuneKernel(se::Stream* /*stream*/) { return false; }
// Execute the kernel for the thunk on the given stream. This method must be
// called after Initialize and can be called multiple times over Thunk's
diff --git a/tensorflow/compiler/xla/service/hlo.proto b/tensorflow/compiler/xla/service/hlo.proto
index be9098f555..fa218657fe 100644
--- a/tensorflow/compiler/xla/service/hlo.proto
+++ b/tensorflow/compiler/xla/service/hlo.proto
@@ -34,6 +34,7 @@ import "tensorflow/compiler/xla/xla_data.proto";
option cc_enable_arenas = true;
// Serialization of HloInstruction.
+// Next ID: 51
message HloInstructionProto {
reserved 10;
reserved "parameter_name";
@@ -74,6 +75,11 @@ message HloInstructionProto {
// Describes the dimension numbers used for a convolution.
xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16;
+ // The number of feature groups. Used for a convolution. Must be a divisor of
+ // the input feature dimension and output feature dimension. If not specified,
+ // it will use a default value of 1.
+ int64 feature_group_count = 50;
+
// Describes the [begin, end) index range and stride for slices.
message SliceDimensions {
int64 start = 1;
@@ -133,7 +139,7 @@ message HloInstructionProto {
// Gather dimension numbers.
xla.GatherDimensionNumbers gather_dimension_numbers = 33;
- repeated int64 gather_window_bounds = 34;
+ repeated int64 gather_slice_sizes = 34;
// Compute Host.
string channel_name = 41;
diff --git a/tensorflow/compiler/xla/service/hlo_computation.cc b/tensorflow/compiler/xla/service/hlo_computation.cc
index 441288da1a..db853360f1 100644
--- a/tensorflow/compiler/xla/service/hlo_computation.cc
+++ b/tensorflow/compiler/xla/service/hlo_computation.cc
@@ -23,6 +23,7 @@ limitations under the License.
#include <set>
#include <sstream>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
@@ -901,9 +902,9 @@ void HloComputation::UniquifyName(NameUniquer* name_uniquer) {
HloInstruction* HloComputation::GetInstructionWithName(
tensorflow::StringPiece name) {
auto instructions_in_computation = instructions();
- auto it = c_find_if(instructions_in_computation, [&](HloInstruction* instr) {
- return instr->name() == name;
- });
+ auto it = absl::c_find_if(
+ instructions_in_computation,
+ [&](HloInstruction* instr) { return instr->name() == name; });
return it == instructions_in_computation.end() ? nullptr : *it;
}
diff --git a/tensorflow/compiler/xla/service/hlo_creation_utils.cc b/tensorflow/compiler/xla/service/hlo_creation_utils.cc
index 90d2be118d..83adaddba4 100644
--- a/tensorflow/compiler/xla/service/hlo_creation_utils.cc
+++ b/tensorflow/compiler/xla/service/hlo_creation_utils.cc
@@ -14,6 +14,7 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
@@ -149,13 +150,13 @@ StatusOr<HloInstruction*> MakeConcatHlo(ArraySlice<HloInstruction*> operands,
CHECK_GT(operands.size(), 0);
HloComputation* computation = operands[0]->parent();
- CHECK(c_all_of(operands, [&](HloInstruction* instr) {
+ CHECK(absl::c_all_of(operands, [&](HloInstruction* instr) {
return instr->parent() == computation;
}));
std::vector<const Shape*> operand_shapes;
- c_transform(operands, std::back_inserter(operand_shapes),
- [](HloInstruction* instr) { return &instr->shape(); });
+ absl::c_transform(operands, std::back_inserter(operand_shapes),
+ [](HloInstruction* instr) { return &instr->shape(); });
TF_ASSIGN_OR_RETURN(Shape concat_shape, ShapeInference::InferConcatOpShape(
operand_shapes, dimension));
@@ -174,6 +175,29 @@ StatusOr<HloInstruction*> MakeDotHlo(HloInstruction* lhs, HloInstruction* rhs,
HloInstruction::CreateDot(dot_shape, lhs, rhs, dim_numbers));
}
+StatusOr<HloInstruction*> MakeMapHlo(
+ tensorflow::gtl::ArraySlice<HloInstruction*> operands,
+ HloComputation* map_computation) {
+ CHECK(!operands.empty()) << "Map Hlo requires at least one operand.";
+ HloComputation* computation = operands.front()->parent();
+ std::vector<const Shape*> operand_shapes;
+ int64 max_operand_rank = 0;
+ for (const HloInstruction* operand : operands) {
+ CHECK_EQ(computation, operand->parent());
+ operand_shapes.push_back(&operand->shape());
+ max_operand_rank =
+ std::max(max_operand_rank, ShapeUtil::Rank(operand->shape()));
+ }
+ std::vector<int64> map_dims(max_operand_rank);
+ std::iota(map_dims.begin(), map_dims.end(), 0);
+ TF_ASSIGN_OR_RETURN(
+ Shape map_shape,
+ ShapeInference::InferMapShape(
+ operand_shapes, map_computation->ComputeProgramShape(), map_dims));
+ return computation->AddInstruction(
+ HloInstruction::CreateMap(map_shape, operands, map_computation));
+}
+
StatusOr<HloInstruction*> CollapseFirstNDims(HloInstruction* operand, int64 n) {
CHECK_GT(n, 0);
@@ -205,7 +229,7 @@ StatusOr<HloInstruction*> PrependDegenerateDims(HloInstruction* operand,
const Shape& operand_shape = operand->shape();
new_shape_dims.reserve(n + operand_shape.dimensions_size());
new_shape_dims.insert(new_shape_dims.begin(), n, 1);
- c_copy(operand_shape.dimensions(), std::back_inserter(new_shape_dims));
+ absl::c_copy(operand_shape.dimensions(), std::back_inserter(new_shape_dims));
return MakeReshapeHlo(new_shape_dims, operand);
}
@@ -217,7 +241,7 @@ StatusOr<HloInstruction*> ExpandFirstDimIntoNDims(
std::vector<int64> expanded_shape_dim_bounds;
expanded_shape_dim_bounds.reserve(expanded_dims.size() +
operand->shape().dimensions_size() - 1);
- c_copy(expanded_dims, std::back_inserter(expanded_shape_dim_bounds));
+ absl::c_copy(expanded_dims, std::back_inserter(expanded_shape_dim_bounds));
std::copy(operand->shape().dimensions().begin() + 1,
operand->shape().dimensions().end(),
std::back_inserter(expanded_shape_dim_bounds));
@@ -228,7 +252,7 @@ StatusOr<HloInstruction*> ExpandFirstDimIntoNDims(
StatusOr<HloInstruction*> ElideDegenerateDims(HloInstruction* operand,
ArraySlice<int64> dims_to_elide) {
- CHECK(c_is_sorted(dims_to_elide));
+ CHECK(absl::c_is_sorted(dims_to_elide));
const Shape& input_shape = operand->shape();
// First accumulate in reverse
@@ -245,12 +269,44 @@ StatusOr<HloInstruction*> ElideDegenerateDims(HloInstruction* operand,
}
}
- c_reverse(new_shape_dim_bounds);
+ absl::c_reverse(new_shape_dim_bounds);
Shape output_shape =
ShapeUtil::MakeShape(input_shape.element_type(), new_shape_dim_bounds);
return MakeReshapeHlo(output_shape, operand);
}
+StatusOr<HloInstruction*> InsertDegenerateDims(
+ HloInstruction* operand, ArraySlice<int64> dims_to_insert) {
+ CHECK(absl::c_is_sorted(dims_to_insert));
+
+ const Shape& operand_shape = operand->shape();
+ int64 output_shape_rank =
+ operand_shape.dimensions_size() + dims_to_insert.size();
+ for (auto dim_to_insert : dims_to_insert) {
+ CHECK_LT(dim_to_insert, output_shape_rank);
+ }
+
+ std::vector<int64> output_shape_dim_bounds;
+ output_shape_dim_bounds.reserve(output_shape_rank);
+ int64 operand_dims_idx = 0;
+ int64 dims_to_insert_idx = 0;
+ for (int64 i = 0; i < output_shape_rank; ++i) {
+ if (dims_to_insert_idx < dims_to_insert.size() &&
+ i == dims_to_insert[dims_to_insert_idx]) {
+ output_shape_dim_bounds.push_back(1);
+ ++dims_to_insert_idx;
+ } else {
+ output_shape_dim_bounds.push_back(
+ operand_shape.dimensions(operand_dims_idx));
+ ++operand_dims_idx;
+ }
+ }
+
+ Shape output_shape = ShapeUtil::MakeShape(operand_shape.element_type(),
+ output_shape_dim_bounds);
+ return MakeReshapeHlo(output_shape, operand);
+}
+
StatusOr<HloInstruction*> PadVectorWithZeros(HloInstruction* operand,
int64 zeros_to_prepend,
int64 zeros_to_append) {
diff --git a/tensorflow/compiler/xla/service/hlo_creation_utils.h b/tensorflow/compiler/xla/service/hlo_creation_utils.h
index 49b1402d68..5ff8946fb0 100644
--- a/tensorflow/compiler/xla/service/hlo_creation_utils.h
+++ b/tensorflow/compiler/xla/service/hlo_creation_utils.h
@@ -102,6 +102,12 @@ StatusOr<HloInstruction*> MakeConcatHlo(
StatusOr<HloInstruction*> MakeDotHlo(HloInstruction* lhs, HloInstruction* rhs,
const DotDimensionNumbers& dim_numbers);
+// Creates a Map HLO instruction and adds it to the computation containing the
+// operands. All operands must be in the same computation.
+StatusOr<HloInstruction*> MakeMapHlo(
+ tensorflow::gtl::ArraySlice<HloInstruction*> operands,
+ HloComputation* map_computation);
+
// -----------------------------------------------------------------------------
// Some other miscellaneous helpers to generate common HLO patterns. All of
// these add all the instructions they generate into the computation containing
@@ -144,6 +150,16 @@ StatusOr<HloInstruction*> ExpandFirstDimIntoNDims(
StatusOr<HloInstruction*> ElideDegenerateDims(
HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> dims_to_elide);
+// Inserts (via reshape) a set of degenerate dimensions (dimensions containing
+// exactly one element), `dims_to_insert` into `operand`. The dimensions in
+// `dims_to_insert` refer to the dimensions in the result, and hence should be
+// less than the rank of the result. Also, `dims_to_insert` must be sorted.
+//
+// For example, if `operand` is of shape f32[12,21,8,34] and dims_to_insert is
+// {0, 2}, then the result is `operand` reshaped to [1,12,1,21,8,34].
+StatusOr<HloInstruction*> InsertDegenerateDims(
+ HloInstruction* operand, tensorflow::gtl::ArraySlice<int64> dims_to_insert);
+
// Pads `operand` (which must have rank 1) with `zeros_to_prepend` zeros in the
// front and `zeros_to_append` zeros in the back.
StatusOr<HloInstruction*> PadVectorWithZeros(HloInstruction* operand,
diff --git a/tensorflow/compiler/xla/service/hlo_creation_utils_test.cc b/tensorflow/compiler/xla/service/hlo_creation_utils_test.cc
index 60d3e71757..d123dbb1a0 100644
--- a/tensorflow/compiler/xla/service/hlo_creation_utils_test.cc
+++ b/tensorflow/compiler/xla/service/hlo_creation_utils_test.cc
@@ -28,7 +28,7 @@ using tensorflow::gtl::ArraySlice;
class HloCreationUtilsTest : public HloTestBase {
protected:
- static std::unique_ptr<HloModule> CreateModuleWithProgramShape(
+ std::unique_ptr<HloModule> CreateModuleWithProgramShape(
PrimitiveType primitive_type, ArraySlice<int64> input_shape_dims,
ArraySlice<int64> output_shape_dims, HloInstruction** param,
HloComputation** entry_computation) {
diff --git a/tensorflow/compiler/xla/service/hlo_domain_test.cc b/tensorflow/compiler/xla/service/hlo_domain_test.cc
index ffc18a0f88..70271be304 100644
--- a/tensorflow/compiler/xla/service/hlo_domain_test.cc
+++ b/tensorflow/compiler/xla/service/hlo_domain_test.cc
@@ -490,5 +490,38 @@ TEST_F(HloDomainTest, DumpParseNullSharding) {
ASSERT_TRUE(ParseModule(hlo_string).status().ok());
}
+TEST_F(HloDomainTest, DomainTuple) {
+ const char* const hlo_string = R"(
+HloModule Module
+
+ENTRY entry {
+ p0 = f32[4] parameter(0), sharding={maximal device=0}
+ cst = u32[] constant(0), sharding={maximal device=1}
+ tpl = (u32[], f32[4]) tuple(cst, p0), sharding={{maximal device=1}, {maximal device=0}}
+ ROOT gte = f32[4] get-tuple-element(tpl), index=1, sharding={maximal device=0}
+}
+)";
+
+ TF_ASSERT_OK_AND_ASSIGN(HloModule * module, ParseModule(hlo_string));
+
+ HloDomainIsolator isolator(CreateShardingDomain);
+ TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module));
+ EXPECT_TRUE(isolator_changed);
+
+ // Clear sharding of tpl instruction, in order to test domain sharding
+ // application.
+ auto tpl = FindInstruction(module, "tpl");
+ tpl->clear_sharding();
+
+ HloDomainRemover remover(ShardingMetadata::KindName(),
+ ShardingMetadata::NormalizeShardingDomain);
+ TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module));
+ EXPECT_TRUE(remover_changed);
+
+ EXPECT_EQ(HloSharding::Tuple(tpl->shape(), {HloSharding::AssignDevice(1),
+ HloSharding::AssignDevice(0)}),
+ tpl->sharding());
+}
+
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/service/hlo_element_type_converter.cc b/tensorflow/compiler/xla/service/hlo_element_type_converter.cc
index c804f4364f..b9244b8e9e 100644
--- a/tensorflow/compiler/xla/service/hlo_element_type_converter.cc
+++ b/tensorflow/compiler/xla/service/hlo_element_type_converter.cc
@@ -144,6 +144,7 @@ StatusOr<bool> HloElementTypeConverter::Run(HloModule* module) {
opcode == HloOpcode::kCrossReplicaSum ||
opcode == HloOpcode::kFusion || opcode == HloOpcode::kMap ||
opcode == HloOpcode::kReduce || opcode == HloOpcode::kReduceWindow ||
+ opcode == HloOpcode::kScatter ||
opcode == HloOpcode::kSelectAndScatter ||
opcode == HloOpcode::kConditional) {
continue;
diff --git a/tensorflow/compiler/xla/service/hlo_evaluator.cc b/tensorflow/compiler/xla/service/hlo_evaluator.cc
index 51353eea6e..0455c7f41a 100644
--- a/tensorflow/compiler/xla/service/hlo_evaluator.cc
+++ b/tensorflow/compiler/xla/service/hlo_evaluator.cc
@@ -23,6 +23,7 @@ limitations under the License.
#include <utility>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/index_util.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
@@ -555,43 +556,41 @@ Status HloEvaluator::HandleTuple(HloInstruction* tuple) {
return Status::OK();
}
-// Returns an ShapeUtil::IndexIterationSpace that iterates over the output
-// gather dimensions while keeping the rest of the output dimensions clamped to
-// 0.
-ShapeUtil::IndexIterationSpace IterationSpaceForOutputGatherIndices(
+// Returns an ShapeUtil::IndexIterationSpace that iterates over the output batch
+// dimensions while keeping the rest of the output dimensions clamped to 0.
+ShapeUtil::IndexIterationSpace IterationSpaceForOutputBatchIndices(
const Shape& output_shape, const GatherDimensionNumbers& dim_numbers) {
int64 output_rank = output_shape.dimensions_size();
std::vector<int64> index_base(output_rank, 0);
std::vector<int64> index_count;
index_count.reserve(output_rank);
for (int64 i = 0; i < output_rank; i++) {
- bool is_output_gather_dim =
- !c_binary_search(dim_numbers.output_window_dims(), i);
- index_count.push_back(is_output_gather_dim ? output_shape.dimensions(i)
- : 1);
+ bool is_output_batch_dim =
+ !absl::c_binary_search(dim_numbers.offset_dims(), i);
+ index_count.push_back(is_output_batch_dim ? output_shape.dimensions(i) : 1);
}
return {std::move(index_base), std::move(index_count),
std::vector<int64>(output_rank, 1)};
}
-// Return an ShapeUtil::IndexIterationSpace that iterates over the output window
+// Return an ShapeUtil::IndexIterationSpace that iterates over the output slice
// dimensions while keeping the rest of the output dimensions clamped to 0.
-ShapeUtil::IndexIterationSpace IterationSpaceForOutputWindowIndices(
- int64 output_rank, ArraySlice<int64> window_bounds,
+ShapeUtil::IndexIterationSpace IterationSpaceForOutputOffsetIndices(
+ int64 output_rank, ArraySlice<int64> slice_sizes,
const GatherDimensionNumbers& dim_numbers) {
std::vector<int64> index_base(output_rank, 0);
std::vector<int64> index_count(output_rank, 1);
- int64 window_bounds_idx = 0;
+ int64 slice_sizes_idx = 0;
for (int64 i = 0; i < output_rank; i++) {
bool is_output_window_dim =
- c_binary_search(dim_numbers.output_window_dims(), i);
+ absl::c_binary_search(dim_numbers.offset_dims(), i);
if (is_output_window_dim) {
- while (c_binary_search(dim_numbers.elided_window_dims(),
- window_bounds_idx)) {
- window_bounds_idx++;
+ while (absl::c_binary_search(dim_numbers.collapsed_slice_dims(),
+ slice_sizes_idx)) {
+ slice_sizes_idx++;
}
- index_count[i] = window_bounds[window_bounds_idx++];
+ index_count[i] = slice_sizes[slice_sizes_idx++];
}
}
@@ -599,30 +598,30 @@ ShapeUtil::IndexIterationSpace IterationSpaceForOutputWindowIndices(
std::vector<int64>(output_rank, 1)};
}
-// This functor computes the contribution of gather_indices to an input index
+// This functor computes the contribution of start_indices to an input index
// corresponding to an output index. That is, given an output index I, it picks
-// out the gather output indices in I and uses them to look up a gather index,
-// G, from the gather indices tensor, and expands G into the input space
-// according to gather_dims_to_operand_dims.
-class OutputGatherIndexToInputIndex {
+// out the batch indices in I and uses them to look up a starting index, G, from
+// the start indices tensor, and expands G into the input space according to
+// start_index_map.
+class OutputBatchIndexToInputIndex {
public:
// The constructor does some setup work that is amortized across all
// iterations.
- explicit OutputGatherIndexToInputIndex(
+ explicit OutputBatchIndexToInputIndex(
const GatherDimensionNumbers* dim_numbers, const Shape& input_shape,
- const Shape& output_shape, const Literal* gather_indices)
- : dim_numbers_(*dim_numbers), gather_indices_(*gather_indices) {
+ const Shape& output_shape, const Literal* start_indices)
+ : dim_numbers_(*dim_numbers), start_indices_(*start_indices) {
for (int64 i = 0; i < output_shape.dimensions_size(); i++) {
- output_dim_is_gather_dims_.push_back(
- !c_binary_search(dim_numbers_.output_window_dims(), i));
+ output_dim_is_batch_dims_.push_back(
+ !absl::c_binary_search(dim_numbers_.offset_dims(), i));
}
for (int64 i = 0; i < input_shape.dimensions_size(); i++) {
int64 index_of_input_dim_in_index_vector =
- std::distance(dim_numbers_.gather_dims_to_operand_dims().begin(),
- c_find(dim_numbers_.gather_dims_to_operand_dims(), i));
+ std::distance(dim_numbers_.start_index_map().begin(),
+ absl::c_find(dim_numbers_.start_index_map(), i));
if (index_of_input_dim_in_index_vector ==
- dim_numbers_.gather_dims_to_operand_dims_size()) {
+ dim_numbers_.start_index_map_size()) {
input_dim_value_to_index_vector_.push_back(-1);
} else {
input_dim_value_to_index_vector_.push_back(
@@ -630,14 +629,14 @@ class OutputGatherIndexToInputIndex {
}
}
- index_vector_index_.resize(gather_indices_.shape().dimensions_size());
+ index_vector_index_.resize(start_indices_.shape().dimensions_size());
input_index_.resize(input_shape.dimensions_size());
int64 index_vector_size =
- gather_indices_.shape().dimensions(dim_numbers_.index_vector_dim());
+ start_indices_.shape().dimensions(dim_numbers_.index_vector_dim());
index_vector_.resize(index_vector_size);
}
- // Returns the contribution of gather_indices to the input index corresponding
+ // Returns the contribution of start_indices to the input index corresponding
// to output_index. See gather_inner_loop_body.
//
// This is conceptually a stateless transformation from output_index to the
@@ -659,7 +658,7 @@ class OutputGatherIndexToInputIndex {
}
private:
- // Propagates the gather index dimensions from the output index into
+ // Propagates the batch dimensions from the output index into
// index_vector_index_ by mutating index_vector_index_ in place. Does not
// update the dim_numbers.index_vector_dim() dimension -- that's the dimension
// we iterate over in FetchIndexVector.
@@ -667,7 +666,7 @@ class OutputGatherIndexToInputIndex {
ArraySlice<int64> output_index) {
int64 index_vector_index_i = 0;
for (int64 i = 0, e = output_index.size(); i < e; i++) {
- if (!output_dim_is_gather_dims_[i]) {
+ if (!output_dim_is_batch_dims_[i]) {
continue;
}
@@ -679,14 +678,14 @@ class OutputGatherIndexToInputIndex {
}
}
- // Populates index_vector_ by iterating over gather_indices_ according to
+ // Populates index_vector_ by iterating over start_indices_ according to
// index_vector_index_.
Status FetchIndexVector() {
int64 index_vector_dim = dim_numbers_.index_vector_dim();
for (int64 i = 0, e = index_vector_.size(); i < e; i++) {
index_vector_index_[index_vector_dim] = i;
- TF_ASSIGN_OR_RETURN(index_vector_[i], gather_indices_.GetIntegralAsS64(
- index_vector_index_));
+ TF_ASSIGN_OR_RETURN(index_vector_[i],
+ start_indices_.GetIntegralAsS64(index_vector_index_));
}
return Status::OK();
}
@@ -708,15 +707,15 @@ class OutputGatherIndexToInputIndex {
// PropagateIndexVectorToInputIndex.
std::vector<int64> input_dim_value_to_index_vector_;
- // output_dim_is_gather_dims_[i] is true iff the output index i is a gather
+ // output_dim_is_batch_dims_[i] is true iff the output index i is a gather
// dimension.
- std::vector<bool> output_dim_is_gather_dims_;
+ std::vector<bool> output_dim_is_batch_dims_;
- // The buffer into which we construct an index into gather_indices_ to fetch
+ // The buffer into which we construct an index into start_indices_ to fetch
// the index vector.
std::vector<int64> index_vector_index_;
- // The index vector fetched from gather_indices_.
+ // The index vector fetched from start_indices_.
std::vector<int64> index_vector_;
// The result computed by this functor. operator() returns an ArraySlice into
@@ -724,24 +723,23 @@ class OutputGatherIndexToInputIndex {
std::vector<int64> input_index_;
const GatherDimensionNumbers& dim_numbers_;
- const Literal& gather_indices_;
+ const Literal& start_indices_;
};
-// This functor computes the contribution of the window indices in an output
+// This functor computes the contribution of the offset indices in an output
// index to an input index. That is, given an output index I it picks out the
-// output window indices in I and expands it into a window index into the input
-// shape.
-class OutputWindowIndexToInputIndex {
+// output offset indices in I and expands it into an index into the input shape.
+class OutputOffsetIndexToInputIndex {
public:
// The constructor does some setup work that is amortized across all
// iterations.
- explicit OutputWindowIndexToInputIndex(
+ explicit OutputOffsetIndexToInputIndex(
const GatherDimensionNumbers& dim_numbers, const Shape& input_shape,
const Shape& output_shape) {
std::vector<int64> window_index_to_output_index;
int64 output_index_count = 0;
for (int64 i = 0; i < output_shape.dimensions_size(); i++) {
- if (c_binary_search(dim_numbers.output_window_dims(), i)) {
+ if (absl::c_binary_search(dim_numbers.offset_dims(), i)) {
window_index_to_output_index.push_back(output_index_count++);
} else {
output_index_count++;
@@ -750,7 +748,7 @@ class OutputWindowIndexToInputIndex {
int64 window_dim_count = 0;
for (int64 i = 0; i < input_shape.dimensions_size(); i++) {
- if (c_binary_search(dim_numbers.elided_window_dims(), i)) {
+ if (absl::c_binary_search(dim_numbers.collapsed_slice_dims(), i)) {
input_dim_value_to_output_index_.push_back(-1);
} else {
input_dim_value_to_output_index_.push_back(
@@ -808,20 +806,20 @@ class OutputWindowIndexToInputIndex {
// Rehapes the gather indices input to have a trailing degenerate `1` dimension
// if necessary. Hands over the ownership of the newly created literal (if
-// there is one) to `reshaped_gather_indices`.
+// there is one) to `reshaped_start_indices`.
static StatusOr<std::reference_wrapper<const Literal>> ReshapedGatherIndices(
- int64 index_vector_dim, const Literal& gather_indices,
- std::unique_ptr<Literal>* reshaped_gather_indices) {
- if (gather_indices.shape().dimensions_size() != index_vector_dim) {
- return std::cref(gather_indices);
+ int64 index_vector_dim, const Literal& start_indices,
+ std::unique_ptr<Literal>* reshaped_start_indices) {
+ if (start_indices.shape().dimensions_size() != index_vector_dim) {
+ return std::cref(start_indices);
}
- std::vector<int64> new_shape(gather_indices.shape().dimensions().begin(),
- gather_indices.shape().dimensions().end());
+ std::vector<int64> new_shape(start_indices.shape().dimensions().begin(),
+ start_indices.shape().dimensions().end());
new_shape.push_back(1);
- TF_ASSIGN_OR_RETURN(*reshaped_gather_indices,
- gather_indices.Reshape(new_shape));
- return std::cref(**reshaped_gather_indices);
+ TF_ASSIGN_OR_RETURN(*reshaped_start_indices,
+ start_indices.Reshape(new_shape));
+ return std::cref(**reshaped_start_indices);
}
Status HloEvaluator::HandleGather(HloInstruction* gather) {
@@ -830,34 +828,33 @@ Status HloEvaluator::HandleGather(HloInstruction* gather) {
const GatherDimensionNumbers& dim_numbers =
gather->gather_dimension_numbers();
const Literal& operand = GetEvaluatedLiteralFor(gather->operand(0));
- std::unique_ptr<Literal> reshaped_gather_indices;
+ std::unique_ptr<Literal> reshaped_start_indices;
TF_ASSIGN_OR_RETURN(
- const Literal& gather_indices,
+ const Literal& start_indices,
ReshapedGatherIndices(dim_numbers.index_vector_dim(),
GetEvaluatedLiteralFor(gather->operand(1)),
- &reshaped_gather_indices));
+ &reshaped_start_indices));
// We iterate over the gather dimensions in the output shape in an outer loop
// nest, and iterate over the window dimensions in the output shape in an
// inner loop nest.
- ShapeUtil::IndexIterationSpace gather_indices_iteration_space =
- IterationSpaceForOutputGatherIndices(shape, dim_numbers);
- ShapeUtil::IndexIterationSpace window_indices_iteration_space =
- IterationSpaceForOutputWindowIndices(
- shape.dimensions_size(), gather->gather_window_bounds(), dim_numbers);
+ ShapeUtil::IndexIterationSpace start_indices_iteration_space =
+ IterationSpaceForOutputBatchIndices(shape, dim_numbers);
+ ShapeUtil::IndexIterationSpace offset_indices_iteration_space =
+ IterationSpaceForOutputOffsetIndices(
+ shape.dimensions_size(), gather->gather_slice_sizes(), dim_numbers);
// Scratch buffers that hold an index in the output shape and the
// corresponding index in the input shape.
std::vector<int64> input_index(operand.shape().dimensions_size());
std::vector<int64> output_index(gather->shape().dimensions_size());
- std::vector<int64> input_gather_index_clamped(
- operand.shape().dimensions_size());
+ std::vector<int64> input_index_clamped(operand.shape().dimensions_size());
- OutputGatherIndexToInputIndex output_gather_index_to_input_index(
+ OutputBatchIndexToInputIndex output_batch_index_to_input_index(
&gather->gather_dimension_numbers(), /*input_shape=*/operand.shape(),
- /*output_shape=*/shape, &gather_indices);
- OutputWindowIndexToInputIndex output_window_index_to_input_index(
+ /*output_shape=*/shape, &start_indices);
+ OutputOffsetIndexToInputIndex output_offset_index_to_input_index(
gather->gather_dimension_numbers(), /*input_shape=*/operand.shape(),
/*output_shape=*/shape);
@@ -869,29 +866,29 @@ Status HloEvaluator::HandleGather(HloInstruction* gather) {
ArraySlice<int64> output_gather_index) -> StatusOr<bool> {
TF_ASSIGN_OR_RETURN(
ArraySlice<int64> input_window_index,
- output_window_index_to_input_index(output_window_index));
+ output_offset_index_to_input_index(output_window_index));
for (int i = 0, e = output_index.size(); i < e; i++) {
output_index[i] = output_gather_index[i] + output_window_index[i];
DCHECK_LT(output_index[i], shape.dimensions(i));
}
for (int i = 0, e = input_gather_index.size(); i < e; i++) {
int64 output_dim =
- output_window_index_to_input_index.input_dim_value_to_output_index(i);
+ output_offset_index_to_input_index.input_dim_value_to_output_index(i);
// If 'output_dim' is -1, it means 'i' is an elided window dim. This means
// we set the iteration index to 0, so for the purpose of the following
// calculations we can consider the output dimension size to be 1.
int64 output_dim_size =
output_dim == -1 ? 1 : shape.dimensions(output_dim);
// Clamp the gather index so that the gather region fits in the operand.
- // input_gather_index_clamped[i] = clamp(input_gather_index[i], 0,
+ // input_index_clamped[i] = clamp(input_gather_index[i], 0,
// operand_shape.dimensions(i) -
// output_dim_size);
- input_gather_index_clamped[i] =
+ input_index_clamped[i] =
std::min(operand_shape.dimensions(i) - output_dim_size,
std::max(0LL, input_gather_index[i]));
}
for (int i = 0, e = input_index.size(); i < e; i++) {
- input_index[i] = input_gather_index_clamped[i] + input_window_index[i];
+ input_index[i] = input_index_clamped[i] + input_window_index[i];
DCHECK_GE(input_index[i], 0);
DCHECK_LT(input_index[i], operand_shape.dimensions(i));
}
@@ -902,18 +899,17 @@ Status HloEvaluator::HandleGather(HloInstruction* gather) {
auto gather_outer_loop_body =
[&](ArraySlice<int64> output_gather_index) -> StatusOr<bool> {
- TF_ASSIGN_OR_RETURN(
- ArraySlice<int64> input_gather_index,
- output_gather_index_to_input_index(output_gather_index));
+ TF_ASSIGN_OR_RETURN(ArraySlice<int64> input_gather_index,
+ output_batch_index_to_input_index(output_gather_index));
TF_RETURN_IF_ERROR(ShapeUtil::ForEachIndexWithStatus(
- shape, window_indices_iteration_space,
+ shape, offset_indices_iteration_space,
std::bind(gather_inner_loop_body, std::placeholders::_1,
input_gather_index, output_gather_index)));
return true;
};
TF_RETURN_IF_ERROR(ShapeUtil::ForEachIndexWithStatus(
- shape, gather_indices_iteration_space, gather_outer_loop_body));
+ shape, start_indices_iteration_space, gather_outer_loop_body));
evaluated_[gather] = std::move(result);
return Status::OK();
}
diff --git a/tensorflow/compiler/xla/service/hlo_evaluator_test.cc b/tensorflow/compiler/xla/service/hlo_evaluator_test.cc
index cba72469ce..1394be68e4 100644
--- a/tensorflow/compiler/xla/service/hlo_evaluator_test.cc
+++ b/tensorflow/compiler/xla/service/hlo_evaluator_test.cc
@@ -1826,21 +1826,20 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[2,3] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1, 3}
+ slice_sizes={1, 3}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
EXPECT_TRUE(LiteralTestUtil::Equal(
*LiteralUtil::CreateR2<int32>({{1, 2, 3}, {7, 8, 9}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_TensorFlowGatherV2) {
@@ -1851,21 +1850,20 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[3,2] gather(operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
EXPECT_TRUE(LiteralTestUtil::Equal(
*LiteralUtil::CreateR2<int32>({{1, 3}, {4, 6}, {7, 9}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_TensorFlowGatherMultipleBatchDims) {
@@ -1876,22 +1874,22 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,3,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 2}, {2, 1}});
EXPECT_TRUE(LiteralTestUtil::Equal(
*LiteralUtil::CreateR3<int32>(
{{{1, 3}, {4, 6}, {7, 9}}, {{3, 2}, {6, 5}, {9, 8}}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_TensorFlowGatherNd) {
@@ -1902,11 +1900,11 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
}
)";
ParseAndVerifyModule(hlo_text);
@@ -1914,11 +1912,11 @@ ENTRY main {
LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
{{-4, 4}, {-5, 5}, {-6, 6}}, //
{{-7, 7}, {-8, 8}, {-9, 9}}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
EXPECT_TRUE(
LiteralTestUtil::Equal(*LiteralUtil::CreateR2<int32>({{-1, 1}, {-4, 4}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest,
@@ -1930,11 +1928,11 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
}
)";
ParseAndVerifyModule(hlo_text);
@@ -1942,11 +1940,11 @@ ENTRY main {
LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
{{-4, 4}, {-5, 5}, {-6, 6}}, //
{{-7, 7}, {-8, 8}, {-9, 9}}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
EXPECT_TRUE(
LiteralTestUtil::Equal(*LiteralUtil::CreateR2<int32>({{-2, 2}, {-1, 1}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_DynamicSlice) {
@@ -1957,21 +1955,20 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[1,1] gather(operand, indices),
- output_window_dims={0,1},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={0,1},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({1, 1});
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({1, 1});
EXPECT_TRUE(
LiteralTestUtil::Equal(*LiteralUtil::CreateR2<int32>({{5}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_BatchDynamicSlice) {
@@ -1982,21 +1979,21 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,1,1] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{2, 1}, {1, 1}});
EXPECT_TRUE(
LiteralTestUtil::Equal(*LiteralUtil::CreateR3<int32>({{{8}}, {{5}}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_ZeroDimBounds) {
@@ -2007,20 +2004,19 @@ ENTRY main {
operand = s32[3,0] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[2,0] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1, 0}
+ slice_sizes={1, 0}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand = LiteralUtil::CreateR2<int32>({{}, {}, {}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
EXPECT_TRUE(
LiteralTestUtil::Equal(*LiteralUtil::CreateR2<int32>({{}, {}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
}
TEST_P(HloEvaluatorTest, EvaluateGather_NoOutputWindowDims) {
@@ -2031,21 +2027,474 @@ ENTRY main {
operand = s32[3] parameter(0)
indices = s32[2,2,1] parameter(1)
ROOT gather = s32[2,2] gather(operand, indices),
- output_window_dims={},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1}
+ slice_sizes={1}
}
)";
ParseAndVerifyModule(hlo_text);
std::unique_ptr<Literal> operand = LiteralUtil::CreateR1<int32>({0, 1, 2});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR3<int32>({{{0}, {1}}, {{2}, {1}}});
EXPECT_TRUE(
LiteralTestUtil::Equal(*LiteralUtil::CreateR2<int32>({{0, 1}, {2, 1}}),
- *Evaluate({operand.get(), gather_indices.get()})));
+ *Evaluate({operand.get(), start_indices.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatterV1_Update) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterV1
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *LiteralUtil::CreateR2<int32>({{10, 20, 30}, {4, 5, 6}, {70, 80, 90}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatterV2_Update) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterV2
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[3,2] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={0},
+ inserted_window_dims={1},
+ scatter_dims_to_operand_dims={1},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 30}, {40, 60}, {70, 90}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *LiteralUtil::CreateR2<int32>({{10, 2, 30}, {40, 5, 60}, {70, 8, 90}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatter_Add) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *LiteralUtil::CreateR2<int32>({{11, 22, 33}, {4, 5, 6}, {77, 88, 99}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatter_Mul) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter
+
+mul_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT mul = s32[] multiply(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=mul_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *LiteralUtil::CreateR2<int32>({{10, 40, 90}, {4, 5, 6}, {490, 640, 810}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatter_F32) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter
+
+add_f32 (lhs: f32[], rhs: f32[]) -> f32[] {
+ lhs = f32[] parameter(0)
+ rhs = f32[] parameter(1)
+ ROOT add = f32[] add(f32[] lhs, f32[] rhs)
+}
+
+ENTRY main {
+ operand = f32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = f32[2,3] parameter(2)
+ ROOT scatter = f32[3,3] scatter(operand, indices, updates),
+ to_apply=add_f32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR2<float>(
+ {{1.1, 2.2, 3.3}, {4.4, 5.5, 6.6}, {7.7, 8.8, 9.9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({2, 1});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<float>({{0.4, 1.1, 0.7}, {2.3, 3.1, 1.6}});
+ EXPECT_TRUE(LiteralTestUtil::Near(
+ *LiteralUtil::CreateR2<float>(
+ {{1.1, 2.2, 3.3}, {6.7, 8.6, 8.2}, {8.1, 9.9, 10.6}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()}),
+ ErrorSpec{0.1, 0.01}));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatter_RepeatedIndices) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({1, 1});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *LiteralUtil::CreateR2<int32>({{1, 2, 3}, {84, 105, 126}, {7, 8, 9}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatter_MultipleBatchDims) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterMultipleBatchDims
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,3,2] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={1},
+ inserted_window_dims={1},
+ scatter_dims_to_operand_dims={1},
+ index_vector_dim=2
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{0, 2}, {2, 1}});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR3<int32>(
+ {{{10, 30}, {40, 60}, {70, 90}}, {{5, 5}, {5, 5}, {5, 5}}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *LiteralUtil::CreateR2<int32>({{11, 7, 38}, {44, 10, 71}, {77, 13, 104}}),
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_TensorFlowScatterNd) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterNd
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3,2] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,2] parameter(2)
+ ROOT scatter = s32[3,3,2] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0,1},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
+ {{-4, 4}, {-5, 5}, {-6, 6}}, //
+ {{-7, 7}, {-8, 8}, {-9, 9}}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{-10, 10}, {-40, 40}});
+ std::unique_ptr<Literal> expected =
+ LiteralUtil::CreateR3<int32>({{{-10, 10}, {-2, 2}, {-3, 3}}, //
+ {{-40, 40}, {-5, 5}, {-6, 6}}, //
+ {{-7, 7}, {-8, 8}, {-9, 9}}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *expected,
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest,
+ EvaluateScatter_TensorFlowScatterNd_NonDefaultIndexVectorDim) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterNdNonDefaultIndexVectorDim
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3,2] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,2] parameter(2)
+ ROOT scatter = s32[3,3,2] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0,1},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=0
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
+ {{-4, 4}, {-5, 5}, {-6, 6}}, //
+ {{-7, 7}, {-8, 8}, {-9, 9}}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{-10, 10}, {-20, 20}});
+ std::unique_ptr<Literal> expected =
+ LiteralUtil::CreateR3<int32>({{{-20, 20}, {-10, 10}, {-3, 3}}, //
+ {{-4, 4}, {-5, 5}, {-6, 6}}, //
+ {{-7, 7}, {-8, 8}, {-9, 9}}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *expected,
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_DynamicUpdateSlice) {
+ const char* hlo_text = R"(
+HloModule DynamicUpdateSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[1,1] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={0,1},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=0
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({1, 1});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR2<int32>({{10}});
+ std::unique_ptr<Literal> expected =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 10, 6}, {7, 8, 9}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *expected,
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_BatchDynamicUpdateSlice) {
+ const char* hlo_text = R"(
+HloModule BatchDynamicUpdateSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,1,1] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1,2},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=0
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{2, 1}, {1, 1}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR3<int32>({{{10}}, {{20}}});
+ std::unique_ptr<Literal> expected =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 20, 6}, {7, 10, 9}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *expected,
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_ZeroDimBounds) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter_ZeroDimBounds
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,0] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,0] parameter(2)
+ ROOT scatter = s32[3,0] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR2<int32>({{}, {}, {}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR2<int32>({{}, {}});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *operand,
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
+}
+
+TEST_P(HloEvaluatorTest, EvaluateScatter_NoUpdateWindowDims) {
+ const string hlo_text = R"(
+HloModule Scatter_NoUpdateWindowDims
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3] parameter(0)
+ indices = s32[2,2,1] parameter(1)
+ updates = s32[2,2] parameter(2)
+ ROOT scatter = s32[3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=2
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR1<int32>({0, 1, 2});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR3<int32>({{{0}, {1}}, {{2}, {1}}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20}, {30, 40}});
+ std::unique_ptr<Literal> expected =
+ LiteralUtil::CreateR1<int32>({10, 61, 32});
+ EXPECT_TRUE(LiteralTestUtil::Equal(
+ *expected,
+ *Evaluate({operand.get(), scatter_indices.get(), updates.get()})));
}
// Verifies that HloEvaluator evaluates a HLO instruction that performs
@@ -2064,6 +2513,31 @@ TEST_P(HloEvaluatorTest, DoesCompareBF16) {
std::move(rhs));
}
+TEST_P(HloEvaluatorTest, Bf16Reduction) {
+ const string hlo_text = R"(
+HloModule Bf16Reduction
+
+add_bf16 (lhs: bf16[], rhs: bf16[]) -> bf16[] {
+ lhs = bf16[] parameter(0)
+ rhs = bf16[] parameter(1)
+ ROOT add = bf16[] add(bf16[] lhs, bf16[] rhs)
+}
+
+ENTRY main {
+ arg0 = bf16[4]{0} parameter(0)
+ init = bf16[] constant(0)
+ ROOT %reduce = bf16[] reduce(arg0, init), dimensions={0}, to_apply=add_bf16
+}
+)";
+ ParseAndVerifyModule(hlo_text);
+
+ std::unique_ptr<Literal> arg = LiteralUtil::CreateR1<bfloat16>(
+ {bfloat16(1.0f), bfloat16(3.0f), bfloat16(-2.0f), bfloat16(42.0f)});
+ std::unique_ptr<Literal> expected =
+ LiteralUtil::CreateR0<bfloat16>(bfloat16(44.0f));
+ EXPECT_TRUE(LiteralTestUtil::Equal(*expected, *Evaluate({arg.get()})));
+}
+
INSTANTIATE_TEST_CASE_P(HloEvaluatorTest_Instantiation, HloEvaluatorTest,
::testing::ValuesIn(use_bf16_params));
diff --git a/tensorflow/compiler/xla/service/hlo_evaluator_typed_visitor.h b/tensorflow/compiler/xla/service/hlo_evaluator_typed_visitor.h
index d1ee4a180b..a7c5d71da0 100644
--- a/tensorflow/compiler/xla/service/hlo_evaluator_typed_visitor.h
+++ b/tensorflow/compiler/xla/service/hlo_evaluator_typed_visitor.h
@@ -16,6 +16,7 @@ limitations under the License.
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_HLO_EVALUATOR_TYPED_VISITOR_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_HLO_EVALUATOR_TYPED_VISITOR_H_
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
@@ -86,6 +87,29 @@ bool SafeLess(const NativeT& a, const NativeT& b) {
// of this class.
template <typename ReturnT, typename ElementwiseT = ReturnT>
class HloEvaluatorTypedVisitor : public DfsHloVisitorWithDefault {
+ private:
+ // Get the value in the given literal static_cast as a double.
+ template <
+ typename NativeT,
+ typename std::enable_if<!is_complex_t<NativeT>::value>::type* = nullptr>
+ double GetAsDouble(const Literal& literal,
+ tensorflow::gtl::ArraySlice<int64> input_index) {
+ return static_cast<double>(literal.Get<NativeT>(input_index));
+ }
+
+ // Specialization for complex types. In this case it is not possible to
+ // static_cast value to a double so just CHECK fail. This method is not used
+ // at run-time, but must be available at compile-time to keep the compiler
+ // happy.
+ template <
+ typename NativeT,
+ typename std::enable_if<is_complex_t<NativeT>::value>::type* = nullptr>
+ double GetAsDouble(const Literal& literal,
+ tensorflow::gtl::ArraySlice<int64> input_index) {
+ LOG(FATAL) << "Trying to get complex literal as double: "
+ << literal.ToString();
+ }
+
public:
explicit HloEvaluatorTypedVisitor(HloEvaluator* p) : parent_(p) {}
@@ -1473,6 +1497,10 @@ class HloEvaluatorTypedVisitor : public DfsHloVisitorWithDefault {
}
Status HandleReduce(HloInstruction* reduce) override {
+ // TODO(b/112040122): Support variadic reduce.
+ if (!ShapeUtil::IsArray(reduce->shape())) {
+ return Unimplemented("Variadic reduce is not supported in the Evaluator");
+ }
auto arg = reduce->operand(0);
auto init_value = reduce->operand(1);
tensorflow::gtl::ArraySlice<int64> dimensions(reduce->dimensions());
@@ -1532,7 +1560,7 @@ class HloEvaluatorTypedVisitor : public DfsHloVisitorWithDefault {
IsScalarAdd(function)) {
double computed_result = 0;
auto func = [&](tensorflow::gtl::ArraySlice<int64> input_index) {
- computed_result += arg_literal.Get<float>(input_index);
+ computed_result += GetAsDouble<ReturnT>(arg_literal, input_index);
return true;
};
ShapeUtil::ForEachIndex(arg_literal.shape(), base, arg_dim_counts,
@@ -1771,6 +1799,388 @@ class HloEvaluatorTypedVisitor : public DfsHloVisitorWithDefault {
return Status::OK();
}
+ // Reshapes the scatter indices input to have a trailing degenerate `1`
+ // dimension if necessary. Hands over the ownership of the newly created
+ // literal (if there is one) to `reshaped_indices`.
+ StatusOr<std::reference_wrapper<const Literal>> ReshapedScatterIndices(
+ int64 index_vector_dim, const Literal& indices,
+ std::unique_ptr<Literal>* reshaped_indices) {
+ if (indices.shape().dimensions_size() != index_vector_dim) {
+ return std::cref(indices);
+ }
+
+ std::vector<int64> new_shape(indices.shape().dimensions().begin(),
+ indices.shape().dimensions().end());
+ new_shape.push_back(1);
+ TF_ASSIGN_OR_RETURN(*reshaped_indices, indices.Reshape(new_shape));
+ return std::cref(**reshaped_indices);
+ }
+
+ // Returns an ShapeUtil::IndexIterationSpace that iterates over the update
+ // scatter dimensions while keeping the rest of the update dimensions clamped
+ // to 0.
+ ShapeUtil::IndexIterationSpace IterationSpaceForUpdateScatterIndices(
+ const Shape& updates_shape, const ScatterDimensionNumbers& dim_numbers) {
+ int64 updates_rank = updates_shape.dimensions_size();
+ std::vector<int64> index_base(updates_rank, 0);
+ std::vector<int64> index_count(updates_rank, 1);
+ for (int64 i = 0; i < updates_rank; i++) {
+ bool is_update_scatter_dim =
+ !absl::c_binary_search(dim_numbers.update_window_dims(), i);
+ if (is_update_scatter_dim) {
+ index_count[i] = updates_shape.dimensions(i);
+ }
+ }
+ return {std::move(index_base), std::move(index_count),
+ std::vector<int64>(updates_rank, 1)};
+ }
+
+ // Return an ShapeUtil::IndexIterationSpace that iterates over the update
+ // window dimensions while keeping the rest of the update dimensions clamped
+ // to 0.
+ ShapeUtil::IndexIterationSpace IterationSpaceForUpdateWindowIndices(
+ const Shape& updates_shape, const ScatterDimensionNumbers& dim_numbers) {
+ int64 updates_rank = updates_shape.dimensions_size();
+ std::vector<int64> index_base(updates_rank, 0);
+ std::vector<int64> index_count(updates_rank, 1);
+ for (int64 i = 0; i < updates_rank; i++) {
+ bool is_update_window_dim =
+ absl::c_binary_search(dim_numbers.update_window_dims(), i);
+ if (is_update_window_dim) {
+ index_count[i] = updates_shape.dimensions(i);
+ }
+ }
+ return {std::move(index_base), std::move(index_count),
+ std::vector<int64>(updates_rank, 1)};
+ }
+
+ // This functor computes the contribution of scatter_indices to an input index
+ // corresponding to an update index. That is, given an update index I, it
+ // picks out the scatter indices in I and uses them to look up a scatter
+ // index, S, from the scatter indices tensor, and expands S into the input
+ // space according to scatter_dims_to_operand_dims.
+ //
+ // This is similar to the class HloEvaluator::OutputGatherIndexToInputIndex
+ // that does the corresponding function for Gather.
+ class UpdateScatterIndexToInputIndex {
+ public:
+ // The constructor does some setup work that is amortized across all
+ // iterations.
+ explicit UpdateScatterIndexToInputIndex(
+ const ScatterDimensionNumbers* dim_numbers, const Shape& input_shape,
+ const Shape& updates_shape, const Literal* scatter_indices)
+ : dim_numbers_(*dim_numbers), scatter_indices_(*scatter_indices) {
+ for (int64 i = 0; i < updates_shape.dimensions_size(); i++) {
+ update_dim_is_scatter_dims_.push_back(
+ !absl::c_binary_search(dim_numbers_.update_window_dims(), i));
+ }
+
+ for (int64 i = 0; i < input_shape.dimensions_size(); i++) {
+ int64 index_of_input_dim_in_index_vector =
+ FindIndex(dim_numbers_.scatter_dims_to_operand_dims(), i);
+ if (index_of_input_dim_in_index_vector ==
+ dim_numbers_.scatter_dims_to_operand_dims_size()) {
+ input_dim_value_to_index_vector_.push_back(-1);
+ } else {
+ input_dim_value_to_index_vector_.push_back(
+ index_of_input_dim_in_index_vector);
+ }
+ }
+
+ index_vector_index_.resize(scatter_indices_.shape().dimensions_size());
+ input_index_.resize(input_shape.dimensions_size());
+ int64 index_vector_size =
+ scatter_indices_.shape().dimensions(dim_numbers_.index_vector_dim());
+ index_vector_.resize(index_vector_size);
+ }
+
+ // Returns the contribution of scatter_indices to the input index
+ // corresponding to update_index. See scatter_inner_loop_body.
+ //
+ // This is conceptually a stateless transformation from update_index to the
+ // scatter input index, but:
+ //
+ // - Instead of allocating memory to represent the scatter input index on
+ // every invocation we reuse the same storage for the result
+ // (input_index_), mutating it in place.
+ // - Instead of allocating buffers for temporary values like
+ // index_vector_index_ and index_vector on every invocation, we reuse the
+ // same storage for all invocations.
+ //
+ // This returns an arrayslice into memory owned by the class.
+ StatusOr<tensorflow::gtl::ArraySlice<int64>> operator()(
+ tensorflow::gtl::ArraySlice<int64> update_index) {
+ PropagateUpdateIndexScatterDimsToIndexVectorIndex(update_index);
+ TF_RETURN_IF_ERROR(FetchIndexVector());
+ PropagateIndexVectorToInputIndex();
+ return tensorflow::gtl::ArraySlice<int64>(input_index_);
+ }
+
+ private:
+ // Propagates the scatter index dimensions from the update index into
+ // index_vector_index_ by mutating index_vector_index_ in place. Does not
+ // update the dim_numbers.index_vector_dim() dimension -- that's the
+ // dimension we iterate over in FetchIndexVector.
+ void PropagateUpdateIndexScatterDimsToIndexVectorIndex(
+ tensorflow::gtl::ArraySlice<int64> update_index) {
+ int64 index_vector_index_i = 0;
+ for (int64 i = 0, e = update_index.size(); i < e; i++) {
+ if (!update_dim_is_scatter_dims_[i]) {
+ continue;
+ }
+
+ if (index_vector_index_i == dim_numbers_.index_vector_dim()) {
+ index_vector_index_i++;
+ }
+
+ index_vector_index_[index_vector_index_i++] = update_index[i];
+ }
+ }
+
+ // Populates index_vector_ by iterating over scatter_indices_ according to
+ // index_vector_index_.
+ Status FetchIndexVector() {
+ int64 index_vector_dim = dim_numbers_.index_vector_dim();
+ for (int64 i = 0, e = index_vector_.size(); i < e; i++) {
+ index_vector_index_[index_vector_dim] = i;
+ TF_ASSIGN_OR_RETURN(index_vector_[i], scatter_indices_.GetIntegralAsS64(
+ index_vector_index_));
+ }
+ return Status::OK();
+ }
+
+ // Populates input_index_.
+ void PropagateIndexVectorToInputIndex() {
+ for (int64 i = 0, e = input_index_.size(); i < e; i++) {
+ if (input_dim_value_to_index_vector_[i] != -1) {
+ input_index_[i] = index_vector_[input_dim_value_to_index_vector_[i]];
+ }
+
+ // If input_dim_value_to_index_vector_[i] == -1 then input_index_[i]
+ // remains 0, as set by the constructor.
+ }
+ }
+
+ // input_dim_value_to_index_vector_[i] tells us how to compute dimension i
+ // of the input index from the index vector. See
+ // PropagateIndexVectorToInputIndex.
+ std::vector<int64> input_dim_value_to_index_vector_;
+
+ // update_dim_is_scatter_dims_[i] is true iff the update index i is a
+ // scatter dimension.
+ std::vector<bool> update_dim_is_scatter_dims_;
+
+ // The buffer into which we construct an index into scatter_indices_ to
+ // fetch the index vector.
+ std::vector<int64> index_vector_index_;
+
+ // The index vector fetched from scatter_indices_.
+ std::vector<int64> index_vector_;
+
+ // The result computed by this functor. operator() returns an ArraySlice
+ // into this vector.
+ std::vector<int64> input_index_;
+
+ const ScatterDimensionNumbers& dim_numbers_;
+ const Literal& scatter_indices_;
+ };
+
+ // This functor computes the contribution of the window indices in an update
+ // index to an input index. That is, given an update index I it picks out the
+ // update window indices in I and expands it into a window index into the
+ // input shape.
+ //
+ // This is similar to the class HloEvaluator::OutputWindowIndexToInputIndex
+ // that does the corresponding function for Gather.
+ class UpdateWindowIndexToInputIndex {
+ public:
+ // The constructor does some setup work that is amortized across all
+ // iterations.
+ explicit UpdateWindowIndexToInputIndex(
+ const ScatterDimensionNumbers& dim_numbers, const Shape& input_shape,
+ const Shape& updates_shape) {
+ std::vector<int64> window_index_to_update_index;
+ int64 update_index_count = 0;
+ for (int64 i = 0; i < updates_shape.dimensions_size(); i++) {
+ if (absl::c_binary_search(dim_numbers.update_window_dims(), i)) {
+ window_index_to_update_index.push_back(update_index_count++);
+ } else {
+ update_index_count++;
+ }
+ }
+
+ int64 window_dim_count = 0;
+ for (int64 i = 0; i < input_shape.dimensions_size(); i++) {
+ if (absl::c_binary_search(dim_numbers.inserted_window_dims(), i)) {
+ input_dim_value_to_update_index_.push_back(-1);
+ } else {
+ input_dim_value_to_update_index_.push_back(
+ window_index_to_update_index[window_dim_count++]);
+ }
+ }
+
+ input_index_.resize(input_shape.dimensions_size());
+ }
+
+ // Returns the contribution of the window indices to the input index
+ // corresponding to update_index. See scatter_inner_loop_body.
+ //
+ // This is conceptually a stateless transformation from update_index to the
+ // window input index, but instead of allocating memory to represent the
+ // scatter input index on every invocation we reuse the same storage for the
+ // result (input_index_), mutating it in place.
+ //
+ // This returns an arrayslice into memory owned by the class.
+ StatusOr<tensorflow::gtl::ArraySlice<int64>> operator()(
+ tensorflow::gtl::ArraySlice<int64> update_index) {
+ PropagateUpdateIndexWindowDimsToInputIndex(update_index);
+ return tensorflow::gtl::ArraySlice<int64>(input_index_);
+ }
+
+ // Returns for a given 'input_dim' the corresponding update dimension index,
+ // or -1 if 'input_dim' is an elided window dimension.
+ int64 input_dim_value_to_update_index(int64 input_dim) {
+ return input_dim_value_to_update_index_[input_dim];
+ }
+
+ private:
+ // Propagates window dimensions from the update index to input_index_ by
+ // mutating input_index_ in place.
+ void PropagateUpdateIndexWindowDimsToInputIndex(
+ tensorflow::gtl::ArraySlice<int64> update_index) {
+ for (int64 i = 0, e = input_index_.size(); i < e; i++) {
+ if (input_dim_value_to_update_index_[i] != -1) {
+ input_index_[i] = update_index[input_dim_value_to_update_index_[i]];
+ }
+
+ // If input_dim_value_to_index_vector_[i] == -1 then input_index_[i]
+ // remains 0, as set by the constructor.
+ }
+ }
+
+ // input_dim_value_to_index_vector_[i] tells us how to compute dimension i
+ // of the input index from the update index. See
+ // PropagateUpdateIndexWindowDimsToInputIndex.
+ std::vector<int64> input_dim_value_to_update_index_;
+
+ // The result computed by this functor. operator() returns an ArraySlice
+ // into this vector.
+ std::vector<int64> input_index_;
+ };
+
+ Status HandleScatter(HloInstruction* scatter) override {
+ const ScatterDimensionNumbers& dim_numbers =
+ scatter->scatter_dimension_numbers();
+ const Literal& operand =
+ parent_->GetEvaluatedLiteralFor(scatter->operand(0));
+ std::unique_ptr<Literal> reshaped_scatter_indices;
+ TF_ASSIGN_OR_RETURN(const Literal& scatter_indices,
+ ReshapedScatterIndices(dim_numbers.index_vector_dim(),
+ parent_->GetEvaluatedLiteralFor(
+ scatter->operand(1)),
+ &reshaped_scatter_indices));
+ const Literal& updates =
+ parent_->GetEvaluatedLiteralFor(scatter->operand(2));
+ const Shape& updates_shape = updates.shape();
+ const Shape& operand_shape = operand.shape();
+
+ ShapeUtil::IndexIterationSpace scatter_indices_iteration_space =
+ IterationSpaceForUpdateScatterIndices(updates_shape, dim_numbers);
+ ShapeUtil::IndexIterationSpace window_indices_iteration_space =
+ IterationSpaceForUpdateWindowIndices(updates_shape, dim_numbers);
+
+ std::vector<int64> input_index(operand_shape.dimensions_size());
+ std::vector<int64> update_index(updates_shape.dimensions_size());
+ std::vector<int64> input_scatter_index_clamped(
+ operand_shape.dimensions_size());
+
+ UpdateScatterIndexToInputIndex update_scatter_index_to_input_index(
+ &scatter->scatter_dimension_numbers(), /*input_shape=*/operand_shape,
+ updates_shape, &scatter_indices);
+ UpdateWindowIndexToInputIndex update_window_index_to_input_index(
+ scatter->scatter_dimension_numbers(), /*input_shape=*/operand_shape,
+ updates_shape);
+
+ // Initialize the result with the operand. This makes it easier to handle
+ // the updates even when the indices are repeated.
+ std::unique_ptr<Literal> result = operand.CloneToUnique();
+ HloEvaluator embedded_evaluator;
+ auto scatter_inner_loop_body =
+ [&](tensorflow::gtl::ArraySlice<int64> update_window_index,
+ tensorflow::gtl::ArraySlice<int64> input_scatter_index,
+ tensorflow::gtl::ArraySlice<int64> update_scatter_index)
+ -> StatusOr<bool> {
+ TF_ASSIGN_OR_RETURN(
+ tensorflow::gtl::ArraySlice<int64> input_window_index,
+ update_window_index_to_input_index(update_window_index));
+ for (int i = 0, e = update_index.size(); i < e; i++) {
+ update_index[i] = update_scatter_index[i] + update_window_index[i];
+ DCHECK_LT(update_index[i], updates_shape.dimensions(i));
+ }
+ for (int i = 0, e = input_scatter_index.size(); i < e; i++) {
+ int64 update_dim =
+ update_window_index_to_input_index.input_dim_value_to_update_index(
+ i);
+ // If 'update_dim' is -1, it means 'i' is an elided window dim. This
+ // means we set the iteration index to 0, so for the purpose of the
+ // following calculations we can consider the update dimension size to
+ // be 1.
+ int64 update_dim_size =
+ update_dim == -1 ? 1 : updates_shape.dimensions(update_dim);
+ // Clamp the scatter index so that the scatter region fits in the
+ // operand. input_scatter_index_clamped[i] =
+ // clamp(input_scatter_index[i], 0,
+ // operand_shape.dimensions(i) -
+ // update_dim_size);
+ input_scatter_index_clamped[i] =
+ std::min(operand_shape.dimensions(i) - update_dim_size,
+ std::max(0LL, input_scatter_index[i]));
+ }
+ for (int i = 0, e = input_index.size(); i < e; i++) {
+ input_index[i] = input_scatter_index_clamped[i] + input_window_index[i];
+ DCHECK_GE(input_index[i], 0);
+ DCHECK_LT(input_index[i], operand_shape.dimensions(i));
+ }
+
+ auto result_value_literal =
+ LiteralUtil::CreateR0<ReturnT>(result->Get<ReturnT>(input_index));
+ auto update_value_literal =
+ LiteralUtil::CreateR0<ReturnT>(updates.Get<ReturnT>(update_index));
+ std::unique_ptr<Literal> updated_result =
+ embedded_evaluator
+ .Evaluate<const Literal*>(
+ *scatter->to_apply(),
+ {result_value_literal.get(), update_value_literal.get()})
+ .ConsumeValueOrDie();
+ // Clear visit states so that the we can use the evaluate again on the
+ // same computation.
+ embedded_evaluator.ResetVisitStates();
+ result->Set<ReturnT>(input_index, updated_result->Get<ReturnT>({}));
+ return true;
+ };
+
+ auto scatter_outer_loop_body =
+ [&](tensorflow::gtl::ArraySlice<int64> update_scatter_index)
+ -> StatusOr<bool> {
+ TF_ASSIGN_OR_RETURN(
+ tensorflow::gtl::ArraySlice<int64> input_scatter_index,
+ update_scatter_index_to_input_index(update_scatter_index));
+ TF_RETURN_IF_ERROR(ShapeUtil::ForEachIndexWithStatus(
+ updates_shape, window_indices_iteration_space,
+ [&](tensorflow::gtl::ArraySlice<int64> update_window_index) {
+ return scatter_inner_loop_body(
+ update_window_index, input_scatter_index, update_scatter_index);
+ }));
+ return true;
+ };
+
+ TF_RETURN_IF_ERROR(ShapeUtil::ForEachIndexWithStatus(
+ updates_shape, scatter_indices_iteration_space,
+ scatter_outer_loop_body));
+ parent_->evaluated_[scatter] = std::move(result);
+ return Status::OK();
+ }
+
Status HandleSlice(HloInstruction* slice) override {
auto operand = slice->operand(0);
const Shape& shape = slice->shape();
diff --git a/tensorflow/compiler/xla/service/hlo_execution_profile.cc b/tensorflow/compiler/xla/service/hlo_execution_profile.cc
index c3ccbf0f0c..f554401787 100644
--- a/tensorflow/compiler/xla/service/hlo_execution_profile.cc
+++ b/tensorflow/compiler/xla/service/hlo_execution_profile.cc
@@ -19,6 +19,7 @@ limitations under the License.
#include <utility>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/human_readable_profile_builder.h"
@@ -67,11 +68,11 @@ std::unique_ptr<HloProfilePrinterData> CreateHloProfilePrinterData(
// The profile indices were computed deterministically in
// HloProfileIndexMap::HloProfileIndexMap.
- c_sort(computation_and_profile_idx_list,
- [](const std::pair<const HloComputation*, int64>& left,
- const std::pair<const HloComputation*, int64>& right) {
- return left.second < right.second;
- });
+ absl::c_sort(computation_and_profile_idx_list,
+ [](const std::pair<const HloComputation*, int64>& left,
+ const std::pair<const HloComputation*, int64>& right) {
+ return left.second < right.second;
+ });
for (const auto& pair : computation_and_profile_idx_list) {
CHECK_LT(pair.second, profile_counters_size);
diff --git a/tensorflow/compiler/xla/service/hlo_instruction.cc b/tensorflow/compiler/xla/service/hlo_instruction.cc
index 8690f2cdaa..2b81213509 100644
--- a/tensorflow/compiler/xla/service/hlo_instruction.cc
+++ b/tensorflow/compiler/xla/service/hlo_instruction.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include <unordered_set>
#include <utility>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/protobuf_util.h"
@@ -281,27 +282,14 @@ StatusOr<std::unique_ptr<HloInstruction>> HloInstruction::CreateFromProto(
case HloOpcode::kInfeed: {
const Shape& data_shape =
ShapeUtil::GetTupleElementShape(proto.shape(), 0);
- if (proto.operand_ids_size() == 0) {
- // TODO(b/80000000): Remove this when all uses of infeed are
- // converted to take tokens.
- instruction = CreateInfeed(data_shape, proto.infeed_config());
- } else {
- CHECK_EQ(proto.operand_ids_size(), 1);
- instruction =
- CreateInfeed(data_shape, operands(0), proto.infeed_config());
- }
+ TF_RET_CHECK(proto.operand_ids_size() == 1);
+ instruction =
+ CreateInfeed(data_shape, operands(0), proto.infeed_config());
} break;
case HloOpcode::kOutfeed:
- if (proto.operand_ids_size() == 1) {
- // TODO(b/80000000): Remove this when all uses of outfeed are
- // converted to take tokens.
- instruction = CreateOutfeed(proto.outfeed_shape(), operands(0),
- proto.outfeed_config());
- } else {
- CHECK_EQ(proto.operand_ids_size(), 2);
- instruction = CreateOutfeed(proto.outfeed_shape(), operands(0),
- operands(1), proto.outfeed_config());
- }
+ TF_RET_CHECK(proto.operand_ids_size() == 2);
+ instruction = CreateOutfeed(proto.outfeed_shape(), operands(0),
+ operands(1), proto.outfeed_config());
break;
case HloOpcode::kCrossReplicaSum: {
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
@@ -335,9 +323,10 @@ StatusOr<std::unique_ptr<HloInstruction>> HloInstruction::CreateFromProto(
<< proto.operand_ids_size();
TF_RET_CHECK(proto.has_window());
TF_RET_CHECK(proto.has_convolution_dimension_numbers());
- instruction =
- CreateConvolve(proto.shape(), operands(0), operands(1),
- proto.window(), proto.convolution_dimension_numbers());
+ instruction = CreateConvolve(
+ proto.shape(), operands(0), operands(1), proto.window(),
+ proto.convolution_dimension_numbers(),
+ std::max(static_cast<int64>(proto.feature_group_count()), 1LL));
break;
case HloOpcode::kReduceWindow:
TF_RET_CHECK(proto.operand_ids_size() == 2)
@@ -391,7 +380,7 @@ StatusOr<std::unique_ptr<HloInstruction>> HloInstruction::CreateFromProto(
<< "DynamicSlice instruction should have 2 operands but sees "
<< proto.operand_ids_size();
std::vector<int64> slice_sizes(proto.dynamic_slice_sizes_size());
- c_copy(proto.dynamic_slice_sizes(), slice_sizes.begin());
+ absl::c_copy(proto.dynamic_slice_sizes(), slice_sizes.begin());
instruction = CreateDynamicSlice(proto.shape(), operands(0), operands(1),
slice_sizes);
break;
@@ -404,13 +393,12 @@ StatusOr<std::unique_ptr<HloInstruction>> HloInstruction::CreateFromProto(
<< "Gather instruction should have GatherDimensionNumbers set.";
std::unique_ptr<GatherDimensionNumbers> gather_dimension_numbers =
MakeUnique<GatherDimensionNumbers>(proto.gather_dimension_numbers());
- std::vector<int64> gather_window_bounds;
- for (int64 bound : proto.gather_window_bounds()) {
- gather_window_bounds.push_back(bound);
+ std::vector<int64> gather_slice_sizes;
+ for (int64 bound : proto.gather_slice_sizes()) {
+ gather_slice_sizes.push_back(bound);
}
- instruction =
- CreateGather(proto.shape(), operands(0), operands(1),
- *gather_dimension_numbers, gather_window_bounds);
+ instruction = CreateGather(proto.shape(), operands(0), operands(1),
+ *gather_dimension_numbers, gather_slice_sizes);
break;
}
case HloOpcode::kScatter: {
@@ -622,10 +610,10 @@ HloInstruction::CreateGetTupleElement(const Shape& shape,
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvolve(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
- const Window& window,
- const ConvolutionDimensionNumbers& dimension_numbers) {
- return MakeUnique<HloConvolutionInstruction>(shape, lhs, rhs, window,
- dimension_numbers);
+ const Window& window, const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count) {
+ return MakeUnique<HloConvolutionInstruction>(
+ shape, lhs, rhs, window, dimension_numbers, feature_group_count);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFft(
@@ -694,11 +682,6 @@ HloInstruction::CreateCrossReplicaSum(
return MakeUnique<HloInfeedInstruction>(infeed_shape, token_operand, config);
}
-/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateInfeed(
- const Shape& infeed_shape, const string& config) {
- return MakeUnique<HloInfeedInstruction>(infeed_shape, config);
-}
-
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateOutfeed(
const Shape& outfeed_shape, HloInstruction* operand,
HloInstruction* token_operand, tensorflow::StringPiece outfeed_config) {
@@ -706,13 +689,6 @@ HloInstruction::CreateCrossReplicaSum(
token_operand, outfeed_config);
}
-/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateOutfeed(
- const Shape& outfeed_shape, HloInstruction* operand,
- tensorflow::StringPiece outfeed_config) {
- return MakeUnique<HloOutfeedInstruction>(outfeed_shape, operand,
- outfeed_config);
-}
-
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSend(
HloInstruction* operand, HloInstruction* token, int64 channel_id,
bool is_host_transfer) {
@@ -1102,11 +1078,11 @@ bool HloInstruction::HasSideEffect() const {
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateGather(
- const Shape& shape, HloInstruction* operand, HloInstruction* gather_indices,
+ const Shape& shape, HloInstruction* operand, HloInstruction* start_indices,
const GatherDimensionNumbers& gather_dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds) {
- return MakeUnique<HloGatherInstruction>(shape, operand, gather_indices,
- gather_dim_numbers, window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes) {
+ return MakeUnique<HloGatherInstruction>(shape, operand, start_indices,
+ gather_dim_numbers, slice_sizes);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateScatter(
@@ -3206,6 +3182,10 @@ void HloInstruction::set_convolution_dimension_numbers(
}
}
+int64 HloInstruction::feature_group_count() const {
+ return Cast<HloConvolutionInstruction>(this)->feature_group_count();
+}
+
HloComputation* HloInstruction::select() const {
return Cast<HloSelectAndScatterInstruction>(this)->select();
}
@@ -3246,9 +3226,8 @@ const GatherDimensionNumbers& HloInstruction::gather_dimension_numbers() const {
return Cast<HloGatherInstruction>(this)->gather_dimension_numbers();
}
-tensorflow::gtl::ArraySlice<int64> HloInstruction::gather_window_bounds()
- const {
- return Cast<HloGatherInstruction>(this)->gather_window_bounds();
+tensorflow::gtl::ArraySlice<int64> HloInstruction::gather_slice_sizes() const {
+ return Cast<HloGatherInstruction>(this)->gather_slice_sizes();
}
const ScatterDimensionNumbers& HloInstruction::scatter_dimension_numbers()
diff --git a/tensorflow/compiler/xla/service/hlo_instruction.h b/tensorflow/compiler/xla/service/hlo_instruction.h
index 3c575ae6ea..8d8f149ee3 100644
--- a/tensorflow/compiler/xla/service/hlo_instruction.h
+++ b/tensorflow/compiler/xla/service/hlo_instruction.h
@@ -402,7 +402,8 @@ class HloInstruction {
static std::unique_ptr<HloInstruction> CreateConvolve(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
const Window& window,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Creates an FFT op, of the type indicated by fft_type.
static std::unique_ptr<HloInstruction> CreateFft(
@@ -486,11 +487,6 @@ class HloInstruction {
static std::unique_ptr<HloInstruction> CreateInfeed(
const Shape& infeed_shape, HloInstruction* token_operand,
const string& config);
- // Overload which does not require a token.
- // TODO(b/80000000): Remove this overload when all uses of infeed are
- // converted to take tokens.
- static std::unique_ptr<HloInstruction> CreateInfeed(const Shape& infeed_shape,
- const string& config);
// Creates an outfeed instruction, which outputs data. outfeed_shape is the
// shape of the data being outfed *not* the shape of the outfeed instruction
@@ -498,12 +494,6 @@ class HloInstruction {
static std::unique_ptr<HloInstruction> CreateOutfeed(
const Shape& outfeed_shape, HloInstruction* operand,
HloInstruction* token_operand, tensorflow::StringPiece outfeed_config);
- // Overload which does not require a token.
- // TODO(b/80000000): Remove this overload when all uses of outfeed are
- // converted to take tokens.
- static std::unique_ptr<HloInstruction> CreateOutfeed(
- const Shape& outfeed_shape, HloInstruction* operand,
- tensorflow::StringPiece outfeed_config);
// Creates an asynchronous send instruction with the given channel id, which
// initiates sending the operand data to a unique receive instruction in
@@ -677,9 +667,9 @@ class HloInstruction {
static std::unique_ptr<HloInstruction> CreateGather(
const Shape& shape, HloInstruction* operand,
- HloInstruction* gather_indices,
+ HloInstruction* start_indices,
const GatherDimensionNumbers& gather_dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes);
static std::unique_ptr<HloInstruction> CreateScatter(
const Shape& shape, HloInstruction* operand,
@@ -1466,6 +1456,10 @@ class HloInstruction {
void set_convolution_dimension_numbers(
const ConvolutionDimensionNumbers& dnums);
+ // The number of feature groups. Must be a divisor of the input feature
+ // dimension and output feature dimension.
+ int64 feature_group_count() const;
+
// Delegates to HloSelectAndScatterInstruction::select.
HloComputation* select() const;
@@ -1495,8 +1489,8 @@ class HloInstruction {
// Delegates to HloGatherInstruction::gather_dimension_numbers.
const GatherDimensionNumbers& gather_dimension_numbers() const;
- // Delegates to HloGatherInstruction::gather_window_bounds.
- tensorflow::gtl::ArraySlice<int64> gather_window_bounds() const;
+ // Delegates to HloGatherInstruction::gather_slice_sizes.
+ tensorflow::gtl::ArraySlice<int64> gather_slice_sizes() const;
// Delegates to HloScatterInstruction::scatter_dimension_numbers().
const ScatterDimensionNumbers& scatter_dimension_numbers() const;
diff --git a/tensorflow/compiler/xla/service/hlo_instruction_test.cc b/tensorflow/compiler/xla/service/hlo_instruction_test.cc
index 8a694dde80..504b13043f 100644
--- a/tensorflow/compiler/xla/service/hlo_instruction_test.cc
+++ b/tensorflow/compiler/xla/service/hlo_instruction_test.cc
@@ -1355,7 +1355,7 @@ TEST_F(HloInstructionTest, Stringification) {
TEST_F(HloInstructionTest, StringifyGather_0) {
Shape input_tensor_shape = ShapeUtil::MakeShape(F32, {50, 49, 48, 47, 46});
- Shape gather_indices_tensor_shape =
+ Shape start_indices_tensor_shape =
ShapeUtil::MakeShape(S64, {10, 9, 8, 7, 5});
Shape gather_result_shape =
ShapeUtil::MakeShape(F32, {10, 9, 8, 7, 30, 29, 28, 27, 26});
@@ -1363,19 +1363,18 @@ TEST_F(HloInstructionTest, StringifyGather_0) {
HloComputation::Builder builder("Gather");
HloInstruction* input = builder.AddInstruction(
HloInstruction::CreateParameter(0, input_tensor_shape, "input_tensor"));
- HloInstruction* gather_indices =
+ HloInstruction* start_indices =
builder.AddInstruction(HloInstruction::CreateParameter(
- 1, gather_indices_tensor_shape, "gather_indices"));
-
- HloInstruction* gather_instruction =
- builder.AddInstruction(HloInstruction::CreateGather(
- gather_result_shape, input, gather_indices,
- HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
- /*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26}));
+ 1, start_indices_tensor_shape, "start_indices"));
+
+ HloInstruction* gather_instruction = builder.AddInstruction(
+ HloInstruction::CreateGather(gather_result_shape, input, start_indices,
+ HloGatherInstruction::MakeGatherDimNumbers(
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
+ /*index_vector_dim=*/4),
+ /*slice_sizes=*/{30, 29, 28, 27, 26}));
auto module = CreateNewModule();
module->AddEntryComputation(builder.Build());
@@ -1383,15 +1382,15 @@ TEST_F(HloInstructionTest, StringifyGather_0) {
EXPECT_EQ(gather_instruction->ToString(),
"%gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} "
"gather(f32[50,49,48,47,46]{4,3,2,1,0} %input_tensor, "
- "s64[10,9,8,7,5]{4,3,2,1,0} %gather_indices), "
- "output_window_dims={4,5,6,7,8}, elided_window_dims={}, "
- "gather_dims_to_operand_dims={0,1,2,3,4}, "
- "index_vector_dim=4, window_bounds={30,29,28,27,26}");
+ "s64[10,9,8,7,5]{4,3,2,1,0} %start_indices), "
+ "offset_dims={4,5,6,7,8}, collapsed_slice_dims={}, "
+ "start_index_map={0,1,2,3,4}, "
+ "index_vector_dim=4, slice_sizes={30,29,28,27,26}");
}
TEST_F(HloInstructionTest, StringifyGather_1) {
Shape input_tensor_shape = ShapeUtil::MakeShape(F32, {50, 49, 48, 47, 46});
- Shape gather_indices_tensor_shape =
+ Shape start_indices_tensor_shape =
ShapeUtil::MakeShape(S64, {10, 9, 5, 7, 6});
Shape gather_result_shape =
ShapeUtil::MakeShape(F32, {10, 9, 7, 6, 30, 29, 28, 27, 26});
@@ -1399,19 +1398,18 @@ TEST_F(HloInstructionTest, StringifyGather_1) {
HloComputation::Builder builder("Gather");
HloInstruction* input = builder.AddInstruction(
HloInstruction::CreateParameter(0, input_tensor_shape, "input_tensor"));
- HloInstruction* gather_indices =
+ HloInstruction* start_indices =
builder.AddInstruction(HloInstruction::CreateParameter(
- 1, gather_indices_tensor_shape, "gather_indices"));
-
- HloInstruction* gather_instruction =
- builder.AddInstruction(HloInstruction::CreateGather(
- gather_result_shape, input, gather_indices,
- HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
- /*index_vector_dim=*/2),
- /*window_bounds=*/{30, 29, 28, 27, 26}));
+ 1, start_indices_tensor_shape, "start_indices"));
+
+ HloInstruction* gather_instruction = builder.AddInstruction(
+ HloInstruction::CreateGather(gather_result_shape, input, start_indices,
+ HloGatherInstruction::MakeGatherDimNumbers(
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
+ /*index_vector_dim=*/2),
+ /*slice_sizes=*/{30, 29, 28, 27, 26}));
auto module = CreateNewModule();
module->AddEntryComputation(builder.Build());
@@ -1419,10 +1417,10 @@ TEST_F(HloInstructionTest, StringifyGather_1) {
EXPECT_EQ(gather_instruction->ToString(),
"%gather = f32[10,9,7,6,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} "
"gather(f32[50,49,48,47,46]{4,3,2,1,0} %input_tensor, "
- "s64[10,9,5,7,6]{4,3,2,1,0} %gather_indices), "
- "output_window_dims={4,5,6,7,8}, elided_window_dims={}, "
- "gather_dims_to_operand_dims={0,1,2,3,4}, "
- "index_vector_dim=2, window_bounds={30,29,28,27,26}");
+ "s64[10,9,5,7,6]{4,3,2,1,0} %start_indices), "
+ "offset_dims={4,5,6,7,8}, collapsed_slice_dims={}, "
+ "start_index_map={0,1,2,3,4}, "
+ "index_vector_dim=2, slice_sizes={30,29,28,27,26}");
}
TEST_F(HloInstructionTest, StringifyScatter) {
diff --git a/tensorflow/compiler/xla/service/hlo_instructions.cc b/tensorflow/compiler/xla/service/hlo_instructions.cc
index 1de5032670..0751aacdd6 100644
--- a/tensorflow/compiler/xla/service/hlo_instructions.cc
+++ b/tensorflow/compiler/xla/service/hlo_instructions.cc
@@ -17,6 +17,7 @@ limitations under the License.
#include <deque>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
@@ -1528,13 +1529,6 @@ HloInfeedInstruction::HloInfeedInstruction(const Shape& infeed_shape,
AppendOperand(token_operand);
}
-HloInfeedInstruction::HloInfeedInstruction(const Shape& infeed_shape,
- const string& config)
- : HloInstruction(HloOpcode::kInfeed,
- ShapeUtil::MakeTupleShape(
- {infeed_shape, ShapeUtil::MakeTokenShape()})),
- infeed_config_(config) {}
-
HloInstructionProto HloInfeedInstruction::ToProto() const {
HloInstructionProto proto = HloInstruction::ToProto();
proto.set_infeed_config(infeed_config_);
@@ -1561,13 +1555,9 @@ std::unique_ptr<HloInstruction> HloInfeedInstruction::CloneWithNewOperandsImpl(
const Shape& shape,
tensorflow::gtl::ArraySlice<HloInstruction*> new_operands,
HloCloneContext* context) const {
- if (new_operands.empty()) {
- return MakeUnique<HloInfeedInstruction>(infeed_shape(), infeed_config());
- } else {
- CHECK_EQ(new_operands.size(), 1);
- return MakeUnique<HloInfeedInstruction>(infeed_shape(), new_operands[0],
- infeed_config());
- }
+ CHECK_EQ(new_operands.size(), 1);
+ return MakeUnique<HloInfeedInstruction>(infeed_shape(), new_operands[0],
+ infeed_config());
}
HloOutfeedInstruction::HloOutfeedInstruction(
@@ -1583,18 +1573,6 @@ HloOutfeedInstruction::HloOutfeedInstruction(
AppendOperand(token_operand);
}
-HloOutfeedInstruction::HloOutfeedInstruction(
- const Shape& outfeed_shape, HloInstruction* operand,
- tensorflow::StringPiece outfeed_config)
- : HloInstruction(HloOpcode::kOutfeed, ShapeUtil::MakeTokenShape()),
- outfeed_shape_(outfeed_shape),
- outfeed_config_(outfeed_config.begin(), outfeed_config.end()) {
- CHECK(ShapeUtil::Compatible(operand->shape(), outfeed_shape))
- << "Outfeed shape " << outfeed_shape
- << " must be compatible with operand shape " << operand->shape();
- AppendOperand(operand);
-}
-
HloInstructionProto HloOutfeedInstruction::ToProto() const {
HloInstructionProto proto = HloInstruction::ToProto();
proto.set_outfeed_config(outfeed_config());
@@ -1622,22 +1600,19 @@ std::unique_ptr<HloInstruction> HloOutfeedInstruction::CloneWithNewOperandsImpl(
const Shape& shape,
tensorflow::gtl::ArraySlice<HloInstruction*> new_operands,
HloCloneContext* context) const {
- if (new_operands.size() == 1) {
- return MakeUnique<HloOutfeedInstruction>(outfeed_shape(), new_operands[0],
- outfeed_config());
- } else {
- CHECK_EQ(new_operands.size(), 2);
- return MakeUnique<HloOutfeedInstruction>(outfeed_shape(), new_operands[0],
- new_operands[1], outfeed_config());
- }
+ CHECK_EQ(new_operands.size(), 2);
+ return MakeUnique<HloOutfeedInstruction>(outfeed_shape(), new_operands[0],
+ new_operands[1], outfeed_config());
}
HloConvolutionInstruction::HloConvolutionInstruction(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
- const Window& window, const ConvolutionDimensionNumbers& dimension_numbers)
+ const Window& window, const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count)
: HloInstruction(HloOpcode::kConvolution, shape),
window_(window),
- convolution_dimension_numbers_(dimension_numbers) {
+ convolution_dimension_numbers_(dimension_numbers),
+ feature_group_count_(feature_group_count) {
if (window_util::HasBaseDilation(window)) {
SetAndSanitizeName(StrCat(name(), "-base-dilated"));
}
@@ -1675,6 +1650,7 @@ std::vector<string> HloConvolutionInstruction::ExtraAttributesToStringImpl(
}
extra.push_back(StrCat("dim_labels=", ConvolutionDimensionNumbersToString(
convolution_dimension_numbers_)));
+ extra.push_back(StrCat("feature_group_count=", feature_group_count_));
return extra;
}
@@ -1696,9 +1672,9 @@ HloConvolutionInstruction::CloneWithNewOperandsImpl(
tensorflow::gtl::ArraySlice<HloInstruction*> new_operands,
HloCloneContext* context) const {
CHECK_EQ(new_operands.size(), 2);
- return MakeUnique<HloConvolutionInstruction>(shape, new_operands[0],
- new_operands[1], window(),
- convolution_dimension_numbers_);
+ return MakeUnique<HloConvolutionInstruction>(
+ shape, new_operands[0], new_operands[1], window(),
+ convolution_dimension_numbers_, feature_group_count_);
}
HloReduceWindowInstruction::HloReduceWindowInstruction(
@@ -1990,51 +1966,50 @@ HloDynamicSliceInstruction::CloneWithNewOperandsImpl(
}
HloGatherInstruction::HloGatherInstruction(
- const Shape& shape, HloInstruction* operand, HloInstruction* gather_indices,
+ const Shape& shape, HloInstruction* operand, HloInstruction* start_indices,
const GatherDimensionNumbers& gather_dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds)
+ tensorflow::gtl::ArraySlice<int64> slice_sizes)
: HloInstruction(HloOpcode::kGather, shape) {
AppendOperand(operand);
- AppendOperand(gather_indices);
+ AppendOperand(start_indices);
gather_dimension_numbers_ =
MakeUnique<GatherDimensionNumbers>(gather_dim_numbers);
- c_copy(window_bounds, std::back_inserter(gather_window_bounds_));
+ absl::c_copy(slice_sizes, std::back_inserter(gather_slice_sizes_));
}
string HloGatherInstruction::GatherDimensionNumbersToString() const {
CHECK(gather_dimension_numbers_ != nullptr);
- string output_window_dims =
- StrCat("output_window_dims={",
- Join(gather_dimension_numbers_->output_window_dims(), ","), "}");
- string elided_window_dims =
- StrCat("elided_window_dims={",
- Join(gather_dimension_numbers_->elided_window_dims(), ","), "}");
- string gather_dims_to_operand_dims = StrCat(
- "gather_dims_to_operand_dims={",
- Join(gather_dimension_numbers_->gather_dims_to_operand_dims(), ","), "}");
+ string offset_dims =
+ StrCat("offset_dims={",
+ Join(gather_dimension_numbers_->offset_dims(), ","), "}");
+ string collapsed_slice_dims =
+ StrCat("collapsed_slice_dims={",
+ Join(gather_dimension_numbers_->collapsed_slice_dims(), ","), "}");
+ string start_index_map =
+ StrCat("start_index_map={",
+ Join(gather_dimension_numbers_->start_index_map(), ","), "}");
string index_vector_dim = StrCat(
"index_vector_dim=", gather_dimension_numbers_->index_vector_dim());
return Join<std::initializer_list<string>>(
- {output_window_dims, elided_window_dims, gather_dims_to_operand_dims,
- index_vector_dim},
+ {offset_dims, collapsed_slice_dims, start_index_map, index_vector_dim},
", ");
}
/* static */ GatherDimensionNumbers HloGatherInstruction::MakeGatherDimNumbers(
- tensorflow::gtl::ArraySlice<int64> output_window_dims,
- tensorflow::gtl::ArraySlice<int64> elided_window_dims,
- tensorflow::gtl::ArraySlice<int64> gather_dims_to_operand_dims,
+ tensorflow::gtl::ArraySlice<int64> offset_dims,
+ tensorflow::gtl::ArraySlice<int64> collapsed_slice_dims,
+ tensorflow::gtl::ArraySlice<int64> start_index_map,
int64 index_vector_dim) {
GatherDimensionNumbers gather_dim_numbers;
- for (int64 output_window_dim : output_window_dims) {
- gather_dim_numbers.add_output_window_dims(output_window_dim);
+ for (int64 output_window_dim : offset_dims) {
+ gather_dim_numbers.add_offset_dims(output_window_dim);
}
- for (int64 elided_window_dim : elided_window_dims) {
- gather_dim_numbers.add_elided_window_dims(elided_window_dim);
+ for (int64 elided_window_dim : collapsed_slice_dims) {
+ gather_dim_numbers.add_collapsed_slice_dims(elided_window_dim);
}
- for (int64 gather_dim_to_input_dim : gather_dims_to_operand_dims) {
- gather_dim_numbers.add_gather_dims_to_operand_dims(gather_dim_to_input_dim);
+ for (int64 gather_dim_to_input_dim : start_index_map) {
+ gather_dim_numbers.add_start_index_map(gather_dim_to_input_dim);
}
gather_dim_numbers.set_index_vector_dim(index_vector_dim);
@@ -2044,8 +2019,8 @@ string HloGatherInstruction::GatherDimensionNumbersToString() const {
HloInstructionProto HloGatherInstruction::ToProto() const {
HloInstructionProto proto = HloInstruction::ToProto();
*proto.mutable_gather_dimension_numbers() = gather_dimension_numbers();
- for (int64 bound : gather_window_bounds()) {
- proto.add_gather_window_bounds(bound);
+ for (int64 bound : gather_slice_sizes()) {
+ proto.add_gather_slice_sizes(bound);
}
return proto;
}
@@ -2053,7 +2028,7 @@ HloInstructionProto HloGatherInstruction::ToProto() const {
std::vector<string> HloGatherInstruction::ExtraAttributesToStringImpl(
const HloPrintOptions& options) const {
return {GatherDimensionNumbersToString(),
- StrCat("window_bounds={", Join(gather_window_bounds(), ","), "}")};
+ StrCat("slice_sizes={", Join(gather_slice_sizes(), ","), "}")};
}
bool HloGatherInstruction::IdenticalSlowPath(
@@ -2064,7 +2039,7 @@ bool HloGatherInstruction::IdenticalSlowPath(
return protobuf_util::ProtobufEquals(
gather_dimension_numbers(),
casted_other.gather_dimension_numbers()) &&
- gather_window_bounds() == casted_other.gather_window_bounds();
+ gather_slice_sizes() == casted_other.gather_slice_sizes();
}
std::unique_ptr<HloInstruction> HloGatherInstruction::CloneWithNewOperandsImpl(
@@ -2074,7 +2049,7 @@ std::unique_ptr<HloInstruction> HloGatherInstruction::CloneWithNewOperandsImpl(
CHECK_EQ(new_operands.size(), 2);
return MakeUnique<HloGatherInstruction>(
shape, new_operands[0], new_operands[1], gather_dimension_numbers(),
- gather_window_bounds());
+ gather_slice_sizes());
}
HloScatterInstruction::HloScatterInstruction(
diff --git a/tensorflow/compiler/xla/service/hlo_instructions.h b/tensorflow/compiler/xla/service/hlo_instructions.h
index 9586ad6673..803dbeabeb 100644
--- a/tensorflow/compiler/xla/service/hlo_instructions.h
+++ b/tensorflow/compiler/xla/service/hlo_instructions.h
@@ -883,10 +883,6 @@ class HloInfeedInstruction : public HloInstruction {
explicit HloInfeedInstruction(const Shape& infeed_shape,
HloInstruction* token_operand,
const string& config);
- // TODO(b/80000000): Remove this constructor when all uses of infeed are
- // converted to take tokens.
- explicit HloInfeedInstruction(const Shape& infeed_shape,
- const string& config);
// Returns the infeed configuration string. The infeed configuration includes
// any metadata needed for the backend compiler (e.g., infeed buffer address)
// and is target-dependent.
@@ -925,12 +921,6 @@ class HloOutfeedInstruction : public HloInstruction {
HloInstruction* operand,
HloInstruction* token_operand,
tensorflow::StringPiece outfeed_config);
- // TODO(b/80000000): Remove this constructor when all uses of outfeed are
- // converted to take tokens.
- explicit HloOutfeedInstruction(const Shape& outfeed_shape,
- HloInstruction* operand,
- tensorflow::StringPiece outfeed_config);
-
// Returns the shape for the Outfeed instruction.
const Shape& outfeed_shape() const {
TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(outfeed_shape_));
@@ -965,7 +955,8 @@ class HloConvolutionInstruction : public HloInstruction {
explicit HloConvolutionInstruction(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
const Window& window,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count);
const Window& window() const override { return window_; }
void set_window(const Window& window) override { window_ = window; }
const ConvolutionDimensionNumbers& convolution_dimension_numbers() const {
@@ -975,6 +966,9 @@ class HloConvolutionInstruction : public HloInstruction {
const ConvolutionDimensionNumbers& dnums) {
convolution_dimension_numbers_ = dnums;
}
+ // The number of feature groups. Must be a divisor of the input feature
+ // dimension and output feature dimension.
+ int64 feature_group_count() const { return feature_group_count_; }
string ToCategory() const override;
// Returns a serialized representation of this instruction.
HloInstructionProto ToProto() const override;
@@ -994,6 +988,9 @@ class HloConvolutionInstruction : public HloInstruction {
Window window_;
// Describes the dimension numbers used for a convolution.
ConvolutionDimensionNumbers convolution_dimension_numbers_;
+ // The number of feature groups. Must be a divisor of the input feature
+ // dimension and output feature dimension.
+ int64 feature_group_count_;
};
class HloReduceWindowInstruction : public HloInstruction {
@@ -1215,15 +1212,15 @@ class HloGatherInstruction : public HloInstruction {
public:
explicit HloGatherInstruction(
const Shape& shape, HloInstruction* operand,
- HloInstruction* gather_indices,
+ HloInstruction* start_indices,
const GatherDimensionNumbers& gather_dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes);
const GatherDimensionNumbers& gather_dimension_numbers() const {
CHECK(gather_dimension_numbers_ != nullptr);
return *gather_dimension_numbers_;
}
- tensorflow::gtl::ArraySlice<int64> gather_window_bounds() const {
- return gather_window_bounds_;
+ tensorflow::gtl::ArraySlice<int64> gather_slice_sizes() const {
+ return gather_slice_sizes_;
}
// Returns the dump string of the gather dimension numbers.
string GatherDimensionNumbersToString() const;
@@ -1232,9 +1229,9 @@ class HloGatherInstruction : public HloInstruction {
// Creates an instance of GatherDimensionNumbers.
static GatherDimensionNumbers MakeGatherDimNumbers(
- tensorflow::gtl::ArraySlice<int64> output_window_dims,
- tensorflow::gtl::ArraySlice<int64> elided_window_dims,
- tensorflow::gtl::ArraySlice<int64> gather_dims_to_operand_dims,
+ tensorflow::gtl::ArraySlice<int64> offset_dims,
+ tensorflow::gtl::ArraySlice<int64> collapsed_slice_dims,
+ tensorflow::gtl::ArraySlice<int64> start_index_map,
int64 index_vector_dim);
private:
@@ -1250,7 +1247,7 @@ class HloGatherInstruction : public HloInstruction {
HloCloneContext* context) const override;
std::unique_ptr<GatherDimensionNumbers> gather_dimension_numbers_;
- std::vector<int64> gather_window_bounds_;
+ std::vector<int64> gather_slice_sizes_;
};
class HloScatterInstruction : public HloInstruction {
diff --git a/tensorflow/compiler/xla/service/hlo_lexer.cc b/tensorflow/compiler/xla/service/hlo_lexer.cc
index 71b44507cc..8e0d38b6a6 100644
--- a/tensorflow/compiler/xla/service/hlo_lexer.cc
+++ b/tensorflow/compiler/xla/service/hlo_lexer.cc
@@ -143,8 +143,47 @@ TokKind HloLexer::LexToken() {
return TokKind::kLparen;
case ')':
return TokKind::kRparen;
- case '/':
- return LexComment();
+ case '/': {
+ if (PeekCurrentChar() == '*') {
+ // This is the start of a /*...*/ delimited comment. Save the current
+ // location in case the comment is unterminated so the error message
+ // will point to the beginning of the comment.
+ const char* comment_start = current_ptr_;
+ current_ptr_++;
+ // Advance until '*/' is found.
+ while (true) {
+ int current = GetNextChar();
+ if (current == '*' && PeekCurrentChar() == '/') {
+ // End of comment.
+ current_ptr_++;
+ break;
+ }
+ if (current == kEOF) {
+ // Unterminated comment.
+ current_ptr_ = comment_start;
+ return TokKind::kError;
+ }
+ }
+ // Return no token for the comment. Keep lexing.
+ continue;
+ } else if (PeekCurrentChar() == '/') {
+ // This is the start of a '//' delimited comment. Throw away
+ // everything until end of line or file. The end-of-line character(s)
+ // are left unlexed in the buffer which is harmless because these are
+ // skipped later by the lexer. This approach enables support for
+ // different end-of-line encodings.
+ while (true) {
+ int current = PeekCurrentChar();
+ if (current == kEOF || current == '\n' || current == '\r') {
+ break;
+ }
+ current_ptr_++;
+ }
+ continue;
+ }
+ // A lone '/' is an error.
+ return TokKind::kError;
+ }
case '"':
return LexString();
}
@@ -357,16 +396,6 @@ tensorflow::StringPiece HloLexer::GetLine(LocTy loc) const {
return StringPieceFromPointers(start, end);
}
-TokKind HloLexer::LexComment() {
- auto consumable = RegexpStringPieceFromPointers(token_start_, buf_.end());
- static LazyRE2 comment_pattern = {R"(\/\*.*?\*\/)"};
- if (RE2::Consume(&consumable, *comment_pattern)) {
- current_ptr_ = consumable.begin();
- return TokKind::kComment;
- }
- return TokKind::kError;
-}
-
// Lexes quoted string with escaping characters. If matched, the quoted string
// will be unescaped and stored to str_val_.
TokKind HloLexer::LexString() {
@@ -412,8 +441,6 @@ string TokKindToString(TokKind kind) {
return "kRparen";
case TokKind::kArrow:
return "kArrow";
- case TokKind::kComment:
- return "kComment";
case TokKind::kw_HloModule:
return "kw_HloModule";
case TokKind::kw_ENTRY:
diff --git a/tensorflow/compiler/xla/service/hlo_lexer.h b/tensorflow/compiler/xla/service/hlo_lexer.h
index ceb674f25e..003ac34ace 100644
--- a/tensorflow/compiler/xla/service/hlo_lexer.h
+++ b/tensorflow/compiler/xla/service/hlo_lexer.h
@@ -105,7 +105,6 @@ class HloLexer {
TokKind LexShape();
TokKind LexConstant();
TokKind LexNumberOrPattern();
- TokKind LexComment();
TokKind LexString();
const tensorflow::StringPiece buf_;
diff --git a/tensorflow/compiler/xla/service/hlo_matchers.h b/tensorflow/compiler/xla/service/hlo_matchers.h
index b57c940238..c577b4359a 100644
--- a/tensorflow/compiler/xla/service/hlo_matchers.h
+++ b/tensorflow/compiler/xla/service/hlo_matchers.h
@@ -231,6 +231,7 @@ HLO_MATCHER(Tanh);
HLO_MATCHER(Trace);
HLO_MATCHER(Transpose);
HLO_MATCHER(Tuple);
+HLO_MATCHER(TupleSelect);
HLO_MATCHER(While);
// The special cases below let you check additional information about the
diff --git a/tensorflow/compiler/xla/service/hlo_module.cc b/tensorflow/compiler/xla/service/hlo_module.cc
index 55ff073d3f..76f8236048 100644
--- a/tensorflow/compiler/xla/service/hlo_module.cc
+++ b/tensorflow/compiler/xla/service/hlo_module.cc
@@ -22,6 +22,7 @@ limitations under the License.
#include <unordered_set>
#include <utility>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
@@ -538,9 +539,9 @@ uint64 HloModule::RandomNew64() const {
HloComputation* HloModule::GetComputationWithName(
tensorflow::StringPiece name) {
auto computations_in_module = computations();
- auto it = c_find_if(computations_in_module, [&](HloComputation* computation) {
- return computation->name() == name;
- });
+ auto it = absl::c_find_if(
+ computations_in_module,
+ [&](HloComputation* computation) { return computation->name() == name; });
return it == computations_in_module.end() ? nullptr : *it;
}
diff --git a/tensorflow/compiler/xla/service/hlo_module_group_metadata.h b/tensorflow/compiler/xla/service/hlo_module_group_metadata.h
index 84f2d3f5fb..1b256cd00e 100644
--- a/tensorflow/compiler/xla/service/hlo_module_group_metadata.h
+++ b/tensorflow/compiler/xla/service/hlo_module_group_metadata.h
@@ -166,7 +166,7 @@ class HloModuleGroupMetadata {
//
// Precondition: IsCompanionWhile(instruction) is true.
const std::unordered_set<HloInstruction*>& Companions(
- HloInstruction* instruction) const {
+ const HloInstruction* instruction) const {
CHECK_EQ(companion_set_index_.count(instruction), 1);
return companion_set(companion_set_index_.at(instruction));
}
@@ -243,7 +243,7 @@ class HloModuleGroupMetadata {
companion_sets_;
// Map from each companion while instruction to the index into companion_set_.
- tensorflow::gtl::FlatMap<HloInstruction*, int64> companion_set_index_;
+ tensorflow::gtl::FlatMap<const HloInstruction*, int64> companion_set_index_;
// Map from computation to the instruction using it (a kWhile, kConditional).
tensorflow::gtl::FlatMap<const HloComputation*, TrackedInstruction>
diff --git a/tensorflow/compiler/xla/service/hlo_module_group_util.cc b/tensorflow/compiler/xla/service/hlo_module_group_util.cc
index 9fd0ade153..0dc5676148 100644
--- a/tensorflow/compiler/xla/service/hlo_module_group_util.cc
+++ b/tensorflow/compiler/xla/service/hlo_module_group_util.cc
@@ -29,6 +29,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
+#include "tensorflow/core/lib/gtl/flatset.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
@@ -37,24 +38,38 @@ namespace xla {
std::vector<HloInstruction*> HloModuleGroupUtil::GlobalPredecessors(
HloInstruction* instruction) {
- std::vector<HloInstruction*> predecessors;
-
- // Adds to the unique predecessors list and also add companion instructions
- // if the given predecessor has those.
+ std::vector<HloInstruction*>
+ predecessors; // Use a vector to avoid non-determinism.
+ tensorflow::gtl::FlatSet<HloInstruction*> unique;
+
+ // Adds to the unique predecessors list; if the predecessors is a companion
+ // instruction, also add companion instructions; if the predecessors is a
+ // cross-module all-reduce, also add the all-reduce instructions in the same
+ // group.
auto add_unique_predecessor = [&](HloInstruction* predecessor) {
- if (std::find(predecessors.begin(), predecessors.end(), predecessor) !=
- predecessors.end()) {
+ if (unique.find(predecessor) != unique.end()) {
return;
}
- if (!metadata_.IsCompanionInstruction(predecessor)) {
- predecessors.push_back(predecessor);
+ if (metadata_.IsCompanionInstruction(predecessor)) {
+ for (HloInstruction* instr : metadata_.Companions(predecessor)) {
+ if (unique.insert(instr).second) {
+ predecessors.push_back(instr);
+ }
+ }
return;
}
- for (HloInstruction* companion : metadata_.Companions(predecessor)) {
- predecessors.push_back(companion);
+ if (predecessor->IsCrossModuleAllReduce()) {
+ for (HloInstruction* instr :
+ metadata_.GetAllReduceGroup(*predecessor->all_reduce_id())) {
+ if (unique.insert(instr).second) {
+ predecessors.push_back(instr);
+ }
+ }
+ return;
}
+ unique.insert(predecessor);
+ predecessors.push_back(predecessor);
};
-
// If the given instruction is a companion instruction, we need to find the
// predecessors of all of its companion instructions. If the instruction is an
// all-reduce, we need to find the predecessors of all the peer all-reduce
@@ -98,22 +113,37 @@ std::vector<HloInstruction*> HloModuleGroupUtil::GlobalPredecessors(
std::vector<HloInstruction*> HloModuleGroupUtil::GlobalSuccessors(
HloInstruction* instruction) {
- std::vector<HloInstruction*> successors;
-
- // Adds to the unique successors list and also add companion instructions
- // if the given successor has those.
+ std::vector<HloInstruction*>
+ successors; // Use a vector to avoid non-determinism.
+ tensorflow::gtl::FlatSet<HloInstruction*> unique;
+
+ // Adds to the unique successors list; if the successor is a companion
+ // instruction, also add companion instructions; if the successor is a
+ // cross-module all-reduce, also add the all-reduce instructions in the same
+ // group.
auto add_unique_successor = [&](HloInstruction* successor) {
- if (std::find(successors.begin(), successors.end(), successor) !=
- successors.end()) {
+ if (unique.find(successor) != unique.end()) {
return;
}
- if (!metadata_.IsCompanionInstruction(successor)) {
- successors.push_back(successor);
+ if (metadata_.IsCompanionInstruction(successor)) {
+ for (HloInstruction* instr : metadata_.Companions(successor)) {
+ if (unique.insert(instr).second) {
+ successors.push_back(instr);
+ }
+ }
return;
}
- for (HloInstruction* companion : metadata_.Companions(successor)) {
- successors.push_back(companion);
+ if (successor->IsCrossModuleAllReduce()) {
+ for (HloInstruction* instr :
+ metadata_.GetAllReduceGroup(*successor->all_reduce_id())) {
+ if (unique.insert(instr).second) {
+ successors.push_back(instr);
+ }
+ }
+ return;
}
+ unique.insert(successor);
+ successors.push_back(successor);
};
// If the given instruction is a companion instruction, we need to find the
diff --git a/tensorflow/compiler/xla/service/hlo_opcode.h b/tensorflow/compiler/xla/service/hlo_opcode.h
index ec279867e5..0e0d96ab09 100644
--- a/tensorflow/compiler/xla/service/hlo_opcode.h
+++ b/tensorflow/compiler/xla/service/hlo_opcode.h
@@ -156,7 +156,7 @@ enum HloOpcodeProperty {
// Returns a string representation of the opcode.
string HloOpcodeString(HloOpcode opcode);
-// Returns a string representation of the opcode.
+// Retrieves the opcode enum by name if the opcode exists.
StatusOr<HloOpcode> StringToHloOpcode(const string& opcode_name);
inline std::ostream& operator<<(std::ostream& os, HloOpcode opcode) {
diff --git a/tensorflow/compiler/xla/service/hlo_parser.cc b/tensorflow/compiler/xla/service/hlo_parser.cc
index 2a8c6ecd92..e48c9d2c41 100644
--- a/tensorflow/compiler/xla/service/hlo_parser.cc
+++ b/tensorflow/compiler/xla/service/hlo_parser.cc
@@ -15,6 +15,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/hlo_parser.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_domain_metadata.h"
@@ -635,12 +636,13 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
}
std::vector<ReplicaGroup> replica_groups;
if (tmp_groups) {
- c_transform(*tmp_groups, std::back_inserter(replica_groups),
- [](const std::vector<int64>& ids) {
- ReplicaGroup group;
- *group.mutable_replica_ids() = {ids.begin(), ids.end()};
- return group;
- });
+ absl::c_transform(
+ *tmp_groups, std::back_inserter(replica_groups),
+ [](const std::vector<int64>& ids) {
+ ReplicaGroup group;
+ *group.mutable_replica_ids() = {ids.begin(), ids.end()};
+ return group;
+ });
}
instruction = builder->AddInstruction(HloInstruction::CreateAllToAll(
shape, operands, replica_groups, barrier ? *barrier : ""));
@@ -825,9 +827,12 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
case HloOpcode::kConvolution: {
optional<Window> window;
optional<ConvolutionDimensionNumbers> dnums;
+ optional<int64> feature_group_count;
attrs["window"] = {/*required=*/false, AttrTy::kWindow, &window};
attrs["dim_labels"] = {/*required=*/true,
AttrTy::kConvolutionDimensionNumbers, &dnums};
+ attrs["feature_group_count"] = {/*required=*/false, AttrTy::kInt64,
+ &feature_group_count};
if (!ParseOperands(&operands, /*expected_size=*/2) ||
!ParseAttributes(attrs)) {
return false;
@@ -835,8 +840,12 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
if (!window) {
window.emplace();
}
+ if (!feature_group_count) {
+ feature_group_count = 1;
+ }
instruction = builder->AddInstruction(HloInstruction::CreateConvolve(
- shape, /*lhs=*/operands[0], /*rhs=*/operands[1], *window, *dnums));
+ shape, /*lhs=*/operands[0], /*rhs=*/operands[1], *window, *dnums,
+ feature_group_count.value()));
break;
}
case HloOpcode::kFft: {
@@ -1073,7 +1082,8 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
case HloOpcode::kInfeed: {
optional<string> config;
attrs["infeed_config"] = {/*required=*/false, AttrTy::kString, &config};
- if (!ParseOperands(&operands) || !ParseAttributes(attrs)) {
+ if (!ParseOperands(&operands, /*expected_size=*/1) ||
+ !ParseAttributes(attrs)) {
return false;
}
// We need to know the infeed data shape to construct the infeed
@@ -1085,41 +1095,21 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
return Error(lexer_.GetLoc(),
"infeed must have a non-empty tuple shape");
}
-
- if (operands.empty()) {
- // TODO(b/80000000): Remove this when all uses of infeed are
- // converted to take tokens.
- instruction = builder->AddInstruction(HloInstruction::CreateInfeed(
- ShapeUtil::GetTupleElementShape(shape, 0), config ? *config : ""));
- } else if (operands.size() == 1) {
- instruction = builder->AddInstruction(HloInstruction::CreateInfeed(
- ShapeUtil::GetTupleElementShape(shape, 0), operands[0],
- config ? *config : ""));
- } else {
- return Error(lexer_.GetLoc(),
- "infeed must have exactly zero or one operands");
- }
+ instruction = builder->AddInstruction(HloInstruction::CreateInfeed(
+ ShapeUtil::GetTupleElementShape(shape, 0), operands[0],
+ config ? *config : ""));
break;
}
case HloOpcode::kOutfeed: {
optional<string> config;
attrs["outfeed_config"] = {/*required=*/false, AttrTy::kString, &config};
- if (!ParseOperands(&operands) || !ParseAttributes(attrs)) {
+ if (!ParseOperands(&operands, /*expected_size=*/2) ||
+ !ParseAttributes(attrs)) {
return false;
}
- if (operands.size() == 1) {
- // TODO(b/80000000): Remove this when all uses of outfeed are
- // converted to take tokens.
- instruction = builder->AddInstruction(HloInstruction::CreateOutfeed(
- operands[0]->shape(), operands[0], config ? *config : ""));
- } else if (operands.size() == 2) {
- instruction = builder->AddInstruction(
- HloInstruction::CreateOutfeed(operands[0]->shape(), operands[0],
- operands[1], config ? *config : ""));
- } else {
- return Error(lexer_.GetLoc(),
- "outfeed must have exactly one or two operands");
- }
+ instruction = builder->AddInstruction(
+ HloInstruction::CreateOutfeed(operands[0]->shape(), operands[0],
+ operands[1], config ? *config : ""));
break;
}
case HloOpcode::kRng: {
@@ -1245,22 +1235,21 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
break;
}
case HloOpcode::kGather: {
- optional<std::vector<tensorflow::int64>> output_window_dims;
- attrs["output_window_dims"] = {
- /*required=*/true, AttrTy::kBracedInt64List, &output_window_dims};
- optional<std::vector<tensorflow::int64>> elided_window_dims;
- attrs["elided_window_dims"] = {
- /*required=*/true, AttrTy::kBracedInt64List, &elided_window_dims};
- optional<std::vector<tensorflow::int64>> gather_dims_to_operand_dims;
- attrs["gather_dims_to_operand_dims"] = {/*required=*/true,
- AttrTy::kBracedInt64List,
- &gather_dims_to_operand_dims};
+ optional<std::vector<tensorflow::int64>> offset_dims;
+ attrs["offset_dims"] = {/*required=*/true, AttrTy::kBracedInt64List,
+ &offset_dims};
+ optional<std::vector<tensorflow::int64>> collapsed_slice_dims;
+ attrs["collapsed_slice_dims"] = {
+ /*required=*/true, AttrTy::kBracedInt64List, &collapsed_slice_dims};
+ optional<std::vector<tensorflow::int64>> start_index_map;
+ attrs["start_index_map"] = {/*required=*/true, AttrTy::kBracedInt64List,
+ &start_index_map};
optional<tensorflow::int64> index_vector_dim;
attrs["index_vector_dim"] = {/*required=*/true, AttrTy::kInt64,
&index_vector_dim};
- optional<std::vector<tensorflow::int64>> window_bounds;
- attrs["window_bounds"] = {/*required=*/true, AttrTy::kBracedInt64List,
- &window_bounds};
+ optional<std::vector<tensorflow::int64>> slice_sizes;
+ attrs["slice_sizes"] = {/*required=*/true, AttrTy::kBracedInt64List,
+ &slice_sizes};
if (!ParseOperands(&operands, /*expected_size=*/2) ||
!ParseAttributes(attrs)) {
@@ -1269,14 +1258,14 @@ bool HloParser::ParseInstruction(HloComputation::Builder* builder,
GatherDimensionNumbers dim_numbers =
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/*output_window_dims,
- /*elided_window_dims=*/*elided_window_dims,
- /*gather_dims_to_operand_dims=*/*gather_dims_to_operand_dims,
+ /*offset_dims=*/*offset_dims,
+ /*collapsed_slice_dims=*/*collapsed_slice_dims,
+ /*start_index_map=*/*start_index_map,
/*index_vector_dim=*/*index_vector_dim);
instruction = builder->AddInstruction(HloInstruction::CreateGather(
- shape, /*operand=*/operands[0], /*gather_indices=*/operands[1],
- dim_numbers, *window_bounds));
+ shape, /*operand=*/operands[0], /*start_indices=*/operands[1],
+ dim_numbers, *slice_sizes));
break;
}
case HloOpcode::kScatter: {
@@ -1824,7 +1813,6 @@ bool HloParser::ParseDenseLiteral(std::unique_ptr<Literal>* literal,
break;
}
case TokKind::kComma:
- case TokKind::kComment:
// Skip.
lexer_.Lex();
break;
diff --git a/tensorflow/compiler/xla/service/hlo_parser_test.cc b/tensorflow/compiler/xla/service/hlo_parser_test.cc
index 4cd21841f4..0d7919346b 100644
--- a/tensorflow/compiler/xla/service/hlo_parser_test.cc
+++ b/tensorflow/compiler/xla/service/hlo_parser_test.cc
@@ -380,7 +380,7 @@ ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,2
%input = f32[1,2,1]{2,1,0} parameter(0)
%copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input)
%filter = f32[1,1,1]{2,1,0} parameter(1)
- ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), window={size=1}, dim_labels=b0f_0io->b0f
+ ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), window={size=1}, dim_labels=b0f_0io->b0f, feature_group_count=1
}
)"
@@ -393,7 +393,7 @@ R"(HloModule ConvolveR2_module
ENTRY %ConvolveR2.v3 (input: f32[1,2], filter: f32[1,1]) -> f32[1,2] {
%input = f32[1,2]{1,0} parameter(0)
%filter = f32[1,1]{1,0} parameter(1)
- ROOT %convolution = f32[1,2]{0,1} convolution(f32[1,2]{1,0} %input, f32[1,1]{1,0} %filter), dim_labels=bf_io->bf
+ ROOT %convolution = f32[1,2]{0,1} convolution(f32[1,2]{1,0} %input, f32[1,1]{1,0} %filter), dim_labels=bf_io->bf, feature_group_count=1
}
)"
@@ -406,7 +406,7 @@ R"(HloModule ConvolveBackward_module
ENTRY %ConvolveBackward (input: f32[128,7,7,512], filter: f32[3,3,512,512]) -> f32[128,14,14,512] {
%input = f32[128,7,7,512]{0,3,2,1} parameter(0)
%filter = f32[3,3,512,512]{3,2,1,0} parameter(1)
- ROOT %convolution-base-dilated = f32[128,14,14,512]{0,3,2,1} convolution(f32[128,7,7,512]{0,3,2,1} %input, f32[3,3,512,512]{3,2,1,0} %filter), window={size=3x3 pad=1_2x1_2 lhs_dilate=2x2 rhs_reversal=1x1}, dim_labels=b01f_01oi->b01f
+ ROOT %convolution-base-dilated = f32[128,14,14,512]{0,3,2,1} convolution(f32[128,7,7,512]{0,3,2,1} %input, f32[3,3,512,512]{3,2,1,0} %filter), window={size=3x3 pad=1_2x1_2 lhs_dilate=2x2 rhs_reversal=1x1}, dim_labels=b01f_01oi->b01f, feature_group_count=1
}
)"
@@ -752,10 +752,10 @@ ENTRY %sparse_f32_r1 () -> f32[9] {
"gather",
R"(HloModule StringifyGather
-ENTRY %Gather (input_tensor: f32[50,49,48,47,46], gather_indices: s64[10,9,8,7,5]) -> f32[10,9,8,7,30,29,28,27,26] {
+ENTRY %Gather (input_tensor: f32[50,49,48,47,46], start_indices: s64[10,9,8,7,5]) -> f32[10,9,8,7,30,29,28,27,26] {
%input_tensor = f32[50,49,48,47,46]{4,3,2,1,0} parameter(0)
- %gather_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
- ROOT %gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} gather(f32[50,49,48,47,46]{4,3,2,1,0} %input_tensor, s64[10,9,8,7,5]{4,3,2,1,0} %gather_indices), output_window_dims={4,5,6,7,8}, elided_window_dims={}, gather_dims_to_operand_dims={0,1,2,3,4}, index_vector_dim=4, window_bounds={30,29,28,27,26}
+ %start_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
+ ROOT %gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} gather(f32[50,49,48,47,46]{4,3,2,1,0} %input_tensor, s64[10,9,8,7,5]{4,3,2,1,0} %start_indices), offset_dims={4,5,6,7,8}, collapsed_slice_dims={}, start_index_map={0,1,2,3,4}, index_vector_dim=4, slice_sizes={30,29,28,27,26}
}
)"
@@ -1030,8 +1030,8 @@ R"(HloModule gather
ENTRY Gather {
input_tensor = f32[50,49,48,47,46]{4,3,2,1,0} parameter(0)
- gather_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
- ROOT gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} gather(input_tensor, gather_indices), output_window_dims={4,5,6,7,8}, elided_window_dims={}, gather_dims_to_operand_dims={0,1,2,3,4}, index_vector_dim=4, window_bounds={30,29,28,27,26}
+ start_indices = s64[10,9,8,7,5]{4,3,2,1,0} parameter(1)
+ ROOT gather = f32[10,9,8,7,30,29,28,27,26]{8,7,6,5,4,3,2,1,0} gather(input_tensor, start_indices), offset_dims={4,5,6,7,8}, collapsed_slice_dims={}, start_index_map={0,1,2,3,4}, index_vector_dim=4, slice_sizes={30,29,28,27,26}
}
)"
@@ -1370,7 +1370,7 @@ ENTRY %Convolve1D1Window_0.v3 (input: f32[1,2,1], filter: f32[1,1,1]) -> f32[1,2
%input = f32[1,2,1]{2,1,0} parameter(0)
%copy = f32[1,2,1]{2,0,1} copy(f32[1,2,1]{2,1,0} %input)
%filter = f32[1,1,1]{2,1,0} parameter(1)
- ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), sharding={maximal device=1}, backend_config="foo", dim_labels=b0f_0io->b0f, window={pad=1_1 size=2}
+ ROOT %convolution = f32[1,2,1]{2,0,1} convolution(f32[1,2,1]{2,0,1} %copy, f32[1,1,1]{2,1,0} %filter), feature_group_count=1, sharding={maximal device=1}, backend_config="foo", dim_labels=b0f_0io->b0f, window={pad=1_1 size=2}
}
)";
@@ -1560,6 +1560,81 @@ ENTRY consts {
"last");
}
+TEST_F(HloParserTest, Comments) {
+ const string original = R"(/* module description. */
+HloModule comments:
+
+ENTRY /*comment*/ c1 {
+ /* blah */
+ ROOT const1 = /*foo*/f32[1]{0} constant({12345 /*bar*/})
+ /* comment */
+}
+
+/* something else */
+
+)";
+ auto module = ParseHloString(original);
+ TF_ASSERT_OK(module.status());
+}
+
+TEST_F(HloParserTest, MultilineComments) {
+ const string original = R"(HloModule multiline_comment:
+ENTRY c1 {
+ /*
+ ROOT foo = f32[1]{0} constant({12345})
+ */
+ ROOT const1 = f32[1]{0} constant({12345})
+/*
+a
+b
+c
+d
+
+*/
+})";
+ auto module = ParseHloString(original);
+ TF_ASSERT_OK(module.status());
+}
+
+TEST_F(HloParserTest, UnterminatedComment) {
+ const string original = R"(HloModule unterminated_comment:
+ENTRY c1 {
+/* unterminated
+ ROOT const1 = f32[1]{0} constant({12345})
+})";
+ // Verify that the error message points to the beginning of the unterminated
+ // comment.
+ ExpectHasSubstr(ParseHloString(original).status().error_message(),
+ "/* unterminated\n^");
+}
+
+TEST_F(HloParserTest, SlashSlashComments) {
+ const string original = R"(HloModule slash_slash_comment:
+// Garbage
+ENTRY c1 {
+ // Foo bar
+ ROOT const1 = f32[1]{0} constant({12345}) // Something else
+})";
+ auto module = ParseHloString(original);
+ TF_ASSERT_OK(module.status());
+}
+
+TEST_F(HloParserTest, SlashSlashCommentMsDosEolFormat) {
+ const string original =
+ "HloModule slash_slash_comment:\r\n// Garbage\r\nENTRY c1 {\r\n// Foo "
+ "bar\r\nROOT const1 = f32[1]{0} constant({12345}) // Something else\r\n}";
+ auto module = ParseHloString(original);
+ TF_ASSERT_OK(module.status());
+}
+
+TEST_F(HloParserTest, SlashSlashCommentMacEolFormat) {
+ const string original =
+ "HloModule slash_slash_comment:\r// Garbage\rENTRY c1 {\r// Foo "
+ "bar\rROOT const1 = f32[1]{0} constant({12345}) // Something else\r}";
+ auto module = ParseHloString(original);
+ TF_ASSERT_OK(module.status());
+}
+
TEST_F(HloParserTest, MultipleEntries) {
const string original = R"(HloModule multiple_entries:
ENTRY c1 {
diff --git a/tensorflow/compiler/xla/service/hlo_pass_fix.h b/tensorflow/compiler/xla/service/hlo_pass_fix.h
index 28194deb0e..791b1a97b0 100644
--- a/tensorflow/compiler/xla/service/hlo_pass_fix.h
+++ b/tensorflow/compiler/xla/service/hlo_pass_fix.h
@@ -45,7 +45,7 @@ class HloPassFix : public Pass {
++iteration_count;
if (iteration_count == limit) {
LOG(ERROR)
- << "Unexpectedly number of iterations in HLO passes ("
+ << "Unexpectedly high number of iterations in HLO passes ("
<< iteration_count
<< ")\nIf compilation hangs here, please file a bug with XLA.";
}
diff --git a/tensorflow/compiler/xla/service/hlo_sharding.cc b/tensorflow/compiler/xla/service/hlo_sharding.cc
index 879fb3bbab..0cba9ebbcb 100644
--- a/tensorflow/compiler/xla/service/hlo_sharding.cc
+++ b/tensorflow/compiler/xla/service/hlo_sharding.cc
@@ -453,7 +453,7 @@ tensorflow::gtl::optional<HloSharding> HloSharding::ExtractSingleSharding()
}
size_t HloSharding::Hash() const {
- if (!tuple_) {
+ if (tuple_) {
size_t h = 0;
for (const auto& element : tuple_elements_) {
h = tensorflow::Hash64Combine(h, element.Hash());
diff --git a/tensorflow/compiler/xla/service/hlo_sharding_metadata.cc b/tensorflow/compiler/xla/service/hlo_sharding_metadata.cc
index 94f5a3b273..a2c1d39d0d 100644
--- a/tensorflow/compiler/xla/service/hlo_sharding_metadata.cc
+++ b/tensorflow/compiler/xla/service/hlo_sharding_metadata.cc
@@ -158,7 +158,6 @@ ShapeTree<HloSharding> GetTupleSharding(HloInstruction* tuple) {
const HloSharding* GetOperandSharding(const HloInstruction* operand,
const DomainMetadata::Domain& domain,
const HloSharding& sharding) {
- DCHECK_EQ(domain.reach_set.count(const_cast<HloInstruction*>(operand)), 1);
// Here the user of operand is within the domain instruction set, and since it
// is user of operand, we need to look into the enter_domains set. If this is
// not a kDomain within the user domains set, then return the operand
@@ -203,10 +202,17 @@ StatusOr<int64> ApplyDomainShardingPass(const DomainMetadata::Domain& domain,
for (int64 i = 0; i < instruction->operand_count(); ++i) {
const HloSharding* operand_sharding =
GetOperandSharding(instruction->operand(i), domain, sharding);
- if (operand_sharding != nullptr &&
- shape_tree.element({i}) != *operand_sharding) {
- *shape_tree.mutable_element({i}) = *operand_sharding;
- ++tuple_assigned;
+ if (operand_sharding != nullptr) {
+ HloSharding operand_subsharding = HloSharding::Replicate();
+ if (operand_sharding == &sharding) {
+ operand_subsharding =
+ sharding.GetSubSharding(instruction->shape(), {i});
+ operand_sharding = &operand_subsharding;
+ }
+ if (shape_tree.element({i}) != *operand_sharding) {
+ *shape_tree.mutable_element({i}) = *operand_sharding;
+ ++tuple_assigned;
+ }
}
}
if (tuple_assigned > 0) {
diff --git a/tensorflow/compiler/xla/service/hlo_token.h b/tensorflow/compiler/xla/service/hlo_token.h
index 533429608b..4458c251de 100644
--- a/tensorflow/compiler/xla/service/hlo_token.h
+++ b/tensorflow/compiler/xla/service/hlo_token.h
@@ -44,7 +44,6 @@ enum class TokKind {
kRparen, // ( )
kArrow, // ->
- kComment, // /*xxx*/
// Keywords
kw_HloModule,
diff --git a/tensorflow/compiler/xla/service/hlo_verifier.cc b/tensorflow/compiler/xla/service/hlo_verifier.cc
index 3fae61f704..ac1a663633 100644
--- a/tensorflow/compiler/xla/service/hlo_verifier.cc
+++ b/tensorflow/compiler/xla/service/hlo_verifier.cc
@@ -84,7 +84,8 @@ Status ShapeVerifier::HandleConvolution(HloInstruction* convolution) {
const Shape expected,
ShapeInference::InferConvolveShape(
convolution->operand(0)->shape(), convolution->operand(1)->shape(),
- convolution->window(), convolution->convolution_dimension_numbers()));
+ convolution->window(), convolution->convolution_dimension_numbers(),
+ convolution->feature_group_count()));
return CheckShape(convolution, expected);
}
@@ -156,11 +157,7 @@ Status CheckOperandAndParameter(const HloInstruction* instruction,
Status ShapeVerifier::HandleInfeed(HloInstruction* instruction) {
HloInfeedInstruction* infeed = Cast<HloInfeedInstruction>(instruction);
- // Infeed has an optional single token operand.
- // TODO(b/80000000): Update when token is not optional.
- if (infeed->operand_count() == 1) {
- TF_RETURN_IF_ERROR(CheckIsTokenOperand(instruction, 0));
- }
+ TF_RETURN_IF_ERROR(CheckIsTokenOperand(instruction, 0));
// The output of infeed is a tuple containing the data value and a token.
return CheckShape(infeed,
@@ -170,11 +167,7 @@ Status ShapeVerifier::HandleInfeed(HloInstruction* instruction) {
Status ShapeVerifier::HandleOutfeed(HloInstruction* instruction) {
HloOutfeedInstruction* outfeed = Cast<HloOutfeedInstruction>(instruction);
- // Outfeed has an optional token operand (operand 1).
- // TODO(b/80000000): Update when token is not optional.
- if (outfeed->operand_count() == 2) {
- TF_RETURN_IF_ERROR(CheckIsTokenOperand(instruction, 1));
- }
+ TF_RETURN_IF_ERROR(CheckIsTokenOperand(instruction, 1));
// Outfeed has a separate shape field for the value which is outfed to the
// host. The shape of the instruction itself is always a token.
@@ -194,7 +187,67 @@ Status ShapeVerifier::HandleHostCompute(HloInstruction*) {
return Status::OK();
}
-Status ShapeVerifier::HandleRng(HloInstruction*) { return Status::OK(); }
+bool ShapeVerifier::HasCompatibleElementTypes(const Shape& shape_0,
+ const Shape& shape_1,
+ const Shape& result_shape) {
+ return ShapeUtil::SameElementType(shape_0, shape_1) &&
+ (ShapeUtil::SameElementType(shape_0, result_shape) ||
+ (allow_mixed_precision_ &&
+ ShapeUtil::SameElementTypeIgnoringFpPrecision(shape_0,
+ result_shape)));
+}
+
+Status ShapeVerifier::HandleRng(HloInstruction* instruction) {
+ if (instruction->operand_count() != 2) {
+ return InternalError("Expected two operands for Rng instruction: %s",
+ instruction->ToString().c_str());
+ }
+
+ const Shape& shape_0 = instruction->operand(0)->shape();
+ const Shape& shape_1 = instruction->operand(1)->shape();
+ if (!ShapeUtil::IsScalar(shape_0) || !ShapeUtil::IsScalar(shape_1)) {
+ return InternalError(
+ "Expected scalar types for the two operands of Rng instruction: %s",
+ instruction->ToString().c_str());
+ }
+
+ if (!HasCompatibleElementTypes(shape_0, shape_1, instruction->shape())) {
+ return InternalError(
+ "Expected compatible element types for the result and the two operands"
+ " of Rng instruction: %s",
+ instruction->ToString().c_str());
+ }
+
+ PrimitiveType element_type = shape_0.element_type();
+ switch (instruction->random_distribution()) {
+ case RNG_UNIFORM:
+ if (!primitive_util::IsFloatingPointType(element_type) &&
+ !primitive_util::IsIntegralType(element_type) &&
+ element_type != PRED) {
+ return InternalError(
+ "Element type not supported."
+ " Expected element to be of floating point type, integral type or"
+ " predicate type for RngUniform: %s",
+ instruction->ToString().c_str());
+ }
+ break;
+
+ case RNG_NORMAL:
+ if (!primitive_util::IsFloatingPointType(element_type)) {
+ return InternalError(
+ "Element type not supported."
+ " Expected element to be FloatingPointType for RngNormal: %s",
+ instruction->ToString().c_str());
+ }
+ break;
+ default:
+ return InternalError(
+ "Invalid Rng distribution %s",
+ RandomDistribution_Name(instruction->random_distribution()).c_str());
+ }
+
+ return Status::OK();
+}
Status ShapeVerifier::HandleReverse(HloInstruction* reverse) {
return CheckShape(
@@ -463,9 +516,9 @@ namespace {
// inputs.
Status CheckMixedPrecisionOperands(const HloInstruction* instruction) {
switch (instruction->opcode()) {
- // White list the following opcodes for mixed-precision check, because they
- // involve data pass through or grouping via tuples, where the precisions
- // of buffers can be different.
+ // White list the following opcodes for mixed-precision check, because
+ // they involve data pass through or grouping via tuples, where the
+ // precisions of buffers can be different.
case HloOpcode::kCall:
case HloOpcode::kConditional:
case HloOpcode::kConstant:
@@ -519,7 +572,7 @@ Status ShapeVerifier::HandleGather(HloInstruction* gather) {
gather,
ShapeInference::InferGatherShape(
gather->operand(0)->shape(), gather->operand(1)->shape(),
- gather->gather_dimension_numbers(), gather->gather_window_bounds()));
+ gather->gather_dimension_numbers(), gather->gather_slice_sizes()));
}
Status ShapeVerifier::HandleScatter(HloInstruction* scatter) {
@@ -647,7 +700,8 @@ string ComputationsToString(
// Verifies various invariants about the structure of the HLO:
//
-// (1) each instruction has a non-null parent() set to the HloComputation which
+// (1) each instruction has a non-null parent() set to the HloComputation
+// which
// contains it.
//
// (2) each computation has a non-null parent() set to the HloModule which
@@ -681,9 +735,9 @@ Status VerifyHloStructure(HloModule* module) {
}
// Check that operands are in the same computation separately from verifying
- // parent() correctness so conditions like a null HloInstruction::parent() are
- // identified and reported explicitly above rather than reporting a mismatched
- // operand.
+ // parent() correctness so conditions like a null HloInstruction::parent()
+ // are identified and reported explicitly above rather than reporting a
+ // mismatched operand.
for (const HloComputation* computation : module->computations()) {
for (const HloInstruction* instruction : computation->instructions()) {
for (int i = 0; i < instruction->operand_count(); ++i) {
@@ -707,13 +761,14 @@ Status HloVerifier::CheckFusionInstruction(HloInstruction* fusion) const {
HloComputation* fused_computation = fusion->fused_instructions_computation();
if (fusion != fused_computation->FusionInstruction()) {
return InternalError(
- "Instruction of fused computation does not match expected instruction "
+ "Instruction of fused computation does not match expected "
+ "instruction "
"%s.",
fusion->ToString().c_str());
}
- // Fused root instruction and fused parameters must all be owned by the fusion
- // computation.
+ // Fused root instruction and fused parameters must all be owned by the
+ // fusion computation.
bool root_owned = false;
const std::vector<HloInstruction*>& fused_parameters =
fusion->fused_parameters();
@@ -755,8 +810,8 @@ Status HloVerifier::CheckFusionInstruction(HloInstruction* fusion) const {
fusion->ToString().c_str());
}
- // All uses of fused instructions must be in the fusion computation, and every
- // non-root instruction must have at least one use.
+ // All uses of fused instructions must be in the fusion computation, and
+ // every non-root instruction must have at least one use.
for (auto* instruction :
fusion->fused_instructions_computation()->instructions()) {
if (instruction != fused_root) {
@@ -800,7 +855,8 @@ Status HloVerifier::CheckFusionInstruction(HloInstruction* fusion) const {
if (!ShapeUtil::Compatible(fused_param->shape(),
fusion->operand(param_no)->shape())) {
return InternalError(
- "Shape mismatch between parameter number %lld and its operand in %s.",
+ "Shape mismatch between parameter number %lld and its operand in "
+ "%s.",
param_no, fusion->ToString().c_str());
}
}
@@ -918,8 +974,9 @@ Status CheckSameChannel(const HloInstruction* instr1,
return Status::OK();
}
-// Checks if the given two instructions have the same is_host_transfer attribute
-// value. Intsructions must be send/recv instructions or their 'done' variant.
+// Checks if the given two instructions have the same is_host_transfer
+// attribute value. Intsructions must be send/recv instructions or their
+// 'done' variant.
Status CheckSameIsHostTransfer(const HloInstruction* instr1,
const HloInstruction* instr2) {
const HloSendRecvInstruction* send_recv1 =
@@ -930,7 +987,8 @@ Status CheckSameIsHostTransfer(const HloInstruction* instr1,
TF_RET_CHECK(send_recv2 != nullptr);
if (send_recv1->is_host_transfer() != send_recv2->is_host_transfer()) {
return InternalError(
- "Expected instructions to have the same is-host-transfer property: %s, "
+ "Expected instructions to have the same is-host-transfer property: "
+ "%s, "
"%s ",
instr1->ToString().c_str(), instr2->ToString().c_str());
}
@@ -949,7 +1007,8 @@ Status VerifySendsAndRecvs(const HloModule& module) {
host_channels.insert({sendrecv->channel_id(), sendrecv});
if (!it_inserted.second) {
return FailedPrecondition(
- "Channel %lld is used for multiple host send/recv instructions: %s "
+ "Channel %lld is used for multiple host send/recv instructions: "
+ "%s "
"and "
"%s",
sendrecv->channel_id(), sendrecv->ToString().c_str(),
diff --git a/tensorflow/compiler/xla/service/hlo_verifier.h b/tensorflow/compiler/xla/service/hlo_verifier.h
index 5a56a44f35..c942fab08e 100644
--- a/tensorflow/compiler/xla/service/hlo_verifier.h
+++ b/tensorflow/compiler/xla/service/hlo_verifier.h
@@ -106,6 +106,13 @@ class ShapeVerifier : public DfsHloVisitor {
Status CheckVariadicShape(const HloInstruction* instruction);
private:
+ // Return true if the shapes of the two operands have the same element type,
+ // and the result shape either has the same element type as the operand
+ // shapes or mixed precision is allowed and the result shape and the operand
+ // shapes have floating point element types.
+ bool HasCompatibleElementTypes(const Shape& shape_0, const Shape& shape_1,
+ const Shape& result_shape);
+
// Whether the inputs and output of an instruction can contain both F32s and
// BF16s. Tuples that include both F32s and BF16s are allowed regardless of
// this flag.
diff --git a/tensorflow/compiler/xla/service/hlo_verifier_test.cc b/tensorflow/compiler/xla/service/hlo_verifier_test.cc
index 04c6ba3eeb..d764964f3c 100644
--- a/tensorflow/compiler/xla/service/hlo_verifier_test.cc
+++ b/tensorflow/compiler/xla/service/hlo_verifier_test.cc
@@ -34,7 +34,17 @@ namespace {
using ::testing::HasSubstr;
-using HloVerifierTest = HloTestBase;
+class HloVerifierTest : public HloTestBase {
+ public:
+ HloVerifierTest()
+ : HloTestBase(/*allow_mixed_precision_in_hlo_verifier=*/false) {}
+};
+
+class HloVerifierTestAllowMixedPrecision : public HloTestBase {
+ public:
+ HloVerifierTestAllowMixedPrecision()
+ : HloTestBase(/*allow_mixed_precision_in_hlo_verifier=*/true) {}
+};
TEST_F(HloVerifierTest, NullInstructionParent) {
HloComputation::Builder builder(TestName());
@@ -174,5 +184,96 @@ ENTRY entry {
HasSubstr("shape does not match parameter"));
}
+TEST_F(HloVerifierTest, RngOpnd0NotScalar) {
+ const char* const hlo_string = R"(
+ HloModule Module
+
+ ENTRY RngOpnd0NotScalar {
+ constant.0 = f32[] constant(0)
+ constant.1 = f16[2] constant({1, 3})
+ ROOT rng.0 = f32[10]{0} rng(f32[] constant.0, f16[2] constant.1),
+ distribution=rng_uniform
+ }
+ )";
+ TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(hlo_string));
+
+ auto status = verifier().Run(module.get()).status();
+ ASSERT_FALSE(status.ok());
+ EXPECT_THAT(status.error_message(), HasSubstr("Expected scalar type"));
+}
+
+TEST_F(HloVerifierTest, RngOperandElementTypesDoNotMatch) {
+ const char* const hlo_string = R"(
+ HloModule Module
+
+ ENTRY RngOperandElementTypesNotMatch {
+ constant.0 = f32[] constant(0)
+ constant.1 = f16[] constant(1)
+ ROOT rng.0 = f32[10]{0} rng(f32[] constant.0, f16[] constant.1),
+ distribution=rng_normal
+ }
+ )";
+ TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(hlo_string));
+
+ auto status = verifier().Run(module.get()).status();
+ ASSERT_FALSE(status.ok());
+ EXPECT_THAT(status.error_message(),
+ HasSubstr("Expected compatible element types"));
+}
+
+TEST_F(HloVerifierTest, RngMixedPrecisionNotAllowed) {
+ const char* const hlo_string = R"(
+ HloModule Module
+
+ ENTRY RngResultElementTypeNotMatch {
+ constant.0 = f32[] constant(0)
+ constant.1 = f32[] constant(1)
+ ROOT rng.0 = f16[10]{0} rng(f32[] constant.0, f32[] constant.1),
+ distribution=rng_normal
+ }
+ )";
+ TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(hlo_string));
+
+ auto status = verifier().Run(module.get()).status();
+ ASSERT_FALSE(status.ok());
+ EXPECT_THAT(status.error_message(),
+ HasSubstr("Expected compatible element types"));
+}
+
+TEST_F(HloVerifierTestAllowMixedPrecision, RngMixedPrecisionAllowed) {
+ const char* const hlo_string = R"(
+ HloModule Module
+
+ ENTRY RngResultElementTypeNotMatch {
+ constant.0 = f32[] constant(0)
+ constant.1 = f32[] constant(1)
+ ROOT rng.0 = f16[10]{0} rng(f32[] constant.0, f32[] constant.1),
+ distribution=rng_normal
+ }
+ )";
+ TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(hlo_string));
+
+ auto status = verifier().Run(module.get()).status();
+ ASSERT_TRUE(status.ok());
+}
+
+TEST_F(HloVerifierTest, RngElementTypeNotSupported) {
+ const char* const hlo_string = R"(
+ HloModule Module
+
+ ENTRY RngElementTypeNotSupported {
+ constant.0 = s32[] constant(0)
+ constant.1 = s32[] constant(1)
+ ROOT rng.0 = s32[10]{0} rng(s32[] constant.0, s32[] constant.1),
+ distribution=rng_normal
+ }
+ )";
+ TF_ASSERT_OK_AND_ASSIGN(auto module, ParseHloString(hlo_string));
+
+ auto status = verifier().Run(module.get()).status();
+ ASSERT_FALSE(status.ok());
+ EXPECT_THAT(status.error_message(), HasSubstr("Element type not supported"));
+}
+
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/service/indexed_array_analysis.cc b/tensorflow/compiler/xla/service/indexed_array_analysis.cc
index 3531b7223f..39dff567d4 100644
--- a/tensorflow/compiler/xla/service/indexed_array_analysis.cc
+++ b/tensorflow/compiler/xla/service/indexed_array_analysis.cc
@@ -14,6 +14,7 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/indexed_array_analysis.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/util.h"
@@ -153,7 +154,7 @@ StatusOr<Analysis::Array*> IndexedArrayAnalysis::ComputeArrayFor(
TF_ASSIGN_OR_RETURN(
computed_array,
ComputeArrayForGather(instr->shape(), instr->gather_dimension_numbers(),
- instr->gather_window_bounds(),
+ instr->gather_slice_sizes(),
FindOrDie(cache_, instr->operand(0)),
FindOrDie(cache_, instr->operand(1))));
} else if (instr->opcode() == HloOpcode::kReshape) {
@@ -251,24 +252,23 @@ StatusOr<ScalarIndexedArray*> IndexedArrayAnalysis::FoldGatherOfGather(
StatusOr<Analysis::Array*> IndexedArrayAnalysis::ComputeArrayForGather(
const Shape& shape, const GatherDimensionNumbers& dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds, Array* source,
+ tensorflow::gtl::ArraySlice<int64> slice_sizes, Array* source,
Array* indices) {
if (dim_numbers.index_vector_dim() != indices->shape().dimensions_size()) {
VLOG(3) << "ComputeArrayForGather: indices are not scalar";
return nullptr;
}
- CHECK_EQ(dim_numbers.gather_dims_to_operand_dims_size(), 1);
+ CHECK_EQ(dim_numbers.start_index_map_size(), 1);
- // We can also handle dim_numbers.elided_window_dims_size() == 0 here, should
- // it become relevant.
+ // We can also handle dim_numbers.collapsed_slice_dims_size() == 0 here,
+ // should it become relevant.
- if (dim_numbers.elided_window_dims_size() != 1 ||
- dim_numbers.elided_window_dims(0) !=
- dim_numbers.gather_dims_to_operand_dims(0)) {
+ if (dim_numbers.collapsed_slice_dims_size() != 1 ||
+ dim_numbers.collapsed_slice_dims(0) != dim_numbers.start_index_map(0)) {
VLOG(3) << "ComputeArrayForGather: gather operations must elide "
- "gather_dims_to_operand_dims[0] and "
- "gather_dims_to_operand_dims[0] only";
+ "start_index_map[0] and "
+ "start_index_map[0] only";
return nullptr;
}
@@ -277,27 +277,27 @@ StatusOr<Analysis::Array*> IndexedArrayAnalysis::ComputeArrayForGather(
// arrays from an array of size [7,4,6]. We check that condition down below:
for (int64 i = 0, e = source->shape().dimensions_size(); i < e; i++) {
- if (i != dim_numbers.elided_window_dims(0) &&
- source->shape().dimensions(i) != window_bounds[i]) {
- VLOG(3) << "ComputeArrayForGather: window_bounds[" << i
+ if (i != dim_numbers.collapsed_slice_dims(0) &&
+ source->shape().dimensions(i) != slice_sizes[i]) {
+ VLOG(3) << "ComputeArrayForGather: slice_sizes[" << i
<< "] != source->shape().dimensions(" << i << ") -- "
- << source->shape().dimensions(i) << " vs. " << window_bounds[i]
- << " with dim_numbers.elided_window_dims(0) = "
- << dim_numbers.elided_window_dims(0);
+ << source->shape().dimensions(i) << " vs. " << slice_sizes[i]
+ << " with dim_numbers.collapsed_slice_dims(0) = "
+ << dim_numbers.collapsed_slice_dims(0);
return nullptr;
}
}
- int64 source_dim = dim_numbers.gather_dims_to_operand_dims(0);
+ int64 source_dim = dim_numbers.start_index_map(0);
std::vector<int64> output_dims;
for (int64 i = 0, e = shape.dimensions_size(); i < e; i++) {
- if (!c_binary_search(dim_numbers.output_window_dims(), i)) {
+ if (!absl::c_binary_search(dim_numbers.offset_dims(), i)) {
output_dims.push_back(i);
}
}
if (auto* indexed = dynamic_cast<ScalarIndexedArray*>(source)) {
- if (c_linear_search(indexed->output_dims(), source_dim)) {
+ if (absl::c_linear_search(indexed->output_dims(), source_dim)) {
return FoldGatherOfGather(indexed, indices, source_dim, output_dims,
shape);
}
@@ -315,7 +315,7 @@ namespace {
// [values.begin()+index, values.end()) is equal to `product`. If there is no
// such index, return -1. All integers in `values` must be positive.
int64 FindSuffixWithProduct(ArraySlice<int64> values, int64 product) {
- DCHECK(c_all_of(values, [](int64 value) { return value > 0; }));
+ DCHECK(absl::c_all_of(values, [](int64 value) { return value > 0; }));
int64 current_product = 1;
int64 i;
@@ -389,26 +389,26 @@ std::vector<ReshapePassthroughDimPair> ComputeReshapePassthroughDimPairs(
result_subarray_size *= result_shape[result_dim];
}
- c_reverse(result);
+ absl::c_reverse(result);
if (VLOG_IS_ON(3)) {
std::vector<string> result_strings;
- c_transform(result, std::back_inserter(result_strings),
- [](ReshapePassthroughDimPair value) {
- return tensorflow::strings::StrCat(value.result_dim, "->",
- value.operand_dim);
- });
+ absl::c_transform(result, std::back_inserter(result_strings),
+ [](ReshapePassthroughDimPair value) {
+ return tensorflow::strings::StrCat(
+ value.result_dim, "->", value.operand_dim);
+ });
VLOG(3) << "For a reshape from [" << Join(operand_shape, ",") << "] to ["
<< Join(result_shape, ",") << "] passthrough indices are ["
<< Join(result_strings, ",") << "] (legend: `result`->`operand`)";
}
- DCHECK(c_is_sorted(
+ DCHECK(absl::c_is_sorted(
result, [](ReshapePassthroughDimPair lhs, ReshapePassthroughDimPair rhs) {
return lhs.result_dim < rhs.result_dim;
}));
- DCHECK(c_is_sorted(
+ DCHECK(absl::c_is_sorted(
result, [](ReshapePassthroughDimPair lhs, ReshapePassthroughDimPair rhs) {
return lhs.operand_dim < rhs.operand_dim;
}));
@@ -420,20 +420,20 @@ std::vector<ReshapePassthroughDimPair> ComputeReshapePassthroughDimPairs(
// `passthrough_dims`.
bool IsReshapePassthroughOperandDim(
ArraySlice<ReshapePassthroughDimPair> passthrough_dims, int64 dim) {
- return c_any_of(passthrough_dims,
- [&](ReshapePassthroughDimPair passthrough_dim_pair) {
- return passthrough_dim_pair.operand_dim == dim;
- });
+ return absl::c_any_of(passthrough_dims,
+ [&](ReshapePassthroughDimPair passthrough_dim_pair) {
+ return passthrough_dim_pair.operand_dim == dim;
+ });
}
// Maps `operand_dim` which must be an passthrough operand dimension to its
// corresponding passthrough result dimension based on `passthrough_dims`.
int64 MapPassthroughOperandDimToResultDim(
ArraySlice<ReshapePassthroughDimPair> passthrough_dims, int64 operand_dim) {
- auto it = c_find_if(passthrough_dims,
- [&](ReshapePassthroughDimPair passthrough_dim_pair) {
- return passthrough_dim_pair.operand_dim == operand_dim;
- });
+ auto it = absl::c_find_if(
+ passthrough_dims, [&](ReshapePassthroughDimPair passthrough_dim_pair) {
+ return passthrough_dim_pair.operand_dim == operand_dim;
+ });
CHECK(it != passthrough_dims.end());
return it->result_dim;
}
@@ -454,8 +454,8 @@ int64 FindSourcePositionForPassthroughResultDim(ArraySlice<int64> operand_shape,
Shape StripDegenerateDimensions(const Shape& shape) {
DimensionVector new_dims;
- c_copy_if(shape.dimensions(), std::back_inserter(new_dims),
- [](int64 dim) { return dim != 1; });
+ absl::c_copy_if(shape.dimensions(), std::back_inserter(new_dims),
+ [](int64 dim) { return dim != 1; });
return ShapeUtil::MakeShape(shape.element_type(), new_dims);
}
}; // namespace
@@ -553,8 +553,8 @@ StatusOr<ScalarIndexedArray*> IndexedArrayAnalysis::ReshapeToAddDegenerateDims(
}();
DimensionVector new_result_shape_dims;
- c_copy(operand->shape().dimensions(),
- std::back_inserter(new_result_shape_dims));
+ absl::c_copy(operand->shape().dimensions(),
+ std::back_inserter(new_result_shape_dims));
for (int64 degenerate_dim : degenerate_dims) {
InsertAt(&new_result_shape_dims, degenerate_dim, 1);
}
@@ -695,8 +695,8 @@ IndexedArrayAnalysis::FoldReshapeOfGatherNoDegenerateDims(
operand_dim);
};
- if (!c_all_of(scalar_indexed->output_dims(),
- is_reshape_passthrough_operand_dim)) {
+ if (!absl::c_all_of(scalar_indexed->output_dims(),
+ is_reshape_passthrough_operand_dim)) {
VLOG(3) << "Not all output dims are passthrough dims "
<< ToString(scalar_indexed);
return nullptr;
@@ -735,11 +735,11 @@ IndexedArrayAnalysis::FoldReshapeOfGatherNoDegenerateDims(
// operand = s32[3,5,2] constant({...})
// indices = s32[7] parameter(0)
// gather = s32[3,2,7] gather(operand, indices),
- // output_window_dims={0,1},
- // elided_window_dims={1},
- // gather_dims_to_operand_dims={1},
+ // offset_dims={0,1},
+ // collapsed_slice_dims={1},
+ // start_index_map={1},
// index_vector_dim=1,
- // window_bounds={3,1,2}
+ // slice_sizes={3,1,2}
// reshape = s32[6,7] reshape(gather)
//
// In this case the gather maps to:
@@ -764,8 +764,8 @@ IndexedArrayAnalysis::FoldReshapeOfGatherNoDegenerateDims(
&new_scalar_indexed_source_shape, source_dim_for_new_scalar_indexed_node,
scalar_indexed_source_shape.dimensions(scalar_indexed->source_dim()));
- CHECK_EQ(c_accumulate(new_scalar_indexed_source_shape, 1LL,
- std::multiplies<int64>()),
+ CHECK_EQ(absl::c_accumulate(new_scalar_indexed_source_shape, 1LL,
+ std::multiplies<int64>()),
ShapeUtil::ElementsIn(scalar_indexed_source_shape));
CHECK(IsReshapePassthroughOperandDim(
@@ -781,9 +781,9 @@ IndexedArrayAnalysis::FoldReshapeOfGatherNoDegenerateDims(
};
std::vector<int64> output_dims_for_new_scalar_indexed_node;
- c_transform(scalar_indexed->output_dims(),
- std::back_inserter(output_dims_for_new_scalar_indexed_node),
- map_passthrough_operand_dim_to_result_dim);
+ absl::c_transform(scalar_indexed->output_dims(),
+ std::back_inserter(output_dims_for_new_scalar_indexed_node),
+ map_passthrough_operand_dim_to_result_dim);
TF_ASSIGN_OR_RETURN(const Literal* new_scalar_indexed_source_literal,
TakeOwnership(scalar_indexed->literal().Reshape(
@@ -874,11 +874,12 @@ IndexedArrayAnalysis::ComputeArrayForElementwiseBinaryOp(HloOpcode opcode,
ArraySlice<int64> broadcast_dims = broadcast_instr->dimensions();
auto is_broadcasted_dim = [&](int64 output_dim) {
- return c_find(broadcast_dims, output_dim) == broadcast_dims.end();
+ return absl::c_find(broadcast_dims, output_dim) == broadcast_dims.end();
};
// All of the output dims must be "broadcasted" dims for the other operand.
- if (!c_all_of(scalar_indexed_const->output_dims(), is_broadcasted_dim)) {
+ if (!absl::c_all_of(scalar_indexed_const->output_dims(),
+ is_broadcasted_dim)) {
return nullptr;
}
diff --git a/tensorflow/compiler/xla/service/indexed_array_analysis.h b/tensorflow/compiler/xla/service/indexed_array_analysis.h
index e923dc39f7..675eb31d26 100644
--- a/tensorflow/compiler/xla/service/indexed_array_analysis.h
+++ b/tensorflow/compiler/xla/service/indexed_array_analysis.h
@@ -265,7 +265,7 @@ class IndexedArrayAnalysis {
StatusOr<Array*> ComputeArrayForGather(
const Shape& shape, const GatherDimensionNumbers& dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds, Array* source,
+ tensorflow::gtl::ArraySlice<int64> slice_sizes, Array* source,
Array* indices);
StatusOr<Array*> ComputeArrayForDotWithIndexedLhs(
diff --git a/tensorflow/compiler/xla/service/indexed_array_analysis_test.cc b/tensorflow/compiler/xla/service/indexed_array_analysis_test.cc
index 5f4b42799b..97052edf7d 100644
--- a/tensorflow/compiler/xla/service/indexed_array_analysis_test.cc
+++ b/tensorflow/compiler/xla/service/indexed_array_analysis_test.cc
@@ -82,11 +82,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[5] parameter(1)
ROOT gather = s32[5,3] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,3}
+ slice_sizes={1,3}
}
)";
@@ -102,11 +102,11 @@ ENTRY main {
operand = s32[3,3] constant(s32[3,3]{{1,2,3},{1,2,3},{1,2,3}})
indices = s32[5] parameter(0)
ROOT gather = s32[5,3] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,3}
+ slice_sizes={1,3}
}
)";
@@ -122,11 +122,11 @@ ENTRY main {
operand = s32[3,3] constant(s32[3,3]{{1,2,3},{1,2,3},{1,2,3}})
indices = s32[5,2] parameter(0)
ROOT gather = s32[5] gather(operand, indices),
- output_window_dims={},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1}
+ slice_sizes={1,1}
}
)";
@@ -141,11 +141,11 @@ ENTRY main {
operand = s32[3,3,1] parameter(0)
indices = s32[5] parameter(1)
ROOT gather = s32[5,3] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,2},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0,2},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,3,1}
+ slice_sizes={1,3,1}
}
)";
@@ -160,11 +160,11 @@ ENTRY main {
operand = s32[3,3,1] parameter(0)
indices = s32[5] parameter(1)
ROOT gather = s32[5,2,3] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={2},
- gather_dims_to_operand_dims={0},
+ offset_dims={1,2},
+ collapsed_slice_dims={2},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={2,3,1}
+ slice_sizes={2,3,1}
}
)";
@@ -179,11 +179,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[5] parameter(1)
ROOT gather = s32[5,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,2}
+ slice_sizes={1,2}
}
)";
@@ -199,17 +199,17 @@ ENTRY main {
indices_a = s32[5] parameter(0)
indices_b = s32[2] parameter(1)
gather_a = s32[5,3] gather(operand, indices_a),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,3}
+ slice_sizes={1,3}
ROOT gather_b = s32[2,3] gather(gather_a, indices_b),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,3}
+ slice_sizes={1,3}
}
)";
@@ -228,17 +228,17 @@ ENTRY main {
indices_a = s32[5,7] parameter(1)
indices_b = s32[2] parameter(2)
gather_a = s32[5,3,7] gather(operand, indices_a),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3,1}
+ slice_sizes={3,1}
ROOT gather_b = s32[5,3,2] gather(gather_a, indices_b),
- output_window_dims={0,1},
- elided_window_dims={2},
- gather_dims_to_operand_dims={2},
+ offset_dims={0,1},
+ collapsed_slice_dims={2},
+ start_index_map={2},
index_vector_dim=1,
- window_bounds={5,3,1}
+ slice_sizes={5,3,1}
}
)";
@@ -256,17 +256,17 @@ ENTRY main {
indices_a = s32[2] parameter(1)
indices_b = s32[5,7] parameter(2)
gather_a = s32[2,6] gather(operand, indices_a),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,6}
+ slice_sizes={1,6}
ROOT gather_b = s32[5,6,7] gather(gather_a, indices_b),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1,6}
+ slice_sizes={1,6}
}
)";
@@ -284,17 +284,17 @@ ENTRY main {
indices_a = s32[5,7] parameter(1)
indices_b = s32[4,8] parameter(2)
gather_a = s32[5,3,7] gather(operand, indices_a),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3,1}
+ slice_sizes={3,1}
ROOT gather_b = s32[4,5,3,8] gather(gather_a, indices_b),
- output_window_dims={1,2},
- elided_window_dims={2},
- gather_dims_to_operand_dims={2},
+ offset_dims={1,2},
+ collapsed_slice_dims={2},
+ start_index_map={2},
index_vector_dim=2,
- window_bounds={5,3,1}
+ slice_sizes={5,3,1}
}
)";
@@ -312,11 +312,11 @@ ENTRY main {
operand = s32[3,4] constant(s32[3,4]{{1,2,3,4},{1,2,3,4},{1,2,3,4}})
indices = s32[5] parameter(0)
gather = s32[5,4] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT reshape = s32[5,2,2] reshape(gather)
}
)";
@@ -333,11 +333,11 @@ ENTRY main {
operand = s32[3,4] constant(s32[3,4]{{1,2,3,4},{1,2,3,4},{1,2,3,4}})
indices = s32[5,7] parameter(0)
gather = s32[5,4,7] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT reshape = s32[5,2,2,7] reshape(gather)
}
)";
@@ -358,11 +358,11 @@ ENTRY main {
{{1,2,3,4,5,6},{1,2,3,4,5,6}}})
indices = s32[5,7] parameter(0)
gather = s32[5,2,6,7] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1,2},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1,2,6}
+ slice_sizes={1,2,6}
ROOT reshape = s32[5,3,4,7] reshape(gather)
}
)";
@@ -381,11 +381,11 @@ ENTRY main {
{1,2,3,4,5,6},{1,2,3,4,5,6}})
indices = s32[1] parameter(0)
gather = s32[1,6] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,6}
+ slice_sizes={1,6}
ROOT reshape = s32[1,1,6] reshape(gather)
}
)";
@@ -408,14 +408,14 @@ ENTRY main {
operand = s32[2,3]{1,0} constant(s32[2,3] { { 1, 2, 3 }, { 1, 2, 3 } })
i.0 = s64[1,3]{1,0} parameter(0)
- g.0 = s32[1,3,3]{2,1,0} gather(operand, i.0), output_window_dims={2},
- elided_window_dims={0}, gather_dims_to_operand_dims={0},
- index_vector_dim=2, window_bounds={1,3}
+ g.0 = s32[1,3,3]{2,1,0} gather(operand, i.0), offset_dims={2},
+ collapsed_slice_dims={0}, start_index_map={0},
+ index_vector_dim=2, slice_sizes={1,3}
i.1 = s64[1] parameter(1)
- g.1 = s32[1,1,3]{2,1,0} gather(g.0, i.1), output_window_dims={0,2},
- elided_window_dims={1}, gather_dims_to_operand_dims={1},
- index_vector_dim=1, window_bounds={1,1,3}
+ g.1 = s32[1,1,3]{2,1,0} gather(g.0, i.1), offset_dims={0,2},
+ collapsed_slice_dims={1}, start_index_map={1},
+ index_vector_dim=1, slice_sizes={1,1,3}
ROOT reshape = s32[1,3]{1,0} reshape(g.1)
}
@@ -441,11 +441,11 @@ ENTRY main {
operand = s32[1,6] constant(s32[1,6]{{1,2,3,4,5,6}})
indices = s32[1] parameter(0)
gather = s32[1,6] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,6}
+ slice_sizes={1,6}
ROOT reshape = s32[1,1,6] reshape(gather)
}
)";
@@ -469,11 +469,11 @@ ENTRY main {
{1,2,3,4,5,6},{1,2,3,4,5,6}}})
indices = s32[1] parameter(0)
gather = s32[1,1,6] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1,2},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={1,1,6}
+ slice_sizes={1,1,6}
ROOT reshape = s32[1,1,1,6] reshape(gather)
}
)";
@@ -500,11 +500,11 @@ ENTRY main {
{1,2,3,4,5,6},{1,2,3,4,5,6}})
indices = s32[1,5] parameter(0)
gather = s32[1,5,6] gather(operand, indices),
- output_window_dims={2},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={2},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1,6}
+ slice_sizes={1,6}
ROOT reshape = s32[1,1,5,6] reshape(gather)
}
)";
@@ -530,11 +530,11 @@ ENTRY main {
operand = s32[3,4] constant(s32[3,4]{{1,2,3,4},{1,2,3,4},{1,2,3,4}})
indices = s32[5,6] parameter(0)
gather = s32[5,4,6] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT reshape = s32[5,2,2,2,3] reshape(gather)
}
)";
@@ -562,11 +562,11 @@ ENTRY main {
{{1,2},{3,4},{5,6},{7,8},{9,10}}})
indices = s32[7] parameter(0)
gather = s32[3,2,7] gather(operand, indices),
- output_window_dims={0,1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0,1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3,1,2}
+ slice_sizes={3,1,2}
ROOT reshape = s32[6,7] reshape(gather)
}
)";
@@ -594,11 +594,11 @@ ENTRY main {
{{1},{2},{3},{4}}})
indices = s32[5,6] parameter(0)
gather = s32[5,4,6,1] gather(operand, indices),
- output_window_dims={1,3},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1,3},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=2,
- window_bounds={1,4,1}
+ slice_sizes={1,4,1}
ROOT reshape = s32[5,2,2,2,3,1] reshape(gather)
}
)";
@@ -623,11 +623,11 @@ ENTRY main {
operand = f32[3,4] constant(f32[3,4]{{1,2,3,4},{1,3,2,4},{4,3,2,1}})
indices = s32[5] parameter(0)
gather = f32[5,4] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT tanh = f32[5,4] tanh(gather)
}
)";
@@ -650,11 +650,11 @@ ENTRY main {
constant_broadcasted = s32[5,4] broadcast(constant), dimensions={}
indices = s32[5] parameter(0)
gather = s32[5,4] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT add = s32[5,4] add(gather, constant_broadcasted)
}
)";
@@ -678,11 +678,11 @@ ENTRY main {
constant_broadcasted = s32[5,4] broadcast(constant), dimensions={}
indices = s32[5] parameter(0)
gather = s32[5,4] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT sub = s32[5,4] subtract(gather, constant_broadcasted)
}
)";
@@ -706,11 +706,11 @@ ENTRY main {
constant_broadcasted = s32[5,4] broadcast(constant), dimensions={}
indices = s32[5] parameter(0)
gather = s32[5,4] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT sub = s32[5,4] subtract(constant_broadcasted, gather)
}
)";
@@ -733,11 +733,11 @@ ENTRY main {
constant_broadcasted = s32[5,4] broadcast(constant_vect), dimensions={1}
indices = s32[5] parameter(0)
gather = s32[5,4] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT add = s32[5,4] add(gather, constant_broadcasted)
}
)";
@@ -760,11 +760,11 @@ ENTRY main {
constant_broadcasted = s32[5,4] broadcast(constant_vect), dimensions={0}
indices = s32[5] parameter(0)
gather = s32[5,4] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT add = s32[5,4] add(gather, constant_broadcasted)
}
)";
@@ -808,11 +808,11 @@ ENTRY main {
dot_rhs_constant = s32[4,3] constant(s32[4,3]{{1,2,3},{4,5,6},{7,8,9},{10,11,12}})
indices = s32[5] parameter(0)
dot_lhs = s32[5,4] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,4}
+ slice_sizes={1,4}
ROOT dot = s32[5,3] dot(dot_lhs, dot_rhs_constant), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
@@ -835,11 +835,11 @@ ENTRY main {
dot_rhs_constant = s32[3,3] constant(s32[3,3]{{1,2,3},{4,5,6},{7,8,9}})
indices = s32[5] parameter(0)
dot_lhs = s32[3,5] gather(gather_operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3,1}
+ slice_sizes={3,1}
ROOT dot = s32[5,3] dot(dot_lhs, dot_rhs_constant), lhs_contracting_dims={0}, rhs_contracting_dims={0}
}
)";
@@ -863,11 +863,11 @@ ENTRY main {
dot_lhs_constant = s32[4,3] constant(s32[4,3]{{1,2,3},{4,5,6},{7,8,9},{10,11,12}})
indices = s32[5] parameter(0)
dot_rhs = s32[3,5] gather(gather_operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3,1}
+ slice_sizes={3,1}
ROOT dot = s32[4,5] dot(dot_lhs_constant, dot_rhs), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
@@ -892,11 +892,11 @@ ENTRY main {
dot_lhs_constant = s32[4,3] constant(s32[4,3]{{1,2,3},{4,5,6},{7,8,9},{10,11,12}})
indices = s32[5] parameter(0)
dot_rhs = s32[5,3] gather(gather_operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1,3}
+ slice_sizes={1,3}
ROOT dot = s32[4,5] dot(dot_lhs_constant, dot_rhs), lhs_contracting_dims={1}, rhs_contracting_dims={1}
}
)";
@@ -921,11 +921,11 @@ ENTRY main {
dot_lhs_constant = s32[2,2,3] constant(s32[2,2,3]{{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}})
indices = s32[4] parameter(0)
dot_rhs = s32[2,3,4] gather(gather_operand, indices),
- output_window_dims={0,1},
- elided_window_dims={2},
- gather_dims_to_operand_dims={2},
+ offset_dims={0,1},
+ collapsed_slice_dims={2},
+ start_index_map={2},
index_vector_dim=1,
- window_bounds={2,3,1}
+ slice_sizes={2,3,1}
ROOT dot = s32[2,2,4] dot(dot_lhs_constant, dot_rhs),
lhs_contracting_dims={2}, rhs_contracting_dims={1},
lhs_batch_dims={0}, rhs_batch_dims={0}
@@ -952,11 +952,11 @@ ENTRY main {
dot_rhs_constant = s32[2,3] constant(s32[2,3]{{1,2,3},{4,5,6}})
indices = s32[2] parameter(0)
dot_lhs = s32[3,2] gather(gather_operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3,1}
+ slice_sizes={3,1}
ROOT dot = s32[3,3] dot(dot_lhs, dot_rhs_constant), lhs_contracting_dims={1}, rhs_contracting_dims={0}
}
)";
diff --git a/tensorflow/compiler/xla/service/instruction_fusion.cc b/tensorflow/compiler/xla/service/instruction_fusion.cc
index f33942d679..2fd2214806 100644
--- a/tensorflow/compiler/xla/service/instruction_fusion.cc
+++ b/tensorflow/compiler/xla/service/instruction_fusion.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include <numeric>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/core/lib/core/errors.h"
@@ -497,7 +498,7 @@ HloInstruction* InstructionFusion::FuseIntoMultiOutput(
bool InstructionFusion::MultiOutputFusionCreatesCycle(
HloInstruction* producer, HloInstruction* consumer) {
- return c_any_of(
+ return absl::c_any_of(
consumer->operands(), [&](const HloInstruction* consumer_operand) {
// The fusion algorithm traverses the HLO graph in reverse post order.
// Thus `cosumers` is visited before its operands (including
diff --git a/tensorflow/compiler/xla/service/interpreter/executor.h b/tensorflow/compiler/xla/service/interpreter/executor.h
index 9b109022fb..db6b910b32 100644
--- a/tensorflow/compiler/xla/service/interpreter/executor.h
+++ b/tensorflow/compiler/xla/service/interpreter/executor.h
@@ -104,7 +104,7 @@ class XlaInterpreterExecutor : public internal::StreamExecutorInterface {
}
// No "synchronize all activity" implemented for this platform at the moment.
- bool SynchronizeAllActivity() override { return false; }
+ bool SynchronizeAllActivity() override { return true; }
bool SynchronousMemZero(DeviceMemoryBase *location, uint64 size) override {
return false;
}
diff --git a/tensorflow/compiler/xla/service/layout_assignment.cc b/tensorflow/compiler/xla/service/layout_assignment.cc
index b5a9d6e8e7..805fdb2d5b 100644
--- a/tensorflow/compiler/xla/service/layout_assignment.cc
+++ b/tensorflow/compiler/xla/service/layout_assignment.cc
@@ -1563,7 +1563,7 @@ Status LayoutAssignment::ClearComputationLayouts(HloComputation* computation) {
// and the computation result. The latter two are specified in
// computation_layout, so we only need to keep the existing layouts for
// infeeds. Clearing the layouts here avoids hiding potential bugs in the
- // layout assignment pass that may accidently use the existing layout.
+ // layout assignment pass that may accidentally use the existing layout.
for (HloInstruction* instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kBitcast) {
// bitcasts are inherently layout sensitive and so a bitcast instruction
diff --git a/tensorflow/compiler/xla/service/llvm_ir/BUILD b/tensorflow/compiler/xla/service/llvm_ir/BUILD
index cdd3daf73b..ce2d6678a5 100644
--- a/tensorflow/compiler/xla/service/llvm_ir/BUILD
+++ b/tensorflow/compiler/xla/service/llvm_ir/BUILD
@@ -88,6 +88,7 @@ cc_library(
"//tensorflow/compiler/xla:util",
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/core:lib",
+ "@com_google_absl//absl/algorithm:container",
"@llvm//:core",
],
)
diff --git a/tensorflow/compiler/xla/service/llvm_ir/ir_array.h b/tensorflow/compiler/xla/service/llvm_ir/ir_array.h
index 28ca793e3e..cbfd2e7012 100644
--- a/tensorflow/compiler/xla/service/llvm_ir/ir_array.h
+++ b/tensorflow/compiler/xla/service/llvm_ir/ir_array.h
@@ -19,6 +19,7 @@ limitations under the License.
#include <map>
#include <vector>
+#include "absl/algorithm/container.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Value.h"
#include "tensorflow/compiler/xla/map_util.h"
@@ -81,7 +82,7 @@ class IrArray {
}
}
CHECK_NE(index_type_, nullptr);
- CHECK(c_all_of(multidim, [&](llvm::Value* v) {
+ CHECK(absl::c_all_of(multidim, [&](llvm::Value* v) {
return index_type_ == v->getType();
}));
}
diff --git a/tensorflow/compiler/xla/service/multi_output_fusion.h b/tensorflow/compiler/xla/service/multi_output_fusion.h
index 0019cd7254..6aa639a954 100644
--- a/tensorflow/compiler/xla/service/multi_output_fusion.h
+++ b/tensorflow/compiler/xla/service/multi_output_fusion.h
@@ -104,17 +104,17 @@ class MultiOutputFusion : public HloPassInterface {
// InstructionFusion instead.
virtual bool DoProducerConsumerMultiOutputFusion();
- private:
- // Update the internal data structures after instr1 and instr2 are fused into
- // one fusion instruction.
- void Update(HloInstruction* instr1, HloInstruction* instr2);
-
// Optimization fuel is a compiler debugging technique that makes an
// optimization pass stop what it is doing after having made N changes to the
// program, where N is the fuel. By varying N, this can be used to find the
// first single change that makes a test fail.
int64 fuel_;
+ private:
+ // Update the internal data structures after instr1 and instr2 are fused into
+ // one fusion instruction.
+ void Update(HloInstruction* instr1, HloInstruction* instr2);
+
// Computation for the pass.
HloComputation* computation_;
diff --git a/tensorflow/compiler/xla/service/reshape_mover.cc b/tensorflow/compiler/xla/service/reshape_mover.cc
index ca86c5d13e..4df746fca9 100644
--- a/tensorflow/compiler/xla/service/reshape_mover.cc
+++ b/tensorflow/compiler/xla/service/reshape_mover.cc
@@ -38,6 +38,8 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/reshape_mover.h"
#include <algorithm>
+
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
@@ -374,7 +376,7 @@ StatusOr<bool> TryReshapeMoveOnCandidates(
removed = false;
for (auto operand : nontrivial_operands) {
- if (c_any_of(operand->users(), [&](HloInstruction* user) {
+ if (absl::c_any_of(operand->users(), [&](HloInstruction* user) {
return !reshape_candidates->count(user);
})) {
for (auto* user : operand->users()) {
diff --git a/tensorflow/compiler/xla/service/reshape_mover_test.cc b/tensorflow/compiler/xla/service/reshape_mover_test.cc
index ad3b662c20..ccb9fb3e3a 100644
--- a/tensorflow/compiler/xla/service/reshape_mover_test.cc
+++ b/tensorflow/compiler/xla/service/reshape_mover_test.cc
@@ -76,9 +76,13 @@ TEST_F(ReshapeMoverTest, ReshapesWithDifferentInputShapesNotMoved) {
TEST_F(ReshapeMoverTest, 1ConstantAnd1ReshapesOnRngNotMoved) {
HloComputation::Builder builder(TestName());
auto root_shape = ShapeUtil::MakeShape(F32, {8, 7});
- auto rng0 = builder.AddInstruction(
- HloInstruction::CreateRng(ShapeUtil::MakeShape(F32, {1, 8, 1, 7, 1}),
- RandomDistribution::RNG_UNIFORM, {}));
+ auto rng0 = builder.AddInstruction(HloInstruction::CreateRng(
+ ShapeUtil::MakeShape(F32, {1, 8, 1, 7, 1}),
+ RandomDistribution::RNG_UNIFORM,
+ {builder.AddInstruction(
+ HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f))),
+ builder.AddInstruction(HloInstruction::CreateConstant(
+ LiteralUtil::CreateR0<float>(1.0f)))}));
auto reshape0 =
builder.AddInstruction(HloInstruction::CreateReshape(root_shape, rng0));
diff --git a/tensorflow/compiler/xla/service/scatter_expander.cc b/tensorflow/compiler/xla/service/scatter_expander.cc
new file mode 100644
index 0000000000..338f0c09e9
--- /dev/null
+++ b/tensorflow/compiler/xla/service/scatter_expander.cc
@@ -0,0 +1,351 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/scatter_expander.h"
+
+#include "absl/algorithm/container.h"
+#include "tensorflow/compiler/xla/literal_util.h"
+#include "tensorflow/compiler/xla/service/hlo_computation.h"
+#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
+#include "tensorflow/compiler/xla/service/hlo_instruction.h"
+#include "tensorflow/compiler/xla/service/hlo_module.h"
+#include "tensorflow/compiler/xla/service/while_util.h"
+#include "tensorflow/compiler/xla/statusor.h"
+
+namespace xla {
+
+using tensorflow::gtl::ArraySlice;
+
+// Transposes the given scatter_indices such that the index_vector_dim becomes
+// the most-minor dimension.
+static StatusOr<HloInstruction*> TransposeIndexVectorDimToLast(
+ HloInstruction* scatter_indices, int64 index_vector_dim) {
+ const Shape& scatter_indices_shape = scatter_indices->shape();
+
+ if (scatter_indices_shape.dimensions_size() == index_vector_dim) {
+ return scatter_indices;
+ }
+
+ if (index_vector_dim == (scatter_indices_shape.dimensions_size() - 1)) {
+ return scatter_indices;
+ }
+
+ std::vector<int64> permutation;
+ permutation.reserve(scatter_indices_shape.dimensions_size());
+ for (int64 i = 0, e = scatter_indices_shape.dimensions_size(); i < e; i++) {
+ if (i != index_vector_dim) {
+ permutation.push_back(i);
+ }
+ }
+ permutation.push_back(index_vector_dim);
+ return MakeTransposeHlo(scatter_indices, permutation);
+}
+
+// Canonicalizes the scatter_indices tensor in order to keep them uniform while
+// performing the scatter operation.
+static StatusOr<HloInstruction*> CanonicalizeScatterIndices(
+ HloInstruction* scatter_indices, int64 index_vector_dim) {
+ // Transpose the non-index-vector dimensions to the front.
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * transposed_scatter_indices,
+ TransposeIndexVectorDimToLast(scatter_indices, index_vector_dim));
+ bool indices_are_scalar =
+ index_vector_dim == scatter_indices->shape().dimensions_size();
+
+ // The number of dimensions in scatter_indices that are index dimensions.
+ const int64 index_dims_in_scatter_indices = indices_are_scalar ? 0 : 1;
+
+ // If there is only one index (i.e. scatter_indices has rank 1 and this
+ // scatter is really just a dynamic update slice) add a leading degenerate
+ // dimension for uniformity. Otherwise create a "collapsed" leading dimension
+ // that subsumes all of the non-index-vector dimensions.
+ const Shape& shape = transposed_scatter_indices->shape();
+ if (shape.dimensions_size() == index_dims_in_scatter_indices) {
+ return PrependDegenerateDims(transposed_scatter_indices, 1);
+ } else {
+ // Collapse all but the dimensions (0 or 1) in scatter_indices containing
+ // the index vectors.
+ return CollapseFirstNDims(
+ transposed_scatter_indices,
+ shape.dimensions_size() - index_dims_in_scatter_indices);
+ }
+}
+
+// Permutes the `updates` tensor such that all the scatter dims appear in the
+// major dimensions and all the window dimensions appear in the minor
+// dimensions.
+static StatusOr<HloInstruction*> PermuteScatterAndWindowDims(
+ HloInstruction* updates, ArraySlice<int64> update_window_dims) {
+ std::vector<int64> permutation;
+ const int64 updates_rank = ShapeUtil::Rank(updates->shape());
+ permutation.reserve(updates_rank);
+
+ for (int64 i = 0; i < updates_rank; ++i) {
+ bool is_scatter_dim = !absl::c_binary_search(update_window_dims, i);
+ if (is_scatter_dim) {
+ permutation.push_back(i);
+ }
+ }
+ for (auto window_dim : update_window_dims) {
+ permutation.push_back(window_dim);
+ }
+
+ return MakeTransposeHlo(updates, permutation);
+}
+
+// Expands or contracts the scatter indices in the updates tensor.
+static StatusOr<HloInstruction*> AdjustScatterDims(
+ const Shape& scatter_indices_shape, HloInstruction* updates,
+ int64 index_vector_dim) {
+ int64 num_scatter_dims = scatter_indices_shape.dimensions_size();
+ if (index_vector_dim < scatter_indices_shape.dimensions_size()) {
+ --num_scatter_dims;
+ }
+ if (num_scatter_dims == 0) {
+ // If there are no scatter dims, this must be a dynamic-update-slice kind of
+ // scatter. In this case, we prepend a degenerate dimension to work
+ // uniformly in the while loop.
+ return PrependDegenerateDims(updates, 1);
+ }
+ return CollapseFirstNDims(updates, num_scatter_dims);
+}
+
+// Expands an index vector from the scatter_indices tensor into a vector that
+// can be used to dynamic-update-slice to perform the scatter update.
+static StatusOr<HloInstruction*> ExpandIndexVectorIntoOperandSpace(
+ HloInstruction* index_vector, const ScatterDimensionNumbers& dim_numbers,
+ int64 operand_rank) {
+ HloComputation* computation = index_vector->parent();
+ const Shape& index_shape = index_vector->shape();
+ HloInstruction* zero =
+ computation->AddInstruction(HloInstruction::CreateConstant(
+ LiteralUtil::CreateFromDimensions(index_shape.element_type(), {1})));
+
+ // We extract out individual components from the smaller index and concatenate
+ // them (interspersing zeros as needed) into the larger index.
+ std::vector<HloInstruction*> expanded_index_components;
+
+ for (int i = 0; i < operand_rank; i++) {
+ int64 index_vector_dim_index =
+ FindIndex(dim_numbers.scatter_dims_to_operand_dims(), i);
+ if (index_vector_dim_index !=
+ dim_numbers.scatter_dims_to_operand_dims_size()) {
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * component_to_concat,
+ MakeSliceHlo(index_vector, /*start_indices=*/{index_vector_dim_index},
+ /*limit_indices=*/{index_vector_dim_index + 1},
+ /*strides=*/{1}));
+ expanded_index_components.push_back(component_to_concat);
+ } else {
+ expanded_index_components.push_back(zero);
+ }
+ }
+
+ return MakeConcatHlo(expanded_index_components, /*dimension=*/0);
+}
+
+// Body of the while loop that performs the scatter operation using other HLOs.
+static StatusOr<std::vector<HloInstruction*>> ScatterLoopBody(
+ HloInstruction* scatter, HloInstruction* induction_var,
+ const std::vector<HloInstruction*>& loop_state) {
+ const ScatterDimensionNumbers& dim_numbers =
+ scatter->scatter_dimension_numbers();
+ CHECK_EQ(loop_state.size(), 3);
+ HloInstruction* operand = loop_state[0];
+ HloInstruction* scatter_indices = loop_state[1];
+ HloInstruction* updates = loop_state[2];
+
+ bool has_scalar_indices = scatter_indices->shape().dimensions_size() == 1;
+ CHECK_EQ(has_scalar_indices,
+ dim_numbers.index_vector_dim() ==
+ scatter->operand(1)->shape().dimensions_size());
+
+ // Build a vector form of the induction variable of the while loop.
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * induction_var_as_vector,
+ MakeBroadcastHlo(induction_var, /*broadcast_dimensions=*/{},
+ /*result_shape_bounds=*/{1}));
+
+ // Pick the index to scatter from scatter_indices based on the induction_var
+ // and transform that to an index into the `operand` space.
+ HloInstruction* index_vector;
+ if (has_scalar_indices) {
+ TF_ASSIGN_OR_RETURN(
+ index_vector,
+ MakeDynamicSliceHlo(scatter_indices, induction_var_as_vector, {1}));
+ } else {
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * index_into_scatter_indices,
+ PadVectorWithZeros(induction_var_as_vector,
+ /*zeros_to_prepend=*/0, /*zeros_to_append=*/1));
+ int index_vector_size = scatter_indices->shape().dimensions(1);
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * index_vector_2d,
+ MakeDynamicSliceHlo(scatter_indices, index_into_scatter_indices,
+ {1, index_vector_size}));
+ TF_ASSIGN_OR_RETURN(index_vector,
+ ElideDegenerateDims(index_vector_2d, {0}));
+ }
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * scatter_slice_start,
+ ExpandIndexVectorIntoOperandSpace(index_vector, dim_numbers,
+ operand->shape().dimensions_size()));
+
+ // Extract the slice to be used to update from `updates` tensor for the
+ // induction_var corresponding to this iteration of the while loop.
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * index_into_updates,
+ PadVectorWithZeros(
+ induction_var_as_vector, /*zeros_to_prepend=*/0,
+ /*zeros_to_append=*/updates->shape().dimensions_size() - 1));
+ std::vector<int64> update_slice_bounds(updates->shape().dimensions().begin(),
+ updates->shape().dimensions().end());
+ update_slice_bounds[0] = 1;
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * update_slice,
+ MakeDynamicSliceHlo(updates, index_into_updates, update_slice_bounds));
+ TF_ASSIGN_OR_RETURN(HloInstruction * update_slice_for_scatter,
+ ElideDegenerateDims(update_slice, {0}));
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * update_slice_with_dims_inserted,
+ InsertDegenerateDims(update_slice_for_scatter,
+ AsInt64Slice(dim_numbers.inserted_window_dims())));
+
+ // Extact the slice to update from `operand` tensor.
+ const Shape& update_slice_shape = update_slice_with_dims_inserted->shape();
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * operand_slice_to_update,
+ MakeDynamicSliceHlo(operand, scatter_slice_start,
+ AsInt64Slice(update_slice_shape.dimensions())));
+
+ // Compute the new value for the slice to be updated in `operand` tensor by
+ // combining the existing value and the update value using the update
+ // computation.
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * updated_operand_slice,
+ MakeMapHlo({operand_slice_to_update, update_slice_with_dims_inserted},
+ scatter->to_apply()));
+
+ // Write the updated value of the slice into `operand` tensor.
+ TF_ASSIGN_OR_RETURN(HloInstruction * updated_operand,
+ MakeDynamicUpdateSliceHlo(operand, updated_operand_slice,
+ scatter_slice_start));
+
+ return StatusOr<std::vector<HloInstruction*>>{
+ {updated_operand, scatter_indices, updates}};
+}
+
+// High Level Algorithm.
+//
+// 1. Canonicalize the scatter_indices tensor such that it has rank 2, where
+// each row is an index into the operand.
+// 2. Canonicalize the updates tensor such that is has rank `num_window_dims+1`
+// and the scatter dim is the most-major dimension.
+// 3. Iterate over the set of indices in the canonicalized scatter_indices
+// tensor using a while loop, updating the operand for each such index. Each
+// iteration of this while loop performs the following:
+// a. Pick the index from scatter_indices for this iteration.
+// b. Transfrom this index into an index into the operand space.
+// c. Extract the slice to be used to update from the updates tensor.
+// d. Extract the slice to update from the operand tensor.
+// e. Compute the new value for the slice to update by combining the slices
+// from c. and d. using the update_computation of scatter.
+// f. Write the updated value of the slice into the operand tensor.
+
+StatusOr<HloInstruction*> ScatterExpander::ExpandScatter(
+ HloInstruction* scatter) {
+ HloInstruction* operand = scatter->mutable_operand(0);
+ HloInstruction* scatter_indices = scatter->mutable_operand(1);
+ HloInstruction* updates = scatter->mutable_operand(2);
+ const ScatterDimensionNumbers& dim_numbers =
+ scatter->scatter_dimension_numbers();
+
+ // If the updates tensor is empty, there is no need to update the operand. We
+ // can return the operand as is.
+ if (ShapeUtil::IsZeroElementArray(updates->shape())) {
+ return operand;
+ }
+
+ // Compute the trip count for the while loop to be used for scatter. This
+ // should be the number of indices we should scatter into the operand.
+ const Shape& scatter_indices_shape = scatter_indices->shape();
+ int64 scatter_loop_trip_count = 1;
+ for (int64 i = 0, e = scatter_indices_shape.dimensions_size(); i < e; i++) {
+ if (i != dim_numbers.index_vector_dim()) {
+ scatter_loop_trip_count *= scatter_indices_shape.dimensions(i);
+ }
+ }
+ if (!IsInt32(scatter_loop_trip_count)) {
+ return Unimplemented(
+ "Scatter operations with more than 2147483647 scatter indices are not "
+ "supported. This error occurred for %s.",
+ scatter->ToString().c_str());
+ }
+
+ // Canonicalize the scatter_indices, after which the size of its most-major
+ // dimension must be same as the while loop trip count.
+ TF_ASSIGN_OR_RETURN(HloInstruction * canonical_scatter_indices,
+ CanonicalizeScatterIndices(
+ scatter_indices, dim_numbers.index_vector_dim()));
+ CHECK_EQ(scatter_loop_trip_count,
+ canonical_scatter_indices->shape().dimensions(0));
+
+ // Canonicalize the updates, after which the size of its most-major dimension
+ // must be same as the while loop trip count.
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * canonical_updates,
+ PermuteScatterAndWindowDims(
+ updates, AsInt64Slice(dim_numbers.update_window_dims())));
+ TF_ASSIGN_OR_RETURN(
+ HloInstruction * adjusted_canonical_updates,
+ AdjustScatterDims(scatter_indices->shape(), canonical_updates,
+ dim_numbers.index_vector_dim()));
+ CHECK_EQ(scatter_loop_trip_count,
+ adjusted_canonical_updates->shape().dimensions(0));
+
+ // The while loop that implements the scatter operation.
+ StatusOr<std::vector<HloInstruction*>> scatter_loop_result_status =
+ WhileUtil::MakeCountedLoop(
+ scatter->parent(), scatter_loop_trip_count,
+ {operand, canonical_scatter_indices, adjusted_canonical_updates},
+ [&](HloInstruction* induction_var,
+ const std::vector<HloInstruction*>& loop_state) {
+ return ScatterLoopBody(scatter, induction_var, loop_state);
+ });
+ TF_ASSIGN_OR_RETURN(std::vector<HloInstruction*> scatter_loop_result,
+ scatter_loop_result_status);
+ return scatter_loop_result.front();
+}
+
+StatusOr<bool> ScatterExpander::Run(HloModule* module) {
+ std::vector<HloInstruction*> scatter_instrs;
+ for (HloComputation* computation : module->MakeNonfusionComputations()) {
+ for (HloInstruction* instr : computation->instructions()) {
+ if (instr->opcode() == HloOpcode::kScatter) {
+ scatter_instrs.push_back(instr);
+ }
+ }
+ }
+
+ for (auto instr : scatter_instrs) {
+ TF_ASSIGN_OR_RETURN(HloInstruction * expanded_root, ExpandScatter(instr));
+ TF_RETURN_IF_ERROR(
+ instr->parent()->ReplaceInstruction(instr, expanded_root));
+ }
+
+ return !scatter_instrs.empty();
+}
+
+} // namespace xla
diff --git a/tensorflow/compiler/xla/service/scatter_expander.h b/tensorflow/compiler/xla/service/scatter_expander.h
new file mode 100644
index 0000000000..8f735e877d
--- /dev/null
+++ b/tensorflow/compiler/xla/service/scatter_expander.h
@@ -0,0 +1,34 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_SCATTER_EXPANDER_H_
+#define TENSORFLOW_COMPILER_XLA_SERVICE_SCATTER_EXPANDER_H_
+
+#include "tensorflow/compiler/xla/service/hlo_pass_interface.h"
+
+namespace xla {
+
+class ScatterExpander : public HloPassInterface {
+ public:
+ tensorflow::StringPiece name() const override { return "scatter_expander"; }
+ StatusOr<bool> Run(HloModule* module) override;
+
+ private:
+ StatusOr<HloInstruction*> ExpandScatter(HloInstruction* scatter);
+};
+
+} // namespace xla
+
+#endif // TENSORFLOW_COMPILER_XLA_SERVICE_SCATTER_EXPANDER_H_
diff --git a/tensorflow/compiler/xla/service/service.cc b/tensorflow/compiler/xla/service/service.cc
index e970e885c5..1dbf540d13 100644
--- a/tensorflow/compiler/xla/service/service.cc
+++ b/tensorflow/compiler/xla/service/service.cc
@@ -53,6 +53,7 @@ limitations under the License.
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/stream_executor_no_cuda.h"
#include "tensorflow/core/platform/types.h"
+#include "tensorflow/core/util/ptr_util.h"
using ::tensorflow::strings::Printf;
using ::tensorflow::strings::StrCat;
@@ -408,7 +409,7 @@ Service::ExecuteParallelAndRegisterResult(
streams.push_back(std::move(stream));
if (replica == 0 && profile != nullptr) {
- timers.emplace_back(new se::Timer(streams.back()->parent()));
+ timers.push_back(MakeUnique<se::Timer>(streams.back()->parent()));
streams.back()
->InitTimer(timers.back().get())
.ThenStartTimer(timers.back().get());
@@ -440,7 +441,7 @@ Service::ExecuteParallelAndRegisterResult(
streams.back()->ThenStopTimer(timers.back().get());
}
- result_buffers.emplace_back(std::move(result));
+ result_buffers.push_back(std::move(result));
}
TF_ASSIGN_OR_RETURN(GlobalDataHandle handle,
allocation_tracker_.RegisterReplicatedBuffers(
@@ -558,7 +559,7 @@ StatusOr<GlobalDataHandle> Service::ExecuteAndRegisterResult(
std::vector<tensorflow::gtl::ArraySlice<const ShapedBuffer*>>
replicated_arguments;
for (const auto& arg : arguments) {
- replicated_arguments.emplace_back(arg);
+ replicated_arguments.push_back(arg);
}
TF_ASSIGN_OR_RETURN(auto results, executable->ExecuteOnStreams(
@@ -1052,11 +1053,12 @@ Status Service::TransferFromOutfeed(const TransferFromOutfeedRequest* arg,
executor = replicas[arg->replica_id()];
}
- Literal literal(arg->shape_with_layout());
+ auto literal = Literal::CreateFromShape(arg->shape_with_layout());
+
TF_RETURN_IF_ERROR(
execute_backend_->transfer_manager()->TransferLiteralFromOutfeed(
- executor, arg->shape_with_layout(), literal));
- *result->mutable_literal() = literal.ToProto();
+ executor, arg->shape_with_layout(), *literal));
+ *result->mutable_literal() = literal->ToProto();
return Status::OK();
}
diff --git a/tensorflow/compiler/xla/service/shape_inference.cc b/tensorflow/compiler/xla/service/shape_inference.cc
index a4ea2b28f4..ec6aa6df55 100644
--- a/tensorflow/compiler/xla/service/shape_inference.cc
+++ b/tensorflow/compiler/xla/service/shape_inference.cc
@@ -21,6 +21,7 @@ limitations under the License.
#include <set>
#include <string>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
@@ -1530,7 +1531,7 @@ ShapeInference::InferDegenerateDimensionBroadcastShape(HloOpcode operation,
/* static */ StatusOr<Shape> ShapeInference::InferConvolveShape(
const Shape& lhs, const Shape& rhs, const Window& window,
- const ConvolutionDimensionNumbers& dnums) {
+ const ConvolutionDimensionNumbers& dnums, int64 feature_group_count) {
TF_RETURN_IF_ERROR(ExpectArray(lhs, "lhs of convolution"));
TF_RETURN_IF_ERROR(ExpectArray(rhs, "rhs of convolution"));
@@ -1640,12 +1641,13 @@ ShapeInference::InferDegenerateDimensionBroadcastShape(HloOpcode operation,
const int64 kernel_output_features =
rhs.dimensions(dnums.kernel_output_feature_dimension());
- if (input_features != kernel_input_features) {
+ if (input_features != kernel_input_features * feature_group_count) {
return InvalidArgument(
"Expected LHS feature dimension (value %lld) to match RHS "
- "input feature dimension (value %lld); got <conv>(%s, %s)\n"
+ "input feature dimension * feature_group_count (value %lld); "
+ "got <conv>(%s, %s)\n"
"Dimension numbers: {%s}.",
- input_features, kernel_input_features,
+ input_features, kernel_input_features * feature_group_count,
ShapeUtil::HumanString(lhs).c_str(),
ShapeUtil::HumanString(rhs).c_str(), dnums.DebugString().c_str());
}
@@ -2491,201 +2493,198 @@ ShapeInference::InferDegenerateDimensionBroadcastShape(HloOpcode operation,
static Status ValidateGatherDimensionNumbers(
const Shape& input_shape,
- tensorflow::gtl::ArraySlice<int64> gather_indices_shape,
+ tensorflow::gtl::ArraySlice<int64> start_indices_shape,
const GatherDimensionNumbers& dim_numbers) {
- if (!c_is_sorted(dim_numbers.output_window_dims())) {
+ if (!absl::c_is_sorted(dim_numbers.offset_dims())) {
return InvalidArgument(
"Output window dimensions in gather op must be ascending; got: %s.",
- Join(dim_numbers.output_window_dims(), ", ").c_str());
+ Join(dim_numbers.offset_dims(), ", ").c_str());
}
- if (c_adjacent_find(dim_numbers.output_window_dims()) !=
- dim_numbers.output_window_dims().end()) {
+ if (absl::c_adjacent_find(dim_numbers.offset_dims()) !=
+ dim_numbers.offset_dims().end()) {
return InvalidArgument(
"Output window dimensions in gather op must not repeat; got: %s.",
- Join(dim_numbers.output_window_dims(), ", ").c_str());
+ Join(dim_numbers.offset_dims(), ", ").c_str());
}
- const int64 output_window_dim_count = dim_numbers.output_window_dims_size();
+ const int64 output_offset_dim_count = dim_numbers.offset_dims_size();
const int64 output_shape_rank =
- output_window_dim_count + gather_indices_shape.size() - 1;
+ output_offset_dim_count + start_indices_shape.size() - 1;
- for (int i = 0; i < dim_numbers.output_window_dims_size(); ++i) {
- int64 window_index = dim_numbers.output_window_dims(i);
- if (window_index < 0 || window_index >= output_shape_rank) {
+ for (int i = 0; i < dim_numbers.offset_dims_size(); ++i) {
+ int64 offset_dim = dim_numbers.offset_dims(i);
+ if (offset_dim < 0 || offset_dim >= output_shape_rank) {
return InvalidArgument(
- "Window index %d in gather op is out of bounds; got %lld, but should "
+ "Offset dimension %d in gather op is out of bounds; got %lld, but "
+ "should "
"have been in [0,%lld).",
- i, window_index, output_shape_rank);
+ i, offset_dim, output_shape_rank);
}
}
- if (dim_numbers.gather_dims_to_operand_dims_size() !=
- gather_indices_shape[dim_numbers.index_vector_dim()]) {
+ if (dim_numbers.start_index_map_size() !=
+ start_indices_shape[dim_numbers.index_vector_dim()]) {
return InvalidArgument(
- "Gather op has %d elements in gather_dims_to_operand_dims and the "
- "bound of dimension index_vector_dim=%lld of gather_indices is "
+ "Gather op has %d elements in start_index_map and the "
+ "bound of dimension index_vector_dim=%lld of start_indices is "
"%lld. These two numbers must be equal.",
- dim_numbers.gather_dims_to_operand_dims_size(),
- dim_numbers.index_vector_dim(),
- gather_indices_shape[dim_numbers.index_vector_dim()]);
+ dim_numbers.start_index_map_size(), dim_numbers.index_vector_dim(),
+ start_indices_shape[dim_numbers.index_vector_dim()]);
}
- for (int i = 0; i < dim_numbers.gather_dims_to_operand_dims_size(); i++) {
- int64 gather_dim_to_input_dim = dim_numbers.gather_dims_to_operand_dims(i);
- if (gather_dim_to_input_dim < 0 ||
- gather_dim_to_input_dim >= input_shape.dimensions_size()) {
+ for (int i = 0; i < dim_numbers.start_index_map_size(); i++) {
+ int64 operand_dim_for_start_index_i = dim_numbers.start_index_map(i);
+ if (operand_dim_for_start_index_i < 0 ||
+ operand_dim_for_start_index_i >= input_shape.dimensions_size()) {
return InvalidArgument(
- "Invalid gather_dims_to_operand_dims mapping; domain is [0, %d), "
- "got: %d->%lld.",
- input_shape.dimensions_size(), i, gather_dim_to_input_dim);
+ "Invalid start_index_map; domain is [0, %d), got: %d->%lld.",
+ input_shape.dimensions_size(), i, operand_dim_for_start_index_i);
}
}
- std::vector<int64> sorted_gather_dims_to_operand_dims(
- dim_numbers.gather_dims_to_operand_dims().begin(),
- dim_numbers.gather_dims_to_operand_dims().end());
+ std::vector<int64> sorted_start_index_map(
+ dim_numbers.start_index_map().begin(),
+ dim_numbers.start_index_map().end());
- c_sort(sorted_gather_dims_to_operand_dims);
+ absl::c_sort(sorted_start_index_map);
- if (c_adjacent_find(sorted_gather_dims_to_operand_dims) !=
- sorted_gather_dims_to_operand_dims.end()) {
+ if (absl::c_adjacent_find(sorted_start_index_map) !=
+ sorted_start_index_map.end()) {
return InvalidArgument(
- "Repeated dimensions are not allowed in gather_dims_to_operand_dims; "
+ "Repeated dimensions are not allowed in start_index_map; "
"got: %s.",
- Join(dim_numbers.gather_dims_to_operand_dims(), ", ").c_str());
+ Join(dim_numbers.start_index_map(), ", ").c_str());
}
- for (int64 elided_dim : dim_numbers.elided_window_dims()) {
- if (elided_dim < 0 || elided_dim >= input_shape.dimensions_size()) {
+ for (int64 collapsed_dim : dim_numbers.collapsed_slice_dims()) {
+ if (collapsed_dim < 0 || collapsed_dim >= input_shape.dimensions_size()) {
return InvalidArgument(
- "Invalid elided_window_dims set in gather op; valid range is [0, "
+ "Invalid collapsed_slice_dims set in gather op; valid range is [0, "
"%d), got: %lld.",
- input_shape.dimensions_size(), elided_dim);
+ input_shape.dimensions_size(), collapsed_dim);
}
}
- if (!c_is_sorted(dim_numbers.elided_window_dims())) {
+ if (!absl::c_is_sorted(dim_numbers.collapsed_slice_dims())) {
return InvalidArgument(
- "elided_window_dims in gather op must be sorted; got: %s",
- Join(dim_numbers.elided_window_dims(), ", ").c_str());
+ "collapsed_slice_dims in gather op must be sorted; got: %s",
+ Join(dim_numbers.collapsed_slice_dims(), ", ").c_str());
}
- if (c_adjacent_find(dim_numbers.elided_window_dims()) !=
- dim_numbers.elided_window_dims().end()) {
+ if (absl::c_adjacent_find(dim_numbers.collapsed_slice_dims()) !=
+ dim_numbers.collapsed_slice_dims().end()) {
return InvalidArgument(
- "Repeated dimensions not allowed in elided_window_dims in gather op; "
+ "Repeated dimensions not allowed in collapsed_slice_dims in gather op; "
"got: %s.",
- Join(dim_numbers.elided_window_dims(), ", ").c_str());
+ Join(dim_numbers.collapsed_slice_dims(), ", ").c_str());
}
return Status::OK();
}
/*static*/ StatusOr<Shape> ShapeInference::InferGatherShape(
- const Shape& input_shape, const Shape& gather_indices_shape,
+ const Shape& input_shape, const Shape& start_indices_shape,
const GatherDimensionNumbers& gather_dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds) {
+ tensorflow::gtl::ArraySlice<int64> slice_sizes) {
TF_RETURN_IF_ERROR(
ExpectArray(input_shape, "input tensor operand gather op"));
TF_RETURN_IF_ERROR(
- ExpectArray(gather_indices_shape, "gather indices operand of gather op"));
+ ExpectArray(start_indices_shape, "gather indices operand of gather op"));
- if (!ShapeUtil::ElementIsIntegral(gather_indices_shape)) {
+ if (!ShapeUtil::ElementIsIntegral(start_indices_shape)) {
return InvalidArgument(
"Gather indices parameter must be an integral tensor; got %s.",
- ShapeUtil::HumanString(gather_indices_shape).c_str());
+ ShapeUtil::HumanString(start_indices_shape).c_str());
}
// We implicitly reshape gather indices of shape P[A,B,C] to P[A,B,C,1] if
// index_vector_dim is rank(P). The bounds of this expanded shape is
- // stored in expanded_gather_indices_shape.
+ // stored in expanded_start_indices_shape.
- if (gather_indices_shape.dimensions_size() <
+ if (start_indices_shape.dimensions_size() <
gather_dim_numbers.index_vector_dim() ||
gather_dim_numbers.index_vector_dim() < 0) {
return InvalidArgument(
- "Gather index leaf dimension must be within [0, rank(gather_indices) + "
- "1). rank(gather_indices) is %d and gather index leaf dimension is "
+ "Gather index leaf dimension must be within [0, rank(start_indices) + "
+ "1). rank(start_indices) is %d and gather index leaf dimension is "
"%lld.",
- gather_indices_shape.dimensions_size(),
+ start_indices_shape.dimensions_size(),
gather_dim_numbers.index_vector_dim());
}
- std::vector<int64> expanded_gather_indices_shape;
- expanded_gather_indices_shape.reserve(gather_indices_shape.dimensions_size());
- c_copy(gather_indices_shape.dimensions(),
- std::back_inserter(expanded_gather_indices_shape));
- if (expanded_gather_indices_shape.size() ==
+ std::vector<int64> expanded_start_indices_shape;
+ expanded_start_indices_shape.reserve(start_indices_shape.dimensions_size());
+ absl::c_copy(start_indices_shape.dimensions(),
+ std::back_inserter(expanded_start_indices_shape));
+ if (expanded_start_indices_shape.size() ==
gather_dim_numbers.index_vector_dim()) {
- expanded_gather_indices_shape.push_back(1);
+ expanded_start_indices_shape.push_back(1);
}
TF_RETURN_IF_ERROR(ValidateGatherDimensionNumbers(
- input_shape, expanded_gather_indices_shape, gather_dim_numbers));
+ input_shape, expanded_start_indices_shape, gather_dim_numbers));
- if (window_bounds.size() != input_shape.dimensions_size()) {
+ if (slice_sizes.size() != input_shape.dimensions_size()) {
return InvalidArgument(
- "Gather op must have one window bound for every input dimension; got: "
- "len(window_bounds)=%lu, input_shape.rank=%d.",
- window_bounds.size(), input_shape.dimensions_size());
+ "Gather op must have one slice size for every input dimension; got: "
+ "len(slice_sizes)=%lu, input_shape.rank=%d.",
+ slice_sizes.size(), input_shape.dimensions_size());
}
- if (window_bounds.size() !=
- gather_dim_numbers.output_window_dims_size() +
- gather_dim_numbers.elided_window_dims_size()) {
+ if (slice_sizes.size() !=
+ gather_dim_numbers.offset_dims_size() +
+ gather_dim_numbers.collapsed_slice_dims_size()) {
return InvalidArgument(
- "All components of the window index in a gather op must either be a "
- "output window index or explicitly elided; got len(window_bounds)=%lu, "
- "output_window_bounds=%s, elided_window_bounds=%s.",
- window_bounds.size(),
- Join(gather_dim_numbers.output_window_dims(), ",").c_str(),
- Join(gather_dim_numbers.elided_window_dims(), ",").c_str());
+ "All components of the offset index in a gather op must either be a "
+ "offset dimension or explicitly collapsed; got len(slice_sizes)=%lu, "
+ "output_slice_sizes=%s, collapsed_slice_dims=%s.",
+ slice_sizes.size(), Join(gather_dim_numbers.offset_dims(), ",").c_str(),
+ Join(gather_dim_numbers.collapsed_slice_dims(), ",").c_str());
}
- for (int i = 0; i < window_bounds.size(); i++) {
- int64 window_bound = window_bounds[i];
- int64 corresponding_input_bound = input_shape.dimensions(i);
- if (window_bound < 0 || window_bound > corresponding_input_bound) {
+ for (int i = 0; i < slice_sizes.size(); i++) {
+ int64 slice_size = slice_sizes[i];
+ int64 corresponding_input_size = input_shape.dimensions(i);
+ if (slice_size < 0 || slice_size > corresponding_input_size) {
return InvalidArgument(
- "Window bound at index %d in gather op is out of range, must be "
- "within "
- "[0, %lld), got %lld.",
- i, corresponding_input_bound + 1, window_bound);
+ "Slice size at index %d in gather op is out of range, must be "
+ "within [0, %lld), got %lld.",
+ i, corresponding_input_size + 1, slice_size);
}
}
- for (int i = 0; i < gather_dim_numbers.elided_window_dims_size(); i++) {
- if (window_bounds[gather_dim_numbers.elided_window_dims(i)] != 1) {
+ for (int i = 0; i < gather_dim_numbers.collapsed_slice_dims_size(); i++) {
+ if (slice_sizes[gather_dim_numbers.collapsed_slice_dims(i)] != 1) {
return InvalidArgument(
- "Gather op can only elide window indices with bound 1, but bound is "
+ "Gather op can only collapse slice dims with bound 1, but bound is "
"%lld for index %lld at position %d.",
- window_bounds[gather_dim_numbers.elided_window_dims(i)],
- gather_dim_numbers.elided_window_dims(i), i);
+ slice_sizes[gather_dim_numbers.collapsed_slice_dims(i)],
+ gather_dim_numbers.collapsed_slice_dims(i), i);
}
}
- int64 result_rank = gather_dim_numbers.output_window_dims_size() +
- (expanded_gather_indices_shape.size() - 1);
- int64 window_dims_seen = 0;
+ int64 result_rank = gather_dim_numbers.offset_dims_size() +
+ (expanded_start_indices_shape.size() - 1);
+ int64 offset_dims_seen = 0;
int64 gather_dims_seen = 0;
std::vector<int64> output_dim_bounds;
output_dim_bounds.reserve(result_rank);
for (int64 i = 0; i < result_rank; i++) {
int64 current_bound;
bool is_window_index =
- c_binary_search(gather_dim_numbers.output_window_dims(), i);
+ absl::c_binary_search(gather_dim_numbers.offset_dims(), i);
if (is_window_index) {
- while (c_binary_search(gather_dim_numbers.elided_window_dims(),
- window_dims_seen)) {
- window_dims_seen++;
+ while (absl::c_binary_search(gather_dim_numbers.collapsed_slice_dims(),
+ offset_dims_seen)) {
+ offset_dims_seen++;
}
- current_bound = window_bounds[window_dims_seen++];
+ current_bound = slice_sizes[offset_dims_seen++];
} else {
if (gather_dims_seen == gather_dim_numbers.index_vector_dim()) {
gather_dims_seen++;
}
- current_bound = expanded_gather_indices_shape[gather_dims_seen++];
+ current_bound = expanded_start_indices_shape[gather_dims_seen++];
}
output_dim_bounds.push_back(current_bound);
@@ -2701,12 +2700,12 @@ Status ValidateScatterDimensionNumbers(
tensorflow::gtl::ArraySlice<int64> scatter_indices_shape,
const Shape& updates_shape, const ScatterDimensionNumbers& dim_numbers) {
// Validate update_window_dims in ScatterDimensionNumbers.
- if (!c_is_sorted(dim_numbers.update_window_dims())) {
+ if (!absl::c_is_sorted(dim_numbers.update_window_dims())) {
return InvalidArgument(
"update_window_dims in scatter op must be sorted; got: %s.",
Join(dim_numbers.update_window_dims(), ", ").c_str());
}
- if (c_adjacent_find(dim_numbers.update_window_dims()) !=
+ if (absl::c_adjacent_find(dim_numbers.update_window_dims()) !=
dim_numbers.update_window_dims().end()) {
return InvalidArgument(
"update_window_dims in scatter op must not repeat; got: %s.",
@@ -2723,12 +2722,12 @@ Status ValidateScatterDimensionNumbers(
}
// Validate inserted_window_dims in ScatterDimensionNumbers.
- if (!c_is_sorted(dim_numbers.inserted_window_dims())) {
+ if (!absl::c_is_sorted(dim_numbers.inserted_window_dims())) {
return InvalidArgument(
"inserted_window_dims in scatter op must be sorted; got: %s.",
Join(dim_numbers.inserted_window_dims(), ", ").c_str());
}
- if (c_adjacent_find(dim_numbers.inserted_window_dims()) !=
+ if (absl::c_adjacent_find(dim_numbers.inserted_window_dims()) !=
dim_numbers.inserted_window_dims().end()) {
return InvalidArgument(
"inserted_window_dims in scatter op must not repeat; got: %s.",
@@ -2768,8 +2767,8 @@ Status ValidateScatterDimensionNumbers(
std::vector<int64> sorted_scatter_dims_to_operand_dims(
dim_numbers.scatter_dims_to_operand_dims().begin(),
dim_numbers.scatter_dims_to_operand_dims().end());
- c_sort(sorted_scatter_dims_to_operand_dims);
- if (c_adjacent_find(sorted_scatter_dims_to_operand_dims) !=
+ absl::c_sort(sorted_scatter_dims_to_operand_dims);
+ if (absl::c_adjacent_find(sorted_scatter_dims_to_operand_dims) !=
sorted_scatter_dims_to_operand_dims.end()) {
return InvalidArgument(
"Repeated dimensions not allowed in scatter_dims_to_operand_dims; "
@@ -2836,32 +2835,32 @@ Status ValidateScatterDimensionNumbers(
scatter_dim_numbers));
int64 inserted_dims_seen = 0;
- std::vector<int64> max_update_window_bounds;
+ std::vector<int64> max_update_slice_sizes;
for (int i = 0; i < operand_shape.dimensions_size(); ++i) {
if (inserted_dims_seen < scatter_dim_numbers.inserted_window_dims_size() &&
scatter_dim_numbers.inserted_window_dims(inserted_dims_seen) == i) {
++inserted_dims_seen;
} else {
- max_update_window_bounds.push_back(operand_shape.dimensions(i));
+ max_update_slice_sizes.push_back(operand_shape.dimensions(i));
}
}
for (int i = 0; i < scatter_dim_numbers.update_window_dims_size(); ++i) {
auto update_window_dim = scatter_dim_numbers.update_window_dims(i);
if (updates_shape.dimensions(update_window_dim) >
- max_update_window_bounds[i]) {
+ max_update_slice_sizes[i]) {
return InvalidArgument(
"Bounds of the window dimensions of updates must not exceed the "
"bounds of the corresponding dimensions of operand. For dimension "
"%lld, updates bound is %lld, operand bound is %lld.",
update_window_dim, updates_shape.dimensions(update_window_dim),
- max_update_window_bounds[i]);
+ max_update_slice_sizes[i]);
}
}
int64 scatter_dims_seen = 0;
for (int64 i = 0; i < ShapeUtil::Rank(updates_shape); ++i) {
bool is_update_window_dim =
- c_binary_search(scatter_dim_numbers.update_window_dims(), i);
+ absl::c_binary_search(scatter_dim_numbers.update_window_dims(), i);
if (is_update_window_dim) {
continue;
}
diff --git a/tensorflow/compiler/xla/service/shape_inference.h b/tensorflow/compiler/xla/service/shape_inference.h
index c185b0a1bd..4974ac9916 100644
--- a/tensorflow/compiler/xla/service/shape_inference.h
+++ b/tensorflow/compiler/xla/service/shape_inference.h
@@ -112,7 +112,8 @@ class ShapeInference {
// filter (rhs) to lhs in the way specified by the fields on window.
static StatusOr<Shape> InferConvolveShape(
const Shape& lhs, const Shape& rhs, const Window& window,
- const ConvolutionDimensionNumbers& dimension_numbers);
+ const ConvolutionDimensionNumbers& dimension_numbers,
+ int64 feature_group_count = 1);
// Infers the shape produced by the given FFT type on the given operand.
static StatusOr<Shape> InferFftShape(
@@ -275,9 +276,9 @@ class ShapeInference {
// with the given input shape, gather indices shape and gather dimension
// numbers.
static StatusOr<Shape> InferGatherShape(
- const Shape& input_shape, const Shape& gather_indices_shape,
+ const Shape& input_shape, const Shape& start_indices_shape,
const GatherDimensionNumbers& gather_dim_numbers,
- tensorflow::gtl::ArraySlice<int64> window_bounds);
+ tensorflow::gtl::ArraySlice<int64> slice_sizes);
// Helper that validates the given input shape, scatter indices shape, updates
// shape, and scatter dimension numbers that constitute a scatter operation,
diff --git a/tensorflow/compiler/xla/service/shape_inference_test.cc b/tensorflow/compiler/xla/service/shape_inference_test.cc
index a73fa181cd..4ed8fc6b86 100644
--- a/tensorflow/compiler/xla/service/shape_inference_test.cc
+++ b/tensorflow/compiler/xla/service/shape_inference_test.cc
@@ -1654,11 +1654,11 @@ TEST_F(ScatterGatherShapeInferenceTest, TensorFlowGather) {
ShapeInference::InferGatherShape(
matrix_64_48_, s64_vector_32_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{0},
- /*elided_window_dims=*/{1},
- /*gather_dims_to_operand_dims=*/{1},
+ /*offset_dims=*/{0},
+ /*collapsed_slice_dims=*/{1},
+ /*start_index_map=*/{1},
/*index_vector_dim=*/1),
- /*window_bounds=*/{64, 1}));
+ /*slice_sizes=*/{64, 1}));
EXPECT_TRUE(
ShapeUtil::Equal(gather_shape, ShapeUtil::MakeShape(F32, {64, 32})))
<< ShapeUtil::HumanString(gather_shape);
@@ -1669,11 +1669,11 @@ TEST_F(ScatterGatherShapeInferenceTest, TensorFlowGatherV2) {
ShapeInference::InferGatherShape(
matrix_64_48_, s64_vector_32_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{1},
- /*elided_window_dims=*/{0},
- /*gather_dims_to_operand_dims=*/{0},
+ /*offset_dims=*/{1},
+ /*collapsed_slice_dims=*/{0},
+ /*start_index_map=*/{0},
/*index_vector_dim=*/1),
- /*window_bounds=*/{1, 48}));
+ /*slice_sizes=*/{1, 48}));
EXPECT_TRUE(
ShapeUtil::Equal(gather_shape, ShapeUtil::MakeShape(F32, {32, 48})))
<< ShapeUtil::HumanString(gather_shape);
@@ -1684,11 +1684,11 @@ TEST_F(ScatterGatherShapeInferenceTest, TensorFlowGatherNd) {
ShapeInference::InferGatherShape(
matrix_64_48_, s64_4d_tensor_10_9_8_7_1_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4},
- /*elided_window_dims=*/{0},
- /*gather_dims_to_operand_dims=*/{0},
+ /*offset_dims=*/{4},
+ /*collapsed_slice_dims=*/{0},
+ /*start_index_map=*/{0},
/*index_vector_dim=*/4),
- /*window_bounds=*/{1, 48}));
+ /*slice_sizes=*/{1, 48}));
EXPECT_TRUE(ShapeUtil::Equal(gather_shape,
ShapeUtil::MakeShape(F32, {10, 9, 8, 7, 48})))
<< ShapeUtil::HumanString(gather_shape);
@@ -1700,11 +1700,11 @@ TEST_F(ScatterGatherShapeInferenceTest, TensorFlowBatchDynamicSlice) {
ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26}));
+ /*slice_sizes=*/{30, 29, 28, 27, 26}));
EXPECT_TRUE(ShapeUtil::Equal(
gather_shape,
ShapeUtil::MakeShape(F32, {10, 9, 8, 7, 30, 29, 28, 27, 26})))
@@ -1717,11 +1717,11 @@ TEST_F(ScatterGatherShapeInferenceTest, NonDefaultGatherIndicesLeafDim_A) {
ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_5_7_6_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/2),
- /*window_bounds=*/{30, 29, 28, 27, 26}));
+ /*slice_sizes=*/{30, 29, 28, 27, 26}));
EXPECT_TRUE(ShapeUtil::Equal(
gather_shape,
@@ -1735,11 +1735,11 @@ TEST_F(ScatterGatherShapeInferenceTest, NonDefaultGatherIndicesLeafDim_B) {
ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_5_10_9_7_6_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/0),
- /*window_bounds=*/{30, 29, 28, 27, 26}));
+ /*slice_sizes=*/{30, 29, 28, 27, 26}));
EXPECT_TRUE(ShapeUtil::Equal(
gather_shape,
@@ -1749,16 +1749,15 @@ TEST_F(ScatterGatherShapeInferenceTest, NonDefaultGatherIndicesLeafDim_B) {
TEST_F(ScatterGatherShapeInferenceTest, NoOutputGatherDims) {
// This is equivalent to a dynamic slice.
- TF_ASSERT_OK_AND_ASSIGN(
- Shape gather_shape,
- ShapeInference::InferGatherShape(
- f32_5d_tensor_50_49_48_47_46_, s64_vector_5_,
- HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{0, 1, 2, 3, 4},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
- /*index_vector_dim=*/0),
- /*window_bounds=*/{30, 29, 28, 27, 26}));
+ TF_ASSERT_OK_AND_ASSIGN(Shape gather_shape,
+ ShapeInference::InferGatherShape(
+ f32_5d_tensor_50_49_48_47_46_, s64_vector_5_,
+ HloGatherInstruction::MakeGatherDimNumbers(
+ /*offset_dims=*/{0, 1, 2, 3, 4},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
+ /*index_vector_dim=*/0),
+ /*slice_sizes=*/{30, 29, 28, 27, 26}));
EXPECT_TRUE(ShapeUtil::Equal(gather_shape,
ShapeUtil::MakeShape(F32, {30, 29, 28, 27, 26})))
@@ -1772,11 +1771,11 @@ TEST_F(ScatterGatherShapeInferenceTest, ScalarGatherIndices) {
ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_scalar_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{0, 1, 2, 3},
- /*elided_window_dims=*/{0},
- /*gather_dims_to_operand_dims=*/{0},
+ /*offset_dims=*/{0, 1, 2, 3},
+ /*collapsed_slice_dims=*/{0},
+ /*start_index_map=*/{0},
/*index_vector_dim=*/0),
- /*window_bounds=*/{1, 30, 29, 28, 27}));
+ /*slice_sizes=*/{1, 30, 29, 28, 27}));
EXPECT_TRUE(ShapeUtil::Equal(gather_shape,
ShapeUtil::MakeShape(F32, {30, 29, 28, 27})))
@@ -1787,11 +1786,11 @@ TEST_F(ScatterGatherShapeInferenceTest, TupleShapedTensorInput) {
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
tuple_shape_, s64_vector_32_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{0},
- /*elided_window_dims=*/{1},
- /*gather_dims_to_operand_dims=*/{1},
+ /*offset_dims=*/{0},
+ /*collapsed_slice_dims=*/{1},
+ /*start_index_map=*/{1},
/*index_vector_dim=*/1),
- /*window_bounds=*/{64, 1});
+ /*slice_sizes=*/{64, 1});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
HasSubstr("Expected array argument for input"))
@@ -1802,11 +1801,11 @@ TEST_F(ScatterGatherShapeInferenceTest, TupleShapedGatherIndicesInput) {
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
s64_vector_32_, tuple_shape_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{0},
- /*elided_window_dims=*/{1},
- /*gather_dims_to_operand_dims=*/{1},
+ /*offset_dims=*/{0},
+ /*collapsed_slice_dims=*/{1},
+ /*start_index_map=*/{1},
/*index_vector_dim=*/0),
- /*window_bounds=*/{64, 1});
+ /*slice_sizes=*/{64, 1});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
HasSubstr("Expected array argument for gather indices"))
@@ -1817,11 +1816,11 @@ TEST_F(ScatterGatherShapeInferenceTest, FloatingPointGatherIndicesInput) {
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
s64_vector_32_, vector_32_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{0},
- /*elided_window_dims=*/{1},
- /*gather_dims_to_operand_dims=*/{1},
+ /*offset_dims=*/{0},
+ /*collapsed_slice_dims=*/{1},
+ /*start_index_map=*/{1},
/*index_vector_dim=*/0),
- /*window_bounds=*/{64, 1});
+ /*slice_sizes=*/{64, 1});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
HasSubstr("Gather indices parameter must be an integral tensor"))
@@ -1833,11 +1832,11 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 8, 7},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 8, 7},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().error_message(),
@@ -1850,11 +1849,11 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 7},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 7},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().error_message(),
@@ -1867,14 +1866,14 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 99, 100, 101},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 99, 100, 101},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
- HasSubstr("Window index 2 in gather op is out of bounds"))
+ HasSubstr("Offset dimension 2 in gather op is out of bounds"))
<< statusor.status();
}
@@ -1883,14 +1882,14 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 9},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 9},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
- HasSubstr("Window index 4 in gather op is out of bounds"))
+ HasSubstr("Offset dimension 4 in gather op is out of bounds"))
<< statusor.status();
}
@@ -1899,16 +1898,16 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{4},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{4},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().error_message(),
- HasSubstr("All components of the window index in a gather op must either "
- "be a output window index or explicitly elided"))
+ HasSubstr("All components of the offset index in a gather op must either "
+ "be a offset dimension or explicitly collapsed"))
<< statusor.status();
}
@@ -1917,14 +1916,14 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{0, 1, 2, 3, 19},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{0, 1, 2, 3, 19},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
- HasSubstr("Invalid elided_window_dims set in gather op; valid "
+ HasSubstr("Invalid collapsed_slice_dims set in gather op; valid "
"range is [0, 5), got: 19"))
<< statusor.status();
}
@@ -1934,16 +1933,15 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{0, 1, 2, 3, 3},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{0, 1, 2, 3, 3},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
- EXPECT_THAT(
- statusor.status().error_message(),
- HasSubstr(
- "Repeated dimensions not allowed in elided_window_dims in gather op"))
+ EXPECT_THAT(statusor.status().error_message(),
+ HasSubstr("Repeated dimensions not allowed in "
+ "collapsed_slice_dims in gather op"))
<< statusor.status();
}
@@ -1952,17 +1950,16 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
- EXPECT_THAT(
- statusor.status().error_message(),
- HasSubstr("Gather op has 4 elements in gather_dims_to_operand_dims and "
- "the bound of dimension index_vector_dim=4 of "
- "gather_indices is 5. These two numbers must be equal."))
+ EXPECT_THAT(statusor.status().error_message(),
+ HasSubstr("Gather op has 4 elements in start_index_map and "
+ "the bound of dimension index_vector_dim=4 of "
+ "start_indices is 5. These two numbers must be equal."))
<< statusor.status();
}
@@ -1971,16 +1968,14 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 7},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 7},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
- EXPECT_THAT(
- statusor.status().error_message(),
- HasSubstr("Invalid gather_dims_to_operand_dims mapping; domain is "
- "[0, 5), got: 4->7"))
+ EXPECT_THAT(statusor.status().error_message(),
+ HasSubstr("Invalid start_index_map; domain is [0, 5), got: 4->7"))
<< statusor.status();
}
@@ -1989,16 +1984,15 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 3},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 3},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().error_message(),
- HasSubstr(
- "Repeated dimensions are not allowed in gather_dims_to_operand_dims"))
+ HasSubstr("Repeated dimensions are not allowed in start_index_map"))
<< statusor.status();
}
@@ -2007,14 +2001,14 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{2, 1},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{2, 1},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{1, 1, 28, 27, 26});
+ /*slice_sizes=*/{1, 1, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
- HasSubstr("elided_window_dims in gather op must be sorted"))
+ HasSubstr("collapsed_slice_dims in gather op must be sorted"))
<< statusor.status();
}
@@ -2023,15 +2017,15 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7},
- /*elided_window_dims=*/{2},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7},
+ /*collapsed_slice_dims=*/{2},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 1, 300, 26});
+ /*slice_sizes=*/{30, 29, 1, 300, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
- HasSubstr("Window bound at index 3 in gather op is out of range, "
- "must be within [0, 48), got 300"))
+ HasSubstr("Slice size at index 3 in gather op is out of range, "
+ "must be within [0, 48), got 300."))
<< statusor.status();
}
@@ -2040,16 +2034,15 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 26});
+ /*slice_sizes=*/{30, 29, 28, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(
statusor.status().error_message(),
- HasSubstr(
- "Gather op must have one window bound for every input dimension"))
+ HasSubstr("Gather op must have one slice size for every input dimension"))
<< statusor.status();
}
@@ -2058,15 +2051,15 @@ TEST_F(ScatterGatherShapeInferenceTest,
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_8_7_5_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7},
- /*elided_window_dims=*/{1},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7},
+ /*collapsed_slice_dims=*/{1},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/4),
- /*window_bounds=*/{30, 29, 28, 26, 20});
+ /*slice_sizes=*/{30, 29, 28, 26, 20});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
- HasSubstr("Gather op can only elide window indices with bound 1, "
- "but bound is 29 for index 1 at position 0"))
+ HasSubstr("Gather op can only collapse slice dims with bound 1, "
+ "but bound is 29 for index 1 at position 0."))
<< statusor.status();
}
@@ -2074,16 +2067,16 @@ TEST_F(ScatterGatherShapeInferenceTest, OutOfBoundsGatherIndicesLeafDim) {
StatusOr<Shape> statusor = ShapeInference::InferGatherShape(
f32_5d_tensor_50_49_48_47_46_, s64_4d_tensor_10_9_5_7_6_,
HloGatherInstruction::MakeGatherDimNumbers(
- /*output_window_dims=*/{4, 5, 6, 7, 8},
- /*elided_window_dims=*/{},
- /*gather_dims_to_operand_dims=*/{0, 1, 2, 3, 4},
+ /*offset_dims=*/{4, 5, 6, 7, 8},
+ /*collapsed_slice_dims=*/{},
+ /*start_index_map=*/{0, 1, 2, 3, 4},
/*index_vector_dim=*/32),
- /*window_bounds=*/{30, 29, 28, 27, 26});
+ /*slice_sizes=*/{30, 29, 28, 27, 26});
ASSERT_FALSE(statusor.ok());
EXPECT_THAT(statusor.status().error_message(),
HasSubstr("Gather index leaf dimension must be within [0, "
- "rank(gather_indices) + 1)"))
+ "rank(start_indices) + 1)"))
<< statusor.status();
}
diff --git a/tensorflow/compiler/xla/service/while_loop_constant_sinking.cc b/tensorflow/compiler/xla/service/while_loop_constant_sinking.cc
index 62af45128a..aab1180662 100644
--- a/tensorflow/compiler/xla/service/while_loop_constant_sinking.cc
+++ b/tensorflow/compiler/xla/service/while_loop_constant_sinking.cc
@@ -14,6 +14,7 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/while_loop_constant_sinking.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/service/while_util.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/gtl/flatmap.h"
@@ -32,7 +33,7 @@ static Status ReplaceUsesWhileKeepingLoopInvariance(
std::vector<HloInstruction*> users;
users.reserve(old_instr->user_count());
- c_copy(old_instr->users(), std::back_inserter(users));
+ absl::c_copy(old_instr->users(), std::back_inserter(users));
for (auto* user : users) {
for (int64 i = 0, e = user->operand_count(); i < e; i++) {
@@ -108,10 +109,10 @@ StatusOr<bool> WhileLoopConstantSinking::Run(HloModule* module) {
//
// This will let us sink the constant into the outer while first and then
// into the inner while in a single run of this pass.
- c_copy_if(comp->instructions(), std::back_inserter(while_instrs),
- [](const HloInstruction* instr) {
- return instr->opcode() == HloOpcode::kWhile;
- });
+ absl::c_copy_if(comp->instructions(), std::back_inserter(while_instrs),
+ [](const HloInstruction* instr) {
+ return instr->opcode() == HloOpcode::kWhile;
+ });
}
for (HloInstruction* while_instr : while_instrs) {
diff --git a/tensorflow/compiler/xla/service/while_loop_constant_sinking_test.cc b/tensorflow/compiler/xla/service/while_loop_constant_sinking_test.cc
index 266039d2ff..0e7667de83 100644
--- a/tensorflow/compiler/xla/service/while_loop_constant_sinking_test.cc
+++ b/tensorflow/compiler/xla/service/while_loop_constant_sinking_test.cc
@@ -206,7 +206,8 @@ body {
p_body.0 = f32[2] get-tuple-element((f32[2],f32[2]) p_body), index=0
p_body.1 = f32[2] get-tuple-element((f32[2],f32[2]) p_body), index=1
- outfeed = token[] outfeed(p_body.0)
+ token = token[] after-all()
+ outfeed = token[] outfeed(p_body.0, token)
ROOT root = (f32[2],f32[2],f32[2]) tuple(p_body.0, p_body.1, p_body.1)
}
diff --git a/tensorflow/compiler/xla/service/while_loop_invariant_code_motion.cc b/tensorflow/compiler/xla/service/while_loop_invariant_code_motion.cc
index 09ddcffb22..cb132d4f16 100644
--- a/tensorflow/compiler/xla/service/while_loop_invariant_code_motion.cc
+++ b/tensorflow/compiler/xla/service/while_loop_invariant_code_motion.cc
@@ -14,6 +14,7 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/while_loop_invariant_code_motion.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/service/tuple_util.h"
#include "tensorflow/compiler/xla/service/while_util.h"
#include "tensorflow/compiler/xla/util.h"
@@ -65,8 +66,8 @@ static void CreateLoopInvariantCopy(
};
InlinedVector<HloInstruction*, 4> new_operands;
- c_transform(old_instruction->operands(), std::back_inserter(new_operands),
- get_new_operand);
+ absl::c_transform(old_instruction->operands(),
+ std::back_inserter(new_operands), get_new_operand);
HloInstruction* new_instruction =
parent_of_while->AddInstruction(old_instruction->CloneWithNewOperands(
@@ -197,7 +198,7 @@ WhileLoopInvariantCodeMotion::TryHoistingInvariantInstructionsFromWhileBody(
op->opcode() == HloOpcode::kConstant;
};
- if (!c_all_of(instruction->operands(), is_invariant)) {
+ if (!absl::c_all_of(instruction->operands(), is_invariant)) {
continue;
}
@@ -257,10 +258,10 @@ StatusOr<bool> WhileLoopInvariantCodeMotion::Run(HloModule* module) {
bool changed = false;
std::vector<HloInstruction*> while_instrs;
for (auto* comp : module->computations()) {
- c_copy_if(comp->instructions(), std::back_inserter(while_instrs),
- [](const HloInstruction* instr) {
- return instr->opcode() == HloOpcode::kWhile;
- });
+ absl::c_copy_if(comp->instructions(), std::back_inserter(while_instrs),
+ [](const HloInstruction* instr) {
+ return instr->opcode() == HloOpcode::kWhile;
+ });
}
for (HloInstruction* while_instr : while_instrs) {
diff --git a/tensorflow/compiler/xla/service/while_util.cc b/tensorflow/compiler/xla/service/while_util.cc
index 1ef17b9d7d..52d9c3e5ae 100644
--- a/tensorflow/compiler/xla/service/while_util.cc
+++ b/tensorflow/compiler/xla/service/while_util.cc
@@ -14,6 +14,7 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/while_util.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
@@ -206,7 +207,7 @@ static StatusOr<HloInstruction*> MakeInitTupleFromInitValues(
HloInstruction* zero = computation->AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(0)));
init_values_with_indvar.push_back(zero);
- c_copy(init_values, std::back_inserter(init_values_with_indvar));
+ absl::c_copy(init_values, std::back_inserter(init_values_with_indvar));
return computation->AddInstruction(
HloInstruction::CreateTuple(init_values_with_indvar));
}
@@ -215,8 +216,9 @@ static Shape MakeLoopStateShape(const WhileUtil::LoopStateTy& init_values) {
std::vector<Shape> loop_state_shape_components;
loop_state_shape_components.reserve(init_values.size() + 1);
loop_state_shape_components.push_back(ShapeUtil::MakeShape(S32, {}));
- c_transform(init_values, std::back_inserter(loop_state_shape_components),
- [](HloInstruction* instr) { return instr->shape(); });
+ absl::c_transform(init_values,
+ std::back_inserter(loop_state_shape_components),
+ [](HloInstruction* instr) { return instr->shape(); });
return ShapeUtil::MakeTupleShape(loop_state_shape_components);
}
diff --git a/tensorflow/compiler/xla/service/while_util_test.cc b/tensorflow/compiler/xla/service/while_util_test.cc
index 2ccb919acf..5e69419333 100644
--- a/tensorflow/compiler/xla/service/while_util_test.cc
+++ b/tensorflow/compiler/xla/service/while_util_test.cc
@@ -15,6 +15,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/service/while_util.h"
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/test.h"
@@ -206,7 +207,7 @@ ENTRY main {
auto is_while = [](const HloInstruction* instr) {
return instr->opcode() == HloOpcode::kWhile;
};
- EXPECT_EQ(c_count_if(main->instructions(), is_while), 1);
+ EXPECT_EQ(absl::c_count_if(main->instructions(), is_while), 1);
}
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/shape_util.cc b/tensorflow/compiler/xla/shape_util.cc
index 34869cc507..b69c346f1e 100644
--- a/tensorflow/compiler/xla/shape_util.cc
+++ b/tensorflow/compiler/xla/shape_util.cc
@@ -1014,12 +1014,13 @@ bool ShapeUtil::IsLeafIndex(const Shape& shape, const ShapeIndex& index) {
}
/* static */ int64 ShapeUtil::GetLeafCount(const Shape& shape) {
+ if (!IsTuple(shape)) {
+ return 1;
+ }
int64 count = 0;
- ForEachSubshape(shape, [&](const Shape&, const ShapeIndex& index) {
- if (IsLeafIndex(shape, index)) {
- ++count;
- }
- });
+ for (const Shape& subshape : shape.tuple_shapes()) {
+ count += GetLeafCount(subshape);
+ }
return count;
}
diff --git a/tensorflow/compiler/xla/tests/BUILD b/tensorflow/compiler/xla/tests/BUILD
index 42d52aee78..eac8f977fa 100644
--- a/tensorflow/compiler/xla/tests/BUILD
+++ b/tensorflow/compiler/xla/tests/BUILD
@@ -127,6 +127,7 @@ cc_library(
"//tensorflow/core:lib",
"//tensorflow/core:stream_executor_no_cuda",
"//tensorflow/core:test",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -385,6 +386,7 @@ xla_test(
"//tensorflow/core:lib",
"//tensorflow/core:regexp_internal",
"//tensorflow/core:test",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -709,6 +711,21 @@ xla_test(
],
)
+xla_test(
+ name = "scatter_test",
+ srcs = ["scatter_test.cc"],
+ deps = [
+ ":client_library_test_base",
+ ":hlo_test_base",
+ "//tensorflow/compiler/xla:execution_options_util",
+ "//tensorflow/compiler/xla:status_macros",
+ "//tensorflow/compiler/xla:test",
+ "//tensorflow/compiler/xla/client:xla_builder",
+ "//tensorflow/compiler/xla/service:hlo_parser",
+ "//tensorflow/compiler/xla/tests:xla_internal_test_main",
+ ],
+)
+
# Repeat dot_operation_runtime_test with single-threaded eigen.
xla_test(
name = "dot_operation_single_threaded_runtime_test",
@@ -798,6 +815,7 @@ CONVOLUTION_TEST_DEPS = [
"//tensorflow/compiler/xla/client:padding",
"//tensorflow/compiler/xla/client:xla_builder",
"//tensorflow/compiler/xla/tests:client_library_test_base",
+ "//tensorflow/compiler/xla/tests:hlo_test_base",
"//tensorflow/compiler/xla/tests:literal_test_util",
"//tensorflow/compiler/xla/tests:xla_internal_test_main",
"//tensorflow/core:lib",
@@ -1140,6 +1158,7 @@ xla_test(
name = "reduce_window_test",
timeout = "long",
srcs = [],
+ shard_count = 20,
tags = [
"enable_for_xla_interpreter",
"optonly",
@@ -1525,17 +1544,16 @@ xla_test(
],
deps = [
"//tensorflow/compiler/xla:shape_util",
- "//tensorflow/compiler/xla:types",
"//tensorflow/compiler/xla:xla_data_proto",
"//tensorflow/compiler/xla/client:local_client",
"//tensorflow/compiler/xla/client:xla_builder",
- "//tensorflow/compiler/xla/client:xla_computation",
"//tensorflow/compiler/xla/tests:client_library_test_base",
"//tensorflow/compiler/xla/tests:literal_test_util",
"//tensorflow/compiler/xla/tests:xla_internal_test_main",
"//tensorflow/core:lib",
"//tensorflow/core:stream_executor_no_cuda",
"//tensorflow/core:test",
+ "@com_google_absl//absl/algorithm:container",
],
)
@@ -2061,6 +2079,8 @@ tf_cc_test(
xla_test(
name = "test_utils_test",
srcs = ["test_utils_test.cc"],
+ # There is nothing backend specific in this test, so just pick an arbitrary backend.
+ backends = ["cpu"],
deps = [
":local_client_test_base",
":test_utils",
@@ -2069,6 +2089,7 @@ xla_test(
"//tensorflow/compiler/xla/client:xla_computation",
"//tensorflow/compiler/xla/service:hlo_parser",
"//tensorflow/compiler/xla/tests:xla_internal_test_main",
+ "//tensorflow/core:lib",
"//tensorflow/core:test",
],
)
diff --git a/tensorflow/compiler/xla/tests/client_library_test_base.h b/tensorflow/compiler/xla/tests/client_library_test_base.h
index 4a6e8a3124..b04a3b105c 100644
--- a/tensorflow/compiler/xla/tests/client_library_test_base.h
+++ b/tensorflow/compiler/xla/tests/client_library_test_base.h
@@ -74,8 +74,9 @@ class ClientLibraryTestBase : public ::testing::Test {
string TestName() const;
void SetFastMathDisabled(bool disabled) {
- execution_options_.mutable_debug_options()->set_xla_enable_fast_math(
- !disabled);
+ auto* opts = execution_options_.mutable_debug_options();
+ opts->set_xla_cpu_enable_fast_math(!disabled);
+ opts->set_xla_gpu_enable_fast_math(!disabled);
}
void SetSeed(uint64 seed) { execution_options_.set_seed(seed); }
diff --git a/tensorflow/compiler/xla/tests/convert_test.cc b/tensorflow/compiler/xla/tests/convert_test.cc
index 1adc68cc48..7a203d6873 100644
--- a/tensorflow/compiler/xla/tests/convert_test.cc
+++ b/tensorflow/compiler/xla/tests/convert_test.cc
@@ -19,6 +19,7 @@ limitations under the License.
#include <memory>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/shape_util.h"
@@ -447,11 +448,11 @@ std::vector<float> GetInterestingF16ConversionTestCases() {
XLA_TEST_F(ConvertTest, ConvertR1F16ToR1F32) {
std::vector<float> test_cases = GetInterestingF16ConversionTestCases();
std::vector<half> input;
- c_transform(test_cases, std::back_inserter(input),
- [](float f) { return Eigen::half(f); });
+ absl::c_transform(test_cases, std::back_inserter(input),
+ [](float f) { return Eigen::half(f); });
std::vector<float> expected_output;
- c_transform(input, std::back_inserter(expected_output),
- [](Eigen::half h) { return static_cast<float>(h); });
+ absl::c_transform(input, std::back_inserter(expected_output),
+ [](Eigen::half h) { return static_cast<float>(h); });
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<GlobalData> dot_lhs_handle,
@@ -470,8 +471,8 @@ XLA_TEST_F(ConvertTest, ConvertR1F16ToR1F32) {
XLA_TEST_F(ConvertTest, ConvertR1F32ToR1F16) {
std::vector<float> input = GetInterestingF16ConversionTestCases();
std::vector<half> expected_output;
- c_transform(input, std::back_inserter(expected_output),
- [](float f) { return Eigen::half(f); });
+ absl::c_transform(input, std::back_inserter(expected_output),
+ [](float f) { return Eigen::half(f); });
TF_ASSERT_OK_AND_ASSIGN(
std::unique_ptr<GlobalData> dot_lhs_handle,
diff --git a/tensorflow/compiler/xla/tests/convolution_test.cc b/tensorflow/compiler/xla/tests/convolution_test.cc
index 5ed8122e00..689928aee4 100644
--- a/tensorflow/compiler/xla/tests/convolution_test.cc
+++ b/tensorflow/compiler/xla/tests/convolution_test.cc
@@ -31,6 +31,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
+#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
@@ -465,7 +466,7 @@ void iota_int_init_value(std::vector<T>& values, int init_value) {
}
template <typename T>
-class Convolve2D_1x3x3x5_3x3x5x5_Valid : public ConvolutionTest {
+class Convolve2D_1x3x3x5_3x3x5x3_Valid : public ConvolutionTest {
public:
void RunTest() {
XlaBuilder builder(TestName());
@@ -520,8 +521,139 @@ class Convolve2D_1x3x3x5_3x3x5x5_Valid : public ConvolutionTest {
}
};
-TYPED_TEST_CASE(Convolve2D_1x3x3x5_3x3x5x5_Valid, TestTypes);
-TYPED_TEST(Convolve2D_1x3x3x5_3x3x5x5_Valid, Types) { this->RunTest(); }
+TYPED_TEST_CASE(Convolve2D_1x3x3x5_3x3x5x3_Valid, TestTypes);
+TYPED_TEST(Convolve2D_1x3x3x5_3x3x5x3_Valid, Types) { this->RunTest(); }
+
+template <typename T>
+class Convolve2D_1x3x3x5_3x3x1x15_Depthwise_Valid : public ConvolutionTest {
+ public:
+ void RunTest() {
+ XlaBuilder builder(TestName());
+ std::vector<int64> input_dims = {1, 3, 3, 5};
+ std::vector<int64> filter_dims = {3, 3, 1, 15};
+ Shape input_shape = ShapeUtil::MakeShapeWithType<T>(input_dims);
+ Shape filter_shape = ShapeUtil::MakeShapeWithType<T>(filter_dims);
+ {
+ auto input = Parameter(&builder, 0, input_shape, "input");
+ auto filter = Parameter(&builder, 1, filter_shape, "filter");
+
+ // Tensorflow dimension numbers for 2D convolution.
+ ConvolutionDimensionNumbers dnums;
+ dnums.set_input_batch_dimension(0);
+ dnums.set_output_batch_dimension(0);
+ dnums.add_input_spatial_dimensions(1);
+ dnums.add_output_spatial_dimensions(1);
+ dnums.add_input_spatial_dimensions(2);
+ dnums.add_output_spatial_dimensions(2);
+ dnums.set_input_feature_dimension(3);
+ dnums.set_output_feature_dimension(3);
+ dnums.add_kernel_spatial_dimensions(0);
+ dnums.add_kernel_spatial_dimensions(1);
+ dnums.set_kernel_input_feature_dimension(2);
+ dnums.set_kernel_output_feature_dimension(3);
+
+ ConvWithGeneralDimensions(input, filter, {1, 1}, Padding::kValid, dnums,
+ /*feature_group_count=*/5);
+ }
+
+ std::vector<T> input_elems(ShapeUtil::ElementsIn(input_shape));
+ iota_int_init_value(input_elems, 1);
+ auto input_r1 = LiteralUtil::CreateR1<T>(input_elems);
+ auto input_r4 = input_r1->Reshape(input_dims).ConsumeValueOrDie();
+
+ std::vector<T> filter_elems(ShapeUtil::ElementsIn(filter_shape));
+ iota_int_init_value(filter_elems, 1);
+ auto filter_r1 = LiteralUtil::CreateR1<T>(filter_elems);
+ auto filter_r4 = filter_r1->Reshape(filter_dims).ConsumeValueOrDie();
+
+ auto expected_r1 = LiteralUtil::CreateR1<T>(
+ {static_cast<T>(16029), static_cast<T>(16218), static_cast<T>(16407),
+ static_cast<T>(17172), static_cast<T>(17370), static_cast<T>(17568),
+ static_cast<T>(18369), static_cast<T>(18576), static_cast<T>(18783),
+ static_cast<T>(19620), static_cast<T>(19836), static_cast<T>(20052),
+ static_cast<T>(20925), static_cast<T>(21150), static_cast<T>(21375)});
+ auto expected_r4 = expected_r1->Reshape({1, 1, 1, 15}).ConsumeValueOrDie();
+
+ auto input_literal =
+ client_->TransferToServer(*input_r4).ConsumeValueOrDie();
+ auto filter_literal =
+ client_->TransferToServer(*filter_r4).ConsumeValueOrDie();
+
+ ComputeAndCompareLiteral(&builder, *expected_r4,
+ {input_literal.get(), filter_literal.get()},
+ error_spec_);
+ }
+};
+
+TYPED_TEST_CASE(Convolve2D_1x3x3x5_3x3x1x15_Depthwise_Valid, TestTypes);
+TYPED_TEST(Convolve2D_1x3x3x5_3x3x1x15_Depthwise_Valid, Types) {
+ this->RunTest();
+}
+
+template <typename T>
+class Convolve2D_1x2x2x6_2x2x1x12_Grouped_Valid : public ConvolutionTest {
+ public:
+ void RunTest() {
+ XlaBuilder builder(TestName());
+ std::vector<int64> input_dims = {1, 2, 2, 6};
+ std::vector<int64> filter_dims = {2, 2, 2, 12};
+ Shape input_shape = ShapeUtil::MakeShapeWithType<T>(input_dims);
+ Shape filter_shape = ShapeUtil::MakeShapeWithType<T>(filter_dims);
+ {
+ auto input = Parameter(&builder, 0, input_shape, "input");
+ auto filter = Parameter(&builder, 1, filter_shape, "filter");
+
+ // Tensorflow dimension numbers for 2D convolution.
+ ConvolutionDimensionNumbers dnums;
+ dnums.set_input_batch_dimension(0);
+ dnums.set_output_batch_dimension(0);
+ dnums.add_input_spatial_dimensions(1);
+ dnums.add_output_spatial_dimensions(1);
+ dnums.add_input_spatial_dimensions(2);
+ dnums.add_output_spatial_dimensions(2);
+ dnums.set_input_feature_dimension(3);
+ dnums.set_output_feature_dimension(3);
+ dnums.add_kernel_spatial_dimensions(0);
+ dnums.add_kernel_spatial_dimensions(1);
+ dnums.set_kernel_input_feature_dimension(2);
+ dnums.set_kernel_output_feature_dimension(3);
+
+ ConvWithGeneralDimensions(input, filter, {1, 1}, Padding::kValid, dnums,
+ /*feature_group_count=*/3);
+ }
+
+ std::vector<T> input_elems(ShapeUtil::ElementsIn(input_shape));
+ iota_int_init_value(input_elems, 1);
+ auto input_r1 = LiteralUtil::CreateR1<T>(input_elems);
+ auto input_r4 = input_r1->Reshape(input_dims).ConsumeValueOrDie();
+
+ std::vector<T> filter_elems(ShapeUtil::ElementsIn(filter_shape));
+ iota_int_init_value(filter_elems, 1);
+ auto filter_r1 = LiteralUtil::CreateR1<T>(filter_elems);
+ auto filter_r4 = filter_r1->Reshape(filter_dims).ConsumeValueOrDie();
+
+ auto expected_r1 = LiteralUtil::CreateR1<T>(
+ {static_cast<T>(5076), static_cast<T>(5160), static_cast<T>(5244),
+ static_cast<T>(5328), static_cast<T>(6164), static_cast<T>(6264),
+ static_cast<T>(6364), static_cast<T>(6464), static_cast<T>(7380),
+ static_cast<T>(7496), static_cast<T>(7612), static_cast<T>(7728)});
+ auto expected_r4 = expected_r1->Reshape({1, 1, 1, 12}).ConsumeValueOrDie();
+
+ auto input_literal =
+ client_->TransferToServer(*input_r4).ConsumeValueOrDie();
+ auto filter_literal =
+ client_->TransferToServer(*filter_r4).ConsumeValueOrDie();
+
+ ComputeAndCompareLiteral(&builder, *expected_r4,
+ {input_literal.get(), filter_literal.get()},
+ error_spec_);
+ }
+};
+
+TYPED_TEST_CASE(Convolve2D_1x2x2x6_2x2x1x12_Grouped_Valid, TestTypes);
+TYPED_TEST(Convolve2D_1x2x2x6_2x2x1x12_Grouped_Valid, Types) {
+ this->RunTest();
+}
// Test fixture to run convolution tests with and without convolution
// canonicalization enabled.
@@ -765,5 +897,44 @@ XLA_TEST_F(ConvolutionTest, NoCudnnAlgorithmPicker) {
std::move(*LiteralUtil::CreateFromArray(filter_data))});
}
+class ConvolutionHloTest : public HloTestBase {};
+
+XLA_TEST_F(ConvolutionHloTest, DISABLED_ON_CPU(ConvolveF64Forward)) {
+ constexpr char kHlo[] = R"(
+HloModule TestModule
+
+ENTRY Test {
+ %arg0 = f64[3,56,56,16] parameter(0)
+ %arg1 = f64[3,3,3,64] parameter(1)
+ ROOT %conv = f64[54,54,16,64] convolution(%arg0, %arg1), window={size=3x3}, dim_labels=f01b_i01o->01bf
+})";
+ EXPECT_TRUE(RunAndCompare(kHlo, ErrorSpec{0.001}));
+}
+
+XLA_TEST_F(ConvolutionHloTest, DISABLED_ON_CPU(ConvolveF64BackwardFilter)) {
+ constexpr char kHlo[] = R"(
+HloModule TestModule
+
+ENTRY Test {
+ %arg0 = f64[2,5,8,1] parameter(0)
+ %arg1 = f64[2,5,8,2] parameter(1)
+ ROOT %conv = f64[4,4,1,2] convolution(%arg0, %arg1), window={size=5x8 pad=1_2x1_2}, dim_labels=f01b_i01o->01bf
+})";
+ EXPECT_TRUE(RunAndCompare(kHlo, ErrorSpec{0.001}));
+}
+
+XLA_TEST_F(ConvolutionHloTest, DISABLED_ON_CPU(ConvolveF64BackwardInput)) {
+ constexpr char kHlo[] = R"(
+HloModule TestModule
+
+ENTRY Test {
+ %output = f64[4,5,16,16] parameter(0)
+ %kernel = f64[5,3,7,7] parameter(1)
+ %reverse = f64[5,3,7,7] reverse(f64[5,3,7,7] %kernel), dimensions={2,3}
+ ROOT %convolution = f64[4,3,16,16] convolution(%output, %reverse), window={size=7x7 pad=3_3x3_3}, dim_labels=bf01_io01->bf01
+})";
+ EXPECT_TRUE(RunAndCompare(kHlo, ErrorSpec{0.001}));
+}
+
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/tests/gather_operation_test.cc b/tensorflow/compiler/xla/tests/gather_operation_test.cc
index b77bece85a..f866ed6519 100644
--- a/tensorflow/compiler/xla/tests/gather_operation_test.cc
+++ b/tensorflow/compiler/xla/tests/gather_operation_test.cc
@@ -30,8 +30,8 @@ using tensorflow::gtl::nullopt;
class GatherOperationTest : public HloTestBase {
protected:
void RunTest(const string& hlo_text, Literal* operand,
- Literal* gather_indices) {
- RunTest(hlo_text, {operand, gather_indices});
+ Literal* start_indices) {
+ RunTest(hlo_text, {operand, start_indices});
}
void RunTest(const string& hlo_text,
@@ -52,18 +52,17 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[2,3] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1, 3}
+ slice_sizes={1, 3}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, TensorFlowGatherV2) {
@@ -74,18 +73,17 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[3,2] gather(operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, TensorFlowGatherMultipleBatchDims) {
@@ -96,18 +94,18 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,3,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 2}, {2, 1}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, TensorFlowGatherNdMultipleBatchDims_0) {
@@ -118,18 +116,18 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2,2] parameter(1)
ROOT gather = s32[2,2] gather(operand, indices),
- output_window_dims={},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=2,
- window_bounds={1, 1}
+ slice_sizes={1, 1}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR3<int32>({{{0, 2}, {2, 1}}, {{1, 2}, {2, 0}}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, TensorFlowGatherNdMultipleBatchDims_1) {
@@ -140,18 +138,18 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2,2] parameter(1)
ROOT gather = s32[2,1,1,2] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=2,
- window_bounds={1, 1}
+ slice_sizes={1, 1}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR3<int32>({{{0, 2}, {2, 1}}, {{1, 2}, {2, 0}}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, TensorFlowGatherNd) {
@@ -162,20 +160,20 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
{{-4, 4}, {-5, 5}, {-6, 6}}, //
{{-7, 7}, {-8, 8}, {-9, 9}}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, TensorFlowGatherNdNonDefaultIndexVectorDim) {
@@ -186,20 +184,20 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
{{-4, 4}, {-5, 5}, {-6, 6}}, //
{{-7, 7}, {-8, 8}, {-9, 9}}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, DynamicSlice) {
@@ -210,18 +208,17 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[1,1] gather(operand, indices),
- output_window_dims={0,1},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={0,1},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({1, 1});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({1, 1});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, BatchDynamicSlice) {
@@ -232,18 +229,18 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
ROOT gather = s32[2,1,1] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{2, 1}, {1, 1}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, ZeroDimBounds) {
@@ -254,17 +251,16 @@ ENTRY main {
operand = s32[3,0] parameter(0)
indices = s32[2] parameter(1)
ROOT gather = s32[2,0] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1, 0}
+ slice_sizes={1, 0}
}
)";
std::unique_ptr<Literal> operand = LiteralUtil::CreateR2<int32>({{}, {}, {}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, OutOfBoundsIndex) {
@@ -278,19 +274,19 @@ ENTRY main {
operand = s32[3,3]{1,0} parameter(0)
indices = s32[6,2]{1,0} parameter(1)
gather = s32[6,1,1]{2,1,0} gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1}
+ slice_sizes={1,1}
ROOT result = s32[6]{0} reshape(gather)
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR2<int32>(
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR2<int32>(
{{2, 7}, {2, 1}, {1, 1}, {5, 1}, {2147483647, 1}, {1, 2}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, OutOfBoundsUnsignedIndex) {
@@ -304,19 +300,19 @@ ENTRY main {
operand = s32[3,3]{1,0} parameter(0)
indices = u32[6,2]{1,0} parameter(1)
gather = s32[6,1,1]{2,1,0} gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1}
+ slice_sizes={1,1}
ROOT result = s32[6]{0} reshape(gather)
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR2<uint32>(
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR2<uint32>(
{{2, 7}, {2, 1}, {1, 1}, {5, 1}, {2147483648u, 1}, {1, 2}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, NegativeIndex) {
@@ -330,19 +326,19 @@ ENTRY main {
operand = s32[3,3]{1,0} parameter(0)
indices = s32[6,2]{1,0} parameter(1)
gather = s32[6,1,1]{2,1,0} gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1}
+ slice_sizes={1,1}
ROOT result = s32[6]{0} reshape(gather)
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR2<int32>(
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR2<int32>(
{{2, -1}, {2, 1}, {1, 1}, {-500, 1}, {-2147483648, 1}, {1, 2}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, NegativeIndexIntoUnsignedOperand) {
@@ -356,19 +352,19 @@ ENTRY main {
operand = u32[3,3]{1,0} parameter(0)
indices = s32[6,2]{1,0} parameter(1)
gather = u32[6,1,1]{2,1,0} gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1}
+ slice_sizes={1,1}
ROOT result = u32[6]{0} reshape(gather)
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<uint32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR2<int32>(
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR2<int32>(
{{2, -1}, {2, 1}, {1, 1}, {-500, 1}, {-2147483648, 1}, {1, 2}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, OneScalarIndex) {
@@ -379,17 +375,17 @@ ENTRY main {
operand = s32[2,3,2]{2,1,0} parameter(0)
index = s32[] parameter(1)
ROOT gather = s32[1,3,2]{2,1,0} gather(operand, index),
- output_window_dims={0,1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0},
+ offset_dims={0,1,2},
+ collapsed_slice_dims={},
+ start_index_map={0},
index_vector_dim=0,
- window_bounds={1,3,2}
+ slice_sizes={1,3,2}
}
)";
std::unique_ptr<Literal> operand = LiteralUtil::CreateR3<int32>(
{{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR0<int32>(1);
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR0<int32>(1);
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, ScalarResult) {
@@ -400,16 +396,16 @@ ENTRY main {
operand = s32[4]{0} parameter(0)
index = s32[] parameter(1)
ROOT gather = s32[] gather(operand, index),
- output_window_dims={},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=0,
- window_bounds={1}
+ slice_sizes={1}
}
)";
std::unique_ptr<Literal> operand = LiteralUtil::CreateR1<int32>({1, 2, 3, 4});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR0<int32>(1);
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR0<int32>(1);
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, ZeroSizedResult) {
@@ -420,17 +416,17 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[0] parameter(1)
ROOT gather = s32[0,3] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0},
- gather_dims_to_operand_dims={0},
+ offset_dims={1},
+ collapsed_slice_dims={0},
+ start_index_map={0},
index_vector_dim=1,
- window_bounds={1, 3}
+ slice_sizes={1, 3}
}
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices = LiteralUtil::CreateR1<int32>({});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, FusedTensorFlowGatherV2) {
@@ -441,11 +437,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
gather = s32[3,2] gather(operand, indices),
- output_window_dims={0},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={0},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=1,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
one = s32[] constant(1)
one_broadcasted = s32[3,2] broadcast(one), dimensions={}
ROOT result = s32[3,2]{1,0} add(gather, one_broadcasted)
@@ -453,9 +449,8 @@ ENTRY main {
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({0, 2});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({0, 2});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, FusedTensorFlowGatherMultipleBatchDims) {
@@ -466,11 +461,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,3,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={1},
- gather_dims_to_operand_dims={1},
+ offset_dims={1},
+ collapsed_slice_dims={1},
+ start_index_map={1},
index_vector_dim=2,
- window_bounds={3, 1}
+ slice_sizes={3, 1}
one = s32[] constant(1)
one_broadcasted = s32[2,3,2] broadcast(one), dimensions={}
ROOT result = s32[2,3,2]{2,1,0} add(gather, one_broadcasted)
@@ -478,9 +473,9 @@ ENTRY main {
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 2}, {2, 1}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, FusedTensorFlowGatherNdMultipleBatchDims) {
@@ -491,11 +486,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2,2] parameter(1)
gather = s32[2,2] gather(operand, indices),
- output_window_dims={},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=2,
- window_bounds={1, 1}
+ slice_sizes={1, 1}
one = s32[] constant(1)
one_broadcasted = s32[2,2] broadcast(one), dimensions={}
ROOT result = s32[2,2]{1,0} add(gather, one_broadcasted)
@@ -503,9 +498,9 @@ ENTRY main {
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR3<int32>({{{0, 2}, {2, 1}}, {{1, 2}, {2, 0}}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, FusedTensorFlowGatherNd) {
@@ -516,11 +511,11 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=1,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
one = s32[] constant(1)
one_broadcasted = s32[2,2] broadcast(one), dimensions={}
ROOT result = s32[2,2]{1,0} add(gather, one_broadcasted)
@@ -530,9 +525,9 @@ ENTRY main {
LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
{{-4, 4}, {-5, 5}, {-6, 6}}, //
{{-7, 7}, {-8, 8}, {-9, 9}}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest,
@@ -544,11 +539,11 @@ ENTRY main {
operand = s32[3,3,2] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,2] gather(operand, indices),
- output_window_dims={1},
- elided_window_dims={0,1},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1},
+ collapsed_slice_dims={0,1},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1,2}
+ slice_sizes={1,1,2}
one = s32[] constant(1)
one_broadcasted = s32[2,2] broadcast(one), dimensions={}
ROOT result = s32[2,2]{1,0} add(gather, one_broadcasted)
@@ -558,9 +553,9 @@ ENTRY main {
LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
{{-4, 4}, {-5, 5}, {-6, 6}}, //
{{-7, 7}, {-8, 8}, {-9, 9}}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, FusedDynamicSlice) {
@@ -571,11 +566,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2] parameter(1)
gather = s32[1,1] gather(operand, indices),
- output_window_dims={0,1},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={0,1},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
one = s32[] constant(1)
one_broadcasted = s32[1,1] broadcast(one), dimensions={}
ROOT result = s32[1,1]{1,0} add(gather, one_broadcasted)
@@ -583,9 +578,8 @@ ENTRY main {
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
- LiteralUtil::CreateR1<int32>({1, 1});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ std::unique_ptr<Literal> start_indices = LiteralUtil::CreateR1<int32>({1, 1});
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
XLA_TEST_F(GatherOperationTest, FusedBatchDynamicSlice) {
@@ -596,11 +590,11 @@ ENTRY main {
operand = s32[3,3] parameter(0)
indices = s32[2,2] parameter(1)
gather = s32[2,1,1] gather(operand, indices),
- output_window_dims={1,2},
- elided_window_dims={},
- gather_dims_to_operand_dims={0,1},
+ offset_dims={1,2},
+ collapsed_slice_dims={},
+ start_index_map={0,1},
index_vector_dim=0,
- window_bounds={1,1}
+ slice_sizes={1,1}
one = s32[] constant(1)
one_broadcasted = s32[2,1,1] broadcast(one), dimensions={}
ROOT result = s32[2,1,1]{2,1,0} add(gather, one_broadcasted)
@@ -608,9 +602,9 @@ ENTRY main {
)";
std::unique_ptr<Literal> operand =
LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
- std::unique_ptr<Literal> gather_indices =
+ std::unique_ptr<Literal> start_indices =
LiteralUtil::CreateR2<int32>({{2, 1}, {1, 1}});
- RunTest(hlo_text, operand.get(), gather_indices.get());
+ RunTest(hlo_text, operand.get(), start_indices.get());
}
class GatherClientLibraryTest : public ClientLibraryTestBase {};
@@ -622,11 +616,11 @@ XLA_TEST_F(GatherClientLibraryTest, DISABLED_ON_GPU(Basic)) {
// operand = s32[3,3] parameter(0)
// indices = s32[2] parameter(1)
// ROOT gather = s32[2,3] gather(operand, indices),
- // output_window_dims={1},
- // elided_window_dims={0},
- // gather_dims_to_operand_dims={0},
+ // offset_dims={1},
+ // collapsed_slice_dims={0},
+ // start_index_map={0},
// index_vector_dim=1,
- // window_bounds={1, 3}
+ // slice_sizes={1, 3}
// }
XlaBuilder builder("gather_basic");
@@ -637,9 +631,9 @@ XLA_TEST_F(GatherClientLibraryTest, DISABLED_ON_GPU(Basic)) {
auto operand = Parameter(&builder, 0, operand_shape, "operand");
auto indices = Parameter(&builder, 1, indices_shape, "indices");
GatherDimensionNumbers dim_numbers;
- dim_numbers.add_output_window_dims(1);
- dim_numbers.add_elided_window_dims(0);
- dim_numbers.add_gather_dims_to_operand_dims(0);
+ dim_numbers.add_offset_dims(1);
+ dim_numbers.add_collapsed_slice_dims(0);
+ dim_numbers.add_start_index_map(0);
dim_numbers.set_index_vector_dim(1);
Gather(operand, indices, dim_numbers, {1, 3});
diff --git a/tensorflow/compiler/xla/tests/hlo_test_base.cc b/tensorflow/compiler/xla/tests/hlo_test_base.cc
index 0dce1b22a3..b6b8c43bd9 100644
--- a/tensorflow/compiler/xla/tests/hlo_test_base.cc
+++ b/tensorflow/compiler/xla/tests/hlo_test_base.cc
@@ -20,12 +20,15 @@ limitations under the License.
#include <string>
#include <utility>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/ptr_util.h"
+#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/service/platform_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
+#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/types.h"
@@ -83,21 +86,38 @@ ProgramShape GetProgramShapeWithLayout(const HloModule& module) {
} // namespace
-HloTestBase::HloTestBase()
- : HloTestBase(GetTestPlatform(), GetReferencePlatform()) {}
+HloTestBase::HloTestBase(bool allow_mixed_precision_in_hlo_verifier)
+ : HloTestBase(GetTestPlatform(), GetReferencePlatform(),
+ allow_mixed_precision_in_hlo_verifier) {}
HloTestBase::HloTestBase(se::Platform* test_platform,
- se::Platform* reference_platform)
+ se::Platform* reference_platform,
+ bool allow_mixed_precision_in_hlo_verifier)
: test_runner_(test_platform), reference_runner_(reference_platform) {
- hlo_verifier_ = MakeUnique<HloVerifier>(/*allow_mixed_precision=*/true);
+ hlo_verifier_ =
+ MakeUnique<HloVerifier>(allow_mixed_precision_in_hlo_verifier);
}
-/* static */
std::unique_ptr<HloModule> HloTestBase::CreateNewModule(const string& name) {
return MakeUnique<HloModule>(name, GetModuleConfigForTest());
}
-/*static*/ DebugOptions HloTestBase::GetDebugOptionsForTest() {
+/* static */
+StatusOr<bool> HloTestBase::RunHloPass(HloPassInterface* hlo_pass,
+ HloModule* module) {
+ const string module_str_before_run = module->ToProto().ShortDebugString();
+ const auto status_or = hlo_pass->Run(module);
+ if (status_or.status().ok()) {
+ const string module_str_after_run = module->ToProto().ShortDebugString();
+ if (!status_or.ValueOrDie()) {
+ // Check that the proto remains same.
+ EXPECT_EQ(module_str_after_run, module_str_before_run);
+ }
+ }
+ return status_or;
+}
+
+DebugOptions HloTestBase::GetDebugOptionsForTest() {
auto debug_options = legacy_flags::GetDebugOptionsFromFlags();
// TODO(b/38354253): Change tests to use Parameters instead of Constants.
debug_options.add_xla_disable_hlo_passes("constant_folding");
@@ -196,7 +216,7 @@ StatusOr<::testing::AssertionResult> HloTestBase::RunAndCompareInternal(
MakeFakeArguments(module.get()).ConsumeValueOrDie();
std::vector<Literal*> fake_argument_ptrs;
- c_transform(
+ absl::c_transform(
fake_arguments, std::back_inserter(fake_argument_ptrs),
[](const std::unique_ptr<Literal>& literal) { return literal.get(); });
@@ -210,7 +230,7 @@ StatusOr<::testing::AssertionResult> HloTestBase::RunAndCompareInternal(
const auto& fake_arguments =
MakeFakeArguments(module.get()).ConsumeValueOrDie();
std::vector<Literal*> fake_argument_ptrs;
- c_transform(
+ absl::c_transform(
fake_arguments, std::back_inserter(fake_argument_ptrs),
[](const std::unique_ptr<Literal>& literal) { return literal.get(); });
@@ -245,7 +265,7 @@ StatusOr<::testing::AssertionResult> HloTestBase::RunAndCompareInternal(
MakeFakeArguments(module_or_status.ValueOrDie().get())
.ConsumeValueOrDie();
std::vector<Literal*> fake_argument_ptrs;
- c_transform(
+ absl::c_transform(
fake_arguments, std::back_inserter(fake_argument_ptrs),
[](const std::unique_ptr<Literal>& literal) { return literal.get(); });
return test_runner_
@@ -300,8 +320,8 @@ StatusOr<::testing::AssertionResult> HloTestBase::RunAndCompareInternal(
HloComputation* HloTestBase::FindComputation(HloModule* module,
tensorflow::StringPiece name) {
auto computations = module->computations();
- auto it = c_find_if(computations,
- [&](HloComputation* c) { return c->name() == name; });
+ auto it = absl::c_find_if(
+ computations, [&](HloComputation* c) { return c->name() == name; });
if (it == computations.end()) {
return nullptr;
}
@@ -312,8 +332,8 @@ HloInstruction* HloTestBase::FindInstruction(HloModule* module,
tensorflow::StringPiece name) {
for (const HloComputation* c : module->computations()) {
auto instructions = c->instructions();
- auto it = c_find_if(instructions,
- [&](HloInstruction* i) { return i->name() == name; });
+ auto it = absl::c_find_if(
+ instructions, [&](HloInstruction* i) { return i->name() == name; });
if (it != instructions.end()) {
return *it;
}
diff --git a/tensorflow/compiler/xla/tests/hlo_test_base.h b/tensorflow/compiler/xla/tests/hlo_test_base.h
index bb55e562ad..5c7304b4de 100644
--- a/tensorflow/compiler/xla/tests/hlo_test_base.h
+++ b/tensorflow/compiler/xla/tests/hlo_test_base.h
@@ -72,30 +72,39 @@ class HloTestBase : public ::testing::Test {
// options from command-line flags. If you want a fresh HloModule object and
// then add HloComputations to it, it's recommended to use this method in your
// tests.
- static std::unique_ptr<HloModule> CreateNewModule(
- const string& name = TestName());
+ std::unique_ptr<HloModule> CreateNewModule(const string& name = TestName());
+
+ // Runs the hlo_pass with the provided module and returns the result. This
+ // function also verifies that the module remains unchanged when hlo_pass
+ // returns false as the StatusOr value.
+ static StatusOr<bool> RunHloPass(HloPassInterface* hlo_pass,
+ HloModule* module);
protected:
// This uses the interpreter backend as the reference backend and
// automatically finds another supported backend as the test backend. If the
// interpreter is the only supported backend, it will be both the test backend
// and the reference backend.
- HloTestBase();
+ HloTestBase(bool allow_mixed_precision_in_hlo_verifier = true);
// If your test doesn't use interpreter as the reference backend, you can use
// this constructor. Note that your test target is responsible for linking in
// both needed backends.
- HloTestBase(se::Platform* test_platform, se::Platform* reference_platform);
+ HloTestBase(se::Platform* test_platform, se::Platform* reference_platform,
+ bool allow_mixed_precision_in_hlo_verifier = true);
~HloTestBase() override {}
// Populates debug options from command-line flags and adjusts the options for
// testing. It is recommended to use this when you need to pass in
// DebugOptions, e.g. when creating a module from a string or a file.
- static DebugOptions GetDebugOptionsForTest();
+ //
+ // This function is virtual so tests can specify an alternative set of debug
+ // options (e.g. disabling additional passes).
+ virtual DebugOptions GetDebugOptionsForTest();
// Gets an HloModuleConfig with options appropriate for tests.
- static HloModuleConfig GetModuleConfigForTest() {
+ HloModuleConfig GetModuleConfigForTest() {
HloModuleConfig config;
config.set_debug_options(GetDebugOptionsForTest());
return config;
diff --git a/tensorflow/compiler/xla/tests/llvm_irgen_test_base.cc b/tensorflow/compiler/xla/tests/llvm_irgen_test_base.cc
index 6fc1115097..0487d31409 100644
--- a/tensorflow/compiler/xla/tests/llvm_irgen_test_base.cc
+++ b/tensorflow/compiler/xla/tests/llvm_irgen_test_base.cc
@@ -51,8 +51,9 @@ void LlvmIrGenTestBase::CompileAndVerifyIr(
std::unique_ptr<HloModule> hlo_module, const string& pattern,
bool match_optimized_ir) {
SetIrHook(match_optimized_ir);
- TF_ASSERT_OK(CompileToExecutable(std::move(hlo_module)).status());
+ Status status = CompileToExecutable(std::move(hlo_module)).status();
ResetIrHook();
+ TF_ASSERT_OK(status);
StatusOr<bool> filecheck_result = RunFileCheck(ir_, pattern);
TF_ASSERT_OK(filecheck_result.status());
@@ -73,9 +74,10 @@ void LlvmIrGenTestBase::CompileAheadOfTimeAndVerifyIr(
std::unique_ptr<HloModule> hlo_module, const AotCompilationOptions& options,
const string& pattern, bool match_optimized_ir) {
SetIrHook(match_optimized_ir);
- TF_ASSERT_OK(
- CompileToAotCompilationResult(std::move(hlo_module), options).status());
+ Status status =
+ CompileToAotCompilationResult(std::move(hlo_module), options).status();
ResetIrHook();
+ TF_ASSERT_OK(status);
StatusOr<bool> filecheck_result = RunFileCheck(ir_, pattern);
ASSERT_TRUE(filecheck_result.ok());
diff --git a/tensorflow/compiler/xla/tests/local_client_aot_test_helper.cc b/tensorflow/compiler/xla/tests/local_client_aot_test_helper.cc
index e310966d8b..60eb21aafd 100644
--- a/tensorflow/compiler/xla/tests/local_client_aot_test_helper.cc
+++ b/tensorflow/compiler/xla/tests/local_client_aot_test_helper.cc
@@ -92,10 +92,10 @@ int main(int argc, char** argv) {
// It's lame to hard-code the buffer assignments, but we need
// local_client_aot_test.cc to be able to easily invoke the function.
CHECK_EQ(result->result_buffer_index(), 1);
- CHECK_EQ(result->buffer_sizes().size(), 3);
- CHECK_EQ(result->buffer_sizes()[0], -2); // param buffer
- CHECK_EQ(result->buffer_sizes()[1], sizeof(float)); // result buffer
- CHECK_EQ(result->buffer_sizes()[2], -1); // const buffer
+ CHECK_EQ(result->buffer_infos().size(), 3);
+ CHECK(result->buffer_infos()[0].is_entry_parameter()); // param buffer
+ CHECK_EQ(result->buffer_infos()[1].size(), sizeof(float)); // result buffer
+ CHECK(result->buffer_infos()[2].is_constant()); // const buffer
if (triple.isOSBinFormatELF()) {
// Check the ELF magic.
CHECK_EQ(result->object_file_data()[0], 0x7F);
diff --git a/tensorflow/compiler/xla/tests/reduce_window_test.cc b/tensorflow/compiler/xla/tests/reduce_window_test.cc
index 1bd6fdab31..cae029fd70 100644
--- a/tensorflow/compiler/xla/tests/reduce_window_test.cc
+++ b/tensorflow/compiler/xla/tests/reduce_window_test.cc
@@ -1261,6 +1261,12 @@ struct R1ReduceWindowTestData {
/*pad_low=*/{5},
/*pad_high=*/{0},
/*reducer=*/Reducer::kAdd},
+
+ {/*base_bounds=*/{4096}, /*window_bounds=*/{4096},
+ /*strides=*/{1},
+ /*pad_low=*/{4095},
+ /*pad_high=*/{0},
+ /*reducer=*/Reducer::kMax},
};
string R1ReduceWindowTestDataToString(
@@ -1341,7 +1347,7 @@ INSTANTIATE_TEST_CASE_P(
// results on the interpreter backend.
class ReduceWindowTextTest : public HloTestBase {};
-TEST_F(ReduceWindowTextTest, R2General256x384) {
+XLA_TEST_F(ReduceWindowTextTest, R2General256x384) {
const string hlo_string = R"(
HloModule R2Window
mul {
@@ -1358,7 +1364,7 @@ ENTRY R2Window {
EXPECT_TRUE(RunAndCompare(hlo_string, ErrorSpec{0.001}));
}
-TEST_F(ReduceWindowTextTest, R2General256x384Layout01) {
+XLA_TEST_F(ReduceWindowTextTest, R2General256x384Layout01) {
const string hlo_string = R"(
HloModule R2Window
mul {
@@ -1375,7 +1381,7 @@ ROOT reduce-window = f32[256,384]{0,1} reduce-window(operand, constant), window=
EXPECT_TRUE(RunAndCompare(hlo_string, ErrorSpec{0.001}));
}
-TEST_F(ReduceWindowTextTest, R2General2x5) {
+XLA_TEST_F(ReduceWindowTextTest, R2General2x5) {
const string hlo_string = R"(
HloModule R2Window
mul {
@@ -1392,7 +1398,7 @@ ENTRY R2Window {
EXPECT_TRUE(RunAndCompare(hlo_string, ErrorSpec{0.001}));
}
-TEST_F(ReduceWindowTextTest, R2EffectiveScalar) {
+XLA_TEST_F(ReduceWindowTextTest, R2EffectiveScalar) {
const string hlo_string = R"(
HloModule R2Window
mul {
@@ -1410,7 +1416,7 @@ ENTRY R2Window {
EXPECT_TRUE(RunAndCompare(hlo_string, ErrorSpec{0.001}));
}
-TEST_F(ReduceWindowTextTest, R3EffectiveScalar) {
+XLA_TEST_F(ReduceWindowTextTest, R3EffectiveScalar) {
const string hlo_string = R"(
HloModule R3Window
mul {
@@ -1428,7 +1434,7 @@ ENTRY R3Window {
EXPECT_TRUE(RunAndCompare(hlo_string, ErrorSpec{0.001}));
}
-TEST_F(HloTestBase, ReduceWindowIdentity) {
+XLA_TEST_F(HloTestBase, ReduceWindowIdentity) {
const string hlo_string = R"(
HloModule ReduceWindowIdentity
identity.pad_to_reduce_window {
@@ -1445,7 +1451,7 @@ ENTRY reduce-window-identity {
EXPECT_TRUE(RunAndCompare(hlo_string, tensorflow::gtl::nullopt));
}
-TEST_F(HloTestBase, ReduceWindowS32) {
+XLA_TEST_F(HloTestBase, ReduceWindowS32) {
const string hlo_string = R"(
HloModule reduce-window
@@ -1464,5 +1470,24 @@ ENTRY %reduce-window (parameter.0: s32[81,8], parameter.1: s32[]) -> s32[82,8] {
EXPECT_TRUE(RunAndCompare(hlo_string, tensorflow::gtl::nullopt));
}
+XLA_TEST_F(HloTestBase, ReduceWindowF16) {
+ const string hlo_string = R"(
+HloModule reduce-window
+
+%identity.pad_to_reduce_window (param0: f16[], param1: f16[]) -> f16[] {
+ %param0 = f16[] parameter(0)
+ ROOT %param1 = f16[] parameter(1)
+}
+
+ENTRY %reduce-window (parameter.0: f16[81,8], parameter.1: f16[]) -> f16[82,8] {
+ %parameter.0 = f16[81,8]{1,0} parameter(0)
+ %parameter.1 = f16[] parameter(1)
+ ROOT %reduce-window = f16[82,8]{1,0} reduce-window(f16[81,8]{1,0} %parameter.0, f16[] %parameter.1), window={size=1x1 pad=0_1x0_0}, to_apply=%identity.pad_to_reduce_window
+}
+
+)";
+ EXPECT_TRUE(RunAndCompare(hlo_string, tensorflow::gtl::nullopt));
+}
+
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/tests/scatter_test.cc b/tensorflow/compiler/xla/tests/scatter_test.cc
new file mode 100644
index 0000000000..922d70b752
--- /dev/null
+++ b/tensorflow/compiler/xla/tests/scatter_test.cc
@@ -0,0 +1,615 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/compiler/xla/service/hlo_parser.h"
+#include "tensorflow/compiler/xla/status_macros.h"
+#include "tensorflow/compiler/xla/test.h"
+#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
+#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
+#include "tensorflow/compiler/xla/tests/test_macros.h"
+
+namespace xla {
+namespace {
+
+using tensorflow::gtl::nullopt;
+
+class ScatterTest : public HloTestBase {
+ protected:
+ void RunTest(const string& hlo_text, Literal* operand,
+ Literal* scatter_indices, Literal* updates) {
+ RunTest(hlo_text, {operand, scatter_indices, updates});
+ }
+
+ void RunTest(const string& hlo_text,
+ tensorflow::gtl::ArraySlice<Literal*> args) {
+ HloModuleConfig config;
+ config.set_debug_options(GetDebugOptionsForTest());
+ TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,
+ ParseHloString(hlo_text, config));
+ EXPECT_TRUE(RunAndCompare(std::move(module), args, nullopt));
+ }
+};
+
+XLA_TEST_F(ScatterTest, TensorFlowScatterV1_Update) {
+ const string hlo_text = R"(
+HloModule TensorFlowScatterV1
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatterV2_Update) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterV2
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[3,2] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={0},
+ inserted_window_dims={1},
+ scatter_dims_to_operand_dims={1},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 30}, {40, 60}, {70, 90}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatter_Add) {
+ const string hlo_text = R"(
+HloModule TensorFlowScatter_Add
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatter_Mul) {
+ const string hlo_text = R"(
+HloModule TensorFlowScatter_Mul
+
+mul_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT mul = s32[] multiply(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=mul_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatter_F32) {
+ const string hlo_text = R"(
+HloModule TensorFlowScatter_F32
+
+add_f32 (lhs: f32[], rhs: f32[]) -> f32[] {
+ lhs = f32[] parameter(0)
+ rhs = f32[] parameter(1)
+ ROOT add = f32[] add(f32[] lhs, f32[] rhs)
+}
+
+ENTRY main {
+ operand = f32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = f32[2,3] parameter(2)
+ ROOT scatter = f32[3,3] scatter(operand, indices, updates),
+ to_apply=add_f32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR2<float>(
+ {{1.1, 2.2, 3.3}, {4.4, 5.5, 6.6}, {7.7, 8.8, 9.9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({2, 1});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<float>({{0.4, 1.1, 0.7}, {2.3, 3.1, 1.6}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatter_RepeatedIndices) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,3] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({1, 1});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20, 30}, {70, 80, 90}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatter_MultipleBatchDims) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterMultipleBatchDims
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,3,2] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={1},
+ inserted_window_dims={1},
+ scatter_dims_to_operand_dims={1},
+ index_vector_dim=2
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{0, 2}, {2, 1}});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR3<int32>(
+ {{{10, 30}, {40, 60}, {70, 90}}, {{5, 5}, {5, 5}, {5, 5}}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatterNd) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterNd
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3,2] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,2] parameter(2)
+ ROOT scatter = s32[3,3,2] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0,1},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
+ {{-4, 4}, {-5, 5}, {-6, 6}}, //
+ {{-7, 7}, {-8, 8}, {-9, 9}}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{-10, 10}, {-40, 40}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, TensorFlowScatterNd_NonDefaultIndexVectorDim) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatterNdNonDefaultIndexVectorDim
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3,2] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,2] parameter(2)
+ ROOT scatter = s32[3,3,2] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0,1},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=0
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR3<int32>({{{-1, 1}, {-2, 2}, {-3, 3}}, //
+ {{-4, 4}, {-5, 5}, {-6, 6}}, //
+ {{-7, 7}, {-8, 8}, {-9, 9}}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{0, 0}, {1, 0}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{-10, 10}, {-20, 20}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, DynamicUpdateSlice) {
+ const char* hlo_text = R"(
+HloModule DynamicUpdateSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[1,1] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={0,1},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=0
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({1, 1});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR2<int32>({{10}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, BatchDynamicUpdateSlice) {
+ const char* hlo_text = R"(
+HloModule BatchDynamicUpdateSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3] parameter(0)
+ indices = s32[2,2] parameter(1)
+ updates = s32[2,1,1] parameter(2)
+ ROOT scatter = s32[3,3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1,2},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=0
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR2<int32>({{2, 1}, {1, 1}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR3<int32>({{{10}}, {{20}}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, ZeroDimBounds) {
+ const char* hlo_text = R"(
+HloModule TensorFlowScatter_ZeroDimBounds
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,0] parameter(0)
+ indices = s32[2] parameter(1)
+ updates = s32[2,0] parameter(2)
+ ROOT scatter = s32[3,0] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR2<int32>({{}, {}, {}});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR1<int32>({0, 2});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR2<int32>({{}, {}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, NoUpdateWindowDims) {
+ const string hlo_text = R"(
+HloModule Scatter_NoUpdateWindowDims
+
+add_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ rhs = s32[] parameter(1)
+ ROOT add = s32[] add(s32[] lhs, s32[] rhs)
+}
+
+ENTRY main {
+ operand = s32[3] parameter(0)
+ indices = s32[2,2,1] parameter(1)
+ updates = s32[2,2] parameter(2)
+ ROOT scatter = s32[3] scatter(operand, indices, updates),
+ to_apply=add_s32,
+ update_window_dims={},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=2
+}
+)";
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR1<int32>({0, 1, 2});
+ std::unique_ptr<Literal> scatter_indices =
+ LiteralUtil::CreateR3<int32>({{{0}, {1}}, {{2}, {1}}});
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR2<int32>({{10, 20}, {30, 40}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, OutOfBoundsIndex) {
+ const string hlo_text = R"(
+HloModule BatchDynamicSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3]{1,0} parameter(0)
+ indices = s32[6,2]{1,0} parameter(1)
+ updates = s32[6,1,1]{2,1,0} parameter(2)
+ ROOT scatter = s32[3,3]{1,0} scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1,2},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices = LiteralUtil::CreateR2<int32>(
+ {{2, 7}, {2, 1}, {1, 1}, {5, 1}, {2147483647, 1}, {1, 2}});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR3<int32>(
+ {{{10}}, {{20}}, {{30}}, {{40}}, {{50}}, {{60}}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, OutOfBoundsUnsignedIndex) {
+ const string hlo_text = R"(
+HloModule BatchDynamicSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3]{1,0} parameter(0)
+ indices = u32[6,2]{1,0} parameter(1)
+ updates = s32[6,1,1]{2,1,0} parameter(2)
+ ROOT scatter = s32[3,3]{1,0} scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1,2},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices = LiteralUtil::CreateR2<uint32>(
+ {{2, 7}, {2, 1}, {1, 1}, {5, 1}, {2147483648u, 1}, {1, 2}});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR3<int32>(
+ {{{10}}, {{20}}, {{30}}, {{40}}, {{50}}, {{60}}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, NegativeIndex) {
+ const string hlo_text = R"(
+HloModule BatchDynamicSlice
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3,3]{1,0} parameter(0)
+ indices = s32[6,2]{1,0} parameter(1)
+ updates = s32[6,1,1]{2,1,0} parameter(2)
+ ROOT scatter = s32[3,3]{1,0} scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={1,2},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0,1},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand =
+ LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
+ std::unique_ptr<Literal> scatter_indices = LiteralUtil::CreateR2<int32>(
+ {{2, 7}, {2, 1}, {1, 1}, {-500, 1}, {-2147483648, 1}, {1, 2}});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR3<int32>(
+ {{{10}}, {{20}}, {{30}}, {{40}}, {{50}}, {{60}}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, OneScalarIndex) {
+ const char* hlo_text = R"(
+HloModule OneScalarIndex
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[2,3,2]{2,1,0} parameter(0)
+ index = s32[] parameter(1)
+ updates = s32[1,3,2]{2,1,0} parameter(2)
+ ROOT scatter = s32[2,3,2]{2,1,0} scatter(operand, index, updates),
+ to_apply=update_s32,
+ update_window_dims={0,1,2},
+ inserted_window_dims={},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=0
+}
+)";
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR3<int32>(
+ {{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}});
+ std::unique_ptr<Literal> scatter_indices = LiteralUtil::CreateR0<int32>(1);
+ std::unique_ptr<Literal> updates =
+ LiteralUtil::CreateR3<int32>({{{10, 20}, {30, 40}, {50, 60}}});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, ScalarUpdate) {
+ const char* hlo_text = R"(
+HloModule ScalarUpdate
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[4]{0} parameter(0)
+ index = s32[] parameter(1)
+ updates = s32[] parameter(2)
+ ROOT scatter = s32[4]{0} scatter(operand, index, updates),
+ to_apply=update_s32,
+ update_window_dims={},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=0
+}
+)";
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR1<int32>({1, 2, 3, 4});
+ std::unique_ptr<Literal> scatter_indices = LiteralUtil::CreateR0<int32>(1);
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR0<int32>(25);
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+XLA_TEST_F(ScatterTest, EmptyIndices) {
+ const string hlo_text = R"(
+HloModule EmptyIndices
+
+update_s32 (lhs: s32[], rhs: s32[]) -> s32[] {
+ lhs = s32[] parameter(0)
+ ROOT rhs = s32[] parameter(1)
+}
+
+ENTRY main {
+ operand = s32[3] parameter(0)
+ indices = s32[0] parameter(1)
+ updates = s32[0] parameter(2)
+ ROOT scatter = s32[3] scatter(operand, indices, updates),
+ to_apply=update_s32,
+ update_window_dims={},
+ inserted_window_dims={0},
+ scatter_dims_to_operand_dims={0},
+ index_vector_dim=1
+}
+)";
+ std::unique_ptr<Literal> operand = LiteralUtil::CreateR1<int32>({1, 2, 3});
+ std::unique_ptr<Literal> scatter_indices = LiteralUtil::CreateR1<int32>({});
+ std::unique_ptr<Literal> updates = LiteralUtil::CreateR1<int32>({});
+ RunTest(hlo_text, operand.get(), scatter_indices.get(), updates.get());
+}
+
+} // namespace
+} // namespace xla
diff --git a/tensorflow/compiler/xla/tests/test_utils.cc b/tensorflow/compiler/xla/tests/test_utils.cc
index 2647937013..f05421f8e1 100644
--- a/tensorflow/compiler/xla/tests/test_utils.cc
+++ b/tensorflow/compiler/xla/tests/test_utils.cc
@@ -13,6 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#include <cmath>
+
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/primitive_util.h"
@@ -26,89 +28,101 @@ namespace {
template <typename FloatT, typename GeneratorT>
void PopulateWithRandomFloatingPointDataImpl(Literal* literal,
- std::minstd_rand0* engine) {
+ std::minstd_rand0* engine,
+ bool no_duplicates) {
CHECK(engine != nullptr);
CHECK_EQ(literal->shape().element_type(),
primitive_util::NativeToPrimitiveType<FloatT>());
- // Create uniform numbers between 1 and 1.125 to avoid creating denormal
- // numbers.
- std::uniform_real_distribution<GeneratorT> generator(1.0f, 1.125f);
- const bool should_index_bias = ShapeUtil::ElementsIn(literal->shape()) > 1000;
- TF_CHECK_OK(literal->Populate<FloatT>(
- [&](tensorflow::gtl::ArraySlice<int64> indices) {
- // Generate a random uniform number from -0.0625 and 0.0625 and bias it
- // with a position dependent number with mean 0.037109375. These number
- // should allow for long chains of accumulation without being too close
- // to zero or too large to accumulate all numbers accurately. Only do
- // this for large literals where the number of elements is much greater
- // than 47 otherwise only negative values are produced.
- //
- // The value is positionally biased using a product of the indices. Add
- // one to each index value to avoid collapsing to zero if any of the
- // indices are zero.
- int64 index_product = 1;
- for (int64 i : indices) {
- index_product *= (1 + i);
- }
- const int64 negative_bias = should_index_bias ? 47 : 0;
- FloatT index_bias =
- static_cast<FloatT>(index_product % 113 - negative_bias) /
- static_cast<FloatT>(256.0f);
- return static_cast<FloatT>(generator(*engine) - 1.0625f) + index_bias;
- }));
+ if (no_duplicates) {
+ // Duplicates may be generated if the number of elements in the literal
+ // exceeds the number of positive values supported by the type.
+ FloatT next_value = std::numeric_limits<FloatT>::min();
+ for (FloatT& value : literal->data<FloatT>()) {
+ value = next_value;
+ next_value =
+ std::nextafter(next_value, std::numeric_limits<FloatT>::max());
+ }
+ std::shuffle(literal->data<FloatT>().begin(), literal->data<FloatT>().end(),
+ *engine);
+ } else {
+ std::uniform_real_distribution<GeneratorT> generator(-0.1f, 0.2f);
+ for (FloatT& value : literal->data<FloatT>()) {
+ value = static_cast<FloatT>(generator(*engine));
+ }
+ }
}
template <typename FloatT>
void PopulateWithRandomFloatingPointData(Literal* literal,
- std::minstd_rand0* engine) {
+ std::minstd_rand0* engine,
+ bool no_duplicates) {
CHECK(engine != nullptr);
- PopulateWithRandomFloatingPointDataImpl<FloatT, FloatT>(literal, engine);
+ PopulateWithRandomFloatingPointDataImpl<FloatT, FloatT>(literal, engine,
+ no_duplicates);
}
template <>
void PopulateWithRandomFloatingPointData<half>(Literal* literal,
- std::minstd_rand0* engine) {
+ std::minstd_rand0* engine,
+ bool no_duplicates) {
+ // no_duplicates is ignored for half types. Unique values can only be
+ // generated for arrays with fewer than ~2**16 elements and no_duplicates is
+ // best-effort anyway.
CHECK(engine != nullptr);
- PopulateWithRandomFloatingPointDataImpl<half, float>(literal, engine);
+ std::uniform_real_distribution<float> generator(-0.1f, 0.2f);
+ for (half& value : literal->data<half>()) {
+ value = static_cast<half>(generator(*engine));
+ }
}
-// The standard library does not have a case for bfloat16, unsurprisingly, so we
-// handle that one specially.
template <>
void PopulateWithRandomFloatingPointData<bfloat16>(Literal* literal,
- std::minstd_rand0* engine) {
+ std::minstd_rand0* engine,
+ bool no_duplicates) {
+ // no_duplicates is ignored for bfloat types. Unique values can only be
+ // generated for arrays with fewer than ~2**16 elements and no_duplicates is
+ // best-effort anyway.
CHECK(engine != nullptr);
- CHECK_EQ(literal->shape().element_type(), BF16);
- std::uniform_real_distribution<float> generator(-0.9f, 1.0f);
- TF_CHECK_OK(literal->Populate<bfloat16>(
- [&](tensorflow::gtl::ArraySlice<int64> /*indices*/) {
- return static_cast<bfloat16>(generator(*engine));
- }));
+ std::uniform_real_distribution<float> generator(-0.1f, 0.2f);
+ for (bfloat16& value : literal->data<bfloat16>()) {
+ value = static_cast<bfloat16>(generator(*engine));
+ }
}
template <typename IntT>
-void PopulateWithRandomIntegralData(Literal* literal,
- std::minstd_rand0* engine) {
+void PopulateWithRandomIntegralData(Literal* literal, std::minstd_rand0* engine,
+ bool no_duplicates) {
CHECK(engine != nullptr);
CHECK_EQ(literal->shape().element_type(),
primitive_util::NativeToPrimitiveType<IntT>());
- std::uniform_int_distribution<IntT> generator(
- std::numeric_limits<IntT>::lowest(), std::numeric_limits<IntT>::max());
- TF_CHECK_OK(literal->Populate<IntT>(
- [&](tensorflow::gtl::ArraySlice<int64> /*indices*/) {
- return generator(*engine);
- }));
+ if (no_duplicates && ShapeUtil::ElementsIn(literal->shape()) <
+ std::numeric_limits<IntT>::max()) {
+ std::iota(literal->data<IntT>().begin(), literal->data<IntT>().end(), 0);
+ std::shuffle(literal->data<IntT>().begin(), literal->data<IntT>().end(),
+ *engine);
+ } else {
+ std::uniform_int_distribution<IntT> generator(
+ std::numeric_limits<IntT>::lowest(), std::numeric_limits<IntT>::max());
+ for (IntT& value : literal->data<IntT>()) {
+ value = generator(*engine);
+ }
+ }
}
// Similar to MakeFakeLiteral but takes a random number generator engine to
-// enable reusing the engine across randomly generated literals.
+// enable reusing the engine across randomly generated literals. 'no_duplicates'
+// indicates that there should be no duplicate values in each generated
+// array. This is uniqueness is best-effort only. Some types (half and bfloat16)
+// are not supported and uniqueness cannot be guaranteed if the number of
+// elements exceeds the number of different values supported by the type.
StatusOr<std::unique_ptr<Literal>> MakeFakeLiteralInternal(
- const Shape& shape, std::minstd_rand0* engine) {
+ const Shape& shape, std::minstd_rand0* engine, bool no_duplicates) {
if (ShapeUtil::IsTuple(shape)) {
std::vector<std::unique_ptr<Literal>> elements;
for (const Shape& element_shape : shape.tuple_shapes()) {
- TF_ASSIGN_OR_RETURN(std::unique_ptr<Literal> element,
- MakeFakeLiteralInternal(element_shape, engine));
+ TF_ASSIGN_OR_RETURN(
+ std::unique_ptr<Literal> element,
+ MakeFakeLiteralInternal(element_shape, engine, no_duplicates));
elements.push_back(std::move(element));
}
return LiteralUtil::MakeTupleOwned(std::move(elements));
@@ -119,40 +133,52 @@ StatusOr<std::unique_ptr<Literal>> MakeFakeLiteralInternal(
auto literal = MakeUnique<Literal>(shape);
switch (shape.element_type()) {
case BF16:
- PopulateWithRandomFloatingPointData<bfloat16>(literal.get(), engine);
+ PopulateWithRandomFloatingPointData<bfloat16>(literal.get(), engine,
+ no_duplicates);
break;
case F16:
- PopulateWithRandomFloatingPointData<half>(literal.get(), engine);
+ PopulateWithRandomFloatingPointData<half>(literal.get(), engine,
+ no_duplicates);
break;
case F32:
- PopulateWithRandomFloatingPointData<float>(literal.get(), engine);
+ PopulateWithRandomFloatingPointData<float>(literal.get(), engine,
+ no_duplicates);
break;
case F64:
- PopulateWithRandomFloatingPointData<double>(literal.get(), engine);
+ PopulateWithRandomFloatingPointData<double>(literal.get(), engine,
+ no_duplicates);
break;
case S8:
- PopulateWithRandomIntegralData<int8>(literal.get(), engine);
+ PopulateWithRandomIntegralData<int8>(literal.get(), engine,
+ no_duplicates);
break;
case U8:
- PopulateWithRandomIntegralData<uint8>(literal.get(), engine);
+ PopulateWithRandomIntegralData<uint8>(literal.get(), engine,
+ no_duplicates);
break;
case S16:
- PopulateWithRandomIntegralData<int16>(literal.get(), engine);
+ PopulateWithRandomIntegralData<int16>(literal.get(), engine,
+ no_duplicates);
break;
case U16:
- PopulateWithRandomIntegralData<uint16>(literal.get(), engine);
+ PopulateWithRandomIntegralData<uint16>(literal.get(), engine,
+ no_duplicates);
break;
case S32:
- PopulateWithRandomIntegralData<int32>(literal.get(), engine);
+ PopulateWithRandomIntegralData<int32>(literal.get(), engine,
+ no_duplicates);
break;
case U32:
- PopulateWithRandomIntegralData<uint32>(literal.get(), engine);
+ PopulateWithRandomIntegralData<uint32>(literal.get(), engine,
+ no_duplicates);
break;
case S64:
- PopulateWithRandomIntegralData<int64>(literal.get(), engine);
+ PopulateWithRandomIntegralData<int64>(literal.get(), engine,
+ no_duplicates);
break;
case U64:
- PopulateWithRandomIntegralData<uint64>(literal.get(), engine);
+ PopulateWithRandomIntegralData<uint64>(literal.get(), engine,
+ no_duplicates);
break;
case PRED: {
std::uniform_int_distribution<int> generator(0, 1);
@@ -208,16 +234,12 @@ bool NeedsInitValue(const HloUse& use) {
// Generate random values that are constrained to the input_shape minus the
// output_shape so as not to produce wrapping slices, for instance.
-std::unique_ptr<Literal> MakeRandomNonwrappingSliceIndex(
- const Shape& input_shape, const Shape& slice_shape,
- std::minstd_rand0* engine) {
- const int64 rank = ShapeUtil::Rank(input_shape);
- std::vector<int32> start_indices(rank);
+std::unique_ptr<Literal> MakeRandomIndex(
+ tensorflow::gtl::ArraySlice<int64> index_space, std::minstd_rand0* engine) {
+ std::vector<int32> start_indices(index_space.size());
if (engine != nullptr) {
- for (int i = 0; i < rank; ++i) {
- const int32 upper_bound = ShapeUtil::GetDimension(input_shape, i) -
- ShapeUtil::GetDimension(slice_shape, i);
- std::uniform_int_distribution<int32> generator(0, upper_bound);
+ for (int i = 0; i < index_space.size(); ++i) {
+ std::uniform_int_distribution<int32> generator(0, index_space[i]);
start_indices[i] = generator(*engine);
}
}
@@ -254,6 +276,11 @@ std::vector<HloInstruction*> FindConstrainedUses(
auto converted_uses = FindConstrainedUses(dataflow, *instruction);
constrained_uses.insert(constrained_uses.end(), converted_uses.begin(),
converted_uses.end());
+ } else if (opcode == HloOpcode::kSort &&
+ instruction->operand_count() == 2 && op_num == 0) {
+ // Operand 0 of sort is the array of keys used for key/value
+ // (two-operand) kSort instructions.
+ constrained_uses.push_back(instruction);
}
}
}
@@ -267,56 +294,66 @@ std::vector<HloInstruction*> FindConstrainedUses(
StatusOr<std::unique_ptr<Literal>> CreateLiteralForConstrainedUses(
const tensorflow::gtl::ArraySlice<HloInstruction*> constrained_uses,
const HloInstruction& param, std::minstd_rand0* engine) {
- HloInstruction* needs_index = nullptr;
- HloInstruction* needs_constant = nullptr;
+ std::vector<int64> index_space;
+ bool no_duplicates = false;
+ bool needs_constant = false;
ConstantType constant_type = ConstantType::kUnknown;
for (HloInstruction* use : constrained_uses) {
switch (use->opcode()) {
case HloOpcode::kDynamicSlice:
- case HloOpcode::kDynamicUpdateSlice:
- if (needs_index != nullptr) {
- auto needs_index_shape = needs_index->shape();
- auto use_shape = use->shape();
- if (needs_index->opcode() == HloOpcode::kDynamicSlice) {
- needs_index_shape = needs_index->operand(0)->shape();
- }
- if (use->opcode() == HloOpcode::kDynamicSlice) {
- use_shape = use->operand(0)->shape();
+ case HloOpcode::kDynamicUpdateSlice: {
+ const Shape& indexed_shape = use->operand(0)->shape();
+ const Shape& slice_shape = use->opcode() == HloOpcode::kDynamicSlice
+ ? use->shape()
+ : use->operand(1)->shape();
+ const int64 rank = ShapeUtil::Rank(indexed_shape);
+ if (!index_space.empty()) {
+ TF_RET_CHECK(rank == index_space.size());
+ for (int64 i = 0; i < rank; ++i) {
+ index_space[i] = std::min(
+ index_space[i], ShapeUtil::GetDimension(indexed_shape, i) -
+ ShapeUtil::GetDimension(slice_shape, i));
}
- if (!ShapeUtil::Equal(needs_index_shape, use_shape)) {
- return Unimplemented(
- "Conflicting operand generation slice index constraints\n");
+ } else {
+ index_space.resize(rank);
+ for (int64 i = 0; i < rank; ++i) {
+ index_space[i] = ShapeUtil::GetDimension(indexed_shape, i) -
+ ShapeUtil::GetDimension(slice_shape, i);
}
}
- needs_index = use;
break;
+ }
case HloOpcode::kReduce:
case HloOpcode::kReduceWindow:
- needs_constant = use;
+ needs_constant = true;
constant_type = GetInitValue(*use->to_apply());
break;
case HloOpcode::kSelectAndScatter:
- needs_constant = use;
+ needs_constant = true;
constant_type = GetInitValue(*use->scatter());
break;
+ case HloOpcode::kSort:
+ no_duplicates = true;
+ break;
+
default:
return Unimplemented(
"Constrained operand generation not implemented for %s.",
use->ToString().c_str());
}
}
- if (needs_index != nullptr && needs_constant != nullptr) {
- return Unimplemented(
- "Conflicting operand generation constraints.\nNeeds index: %s\nNeeds "
- "constant: %s\n",
- needs_index->ToString().c_str(), needs_constant->ToString().c_str());
+ int constraint_count = 0;
+ constraint_count += no_duplicates ? 1 : 0;
+ constraint_count += !index_space.empty() ? 1 : 0;
+ constraint_count += needs_constant ? 1 : 0;
+ if (constraint_count > 1) {
+ return Unimplemented("Conflicting operand generation constraints.");
}
- if (needs_index != nullptr) {
- return MakeRandomNonwrappingSliceIndex(needs_index->operand(0)->shape(),
- needs_index->shape(), engine);
- } else if (needs_constant != nullptr) {
+ if (!index_space.empty()) {
+ return MakeRandomIndex(index_space, engine);
+ } else if (needs_constant) {
switch (constant_type) {
case ConstantType::kZero:
return LiteralUtil::Zero(param.shape().element_type()).CloneToUnique();
@@ -325,10 +362,11 @@ StatusOr<std::unique_ptr<Literal>> CreateLiteralForConstrainedUses(
case ConstantType::kUnknown:
// We want the identity element for the computation, but we don't really
// know what it is - so any value we generate will be just as wrong.
- return MakeFakeLiteralInternal(param.shape(), engine);
+ return MakeFakeLiteralInternal(param.shape(), engine,
+ /*no_duplicates=*/false);
}
} else {
- return MakeFakeLiteralInternal(param.shape(), engine);
+ return MakeFakeLiteralInternal(param.shape(), engine, no_duplicates);
}
}
@@ -346,18 +384,23 @@ StatusOr<std::unique_ptr<Literal>> MakeConstrainedArgument(
StatusOr<std::unique_ptr<Literal>> MakeFakeLiteral(const Shape& shape,
bool pseudo_random) {
auto engine = pseudo_random ? MakeUnique<std::minstd_rand0>() : nullptr;
- return MakeFakeLiteralInternal(shape, engine.get());
+ return MakeFakeLiteralInternal(shape, engine.get(), /*no_duplicates=*/false);
}
StatusOr<std::vector<std::unique_ptr<Literal>>> MakeFakeArguments(
HloModule* const module, bool pseudo_random) {
+ auto engine = pseudo_random ? MakeUnique<std::minstd_rand0>() : nullptr;
+ return MakeFakeArguments(module, engine.get());
+}
+
+StatusOr<std::vector<std::unique_ptr<Literal>>> MakeFakeArguments(
+ HloModule* const module, std::minstd_rand0* engine) {
TF_ASSIGN_OR_RETURN(auto dataflow, HloDataflowAnalysis::Run(*module));
const auto params = module->entry_computation()->parameter_instructions();
- auto engine = pseudo_random ? MakeUnique<std::minstd_rand0>() : nullptr;
std::vector<std::unique_ptr<Literal>> arguments(params.size());
for (int i = 0; i < params.size(); ++i) {
- TF_ASSIGN_OR_RETURN(arguments[i], MakeConstrainedArgument(
- *dataflow, *params[i], engine.get()));
+ arguments[i] =
+ MakeConstrainedArgument(*dataflow, *params[i], engine).ValueOrDie();
}
return std::move(arguments);
}
diff --git a/tensorflow/compiler/xla/tests/test_utils.h b/tensorflow/compiler/xla/tests/test_utils.h
index e59f215a9a..3a8ad80ed1 100644
--- a/tensorflow/compiler/xla/tests/test_utils.h
+++ b/tensorflow/compiler/xla/tests/test_utils.h
@@ -63,8 +63,17 @@ StatusOr<std::unique_ptr<Literal>> MakeFakeLiteral(const Shape& shape,
// Generates a vector of arguments containing fake data. The number, shape and
// layout of the arguments is appropriate for given HLO module.
//
-// Will handle special cases such as making sure that indices used for dynamic
-// slices are bounded, reduces that call adds use 0 as an init value, etc.
+// A best-effort attempt is made to generate the data in a way which produce
+// stable computation results across platforms. Specifically:
+//
+// (1) Init values of reductions should be the identity of the reduction
+// computation.
+//
+// (2) Indices of dynamic slices and update slices should be in bounds.
+//
+// (3) Keys of key/value sorts should contain no duplicates.
+//
+// These constraints are best-effort only.
//
// If pseudo_random is true, the generated numbers will be generated
// deterministically in a pseudo random way unless the values are constrated to
@@ -78,6 +87,12 @@ StatusOr<std::unique_ptr<Literal>> MakeFakeLiteral(const Shape& shape,
StatusOr<std::vector<std::unique_ptr<Literal>>> MakeFakeArguments(
HloModule* const module, bool pseudo_random = true);
+// Overload which accepts a random number generator. This enables generation of
+// different random values with sequential calls to MakeFakeArguments by reusing
+// the same generator.
+StatusOr<std::vector<std::unique_ptr<Literal>>> MakeFakeArguments(
+ HloModule* const module, std::minstd_rand0* engine);
+
// Check that a given module satisfies various constraints before trying to
// execute it.
Status VerifyHloModule(HloModule* const module,
diff --git a/tensorflow/compiler/xla/tests/test_utils_test.cc b/tensorflow/compiler/xla/tests/test_utils_test.cc
index a2f0338e25..322c8ef090 100644
--- a/tensorflow/compiler/xla/tests/test_utils_test.cc
+++ b/tensorflow/compiler/xla/tests/test_utils_test.cc
@@ -20,6 +20,7 @@ limitations under the License.
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/tests/local_client_test_base.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
+#include "tensorflow/core/lib/core/casts.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace xla {
@@ -72,5 +73,106 @@ XLA_TEST_F(TestUtilsTest, Token) {
TF_ASSERT_OK(MakeFakeArguments(module.get()).status());
}
+XLA_TEST_F(TestUtilsTest, MultipleIndexSpacesForDynamicSlices) {
+ auto module = ParseHloString(
+ R"(HloModule index_space_module
+
+ ENTRY IndexSpace {
+ index_param = s32[3]{0} parameter(0)
+ array_param.1 = f32[123,4,789]{0,1,2} parameter(1)
+ array_param.2 = f32[3,3000,5]{0,1,2} parameter(2)
+ dynamic-slice.1 = f32[1,2,3] dynamic-slice(array_param.1, index_param), dynamic_slice_sizes={1,2,3}
+ ROOT dynamic-slice.2 = f32[3,2,2] dynamic-slice(array_param.2, index_param), dynamic_slice_sizes={3,2,2}
+ })")
+ .ValueOrDie();
+ TF_ASSERT_OK_AND_ASSIGN(std::vector<std::unique_ptr<Literal>> args,
+ MakeFakeArguments(module.get()));
+ ASSERT_EQ(args.size(), 3);
+ const Literal& index_arg = *args[0];
+
+ EXPECT_EQ(index_arg.Get<int32>({0}), 0);
+
+ EXPECT_GE(index_arg.Get<int32>({1}), 0);
+ EXPECT_LE(index_arg.Get<int32>({1}), 2);
+
+ EXPECT_GE(index_arg.Get<int32>({2}), 0);
+ EXPECT_LE(index_arg.Get<int32>({2}), 3);
+}
+
+XLA_TEST_F(TestUtilsTest, MultipleIndexSpacesForDynamicUpdateSlices) {
+ auto module = ParseHloString(
+ R"(HloModule index_space_module
+
+ ENTRY IndexSpace {
+ index_param = s32[3]{0} parameter(0)
+ array_param.1 = f32[123,4,789]{0,1,2} parameter(1)
+ array_param.2 = f32[3,3000,5]{0,1,2} parameter(2)
+ update_param.1 = f32[1,2,3]{0,1,2} parameter(3)
+ update_param.2 = f32[3,2,2]{0,1,2} parameter(4)
+
+ dynamic-update-slice.1 = f32[123,4,789] dynamic-update-slice(array_param.1, update_param.1, index_param)
+ ROOT dynamic-update-slice.2 = f32[3,3000,5] dynamic-update-slice(array_param.2, update_param.2, index_param)
+ })")
+ .ValueOrDie();
+ TF_ASSERT_OK_AND_ASSIGN(std::vector<std::unique_ptr<Literal>> args,
+ MakeFakeArguments(module.get()));
+ ASSERT_EQ(args.size(), 5);
+ const Literal& index_arg = *args[0];
+
+ EXPECT_EQ(index_arg.Get<int32>({0}), 0);
+
+ EXPECT_GE(index_arg.Get<int32>({1}), 0);
+ EXPECT_LE(index_arg.Get<int32>({1}), 2);
+
+ EXPECT_GE(index_arg.Get<int32>({2}), 0);
+ EXPECT_LE(index_arg.Get<int32>({2}), 3);
+}
+
+XLA_TEST_F(TestUtilsTest, NoDuplicatesFloats) {
+ // Inputs which are sort keys in key/value sorts should have no duplicates.
+ auto module = ParseHloString(R"(
+HloModule sort.148.1589
+
+ENTRY %sort.148.1589 (parameter.0: f32[1048576], parameter.1: s32[1048576]) -> (f32[1048576], s32[1048576]) {
+ %parameter.0 = f32[1048576]{0} parameter(0)
+ %parameter.1 = s32[1048576]{0} parameter(1)
+ ROOT %sort.148.1589 = (f32[1048576]{0}, s32[1048576]{0}) sort(f32[1048576]{0} %parameter.0, s32[1048576]{0} %parameter.1), dimensions={0}
+}
+)")
+ .ValueOrDie();
+ TF_ASSERT_OK_AND_ASSIGN(std::vector<std::unique_ptr<Literal>> args,
+ MakeFakeArguments(module.get()));
+ ASSERT_EQ(args.size(), 2);
+ const Literal& key_arg = *args[0];
+
+ tensorflow::gtl::FlatSet<uint32> key_set;
+ for (const float& value : key_arg.data<float>()) {
+ EXPECT_TRUE(key_set.insert(tensorflow::bit_cast<uint32>(value)).second);
+ }
+}
+
+XLA_TEST_F(TestUtilsTest, NoDuplicatesInt32) {
+ // Inputs which are sort keys in key/value sorts should have no duplicates.
+ auto module = ParseHloString(R"(
+HloModule sort.148.1589
+
+ENTRY %sort.148.1589 (parameter.0: s32[1048576], parameter.1: s32[1048576]) -> (s32[1048576], s32[1048576]) {
+ %parameter.0 = s32[1048576]{0} parameter(0)
+ %parameter.1 = s32[1048576]{0} parameter(1)
+ ROOT %sort.148.1589 = (s32[1048576]{0}, s32[1048576]{0}) sort(s32[1048576]{0} %parameter.0, s32[1048576]{0} %parameter.1), dimensions={0}
+}
+)")
+ .ValueOrDie();
+ TF_ASSERT_OK_AND_ASSIGN(std::vector<std::unique_ptr<Literal>> args,
+ MakeFakeArguments(module.get()));
+ ASSERT_EQ(args.size(), 2);
+ const Literal& key_arg = *args[0];
+
+ tensorflow::gtl::FlatSet<int32> key_set;
+ for (const int32& value : key_arg.data<int32>()) {
+ EXPECT_TRUE(key_set.insert(tensorflow::bit_cast<uint32>(value)).second);
+ }
+}
+
} // namespace
} // namespace xla
diff --git a/tensorflow/compiler/xla/tests/tuple_test.cc b/tensorflow/compiler/xla/tests/tuple_test.cc
index d9c1dfa3f7..97bbf80aff 100644
--- a/tensorflow/compiler/xla/tests/tuple_test.cc
+++ b/tensorflow/compiler/xla/tests/tuple_test.cc
@@ -586,7 +586,7 @@ XLA_TEST_F(TupleHloTest,
}));
auto expected =
LiteralUtil::MakeTupleOwned(LiteralUtil::CreateR1<float>({2, 3}));
- auto literal = MakeUnique<Literal>(expected->shape());
+ auto literal = Literal::CreateFromShape(expected->shape());
TF_EXPECT_OK(backend().transfer_manager()->TransferLiteralFromOutfeed(
backend().default_stream_executor(), expected->shape(), *literal));
EXPECT_TRUE(LiteralTestUtil::Equal(*expected, *literal));
diff --git a/tensorflow/compiler/xla/tests/xla_hlo_profile_test.cc b/tensorflow/compiler/xla/tests/xla_hlo_profile_test.cc
index 11f3efb1f3..e12e095ecd 100644
--- a/tensorflow/compiler/xla/tests/xla_hlo_profile_test.cc
+++ b/tensorflow/compiler/xla/tests/xla_hlo_profile_test.cc
@@ -16,6 +16,7 @@ limitations under the License.
#include <memory>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
@@ -116,7 +117,7 @@ Status ParseOneProfileOutputLine(
", Regexp: ", regexp_pattern);
}
- if (!c_linear_search(opcodes_to_ignore, parsed_line.opcode)) {
+ if (!absl::c_linear_search(opcodes_to_ignore, parsed_line.opcode)) {
InsertOrDie(parsed_results, parsed_line.opcode, parsed_line);
}
@@ -294,7 +295,7 @@ XLA_TEST_F(HloProfileTest, ProfileWhileComputation) {
tensorflow::str_util::Split(profile_output, '\n');
auto while_body_profile_start =
- c_find_if(profile_output_lines, [](tensorflow::StringPiece s) {
+ absl::c_find_if(profile_output_lines, [](tensorflow::StringPiece s) {
return tensorflow::str_util::StartsWith(s,
"Execution profile for body");
});
diff --git a/tensorflow/compiler/xla/tools/replay_computation.cc b/tensorflow/compiler/xla/tools/replay_computation.cc
index be4cf4318b..b4774233e5 100644
--- a/tensorflow/compiler/xla/tools/replay_computation.cc
+++ b/tensorflow/compiler/xla/tools/replay_computation.cc
@@ -223,9 +223,13 @@ StatusOr<HloSnapshot> ParseInputFile(const string& filename,
const Options& opts) {
tensorflow::Env* env = tensorflow::Env::Default();
HloSnapshot snapshot;
- if (tensorflow::ReadBinaryProto(env, filename, &snapshot).ok()) {
+ auto s = tensorflow::ReadBinaryProto(env, filename, &snapshot);
+ if (s.ok()) {
return snapshot;
}
+ if (s.code() == tensorflow::error::NOT_FOUND) {
+ return s;
+ }
CHECK(opts.use_fake_data)
<< "Without --use_fake_data, you must pass an HloSnapshot -- HloProto "
"and textual HLO don't carry real data.";
@@ -258,6 +262,9 @@ int RealMain(tensorflow::gtl::ArraySlice<char*> args, const Options& opts) {
StatusOr<HloSnapshot> maybe_snapshot = ParseInputFile(arg, opts);
if (maybe_snapshot.ok()) {
snapshots.push_back(std::move(maybe_snapshot).ValueOrDie());
+ } else {
+ LOG(ERROR) << "Can't handle file " << arg << ": "
+ << maybe_snapshot.status();
}
}
diff --git a/tensorflow/compiler/xla/util.h b/tensorflow/compiler/xla/util.h
index 5ae099a462..cc07346ee5 100644
--- a/tensorflow/compiler/xla/util.h
+++ b/tensorflow/compiler/xla/util.h
@@ -24,6 +24,7 @@ limitations under the License.
#include <type_traits>
#include <vector>
+#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
@@ -434,122 +435,15 @@ std::vector<std::pair<int64, int64>> CommonFactors(
// Removes illegal characters from filenames.
string SanitizeFileName(string file_name);
-template <typename Container, typename Predicate>
-bool c_all_of(const Container& container, Predicate&& predicate) {
- return std::all_of(std::begin(container), std::end(container),
- std::forward<Predicate>(predicate));
-}
-
-template <typename Container, typename Predicate>
-bool c_any_of(const Container& container, Predicate&& predicate) {
- return std::any_of(std::begin(container), std::end(container),
- std::forward<Predicate>(predicate));
-}
-
-template <typename InputContainer, typename OutputIterator,
- typename UnaryOperation>
-OutputIterator c_transform(const InputContainer& input_container,
- OutputIterator output_iterator,
- UnaryOperation&& unary_op) {
- return std::transform(std::begin(input_container), std::end(input_container),
- output_iterator,
- std::forward<UnaryOperation>(unary_op));
-}
-
-template <class InputContainer, class OutputIterator, class UnaryPredicate>
-OutputIterator c_copy_if(const InputContainer& input_container,
- OutputIterator output_iterator,
- UnaryPredicate&& predicate) {
- return std::copy_if(std::begin(input_container), std::end(input_container),
- output_iterator, std::forward<UnaryPredicate>(predicate));
-}
-
-template <class InputContainer, class OutputIterator>
-OutputIterator c_copy(const InputContainer& input_container,
- OutputIterator output_iterator) {
- return std::copy(std::begin(input_container), std::end(input_container),
- output_iterator);
-}
-
-template <class InputContainer>
-void c_sort(InputContainer& input_container) {
- std::sort(std::begin(input_container), std::end(input_container));
-}
-
-template <class InputContainer, class Comparator>
-void c_sort(InputContainer& input_container, Comparator&& comparator) {
- std::sort(std::begin(input_container), std::end(input_container),
- std::forward<Comparator>(comparator));
-}
-
-template <typename Sequence, typename T>
-bool c_binary_search(const Sequence& sequence, T&& value) {
- return std::binary_search(std::begin(sequence), std::end(sequence),
- std::forward<T>(value));
-}
-
-template <typename C>
-bool c_is_sorted(const C& c) {
- return std::is_sorted(std::begin(c), std::end(c));
-}
-
-template <typename C, typename Compare>
-bool c_is_sorted(const C& c, Compare&& comp) {
- return std::is_sorted(std::begin(c), std::end(c),
- std::forward<Compare>(comp));
-}
-
-template <typename C>
-auto c_adjacent_find(C& c) -> decltype(std::begin(c)) {
- return std::adjacent_find(std::begin(c), std::end(c));
-}
-
-template <typename C, typename Pred>
-auto c_find_if(C& c, Pred&& pred) -> decltype(std::begin(c)) {
- return std::find_if(std::begin(c), std::end(c), std::forward<Pred>(pred));
-}
-
-template <typename C, typename Value>
-auto c_find(C& c, Value&& value) -> decltype(std::begin(c)) {
- return std::find(std::begin(c), std::end(c), std::forward<Value>(value));
-}
-
-template <typename Sequence>
-void c_reverse(Sequence& sequence) {
- std::reverse(std::begin(sequence), std::end(sequence));
-}
-
-template <typename Sequence, typename T, typename BinaryOp>
-typename std::decay<T>::type c_accumulate(const Sequence& sequence, T&& init,
- BinaryOp&& binary_op) {
- return std::accumulate(std::begin(sequence), std::end(sequence),
- std::forward<T>(init),
- std::forward<BinaryOp>(binary_op));
-}
-
-template <typename C, typename Pred>
-typename std::iterator_traits<
- decltype(std::begin(std::declval<C>()))>::difference_type
-c_count_if(const C& c, Pred&& pred) {
- return std::count_if(std::begin(c), std::end(c), std::forward<Pred>(pred));
-}
-
-// Determines whether `value` is present in `c`.
-template <typename C, typename T>
-bool c_linear_search(const C& c, T&& value) {
- auto last = std::end(c);
- return std::find(std::begin(c), last, std::forward<T>(value)) != last;
-}
-
template <typename C, typename Value>
int64 FindIndex(const C& c, Value&& value) {
- auto it = c_find(c, std::forward<Value>(value));
+ auto it = absl::c_find(c, std::forward<Value>(value));
return std::distance(c.begin(), it);
}
template <typename T>
bool ArrayContains(tensorflow::gtl::ArraySlice<T> c, const T& value) {
- return c_find(c, value) != c.end();
+ return absl::c_find(c, value) != c.end();
}
template <typename C, typename Value>
@@ -584,8 +478,8 @@ bool IsInt32(T x) {
template <typename T>
Status EraseElementFromVector(std::vector<T>* container, const T& value) {
- // c_find returns a const_iterator which does not seem to work on gcc 4.8.4,
- // and this breaks the ubuntu/xla_gpu build bot.
+ // absl::c_find returns a const_iterator which does not seem to work on
+ // gcc 4.8.4, and this breaks the ubuntu/xla_gpu build bot.
auto it = std::find(container->begin(), container->end(), value);
TF_RET_CHECK(it != container->end());
container->erase(it);
diff --git a/tensorflow/compiler/xla/xla.proto b/tensorflow/compiler/xla/xla.proto
index 10c0adc670..b53f89d63b 100644
--- a/tensorflow/compiler/xla/xla.proto
+++ b/tensorflow/compiler/xla/xla.proto
@@ -104,15 +104,6 @@ message DebugOptions {
// interpretation of this value is left to the backends.
int32 xla_backend_optimization_level = 31;
- // When true, "unsafe" mathematical optimizations are enabled. These
- // transformations include but are not limited to:
- //
- // - Reducing the precision of operations (e.g. using an approximate sin
- // function, or transforming x/y into x * (1/y)).
- // - Assuming that operations never produce or consume NaN or +/- Inf.
- // - Assuming that +0 and -0 are indistinguishable.
- bool xla_enable_fast_math = 32;
-
// Embed the compiler IR as a string in the executable.
bool xla_embed_ir_in_executable = 33;
@@ -194,8 +185,23 @@ message DebugOptions {
// Maximum kernel unroll factor for the GPU backend.
int32 xla_gpu_max_kernel_unroll_factor = 98;
- // Extra options to pass to the compilation backend; specific interpretation
- // of these values is left to the backend.
+ // When true, "unsafe" mathematical optimizations are enabled. These
+ // transformations include but are not limited to:
+ //
+ // - Reducing the precision of operations (e.g. using an approximate sin
+ // function, or transforming x/y into x * (1/y)).
+ // - Assuming that operations never produce or consume NaN or +/- Inf.
+ // - Assuming that +0 and -0 are indistinguishable.
+ bool xla_cpu_enable_fast_math = 99;
+ bool xla_gpu_enable_fast_math = 100;
+
+ // Crashes the program when any kind of verification fails, instead of just
+ // logging the failures. One example is cross checking of convolution results
+ // among different algorithms.
+ bool xla_gpu_crash_on_verification_failures = 101;
+
+ // Extra options to pass to the compilation backend (e.g. LLVM); specific
+ // interpretation of these values is left to the backend.
map<string, string> xla_backend_extra_options = 500;
}
diff --git a/tensorflow/compiler/xla/xla_data.proto b/tensorflow/compiler/xla/xla_data.proto
index 4c35e93d38..27aa94c2cb 100644
--- a/tensorflow/compiler/xla/xla_data.proto
+++ b/tensorflow/compiler/xla/xla_data.proto
@@ -424,25 +424,25 @@ message GatherDimensionNumbers {
// "Window indices" is a term for a set of indices that index into the
// interior of a dynamic-slice from the input tensor, the starting indices for
// which were computed from output_gather_dims (see the operation semantic for
- // how this is defined) and the gather_indices tensor.
+ // how this is defined) and the start_indices tensor.
//
// The window indices for a specific output index Out is computed as:
//
// i = 0
// for (k : [0, input_tensor_shape.rank))
// window_indices[k] =
- // if k in elided_window_dims
+ // if k in collapsed_slice_dims
// then 0
- // else Out[output_window_dims[i++]]
- repeated int64 output_window_dims = 1;
- repeated int64 elided_window_dims = 2;
+ // else Out[offset_dims[i++]]
+ repeated int64 offset_dims = 1;
+ repeated int64 collapsed_slice_dims = 2;
- // This is interpreted as a map from i to gather_dims_to_operand_dims[i]. It
- // transforms the gather index looked up from the gather_indices tensor into
+ // This is interpreted as a map from i to start_index_map[i]. It
+ // transforms the gather index looked up from the start_indices tensor into
// the starting index in the input space.
- repeated int64 gather_dims_to_operand_dims = 3;
+ repeated int64 start_index_map = 3;
- // The dimension in the gather_indices input that contains the starting
+ // The dimension in the start_indices input that contains the starting
// indices.
int64 index_vector_dim = 4;
}
diff --git a/tensorflow/contrib/BUILD b/tensorflow/contrib/BUILD
index cc34db995e..f7e3c8d8fb 100644
--- a/tensorflow/contrib/BUILD
+++ b/tensorflow/contrib/BUILD
@@ -46,6 +46,7 @@ py_library(
"//tensorflow/contrib/gan",
"//tensorflow/contrib/graph_editor:graph_editor_py",
"//tensorflow/contrib/grid_rnn:grid_rnn_py",
+ "//tensorflow/contrib/hadoop",
"//tensorflow/contrib/hooks",
"//tensorflow/contrib/image:distort_image_py",
"//tensorflow/contrib/image:image_py",
@@ -63,6 +64,7 @@ py_library(
"//tensorflow/contrib/linalg:linalg_py",
"//tensorflow/contrib/linear_optimizer:sdca_estimator_py",
"//tensorflow/contrib/linear_optimizer:sdca_ops_py",
+ "//tensorflow/contrib/lite/python:lite",
"//tensorflow/contrib/lookup:lookup_py",
"//tensorflow/contrib/losses:losses_py",
"//tensorflow/contrib/losses:metric_learning_py",
@@ -134,7 +136,6 @@ py_library(
# This is an issue with the tensorrt static library and will be fixed by
# the next tensorrt release, so fix the order here after that.
"//tensorflow/contrib/tensorrt:init_py", # doesn't compile on windows
- "//tensorflow/contrib/lite/python:lite", # unix dependency, need to fix code
]),
)
@@ -146,6 +147,7 @@ cc_library(
"//tensorflow/contrib/coder:all_kernels",
"//tensorflow/contrib/data/kernels:dataset_kernels",
"//tensorflow/contrib/factorization/kernels:all_kernels",
+ "//tensorflow/contrib/hadoop:dataset_kernels",
"//tensorflow/contrib/input_pipeline:input_pipeline_ops_kernels",
"//tensorflow/contrib/layers:sparse_feature_cross_op_kernel",
"//tensorflow/contrib/nearest_neighbor:nearest_neighbor_ops_kernels",
@@ -181,6 +183,7 @@ cc_library(
"//tensorflow/contrib/data:dataset_ops_op_lib",
"//tensorflow/contrib/factorization:all_ops",
"//tensorflow/contrib/framework:all_ops",
+ "//tensorflow/contrib/hadoop:dataset_ops_op_lib",
"//tensorflow/contrib/input_pipeline:input_pipeline_ops_op_lib",
"//tensorflow/contrib/layers:sparse_feature_cross_op_op_lib",
"//tensorflow/contrib/nccl:nccl_ops_op_lib",
diff --git a/tensorflow/contrib/__init__.py b/tensorflow/contrib/__init__.py
index e18ea8df4d..45a7680160 100644
--- a/tensorflow/contrib/__init__.py
+++ b/tensorflow/contrib/__init__.py
@@ -94,8 +94,7 @@ from tensorflow.contrib import tpu
from tensorflow.contrib import training
from tensorflow.contrib import util
from tensorflow.contrib.eager.python import tfe as eager
-if os.name != "nt":
- from tensorflow.contrib.lite.python import lite
+from tensorflow.contrib.lite.python import lite
from tensorflow.contrib.optimizer_v2 import optimizer_v2_symbols as optimizer_v2
from tensorflow.contrib.receptive_field import receptive_field_api as receptive_field
from tensorflow.contrib.recurrent.python import recurrent_api as recurrent
diff --git a/tensorflow/contrib/all_reduce/python/all_reduce.py b/tensorflow/contrib/all_reduce/python/all_reduce.py
index 159d985db5..3b539734a2 100644
--- a/tensorflow/contrib/all_reduce/python/all_reduce.py
+++ b/tensorflow/contrib/all_reduce/python/all_reduce.py
@@ -32,10 +32,10 @@ def _flatten_tensors(tensors):
"""Check tensors for isomorphism and flatten.
Args:
- tensors: list of T @{tf.Tensor} which must all have the same shape.
+ tensors: list of T `tf.Tensor` which must all have the same shape.
Returns:
- tensors: a list of T @{tf.Tensor} which are flattened (1D) views of tensors
+ tensors: a list of T `tf.Tensor` which are flattened (1D) views of tensors
shape: the original shape of each element of input tensors
Raises:
@@ -61,12 +61,12 @@ def _reshape_tensors(tensors, shape):
"""Reshape tensors flattened by _flatten_tensors.
Args:
- tensors: list of T @{tf.Tensor} of identical length 1D tensors.
+ tensors: list of T `tf.Tensor` of identical length 1D tensors.
shape: list of integers describing the desired shape. Product of
the elements must equal the length of each tensor.
Returns:
- list of T @{tf.Tensor} which are the reshaped inputs.
+ list of T `tf.Tensor` which are the reshaped inputs.
"""
reshaped = []
for t in tensors:
@@ -79,12 +79,12 @@ def _padded_split(tensor, pieces):
"""Like split for 1D tensors but pads-out case where len % pieces != 0.
Args:
- tensor: T @{tf.Tensor} that must be 1D.
+ tensor: T `tf.Tensor` that must be 1D.
pieces: a positive integer specifying the number of pieces into which
tensor should be split.
Returns:
- list of T @{tf.Tensor} of length pieces, which hold the values of
+ list of T `tf.Tensor` of length pieces, which hold the values of
thin input tensor, in order. The final tensor may
be zero-padded on the end to make its size equal to those of all
of the other tensors.
@@ -132,11 +132,11 @@ def _strip_padding(tensors, pad_len):
"""Strip the suffix padding added by _padded_split.
Args:
- tensors: list of T @{tf.Tensor} of identical length 1D tensors.
+ tensors: list of T `tf.Tensor` of identical length 1D tensors.
pad_len: number of elements to be stripped from the end of each tensor.
Returns:
- list of T @{tf.Tensor} which are the stripped inputs.
+ list of T `tf.Tensor` which are the stripped inputs.
Raises:
ValueError: tensors must be a non-empty list of 1D tensors, and
@@ -161,12 +161,12 @@ def _ragged_split(tensor, pieces):
"""Like split for 1D tensors but allows case where len % pieces != 0.
Args:
- tensor: T @{tf.Tensor} that must be 1D.
+ tensor: T `tf.Tensor` that must be 1D.
pieces: a positive integer specifying the number of pieces into which
tensor should be split.
Returns:
- list of T @{tf.Tensor} of length pieces, which hold the values of
+ list of T `tf.Tensor` of length pieces, which hold the values of
the input tensor, in order. The final tensor may be shorter
than the others, which will all be of equal length.
@@ -256,7 +256,7 @@ def build_ring_all_reduce(input_tensors, num_workers, num_subchunks,
"""Construct a subgraph performing a ring-style all-reduce of input_tensors.
Args:
- input_tensors: a list of T @{tf.Tensor} objects, which must all
+ input_tensors: a list of T `tf.Tensor` objects, which must all
have the same shape and type.
num_workers: number of worker tasks spanned by input_tensors.
num_subchunks: number of subchunks each device should process in one tick.
@@ -272,7 +272,7 @@ def build_ring_all_reduce(input_tensors, num_workers, num_subchunks,
size.
Returns:
- a list of T @{tf.Tensor} identical sum-reductions of input_tensors.
+ a list of T `tf.Tensor` identical sum-reductions of input_tensors.
"""
if len(input_tensors) < 2:
raise ValueError("input_tensors must be length 2 or longer")
@@ -299,7 +299,7 @@ def _build_ring_gather(input_tensors, devices, num_subchunks,
"""Construct a subgraph for the first (reduction) pass of ring all-reduce.
Args:
- input_tensors: a list of T @{tf.Tensor} 1D input tensors of same
+ input_tensors: a list of T `tf.Tensor` 1D input tensors of same
shape and type.
devices: array of device name strings
num_subchunks: number of subchunks each device should process in one tick.
@@ -311,7 +311,7 @@ def _build_ring_gather(input_tensors, devices, num_subchunks,
ValueError: tensors must all be one dimensional.
Returns:
- list of list of T @{tf.Tensor} of (partially) reduced values where
+ list of list of T `tf.Tensor` of (partially) reduced values where
exactly num_subchunks chunks at each device are fully reduced.
"""
num_devices = len(input_tensors)
@@ -360,11 +360,11 @@ def _apply_unary_to_chunks(f, chunks_by_dev):
"""Apply a unary op to each tensor in chunks_by_dev, on same device.
Args:
- f: a unary function over T @{tf.Tensor}.
- chunks_by_dev: list of lists of T @{tf.Tensor}.
+ f: a unary function over T `tf.Tensor`.
+ chunks_by_dev: list of lists of T `tf.Tensor`.
Returns:
- new list of lists of T @{tf.Tensor} with the same structure as
+ new list of lists of T `tf.Tensor` with the same structure as
chunks_by_dev containing the derived tensors.
"""
output = []
@@ -381,14 +381,14 @@ def _build_ring_scatter(pred_by_s_d, rank_by_s_d,
Args:
pred_by_s_d: as produced by _ring_permutations
rank_by_s_d: as produced by _ring_permutations
- chunks_by_dev: list of list of T @{tf.Tensor} indexed by ints
+ chunks_by_dev: list of list of T `tf.Tensor` indexed by ints
(device, chunk)
Raises:
ValueError: chunks_by_dev is not well-formed
Returns:
- list of T @{tf.Tensor} which are the fully reduced tensors, one
+ list of T `tf.Tensor` which are the fully reduced tensors, one
at each device corresponding to the outer dimension of chunks_by_dev.
"""
num_devices = len(chunks_by_dev)
@@ -448,12 +448,12 @@ def build_recursive_hd_all_reduce(input_tensors, red_op, un_op=None):
the future with edge-case specific logic.
Args:
- input_tensors: list of T @{tf.Tensor} to be elementwise reduced.
+ input_tensors: list of T `tf.Tensor` to be elementwise reduced.
red_op: a binary elementwise reduction Op.
un_op: an optional unary elementwise Op to apply to reduced values.
Returns:
- list of T @{tf.Tensor} which are the fully reduced tensors, one
+ list of T `tf.Tensor` which are the fully reduced tensors, one
at each device of input_tensors.
Raises:
@@ -475,13 +475,13 @@ def _build_recursive_hd_gather(input_tensors, devices, red_op):
"""Construct the gather phase of recursive halving-doubling all-reduce.
Args:
- input_tensors: list of T @{tf.Tensor} to be elementwise reduced.
+ input_tensors: list of T `tf.Tensor` to be elementwise reduced.
devices: a list of strings naming the devices hosting input_tensors,
which will also be used to host the (partial) reduction values.
red_op: a binary elementwise reduction Op.
Returns:
- list of T @{tf.Tensor} which are the fully reduced tensor shards.
+ list of T `tf.Tensor` which are the fully reduced tensor shards.
Raises:
ValueError: num_devices not a power of 2, or tensor len not divisible
@@ -516,12 +516,12 @@ def _build_recursive_hd_scatter(input_tensors, devices):
"""Construct the scatter phase of recursive halving-doublng all-reduce.
Args:
- input_tensors: list of T @{tf.Tensor} that are fully-reduced shards.
+ input_tensors: list of T `tf.Tensor` that are fully-reduced shards.
devices: a list of strings naming the devices on which the reconstituted
full tensors should be placed.
Returns:
- list of T @{tf.Tensor} which are the fully reduced tensors.
+ list of T `tf.Tensor` which are the fully reduced tensors.
"""
num_devices = len(devices)
num_hops = int(math.log(num_devices, 2))
@@ -571,7 +571,7 @@ def build_shuffle_all_reduce(input_tensors, gather_devices, red_op, un_op=None):
un_op: optional elementwise unary Op to be applied to fully-reduced values.
Returns:
- list of T @{tf.Tensor} which are the fully reduced tensors.
+ list of T `tf.Tensor` which are the fully reduced tensors.
"""
input_tensors, shape = _flatten_tensors(input_tensors)
dst_devices = [t.device for t in input_tensors]
@@ -594,7 +594,7 @@ def _build_shuffle_gather(input_tensors, gather_devices, red_op, un_op=None):
un_op: optional elementwise unary Op to be applied to fully-reduced values.
Returns:
- list of T @{tf.Tensor} which are the fully reduced shards.
+ list of T `tf.Tensor` which are the fully reduced shards.
Raises:
ValueError: inputs not well-formed.
@@ -629,7 +629,7 @@ def _build_shuffle_scatter(reduced_shards, dst_devices):
should be reconstituted.
Returns:
- list of T @{tf.Tensor} scattered tensors.
+ list of T `tf.Tensor` scattered tensors.
"""
num_devices = len(dst_devices)
out_tensors = []
@@ -644,7 +644,7 @@ def _split_by_task(devices, values):
Args:
devices: list of device name strings
- values: list of T @{tf.tensor} of same length as devices.
+ values: list of T `tf.tensor` of same length as devices.
Returns:
(per_task_devices, per_task_values) where both values are
@@ -680,14 +680,14 @@ def build_nccl_all_reduce(input_tensors, red_op, un_op=None):
"""Build a subgraph that does one full all-reduce, using NCCL.
Args:
- input_tensors: list of T @{tf.Tensor} of same-shape and type values to
+ input_tensors: list of T `tf.Tensor` of same-shape and type values to
be reduced.
red_op: binary elementwise reduction operator. Must be one of
{tf.add}
un_op: optional unary elementwise Op to apply to fully-reduce values.
Returns:
- list of T @{tf.Tensor} of reduced values.
+ list of T `tf.Tensor` of reduced values.
Raises:
ValueError: red_op not supported.
@@ -709,14 +709,14 @@ def _build_nccl_hybrid(input_tensors, red_op, upper_level_f):
"""Construct a subgraph for NCCL hybrid all-reduce.
Args:
- input_tensors: list of T @{tf.Tensor} of same-shape and type values to
+ input_tensors: list of T `tf.Tensor` of same-shape and type values to
be reduced.
red_op: binary elementwise reduction operator.
upper_level_f: function for reducing one value per worker, across
workers.
Returns:
- list of T @{tf.Tensor} of reduced values.
+ list of T `tf.Tensor` of reduced values.
Raises:
ValueError: inputs not well-formed.
@@ -797,7 +797,7 @@ def _build_shuffle_hybrid(input_tensors, gather_devices, red_op, upper_level_f):
"""Construct a subgraph for Shuffle hybrid all-reduce.
Args:
- input_tensors: list of T @{tf.Tensor} of same-shape and type values to
+ input_tensors: list of T `tf.Tensor` of same-shape and type values to
be reduced.
gather_devices: list of device names on which to host gather shards.
red_op: binary elementwise reduction operator.
@@ -805,7 +805,7 @@ def _build_shuffle_hybrid(input_tensors, gather_devices, red_op, upper_level_f):
workers.
Returns:
- list of T @{tf.Tensor} of reduced values.
+ list of T `tf.Tensor` of reduced values.
Raises:
ValueError: inputs not well-formed.
diff --git a/tensorflow/contrib/autograph/docs/pyfunc_dtypes.md b/tensorflow/contrib/autograph/docs/pyfunc_dtypes.md
new file mode 100644
index 0000000000..bcbb920cc5
--- /dev/null
+++ b/tensorflow/contrib/autograph/docs/pyfunc_dtypes.md
@@ -0,0 +1,33 @@
+# Specifying return data type for `py_func` calls
+
+The `py_func` op requires specifying a
+[data type](https://www.tensorflow.org/guide/tensors#data_types).
+
+When wrapping a function with `py_func`, for instance using
+`@autograph.do_not_convert(run_mode=autograph.RunMode.PY_FUNC)`, you have two
+options to specify the returned data type:
+
+ * explicitly, with a specified `tf.DType` value
+ * by matching the data type of an input argument, which is then assumed to be
+ a `Tensor`
+
+Examples:
+
+Specify an explicit data type:
+
+```
+ def foo(a):
+ return a + 1
+
+ autograph.util.wrap_py_func(f, return_dtypes=[tf.float32])
+```
+
+Match the data type of the first argument:
+
+```
+ def foo(a):
+ return a + 1
+
+ autograph.util.wrap_py_func(
+ f, return_dtypes=[autograph.utils.py_func.MatchDType(0)])
+```
diff --git a/tensorflow/contrib/autograph/impl/api.py b/tensorflow/contrib/autograph/impl/api.py
index 4729c735c6..276a387180 100644
--- a/tensorflow/contrib/autograph/impl/api.py
+++ b/tensorflow/contrib/autograph/impl/api.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
-"""Public API."""
+"""This module contains the user-facing API for AutoGraph."""
from __future__ import absolute_import
from __future__ import division
@@ -42,34 +42,30 @@ from tensorflow.python.util import tf_inspect
# (currently we require (module + class name, type))
-def convert(recursive=False, verbose=False, arg_types=None):
- """Decorator that compiles a function to graph mode.
+# TODO(mdan): This should behave like to_graph (e.g. convert statically).
+def convert(recursive=False, verbose=False):
+ """Decorator that compiles a function to use TensorFlow ops.
- The decorator is dynamic - invoking compilation whenever the decorated
- function is called. This means the parameter values are known at compilation.
+ The decorator is dynamic - it recompiles the target whenever the decorated
+ function is called. This means the parameter values are known at conversion.
+ It also means that repeated calls with different types of parameters will be
+ correctly processed.
Args:
- recursive: Whether to recursively convert any functions that the decorator
- function may call.
- verbose: Whether to output the compiled code in the logs.
- arg_types: See to_graph.
+ recursive: bool, whether to recursively convert any functions or classes
+ that the converted function may use.
+ verbose: bool, whether to output the compiled code in the logs.
Returns:
- A decorator that compiles the given function to graph mode.
-
- Raises:
- ValueError: If any of the arguments are illegal.
+ Callable, a decorator that converts the given function into an equivalent
+ function that uses TensorFlow ops.
"""
- if arg_types is None:
- arg_types = {}
-
def decorator(f):
"""Decorator implementation."""
@wraps(f)
def wrapper(*args, **kwargs):
- return converted_call(f, recursive, verbose, True, arg_types, *args,
- **kwargs)
+ return converted_call(f, recursive, verbose, True, {}, *args, **kwargs)
wrapper = tf_decorator.make_decorator(f, wrapper)
@@ -82,22 +78,34 @@ def convert(recursive=False, verbose=False, arg_types=None):
class RunMode(Enum):
+ """Specifies the way a converted function or method should be executed in TF.
+
+ The enum values have the following semantics:
+
+ * GRAPH: Call this function directly, as-is. This is suitable for functions
+ that were already designed for TF graphs and contain ops.
+ * PY_FUNC: Wrap this function into a py_func op. This is suitable for code
+ that will only run correctly in Python, for example code that renders
+ to the display, reads keyboard input, etc.
+ """
GRAPH = 1
PY_FUNC = 2
def do_not_convert(run_as=RunMode.GRAPH, return_dtypes=None):
- """Decorator that suppresses compilation of a function.
+ """Decorator that suppresses the conversion of a function.
+
+ See also: docs/pyfunc_dtypes.md
Args:
- run_as: RunMode value. Whether to run the function as-is, or wrap it into
- a py_func.
- return_dtypes: See autograph.utils.py_func.wrap_py_func. Setting to None or
- empty list or tuple will create a dummy return value that can be used
- to set control dependencies.
+ run_as: RunMode, specifies how to use the function in TensorFlow.
+ return_dtypes: Optional[Iterable[
+ Union[tf.DType, utils.py_func.MatchDType]]], the return data types of
+ the converted function, if run_as is RunMode.PY_FUNC. Ignored otherwise.
+ May be set to None if the function has no return values.
Returns:
- A decorator that wraps the original function.
+ Callable, a decorator that wraps the original function.
"""
def decorator(f):
@@ -130,9 +138,10 @@ def do_not_convert(run_as=RunMode.GRAPH, return_dtypes=None):
return decorator
+# TODO(mdan): Move to a private, undocumented module.
def converted_call(f, recursive, verbose, force_conversion, arg_types, *args,
**kwargs):
- """Compiles a function call inline."""
+ """Compiles a function call inline. For internal use only."""
# TODO(mdan): This needs cleanup.
# In particular, we may want to avoid renaming functions altogether.
if not force_conversion and conversion.is_whitelisted_for_graph(f):
@@ -202,39 +211,41 @@ def converted_call(f, recursive, verbose, force_conversion, arg_types, *args,
return converted_f(*effective_args, **kwargs)
+# TODO(mdan): Rename: to_ops?
+# TODO(mdan): Looki into overloading as function and decorator, like tfe.defun.
+# TODO(mdan): Remove partial_types.
def to_graph(e,
recursive=True,
verbose=False,
arg_values=None,
arg_types=None,
partial_types=None):
- """Compile a Python entity into equivalent TensorFlow code.
+ """Converts a Python entity into equivalent code that uses TensorFlow ops.
- Currently supported entities:
+ Supported Python entities include:
* functions
* classes
- Classes are handled by converting all their methods into a new class.
+ Classes are converted by converting all their methods into a new class.
Args:
- e: A Python entity.
- recursive: Whether to recursively convert any functions that the decorator
- function may call.
- verbose: Whether to output the compiled code in the logs.
- arg_values: A dict containing value hints for symbols like function
- parameters.
- arg_types: A dict containing type hints for symbols like function
- parameters.
- partial_types: A set of types (e.g. classes) that will not be converted
- entirely. Calls to member functions for these types will be renamed
- independently.
+ e: Union[Callable, Type], the Python entity to convert.
+ recursive: bool, whether to recursively convert any functions that the
+ converted function may call.
+ verbose: bool, whether to output the compiled code in the logs.
+ arg_values: Optional[Dict[Text, Any]], value hints for symbols including
+ function arguments.
+ arg_types: Optional[Dict[Text, Type]], type hints for symbols including
+ function arguments.
+ partial_types: Set[Type], reserved for internal use.
Returns:
- A function with a signature identical to `o`, but which when executed it
- creates TF a graph that has the same functionality as the original entity.
+ Union[Callable, Type], the converted entity, which is the same kind as e
+ (that is, a function is e is a function, a class if e is a class, etc.) but
+ its code has been converted to use TF ops.
+
Raises:
- ValueError: If the converted function defines or refers to symbol names that
- are reserved for AutoGraph.
+ ValueError: If the entity could not be converted.
"""
program_ctx = converter.ProgramContext(
recursive=recursive,
@@ -288,20 +299,23 @@ def to_code(e,
arg_types=None,
partial_types=None,
indentation=' '):
- """Return the equivalent of an entity in TensorFlow code.
+ """Returns the equivalent code that uses TensorFlow ops.
- See `to_graph` for more details.
+ Also see: `to_graph`, `convert`
Args:
- e: A Python entity.
- recursive: See to_graph.
- arg_values: See to_graph.
- arg_types: See to_graph.
- partial_types: See to_graph.
- indentation: String, when to use for each level of indentation.
+ e: Union[Callable, Type], the Python entity to convert.
+ recursive: bool, whether to recursively convert any functions that the
+ converted function may call.
+ arg_values: Optional[Dict[Text, Any]], value hints for symbols including
+ function arguments.
+ arg_types: Optional[Dict[Text, Type]], type hints for symbols including
+ function arguments.
+ partial_types: Set[Type], reserved for internal use.
+ indentation: Text, when to use for each level of indentation.
Returns:
- String.
+ Text, the converted code.
"""
program_ctx = converter.ProgramContext(
recursive=recursive,
diff --git a/tensorflow/contrib/autograph/operators/control_flow.py b/tensorflow/contrib/autograph/operators/control_flow.py
index be38d3f534..9909e52164 100644
--- a/tensorflow/contrib/autograph/operators/control_flow.py
+++ b/tensorflow/contrib/autograph/operators/control_flow.py
@@ -141,7 +141,7 @@ def _dataset_for_stmt(ds, extra_test, body, init_state):
while_body,
init_state=(epoch_number, iterate) + init_state,
extra_deps=())
- # Dropping the epoch number and iterate because they are not not syntactically
+ # Dropping the epoch number and iterate because they are not syntactically
# visible.
results = results[2:]
diff --git a/tensorflow/contrib/autograph/pyct/static_analysis/reaching_definitions.py b/tensorflow/contrib/autograph/pyct/static_analysis/reaching_definitions.py
index 9a84f1231c..7f2b379d3d 100644
--- a/tensorflow/contrib/autograph/pyct/static_analysis/reaching_definitions.py
+++ b/tensorflow/contrib/autograph/pyct/static_analysis/reaching_definitions.py
@@ -39,7 +39,7 @@ from tensorflow.contrib.autograph.pyct.static_analysis import annos
class Definition(object):
"""Definition objects describe a unique definition of a variable.
- Subclasses of this may be used by passing an appropriate factory fuction to
+ Subclasses of this may be used by passing an appropriate factory function to
resolve.
Attributes:
diff --git a/tensorflow/contrib/autograph/pyct/testing/BUILD b/tensorflow/contrib/autograph/pyct/testing/BUILD
index 957db356f7..9ef1ac9663 100644
--- a/tensorflow/contrib/autograph/pyct/testing/BUILD
+++ b/tensorflow/contrib/autograph/pyct/testing/BUILD
@@ -33,7 +33,10 @@ py_test(
size = "large",
srcs = ["codegen_test.py"],
srcs_version = "PY2AND3",
- tags = ["no_windows"],
+ tags = [
+ "no_windows",
+ "nomsan",
+ ],
deps = [
":testing",
"//tensorflow/contrib/autograph/pyct",
diff --git a/tensorflow/contrib/autograph/utils/builtins.py b/tensorflow/contrib/autograph/utils/builtins.py
index ccbe5fc954..4dd440ef19 100644
--- a/tensorflow/contrib/autograph/utils/builtins.py
+++ b/tensorflow/contrib/autograph/utils/builtins.py
@@ -44,6 +44,8 @@ def dynamic_builtin(f, *args, **kwargs):
return dynamic_int(*args, **kwargs)
if f is float:
return dynamic_float(*args, **kwargs)
+ if f is abs:
+ return dynamic_abs(*args, **kwargs)
raise NotImplementedError(
'The "%s" builtin is not yet supported.' % f.__name__)
@@ -81,6 +83,13 @@ def dynamic_float(num_or_tensor, **kwargs):
return float(num_or_tensor)
+def dynamic_abs(num_or_tensor, **kwargs):
+ if tensor_util.is_tensor(num_or_tensor):
+ return math_ops.abs(num_or_tensor, **kwargs)
+ else:
+ return abs(num_or_tensor, **kwargs)
+
+
def dynamic_range(start_or_stop, stop=None, step=None):
"""Implementation of range using dynamic dispatch."""
if type_check.is_tensor(start_or_stop, stop, step):
diff --git a/tensorflow/contrib/autograph/utils/builtins_test.py b/tensorflow/contrib/autograph/utils/builtins_test.py
index b4821f36fc..b1cd5253bc 100644
--- a/tensorflow/contrib/autograph/utils/builtins_test.py
+++ b/tensorflow/contrib/autograph/utils/builtins_test.py
@@ -44,6 +44,23 @@ class BuiltinsTest(test.TestCase):
with self.test_session() as sess:
self.assertEqual(3, sess.run(builtins.dynamic_builtin(len, a)))
+ def test_dynamic_abs_tf_scalar(self):
+ a = constant_op.constant(-1)
+
+ with self.test_session() as sess:
+ self.assertEqual(1, sess.run(builtins.dynamic_builtin(abs, a)))
+
+ def test_dynamic_abs_tf_array(self):
+ a = constant_op.constant([-1, 2, -3])
+
+ with self.test_session() as sess:
+ self.assertListEqual([1, 2, 3],
+ list(sess.run(builtins.dynamic_builtin(abs, a))))
+
+ def test_dynamic_abs_py_scalar(self):
+ a = -1
+ self.assertEqual(1, builtins.dynamic_builtin(abs, a))
+
def test_dynamic_len_tf_matrix(self):
a = constant_op.constant([[1, 2], [3, 4]])
diff --git a/tensorflow/contrib/bayesflow/python/ops/monte_carlo_impl.py b/tensorflow/contrib/bayesflow/python/ops/monte_carlo_impl.py
index 68ead2f760..9afe3df585 100644
--- a/tensorflow/contrib/bayesflow/python/ops/monte_carlo_impl.py
+++ b/tensorflow/contrib/bayesflow/python/ops/monte_carlo_impl.py
@@ -14,8 +14,6 @@
# ==============================================================================
"""Monte Carlo integration and helpers.
-See the @{$python/contrib.bayesflow.monte_carlo} guide.
-
@@expectation
@@expectation_importance_sampler
@@expectation_importance_sampler_logspace
diff --git a/tensorflow/contrib/bigtable/README.md b/tensorflow/contrib/bigtable/README.md
index 88a3909de4..b9abfa8295 100644
--- a/tensorflow/contrib/bigtable/README.md
+++ b/tensorflow/contrib/bigtable/README.md
@@ -1,4 +1,4 @@
-# Bigtable #
+# Google Cloud Bigtable
[Cloud Bigtable](https://cloud.google.com/bigtable/) is a high
performance storage system that can store and serve training data. This contrib
@@ -13,7 +13,7 @@ Bigtable at high speed, in particular to feed modern accelerators. For
general-purpose Cloud Bigtable
APIs, see the [official Cloud Bigtable client library documentation][clientdoc].
-[clientdoc]: https://cloud.google.com/bigtable/docs/reference/libraries
+[clientdoc]: https://cloud.google.com/bigtable/docs/reference/libraries
## Sample Use
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_kernels.cc b/tensorflow/contrib/bigtable/kernels/bigtable_kernels.cc
index a6755a3496..a25a641cdb 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_kernels.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_kernels.cc
@@ -84,6 +84,8 @@ class BigtableClientOp : public OpKernel {
channel_args.SetMaxReceiveMessageSize(
max_receive_message_size_);
channel_args.SetUserAgentPrefix("tensorflow");
+ channel_args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0);
+ channel_args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 60 * 1000);
client_options.set_channel_arguments(channel_args);
std::shared_ptr<google::cloud::bigtable::DataClient> client =
google::cloud::bigtable::CreateDefaultDataClient(
@@ -216,11 +218,11 @@ class ToBigtableOp : public AsyncOpKernel {
OP_REQUIRES_OK_ASYNC(
ctx, GetDatasetFromVariantTensor(ctx->input(1), &dataset), done);
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iterator;
OP_REQUIRES_OK_ASYNC(
ctx,
- dataset->MakeIterator(&iter_ctx, "ToBigtableOpIterator", &iterator),
+ dataset->MakeIterator(IteratorContext(ctx), "ToBigtableOpIterator",
+ &iterator),
done);
int64 timestamp_int;
@@ -243,9 +245,10 @@ class ToBigtableOp : public AsyncOpKernel {
::google::cloud::bigtable::BulkMutation mutation;
// TODO(saeta): Make # of mutations configurable.
for (uint64 i = 0; i < 100 && !end_of_sequence; ++i) {
- OP_REQUIRES_OK_ASYNC(
- ctx, iterator->GetNext(&iter_ctx, &components, &end_of_sequence),
- done);
+ OP_REQUIRES_OK_ASYNC(ctx,
+ iterator->GetNext(IteratorContext(ctx),
+ &components, &end_of_sequence),
+ done);
if (!end_of_sequence) {
OP_REQUIRES_OK_ASYNC(
ctx,
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_lookup_dataset_op.cc b/tensorflow/contrib/bigtable/kernels/bigtable_lookup_dataset_op.cc
index 9e49fa35db..bd32672aa9 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_lookup_dataset_op.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_lookup_dataset_op.cc
@@ -53,7 +53,7 @@ class BigtableLookupDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input,
BigtableTableResource* table,
@@ -61,7 +61,7 @@ class BigtableLookupDatasetOp : public UnaryDatasetOpKernel {
std::vector<string> columns,
const DataTypeVector& output_types,
std::vector<PartialTensorShape> output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
table_(table),
column_families_(std::move(column_families)),
@@ -80,8 +80,8 @@ class BigtableLookupDatasetOp : public UnaryDatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
- return std::unique_ptr<IteratorBase>(new Iterator(
- {this, strings::StrCat(prefix, "::BigtableLookupDataset")}));
+ return std::unique_ptr<IteratorBase>(
+ new Iterator({this, strings::StrCat(prefix, "::BigtableLookup")}));
}
const DataTypeVector& output_dtypes() const override {
@@ -96,6 +96,14 @@ class BigtableLookupDatasetOp : public UnaryDatasetOpKernel {
return "BigtableLookupDatasetOp::Dataset";
}
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
static ::google::cloud::bigtable::Filter MakeFilter(
const std::vector<string>& column_families,
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_prefix_key_dataset_op.cc b/tensorflow/contrib/bigtable/kernels/bigtable_prefix_key_dataset_op.cc
index e960719614..a803fdcb49 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_prefix_key_dataset_op.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_prefix_key_dataset_op.cc
@@ -35,11 +35,13 @@ class BigtablePrefixKeyDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, BigtableTableResource* table,
string prefix)
- : GraphDatasetBase(ctx), table_(table), prefix_(std::move(prefix)) {
+ : DatasetBase(DatasetContext(ctx)),
+ table_(table),
+ prefix_(std::move(prefix)) {
table_->Ref();
}
@@ -47,8 +49,8 @@ class BigtablePrefixKeyDatasetOp : public DatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
- return std::unique_ptr<IteratorBase>(new Iterator(
- {this, strings::StrCat(prefix, "::BigtablePrefixKeyDataset")}));
+ return std::unique_ptr<IteratorBase>(
+ new Iterator({this, strings::StrCat(prefix, "::BigtablePrefixKey")}));
}
const DataTypeVector& output_dtypes() const override {
@@ -68,6 +70,14 @@ class BigtablePrefixKeyDatasetOp : public DatasetOpKernel {
BigtableTableResource* table() const { return table_; }
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
class Iterator : public BigtableReaderDatasetIterator<Dataset> {
public:
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_range_key_dataset_op.cc b/tensorflow/contrib/bigtable/kernels/bigtable_range_key_dataset_op.cc
index 96d3565d9b..5cd0371c79 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_range_key_dataset_op.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_range_key_dataset_op.cc
@@ -39,11 +39,11 @@ class BigtableRangeKeyDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, BigtableTableResource* table,
string start_key, string end_key)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
table_(table),
start_key_(std::move(start_key)),
end_key_(std::move(end_key)) {
@@ -54,8 +54,8 @@ class BigtableRangeKeyDatasetOp : public DatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
- return std::unique_ptr<IteratorBase>(new Iterator(
- {this, strings::StrCat(prefix, "::BigtableRangeKeyDataset")}));
+ return std::unique_ptr<IteratorBase>(
+ new Iterator({this, strings::StrCat(prefix, "::BigtableRangeKey")}));
}
const DataTypeVector& output_dtypes() const override {
@@ -75,6 +75,14 @@ class BigtableRangeKeyDatasetOp : public DatasetOpKernel {
BigtableTableResource* table() const { return table_; }
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
class Iterator : public BigtableReaderDatasetIterator<Dataset> {
public:
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_sample_key_pairs_dataset_op.cc b/tensorflow/contrib/bigtable/kernels/bigtable_sample_key_pairs_dataset_op.cc
index a1a63a975a..6928d9423c 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_sample_key_pairs_dataset_op.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_sample_key_pairs_dataset_op.cc
@@ -52,11 +52,11 @@ class BigtableSampleKeyPairsDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, BigtableTableResource* table,
string prefix, string start_key, string end_key)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
table_(table),
key_range_(MakeMultiModeKeyRange(
std::move(prefix), std::move(start_key), std::move(end_key))) {
@@ -68,7 +68,7 @@ class BigtableSampleKeyPairsDatasetOp : public DatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(new Iterator(
- {this, strings::StrCat(prefix, "::BigtableSampleKeyPairsDataset")}));
+ {this, strings::StrCat(prefix, "::BigtableSampleKeyPairs")}));
}
const DataTypeVector& output_dtypes() const override {
@@ -87,6 +87,14 @@ class BigtableSampleKeyPairsDatasetOp : public DatasetOpKernel {
return "BigtableSampleKeyPairsDatasetOp::Dataset";
}
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
static MultiModeKeyRange MakeMultiModeKeyRange(string prefix,
string start_key,
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_sample_keys_dataset_op.cc b/tensorflow/contrib/bigtable/kernels/bigtable_sample_keys_dataset_op.cc
index a5a47cfe2d..a759fb5063 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_sample_keys_dataset_op.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_sample_keys_dataset_op.cc
@@ -31,10 +31,10 @@ class BigtableSampleKeysDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, BigtableTableResource* table)
- : GraphDatasetBase(ctx), table_(table) {
+ : DatasetBase(DatasetContext(ctx)), table_(table) {
table_->Ref();
}
@@ -43,7 +43,7 @@ class BigtableSampleKeysDatasetOp : public DatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return std::unique_ptr<IteratorBase>(new Iterator(
- {this, strings::StrCat(prefix, "::BigtableSampleKeysDataset")}));
+ {this, strings::StrCat(prefix, "::BigtableSampleKeys")}));
}
const DataTypeVector& output_dtypes() const override {
@@ -63,6 +63,14 @@ class BigtableSampleKeysDatasetOp : public DatasetOpKernel {
BigtableTableResource* table() const { return table_; }
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
class Iterator : public DatasetIterator<Dataset> {
public:
diff --git a/tensorflow/contrib/bigtable/kernels/bigtable_scan_dataset_op.cc b/tensorflow/contrib/bigtable/kernels/bigtable_scan_dataset_op.cc
index 13cb868167..78a920b077 100644
--- a/tensorflow/contrib/bigtable/kernels/bigtable_scan_dataset_op.cc
+++ b/tensorflow/contrib/bigtable/kernels/bigtable_scan_dataset_op.cc
@@ -84,7 +84,7 @@ class BigtableScanDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, BigtableTableResource* table,
string prefix, string start_key, string end_key,
@@ -92,7 +92,7 @@ class BigtableScanDatasetOp : public DatasetOpKernel {
std::vector<string> columns, float probability,
const DataTypeVector& output_types,
std::vector<PartialTensorShape> output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
table_(table),
prefix_(std::move(prefix)),
start_key_(std::move(start_key)),
@@ -111,8 +111,8 @@ class BigtableScanDatasetOp : public DatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
- return std::unique_ptr<IteratorBase>(new Iterator(
- {this, strings::StrCat(prefix, "::BigtableScanDataset")}));
+ return std::unique_ptr<IteratorBase>(
+ new Iterator({this, strings::StrCat(prefix, "::BigtableScan")}));
}
const DataTypeVector& output_dtypes() const override {
@@ -129,6 +129,14 @@ class BigtableScanDatasetOp : public DatasetOpKernel {
BigtableTableResource* table() const { return table_; }
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
class Iterator : public BigtableReaderDatasetIterator<Dataset> {
public:
diff --git a/tensorflow/contrib/bigtable/python/ops/bigtable_api.py b/tensorflow/contrib/bigtable/python/ops/bigtable_api.py
index e6ef513c40..3e1b622867 100644
--- a/tensorflow/contrib/bigtable/python/ops/bigtable_api.py
+++ b/tensorflow/contrib/bigtable/python/ops/bigtable_api.py
@@ -17,8 +17,8 @@
TensorFlow has support for reading from and writing to Cloud Bigtable. To use
TensorFlow + Cloud Bigtable integration, first create a BigtableClient to
configure your connection to Cloud Bigtable, and then create a BigtableTable
-object to allow you to create numerous @{tf.data.Dataset}s to read data, or
-write a @{tf.data.Dataset} object to the underlying Cloud Bigtable table.
+object to allow you to create numerous `tf.data.Dataset`s to read data, or
+write a `tf.data.Dataset` object to the underlying Cloud Bigtable table.
For background on Cloud Bigtable, see: https://cloud.google.com/bigtable .
"""
@@ -203,7 +203,7 @@ class BigtableTable(object):
be retrieved. If end is None, all subsequent row keys will be retrieved.
Returns:
- A @{tf.data.Dataset} containing `tf.string` Tensors corresponding to all
+ A `tf.data.Dataset` containing `tf.string` Tensors corresponding to all
of the row keys between `start` and `end`.
"""
# TODO(saeta): Make inclusive / exclusive configurable?
@@ -219,7 +219,7 @@ class BigtableTable(object):
retrieved.
Returns:
- A @{tf.data.Dataset}. containing `tf.string` Tensors corresponding to all
+ A `tf.data.Dataset`. containing `tf.string` Tensors corresponding to all
of the row keys matching that prefix.
"""
return _BigtablePrefixKeyDataset(self, prefix)
@@ -228,11 +228,11 @@ class BigtableTable(object):
"""Retrieves a sampling of row keys from the Bigtable table.
This dataset is most often used in conjunction with
- @{tf.contrib.data.parallel_interleave} to construct a set of ranges for
+ `tf.contrib.data.parallel_interleave` to construct a set of ranges for
scanning in parallel.
Returns:
- A @{tf.data.Dataset} returning string row keys.
+ A `tf.data.Dataset` returning string row keys.
"""
return _BigtableSampleKeysDataset(self)
@@ -272,7 +272,7 @@ class BigtableTable(object):
that are treated as the column qualifier (column name).
Returns:
- A @{tf.data.Dataset} returning the row keys and the cell contents.
+ A `tf.data.Dataset` returning the row keys and the cell contents.
Raises:
ValueError: If the configured probability is unexpected.
@@ -317,7 +317,7 @@ class BigtableTable(object):
that are treated as the column qualifier (column name).
Returns:
- A @{tf.data.Dataset} returning the row keys and the cell contents.
+ A `tf.data.Dataset` returning the row keys and the cell contents.
Raises:
ValueError: If the configured probability is unexpected.
@@ -335,7 +335,7 @@ class BigtableTable(object):
"""Retrieves row (including values) from the Bigtable service at high speed.
Rows with row-key prefixed by `prefix` will be retrieved. This method is
- similar to `scan_prefix`, but by constrast performs multiple sub-scans in
+ similar to `scan_prefix`, but by contrast performs multiple sub-scans in
parallel in order to achieve higher performance.
Note: The dataset produced by this method is not deterministic!
@@ -373,7 +373,7 @@ class BigtableTable(object):
that are treated as the column qualifier (column name).
Returns:
- A @{tf.data.Dataset} returning the row keys and the cell contents.
+ A `tf.data.Dataset` returning the row keys and the cell contents.
Raises:
ValueError: If the configured probability is unexpected.
@@ -394,7 +394,7 @@ class BigtableTable(object):
"""Retrieves rows (including values) from the Bigtable service.
Rows with row-keys between `start` and `end` will be retrieved. This method
- is similar to `scan_range`, but by constrast performs multiple sub-scans in
+ is similar to `scan_range`, but by contrast performs multiple sub-scans in
parallel in order to achieve higher performance.
Note: The dataset produced by this method is not deterministic!
@@ -435,7 +435,7 @@ class BigtableTable(object):
that are treated as the column qualifier (column name).
Returns:
- A @{tf.data.Dataset} returning the row keys and the cell contents.
+ A `tf.data.Dataset` returning the row keys and the cell contents.
Raises:
ValueError: If the configured probability is unexpected.
@@ -450,12 +450,12 @@ class BigtableTable(object):
"""Writes a dataset to the table.
Args:
- dataset: A @{tf.data.Dataset} to be written to this table. It must produce
+ dataset: A `tf.data.Dataset` to be written to this table. It must produce
a list of number-of-columns+1 elements, all of which must be strings.
The first value will be used as the row key, and subsequent values will
be used as cell values for the corresponding columns from the
corresponding column_families and columns entries.
- column_families: A @{tf.Tensor} of `tf.string`s corresponding to the
+ column_families: A `tf.Tensor` of `tf.string`s corresponding to the
column names to store the dataset's elements into.
columns: A `tf.Tensor` of `tf.string`s corresponding to the column names
to store the dataset's elements into.
@@ -463,7 +463,7 @@ class BigtableTable(object):
Leave as None to use server-provided timestamps.
Returns:
- A @{tf.Operation} that can be run to perform the write.
+ A `tf.Operation` that can be run to perform the write.
Raises:
ValueError: If there are unexpected or incompatible types, or if the
@@ -502,7 +502,7 @@ class BigtableTable(object):
normalized_columns: The column families and column qualifiers to retrieve.
Returns:
- A @{tf.data.Dataset} representing the result of the parallel scan.
+ A `tf.data.Dataset` representing the result of the parallel scan.
"""
if num_parallel_scans is None:
num_parallel_scans = 50
diff --git a/tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py b/tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py
index 68d710d713..c155128c0e 100644
--- a/tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py
+++ b/tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py
@@ -16,7 +16,10 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+
import tempfile
+import numpy as np
+
from tensorflow.contrib.boosted_trees.estimator_batch import estimator
from tensorflow.contrib.boosted_trees.proto import learner_pb2
from tensorflow.contrib.layers.python.layers import feature_column as contrib_feature_column
@@ -26,6 +29,7 @@ from tensorflow.python.feature_column import feature_column_lib as core_feature_
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
+from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import gfile
@@ -473,6 +477,63 @@ class CoreGradientBoostedDecisionTreeEstimators(test_util.TensorFlowTestCase):
classifier.evaluate(input_fn=_multiclass_train_input_fn, steps=1)
classifier.predict(input_fn=_eval_input_fn)
+ def testWeightedCategoricalColumn(self):
+ head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(
+ loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
+
+ learner_config = learner_pb2.LearnerConfig()
+ learner_config.num_classes = 2
+ learner_config.constraints.max_tree_depth = 1
+ model_dir = tempfile.mkdtemp()
+ config = run_config.RunConfig()
+
+ feature_columns = [
+ core_feature_column.weighted_categorical_column(
+ categorical_column=core_feature_column.
+ categorical_column_with_vocabulary_list(
+ key="word", vocabulary_list=["the", "cat", "dog"]),
+ weight_feature_key="weight")
+ ]
+
+ labels = np.array([[1], [1], [0], [0.]], dtype=np.float32)
+
+ def _make_input_fn():
+
+ def _input_fn():
+ features_dict = {}
+ # Sparse tensor representing
+ # example 0: "cat","the"
+ # examaple 1: "dog"
+ # example 2: -
+ # example 3: "the"
+ # Weights for the words are 5 - cat, 6- dog and 1 -the.
+ features_dict["word"] = sparse_tensor.SparseTensor(
+ indices=[[0, 0], [0, 1], [1, 0], [3, 0]],
+ values=constant_op.constant(
+ ["the", "cat", "dog", "the"], dtype=dtypes.string),
+ dense_shape=[4, 3])
+ features_dict["weight"] = sparse_tensor.SparseTensor(
+ indices=[[0, 0], [0, 1], [1, 0], [3, 0]],
+ values=[1., 5., 6., 1.],
+ dense_shape=[4, 3])
+ return features_dict, labels
+
+ return _input_fn
+
+ est = estimator.CoreGradientBoostedDecisionTreeEstimator(
+ head=head_fn,
+ learner_config=learner_config,
+ num_trees=1,
+ examples_per_layer=3,
+ model_dir=model_dir,
+ config=config,
+ feature_columns=feature_columns)
+
+ input_fn = _make_input_fn()
+ est.train(input_fn=input_fn, steps=100)
+ est.evaluate(input_fn=input_fn, steps=1)
+ est.predict(input_fn=input_fn)
+
if __name__ == "__main__":
googletest.main()
diff --git a/tensorflow/contrib/boosted_trees/kernels/split_handler_ops.cc b/tensorflow/contrib/boosted_trees/kernels/split_handler_ops.cc
index 401bec84a2..d9e7a0f466 100644
--- a/tensorflow/contrib/boosted_trees/kernels/split_handler_ops.cc
+++ b/tensorflow/contrib/boosted_trees/kernels/split_handler_ops.cc
@@ -34,7 +34,9 @@
namespace tensorflow {
+using boosted_trees::learner::LearnerConfig;
using boosted_trees::learner::LearnerConfig_MultiClassStrategy;
+using boosted_trees::learner::ObliviousSplitInfo;
using boosted_trees::learner::SplitInfo;
using boosted_trees::learner::stochastic::GradientStats;
using boosted_trees::learner::stochastic::NodeStats;
@@ -158,6 +160,11 @@ class BuildDenseInequalitySplitsOp : public OpKernel {
const Tensor* hessians_t;
OP_REQUIRES_OK(context, context->input("hessians", &hessians_t));
+ const Tensor* weak_learner_type_t;
+ OP_REQUIRES_OK(context,
+ context->input("weak_learner_type", &weak_learner_type_t));
+ const int32 weak_learner_type = weak_learner_type_t->scalar<int32>()();
+
// Find the number of unique partitions before we allocate the output.
std::vector<int32> partition_boundaries;
partition_boundaries.push_back(0);
@@ -188,20 +195,59 @@ class BuildDenseInequalitySplitsOp : public OpKernel {
tensorflow::TTypes<int32>::Vec output_partition_ids =
output_partition_ids_t->vec<int32>();
- Tensor* gains_t = nullptr;
- OP_REQUIRES_OK(
- context, context->allocate_output("gains", TensorShape({num_elements}),
- &gains_t));
+ // For a normal tree, we output a split per partition. For an oblivious
+ // tree, we output one split for all partitions of the layer
+ int32 size_output = num_elements;
+ if (weak_learner_type == LearnerConfig::OBLIVIOUS_DECISION_TREE &&
+ num_elements > 0) {
+ size_output = 1;
+ }
+ Tensor* gains_t = nullptr;
+ OP_REQUIRES_OK(context, context->allocate_output(
+ "gains", TensorShape({size_output}), &gains_t));
tensorflow::TTypes<float>::Vec gains = gains_t->vec<float>();
Tensor* output_splits_t = nullptr;
- OP_REQUIRES_OK(context, context->allocate_output(
- "split_infos", TensorShape({num_elements}),
- &output_splits_t));
+ OP_REQUIRES_OK(context, context->allocate_output("split_infos",
+ TensorShape({size_output}),
+ &output_splits_t));
tensorflow::TTypes<string>::Vec output_splits =
output_splits_t->vec<string>();
+
+ if (num_elements == 0) {
+ return;
+ }
SplitBuilderState state(context);
+ switch (weak_learner_type) {
+ case LearnerConfig::NORMAL_DECISION_TREE: {
+ ComputeNormalDecisionTree(
+ &state, normalizer_ratio, num_elements, partition_boundaries,
+ bucket_boundaries, partition_ids, bucket_ids, gradients_t,
+ hessians_t, &output_partition_ids, &gains, &output_splits);
+ break;
+ }
+ case LearnerConfig::OBLIVIOUS_DECISION_TREE: {
+ ComputeObliviousDecisionTree(
+ &state, normalizer_ratio, num_elements, partition_boundaries,
+ bucket_boundaries, partition_ids, bucket_ids, gradients_t,
+ hessians_t, &output_partition_ids, &gains, &output_splits);
+ break;
+ }
+ }
+ }
+
+ private:
+ void ComputeNormalDecisionTree(
+ SplitBuilderState* state, const float normalizer_ratio,
+ const int num_elements, const std::vector<int32>& partition_boundaries,
+ const tensorflow::TTypes<float>::ConstVec& bucket_boundaries,
+ const tensorflow::TTypes<int32>::ConstVec& partition_ids,
+ const tensorflow::TTypes<int64>::ConstMatrix& bucket_ids,
+ const Tensor* gradients_t, const Tensor* hessians_t,
+ tensorflow::TTypes<int32>::Vec* output_partition_ids,
+ tensorflow::TTypes<float>::Vec* gains,
+ tensorflow::TTypes<string>::Vec* output_splits) {
for (int root_idx = 0; root_idx < num_elements; ++root_idx) {
float best_gain = std::numeric_limits<float>::lowest();
int start_index = partition_boundaries[root_idx];
@@ -213,7 +259,7 @@ class BuildDenseInequalitySplitsOp : public OpKernel {
GradientStats(*gradients_t, *hessians_t, bucket_idx);
}
root_gradient_stats *= normalizer_ratio;
- NodeStats root_stats = state.ComputeNodeStats(root_gradient_stats);
+ NodeStats root_stats = state->ComputeNodeStats(root_gradient_stats);
int32 best_bucket_idx = 0;
NodeStats best_right_node_stats(0);
NodeStats best_left_node_stats(0);
@@ -223,10 +269,10 @@ class BuildDenseInequalitySplitsOp : public OpKernel {
GradientStats g(*gradients_t, *hessians_t, bucket_idx);
g *= normalizer_ratio;
left_gradient_stats += g;
- NodeStats left_stats = state.ComputeNodeStats(left_gradient_stats);
+ NodeStats left_stats = state->ComputeNodeStats(left_gradient_stats);
GradientStats right_gradient_stats =
root_gradient_stats - left_gradient_stats;
- NodeStats right_stats = state.ComputeNodeStats(right_gradient_stats);
+ NodeStats right_stats = state->ComputeNodeStats(right_gradient_stats);
if (left_stats.gain + right_stats.gain > best_gain) {
best_gain = left_stats.gain + right_stats.gain;
best_left_node_stats = left_stats;
@@ -237,20 +283,124 @@ class BuildDenseInequalitySplitsOp : public OpKernel {
SplitInfo split_info;
auto* dense_split =
split_info.mutable_split_node()->mutable_dense_float_binary_split();
- dense_split->set_feature_column(state.feature_column_group_id());
+ dense_split->set_feature_column(state->feature_column_group_id());
dense_split->set_threshold(
bucket_boundaries(bucket_ids(best_bucket_idx, 0)));
auto* left_child = split_info.mutable_left_child();
auto* right_child = split_info.mutable_right_child();
- state.FillLeaf(best_left_node_stats, left_child);
- state.FillLeaf(best_right_node_stats, right_child);
- split_info.SerializeToString(&output_splits(root_idx));
- gains(root_idx) =
- best_gain - root_stats.gain - state.tree_complexity_regularization();
- output_partition_ids(root_idx) = partition_ids(start_index);
+ state->FillLeaf(best_left_node_stats, left_child);
+ state->FillLeaf(best_right_node_stats, right_child);
+ split_info.SerializeToString(&(*output_splits)(root_idx));
+ (*gains)(root_idx) =
+ best_gain - root_stats.gain - state->tree_complexity_regularization();
+ (*output_partition_ids)(root_idx) = partition_ids(start_index);
+ }
+ }
+ void ComputeObliviousDecisionTree(
+ SplitBuilderState* state, const float normalizer_ratio,
+ const int num_elements, const std::vector<int32>& partition_boundaries,
+ const tensorflow::TTypes<float>::ConstVec& bucket_boundaries,
+ const tensorflow::TTypes<int32>::ConstVec& partition_ids,
+ const tensorflow::TTypes<int64>::ConstMatrix& bucket_ids,
+ const Tensor* gradients_t, const Tensor* hessians_t,
+ tensorflow::TTypes<int32>::Vec* output_partition_ids,
+ tensorflow::TTypes<float>::Vec* gains,
+ tensorflow::TTypes<string>::Vec* output_splits) {
+ // Holds the root stats per each node to be split.
+ std::vector<GradientStats> current_layer_stats;
+ current_layer_stats.reserve(num_elements);
+ for (int root_idx = 0; root_idx < num_elements; root_idx++) {
+ const int start_index = partition_boundaries[root_idx];
+ const int end_index = partition_boundaries[root_idx + 1];
+ GradientStats root_gradient_stats;
+ for (int64 bucket_idx = start_index; bucket_idx < end_index;
+ ++bucket_idx) {
+ root_gradient_stats +=
+ GradientStats(*gradients_t, *hessians_t, bucket_idx);
+ }
+ root_gradient_stats *= normalizer_ratio;
+ current_layer_stats.push_back(root_gradient_stats);
+ }
+
+ float best_gain = std::numeric_limits<float>::lowest();
+ int64 best_bucket_idx = 0;
+ std::vector<NodeStats> best_right_node_stats(num_elements, NodeStats(0));
+ std::vector<NodeStats> best_left_node_stats(num_elements, NodeStats(0));
+ std::vector<NodeStats> current_left_node_stats(num_elements, NodeStats(0));
+ std::vector<NodeStats> current_right_node_stats(num_elements, NodeStats(0));
+ int64 current_bucket_id = 0;
+ int64 last_bucket_id = -1;
+ // Indexes offsets for each of the partitions that can be used to access
+ // gradients of a partition for a current bucket we consider.
+ std::vector<int> current_layer_offsets(num_elements, 0);
+ std::vector<GradientStats> left_gradient_stats(num_elements);
+ // The idea is to try every bucket id in increasing order. In each iteration
+ // we calculate the gain of the layer using the current bucket id as split
+ // value, and we also obtain the following bucket id to try.
+ while (current_bucket_id > last_bucket_id) {
+ last_bucket_id = current_bucket_id;
+ int64 next_bucket_id = -1;
+ for (int root_idx = 0; root_idx < num_elements; root_idx++) {
+ int idx =
+ current_layer_offsets[root_idx] + partition_boundaries[root_idx];
+ const int end_index = partition_boundaries[root_idx + 1];
+ if (idx < end_index && bucket_ids(idx, 0) == current_bucket_id) {
+ GradientStats g(*gradients_t, *hessians_t, idx);
+ g *= normalizer_ratio;
+ left_gradient_stats[root_idx] += g;
+ current_layer_offsets[root_idx]++;
+ idx++;
+ }
+ if (idx < end_index &&
+ (bucket_ids(idx, 0) < next_bucket_id || next_bucket_id == -1)) {
+ next_bucket_id = bucket_ids(idx, 0);
+ }
+ }
+ float gain_of_split = 0.0;
+ for (int root_idx = 0; root_idx < num_elements; root_idx++) {
+ GradientStats right_gradient_stats =
+ current_layer_stats[root_idx] - left_gradient_stats[root_idx];
+ NodeStats left_stat =
+ state->ComputeNodeStats(left_gradient_stats[root_idx]);
+ NodeStats right_stat = state->ComputeNodeStats(right_gradient_stats);
+ gain_of_split += left_stat.gain + right_stat.gain;
+ current_left_node_stats[root_idx] = left_stat;
+ current_right_node_stats[root_idx] = right_stat;
+ }
+ if (gain_of_split > best_gain) {
+ best_gain = gain_of_split;
+ best_left_node_stats = current_left_node_stats;
+ best_right_node_stats = current_right_node_stats;
+ }
+ current_bucket_id = next_bucket_id;
+ }
+
+ for (int root_idx = 0; root_idx < num_elements; root_idx++) {
+ best_gain -= state->ComputeNodeStats(current_layer_stats[root_idx]).gain;
+ }
+ best_gain -= num_elements * state->tree_complexity_regularization();
+
+ ObliviousSplitInfo oblivious_split_info;
+ auto* oblivious_dense_split = oblivious_split_info.mutable_split_node()
+ ->mutable_dense_float_binary_split();
+ oblivious_dense_split->set_feature_column(state->feature_column_group_id());
+ oblivious_dense_split->set_threshold(
+ bucket_boundaries(bucket_ids(best_bucket_idx, 0)));
+ (*gains)(0) = best_gain;
+
+ for (int root_idx = 0; root_idx < num_elements; root_idx++) {
+ auto* left_children = oblivious_split_info.add_children_leaves();
+ auto* right_children = oblivious_split_info.add_children_leaves();
+
+ state->FillLeaf(best_left_node_stats[root_idx], left_children);
+ state->FillLeaf(best_right_node_stats[root_idx], right_children);
+
+ const int start_index = partition_boundaries[root_idx];
+ (*output_partition_ids)(root_idx) = partition_ids(start_index);
}
+ oblivious_split_info.SerializeToString(&(*output_splits)(0));
}
};
REGISTER_KERNEL_BUILDER(Name("BuildDenseInequalitySplits").Device(DEVICE_CPU),
diff --git a/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py b/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py
index 2559fe9913..f45010ec26 100644
--- a/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py
+++ b/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py
@@ -64,6 +64,7 @@ from __future__ import print_function
import re
from tensorflow.contrib.boosted_trees.lib.learner.batch import base_split_handler
+from tensorflow.contrib.boosted_trees.proto import learner_pb2
from tensorflow.contrib.boosted_trees.python.ops import gen_quantile_ops
from tensorflow.contrib.boosted_trees.python.ops import gen_stats_accumulator_ops
from tensorflow.contrib.boosted_trees.python.ops import quantile_ops
@@ -171,6 +172,7 @@ class DenseSplitHandler(InequalitySplitHandler):
multiclass_strategy,
init_stamp_token=0,
loss_uses_sum_reduction=False,
+ weak_learner_type=learner_pb2.LearnerConfig.NORMAL_DECISION_TREE,
name=None):
"""Initialize the internal state for this split handler.
@@ -192,6 +194,7 @@ class DenseSplitHandler(InequalitySplitHandler):
stamped objects.
loss_uses_sum_reduction: A scalar boolean tensor that specifies whether
SUM or MEAN reduction was used for the loss.
+ weak_learner_type: Specifies the type of weak learner to use.
name: An optional handler name.
"""
super(DenseSplitHandler, self).__init__(
@@ -209,6 +212,7 @@ class DenseSplitHandler(InequalitySplitHandler):
multiclass_strategy=multiclass_strategy,
loss_uses_sum_reduction=loss_uses_sum_reduction)
self._dense_float_column = dense_float_column
+ self._weak_learner_type = weak_learner_type
# Register dense_make_stats_update function as an Op to the graph.
g = ops.get_default_graph()
dense_make_stats_update.add_to_graph(g)
@@ -269,16 +273,17 @@ class DenseSplitHandler(InequalitySplitHandler):
next_stamp_token, self._multiclass_strategy, class_id,
self._feature_column_group_id, self._l1_regularization,
self._l2_regularization, self._tree_complexity_regularization,
- self._min_node_weight, self._loss_uses_sum_reduction))
-
+ self._min_node_weight, self._loss_uses_sum_reduction,
+ self._weak_learner_type))
return are_splits_ready, partition_ids, gains, split_infos
-def _make_dense_split(
- quantile_accumulator_handle, stats_accumulator_handle, stamp_token,
- next_stamp_token, multiclass_strategy, class_id, feature_column_id,
- l1_regularization, l2_regularization, tree_complexity_regularization,
- min_node_weight, is_multi_dimentional, loss_uses_sum_reduction):
+def _make_dense_split(quantile_accumulator_handle, stats_accumulator_handle,
+ stamp_token, next_stamp_token, multiclass_strategy,
+ class_id, feature_column_id, l1_regularization,
+ l2_regularization, tree_complexity_regularization,
+ min_node_weight, is_multi_dimentional,
+ loss_uses_sum_reduction, weak_learner_type):
"""Function that builds splits for a dense feature column."""
# Get the bucket boundaries
are_splits_ready, buckets = (
@@ -327,7 +332,8 @@ def _make_dense_split(
l2_regularization=l2_regularization,
tree_complexity_regularization=tree_complexity_regularization,
min_node_weight=min_node_weight,
- multiclass_strategy=multiclass_strategy))
+ multiclass_strategy=multiclass_strategy,
+ weak_learner_type=weak_learner_type))
return are_splits_ready, partition_ids, gains, split_infos
@@ -507,7 +513,40 @@ def _make_sparse_split(
return are_splits_ready, partition_ids, gains, split_infos
-def _specialize_make_split(func, is_multi_dimentional):
+def _specialize_make_split_dense(func, is_multi_dimentional):
+ """Builds a specialized version of the function."""
+
+ @function.Defun(
+ dtypes.resource,
+ dtypes.resource,
+ dtypes.int64,
+ dtypes.int64,
+ dtypes.int32,
+ dtypes.int32,
+ dtypes.int32,
+ dtypes.float32,
+ dtypes.float32,
+ dtypes.float32,
+ dtypes.float32,
+ dtypes.bool,
+ dtypes.int32,
+ noinline=True)
+ def f(quantile_accumulator_handle, stats_accumulator_handle, stamp_token,
+ next_stamp_token, multiclass_strategy, class_id, feature_column_id,
+ l1_regularization, l2_regularization, tree_complexity_regularization,
+ min_node_weight, loss_uses_sum_reduction, weak_learner_type):
+ """Function that builds splits for a sparse feature column."""
+ return func(quantile_accumulator_handle, stats_accumulator_handle,
+ stamp_token, next_stamp_token, multiclass_strategy, class_id,
+ feature_column_id, l1_regularization, l2_regularization,
+ tree_complexity_regularization, min_node_weight,
+ is_multi_dimentional, loss_uses_sum_reduction,
+ weak_learner_type)
+
+ return f
+
+
+def _specialize_make_split_sparse(func, is_multi_dimentional):
"""Builds a specialized version of the function."""
@function.Defun(
@@ -537,15 +576,17 @@ def _specialize_make_split(func, is_multi_dimentional):
return f
-make_dense_split_scalar = _specialize_make_split(_make_dense_split,
- is_multi_dimentional=False)
-make_dense_split_tensor = _specialize_make_split(_make_dense_split,
- is_multi_dimentional=True)
-make_sparse_split_scalar = _specialize_make_split(_make_sparse_split,
- is_multi_dimentional=False)
-make_sparse_split_tensor = _specialize_make_split(_make_sparse_split,
- is_multi_dimentional=True)
+make_dense_split_scalar = _specialize_make_split_dense(
+ _make_dense_split, is_multi_dimentional=False)
+
+make_dense_split_tensor = _specialize_make_split_dense(
+ _make_dense_split, is_multi_dimentional=True)
+
+make_sparse_split_scalar = _specialize_make_split_sparse(
+ _make_sparse_split, is_multi_dimentional=False)
+make_sparse_split_tensor = _specialize_make_split_sparse(
+ _make_sparse_split, is_multi_dimentional=True)
@function.Defun(
diff --git a/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler_test.py b/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler_test.py
index 5d82c4cae5..6572f2f414 100644
--- a/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler_test.py
+++ b/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler_test.py
@@ -182,6 +182,133 @@ class DenseSplitHandlerTest(test_util.TensorFlowTestCase):
self.assertAllClose(0.52, split_node.threshold, 0.00001)
+ def testObliviousFeatureSplitGeneration(self):
+ with self.test_session() as sess:
+ # The data looks like the following:
+ # Example | Gradients | Partition | Dense Quantile |
+ # i0 | (0.2, 0.12) | 0 | 2 |
+ # i1 | (-0.5, 0.07) | 0 | 2 |
+ # i2 | (1.2, 0.2) | 0 | 0 |
+ # i3 | (4.0, 0.13) | 1 | 1 |
+ dense_column = array_ops.constant([0.62, 0.62, 0.3, 0.52])
+ gradients = array_ops.constant([0.2, -0.5, 1.2, 4.0])
+ hessians = array_ops.constant([0.12, 0.07, 0.2, 0.13])
+ partition_ids = array_ops.constant([0, 0, 0, 1], dtype=dtypes.int32)
+ class_id = -1
+
+ gradient_shape = tensor_shape.scalar()
+ hessian_shape = tensor_shape.scalar()
+ split_handler = ordinal_split_handler.DenseSplitHandler(
+ l1_regularization=0.1,
+ l2_regularization=1.,
+ tree_complexity_regularization=0.,
+ min_node_weight=0.,
+ epsilon=0.001,
+ num_quantiles=10,
+ feature_column_group_id=0,
+ dense_float_column=dense_column,
+ init_stamp_token=0,
+ gradient_shape=gradient_shape,
+ hessian_shape=hessian_shape,
+ multiclass_strategy=learner_pb2.LearnerConfig.TREE_PER_CLASS,
+ weak_learner_type=learner_pb2.LearnerConfig.OBLIVIOUS_DECISION_TREE)
+ resources.initialize_resources(resources.shared_resources()).run()
+
+ empty_gradients, empty_hessians = get_empty_tensors(
+ gradient_shape, hessian_shape)
+ example_weights = array_ops.ones([4, 1], dtypes.float32)
+
+ update_1 = split_handler.update_stats_sync(
+ 0,
+ partition_ids,
+ gradients,
+ hessians,
+ empty_gradients,
+ empty_hessians,
+ example_weights,
+ is_active=array_ops.constant([True, True]))
+ with ops.control_dependencies([update_1]):
+ are_splits_ready = split_handler.make_splits(
+ np.int64(0), np.int64(1), class_id)[0]
+
+ with ops.control_dependencies([are_splits_ready]):
+ update_2 = split_handler.update_stats_sync(
+ 1,
+ partition_ids,
+ gradients,
+ hessians,
+ empty_gradients,
+ empty_hessians,
+ example_weights,
+ is_active=array_ops.constant([True, True]))
+ with ops.control_dependencies([update_2]):
+ are_splits_ready2, partitions, gains, splits = (
+ split_handler.make_splits(np.int64(1), np.int64(2), class_id))
+ are_splits_ready, are_splits_ready2, partitions, gains, splits = (
+ sess.run([
+ are_splits_ready, are_splits_ready2, partitions, gains, splits
+ ]))
+
+ # During the first iteration, inequality split handlers are not going to
+ # have any splits. Make sure that we return not_ready in that case.
+ self.assertFalse(are_splits_ready)
+ self.assertTrue(are_splits_ready2)
+
+ self.assertAllEqual([0, 1], partitions)
+
+ oblivious_split_info = split_info_pb2.ObliviousSplitInfo()
+ oblivious_split_info.ParseFromString(splits[0])
+ split_node = oblivious_split_info.split_node.dense_float_binary_split
+
+ self.assertAllClose(0.3, split_node.threshold, 0.00001)
+ self.assertEqual(0, split_node.feature_column)
+
+ # Check the split on partition 0.
+ # -(1.2 - 0.1) / (0.2 + 1)
+ expected_left_weight_0 = -0.9166666666666666
+
+ # expected_left_weight_0 * -(1.2 - 0.1)
+ expected_left_gain_0 = 1.008333333333333
+
+ # (-0.5 + 0.2 + 0.1) / (0.19 + 1)
+ expected_right_weight_0 = 0.1680672
+
+ # expected_right_weight_0 * -(-0.5 + 0.2 + 0.1))
+ expected_right_gain_0 = 0.033613445378151252
+
+ # (0.2 + -0.5 + 1.2 - 0.1) ** 2 / (0.12 + 0.07 + 0.2 + 1)
+ expected_bias_gain_0 = 0.46043165467625896
+
+ left_child = oblivious_split_info.children_leaves[0].vector
+ right_child = oblivious_split_info.children_leaves[1].vector
+
+ self.assertAllClose([expected_left_weight_0], left_child.value, 0.00001)
+
+ self.assertAllClose([expected_right_weight_0], right_child.value, 0.00001)
+
+ # Check the split on partition 1.
+ expected_left_weight_1 = 0
+ expected_left_gain_1 = 0
+ # -(4 - 0.1) / (0.13 + 1)
+ expected_right_weight_1 = -3.4513274336283186
+ # expected_right_weight_1 * -(4 - 0.1)
+ expected_right_gain_1 = 13.460176991150442
+ # (-4 + 0.1) ** 2 / (0.13 + 1)
+ expected_bias_gain_1 = 13.460176991150442
+
+ left_child = oblivious_split_info.children_leaves[2].vector
+ right_child = oblivious_split_info.children_leaves[3].vector
+
+ self.assertAllClose([expected_left_weight_1], left_child.value, 0.00001)
+
+ self.assertAllClose([expected_right_weight_1], right_child.value, 0.00001)
+
+ # The layer gain is the sum of the gains of each partition
+ layer_gain = (
+ expected_left_gain_0 + expected_right_gain_0 - expected_bias_gain_0) + (
+ expected_left_gain_1 + expected_right_gain_1 - expected_bias_gain_1)
+ self.assertAllClose(layer_gain, gains[0], 0.00001)
+
def testGenerateFeatureSplitCandidatesLossUsesSumReduction(self):
with self.test_session() as sess:
# The data looks like the following:
diff --git a/tensorflow/contrib/boosted_trees/ops/split_handler_ops.cc b/tensorflow/contrib/boosted_trees/ops/split_handler_ops.cc
index ca5c7f3d8c..9b68a9de96 100644
--- a/tensorflow/contrib/boosted_trees/ops/split_handler_ops.cc
+++ b/tensorflow/contrib/boosted_trees/ops/split_handler_ops.cc
@@ -36,6 +36,7 @@ REGISTER_OP("BuildDenseInequalitySplits")
.Input("tree_complexity_regularization: float")
.Input("min_node_weight: float")
.Input("multiclass_strategy: int32")
+ .Input("weak_learner_type: int32")
.Output("output_partition_ids: int32")
.Output("gains: float32")
.Output("split_infos: string")
@@ -84,6 +85,8 @@ min_node_weight: A scalar, minimum sum of example hessian needed in a child.
be considered.
multiclass_strategy: A scalar, specifying the multiclass handling strategy.
See LearnerConfig.MultiClassStrategy for valid values.
+weak_learner_type: A scalar, specifying the weak learner type to use.
+ See LearnerConfig.WeakLearnerType for valid values.
output_partition_ids: A rank 1 tensor, the partition IDs that we created splits
for.
gains: A rank 1 tensor, for the computed gain for the created splits.
diff --git a/tensorflow/contrib/boosted_trees/proto/learner.proto b/tensorflow/contrib/boosted_trees/proto/learner.proto
index d84ba7438e..c49cb48cde 100644
--- a/tensorflow/contrib/boosted_trees/proto/learner.proto
+++ b/tensorflow/contrib/boosted_trees/proto/learner.proto
@@ -108,6 +108,11 @@ message LearnerConfig {
DIAGONAL_HESSIAN = 3;
}
+ enum WeakLearnerType {
+ NORMAL_DECISION_TREE = 0;
+ OBLIVIOUS_DECISION_TREE = 1;
+ }
+
// Number of classes.
uint32 num_classes = 1;
@@ -141,4 +146,7 @@ message LearnerConfig {
// If you want to average the ensembles (for regularization), provide the
// config below.
AveragingConfig averaging_config = 11;
+
+ // By default we use NORMAL_DECISION_TREE as weak learner.
+ WeakLearnerType weak_learner_type = 12;
}
diff --git a/tensorflow/contrib/boosted_trees/proto/split_info.proto b/tensorflow/contrib/boosted_trees/proto/split_info.proto
index a300c24c8e..850340f5c2 100644
--- a/tensorflow/contrib/boosted_trees/proto/split_info.proto
+++ b/tensorflow/contrib/boosted_trees/proto/split_info.proto
@@ -17,3 +17,10 @@ message SplitInfo {
// Right Leaf node.
tensorflow.boosted_trees.trees.Leaf right_child = 3;
}
+
+message ObliviousSplitInfo {
+ // The split node with the feature_column and threshold defined.
+ tensorflow.boosted_trees.trees.TreeNode split_node = 1;
+ // The new leaves of the tree.
+ repeated tensorflow.boosted_trees.trees.Leaf children_leaves = 2;
+}
diff --git a/tensorflow/contrib/boosted_trees/python/kernel_tests/split_handler_ops_test.py b/tensorflow/contrib/boosted_trees/python/kernel_tests/split_handler_ops_test.py
index 5cd37ec67e..2589504762 100644
--- a/tensorflow/contrib/boosted_trees/python/kernel_tests/split_handler_ops_test.py
+++ b/tensorflow/contrib/boosted_trees/python/kernel_tests/split_handler_ops_test.py
@@ -59,7 +59,8 @@ class SplitHandlerOpsTest(test_util.TensorFlowTestCase):
min_node_weight=0,
class_id=-1,
feature_column_group_id=0,
- multiclass_strategy=learner_pb2.LearnerConfig.TREE_PER_CLASS))
+ multiclass_strategy=learner_pb2.LearnerConfig.TREE_PER_CLASS,
+ weak_learner_type=learner_pb2.LearnerConfig.NORMAL_DECISION_TREE))
partitions, gains, splits = sess.run([partitions, gains, splits])
self.assertAllEqual([0, 1], partitions)
@@ -132,7 +133,8 @@ class SplitHandlerOpsTest(test_util.TensorFlowTestCase):
min_node_weight=0,
class_id=-1,
feature_column_group_id=0,
- multiclass_strategy=learner_pb2.LearnerConfig.FULL_HESSIAN))
+ multiclass_strategy=learner_pb2.LearnerConfig.FULL_HESSIAN,
+ weak_learner_type=learner_pb2.LearnerConfig.NORMAL_DECISION_TREE))
partitions, gains, splits = sess.run([partitions, gains, splits])
self.assertAllEqual([0, 1], partitions)
@@ -171,7 +173,8 @@ class SplitHandlerOpsTest(test_util.TensorFlowTestCase):
min_node_weight=0,
class_id=-1,
feature_column_group_id=0,
- multiclass_strategy=learner_pb2.LearnerConfig.TREE_PER_CLASS))
+ multiclass_strategy=learner_pb2.LearnerConfig.TREE_PER_CLASS,
+ weak_learner_type=learner_pb2.LearnerConfig.NORMAL_DECISION_TREE))
partitions, gains, splits = sess.run([partitions, gains, splits])
# .assertEmpty doesn't exist on ubuntu-contrib
self.assertEqual(0, len(partitions))
diff --git a/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py b/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py
index d0d1249bd6..2f75d8aa99 100644
--- a/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py
+++ b/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py
@@ -218,6 +218,21 @@ def extract_features(features, feature_columns, use_core_columns):
sparse_int_shapes = []
for key in sorted(features.keys()):
tensor = features[key]
+ # TODO(nponomareva): consider iterating over feature columns instead.
+ if isinstance(tensor, tuple):
+ # Weighted categorical feature.
+ categorical_tensor = tensor[0]
+ weight_tensor = tensor[1]
+
+ shape = categorical_tensor.dense_shape
+ indices = array_ops.concat([
+ array_ops.slice(categorical_tensor.indices, [0, 0], [-1, 1]),
+ array_ops.expand_dims(
+ math_ops.to_int64(categorical_tensor.values), -1)
+ ], 1)
+ tensor = sparse_tensor.SparseTensor(
+ indices=indices, values=weight_tensor.values, dense_shape=shape)
+
if isinstance(tensor, sparse_tensor.SparseTensor):
if tensor.values.dtype == dtypes.float32:
sparse_float_names.append(key)
@@ -672,6 +687,8 @@ class GradientBoostedDecisionTreeModel(object):
self._learner_config.constraints.min_node_weight, dtypes.float32)
loss_uses_sum_reduction = self._loss_reduction == losses.Reduction.SUM
loss_uses_sum_reduction = constant_op.constant(loss_uses_sum_reduction)
+ weak_learner_type = constant_op.constant(
+ self._learner_config.weak_learner_type)
epsilon = 0.01
num_quantiles = 100
strategy_tensor = constant_op.constant(strategy)
@@ -696,6 +713,7 @@ class GradientBoostedDecisionTreeModel(object):
multiclass_strategy=strategy_tensor,
init_stamp_token=init_stamp_token,
loss_uses_sum_reduction=loss_uses_sum_reduction,
+ weak_learner_type=weak_learner_type,
))
fc_name_idx += 1
diff --git a/tensorflow/contrib/checkpoint/__init__.py b/tensorflow/contrib/checkpoint/__init__.py
index 2fbaa31d5e..150d734db6 100644
--- a/tensorflow/contrib/checkpoint/__init__.py
+++ b/tensorflow/contrib/checkpoint/__init__.py
@@ -31,6 +31,12 @@ Checkpointable data structures:
@@List
@@Mapping
@@UniqueNameTracker
+
+Checkpoint management:
+@@CheckpointManager
+
+Saving and restoring Python state:
+@@NumpyState
"""
from __future__ import absolute_import
@@ -38,9 +44,11 @@ from __future__ import division
from __future__ import print_function
from tensorflow.contrib.checkpoint.python.containers import UniqueNameTracker
+from tensorflow.contrib.checkpoint.python.python_state import NumpyState
from tensorflow.contrib.checkpoint.python.split_dependency import split_dependency
from tensorflow.contrib.checkpoint.python.visualize import dot_graph_from_checkpoint
from tensorflow.core.protobuf.checkpointable_object_graph_pb2 import CheckpointableObjectGraph
+from tensorflow.python.training.checkpoint_management import CheckpointManager
from tensorflow.python.training.checkpointable.base import CheckpointableBase
from tensorflow.python.training.checkpointable.data_structures import List
from tensorflow.python.training.checkpointable.data_structures import Mapping
diff --git a/tensorflow/contrib/checkpoint/python/BUILD b/tensorflow/contrib/checkpoint/python/BUILD
index 7b200a29bf..ada4168726 100644
--- a/tensorflow/contrib/checkpoint/python/BUILD
+++ b/tensorflow/contrib/checkpoint/python/BUILD
@@ -9,6 +9,7 @@ py_library(
srcs_version = "PY2AND3",
deps = [
":containers",
+ ":python_state",
":split_dependency",
":visualize",
"//tensorflow/python/training/checkpointable:data_structures",
@@ -41,6 +42,33 @@ py_test(
)
py_library(
+ name = "python_state",
+ srcs = ["python_state.py"],
+ srcs_version = "PY2AND3",
+ visibility = ["//tensorflow:internal"],
+ deps = [
+ "//tensorflow/python/training/checkpointable:base",
+ "//third_party/py/numpy",
+ "@six_archive//:six",
+ ],
+)
+
+py_test(
+ name = "python_state_test",
+ srcs = ["python_state_test.py"],
+ deps = [
+ ":python_state",
+ "//tensorflow/python:framework_ops",
+ "//tensorflow/python:framework_test_lib",
+ "//tensorflow/python:session",
+ "//tensorflow/python:variables",
+ "//tensorflow/python/eager:test",
+ "//tensorflow/python/training/checkpointable:util",
+ "//third_party/py/numpy",
+ ],
+)
+
+py_library(
name = "split_dependency",
srcs = ["split_dependency.py"],
srcs_version = "PY2AND3",
diff --git a/tensorflow/contrib/checkpoint/python/python_state.py b/tensorflow/contrib/checkpoint/python/python_state.py
new file mode 100644
index 0000000000..9b11035b6d
--- /dev/null
+++ b/tensorflow/contrib/checkpoint/python/python_state.py
@@ -0,0 +1,166 @@
+"""Utilities for including Python state in TensorFlow checkpoints."""
+# 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.
+# ==============================================================================
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import functools
+
+import numpy
+
+from tensorflow.python.training.checkpointable import base
+
+# pylint: disable=g-import-not-at-top
+try:
+ # In Python 2.x, use the faster string buffering option.
+ from cStringIO import StringIO as BytesIO
+except ImportError:
+ from io import BytesIO
+# pylint: enable=g-import-not-at-top
+
+
+class NumpyState(base.CheckpointableBase):
+ """A checkpointable object whose NumPy array attributes are saved/restored.
+
+ Example usage:
+
+ ```python
+ arrays = tf.contrib.checkpoint.NumpyState()
+ checkpoint = tf.train.Checkpoint(numpy_arrays=arrays)
+ arrays.x = numpy.zeros([3, 4])
+ save_path = checkpoint.save("/tmp/ckpt")
+ arrays.x[1, 1] = 4.
+ checkpoint.restore(save_path)
+ assert (arrays.x == numpy.zeros([3, 4])).all()
+
+ second_checkpoint = tf.train.Checkpoint(
+ numpy_arrays=tf.contrib.checkpoint.NumpyState())
+ # Attributes of NumpyState objects are created automatically by restore()
+ second_checkpoint.restore(save_path)
+ assert (second_checkpoint.numpy_arrays.x == numpy.zeros([3, 4])).all()
+ ```
+
+ Note that `NumpyState` objects re-create the attributes of the previously
+ saved object on `restore()`. This is in contrast to TensorFlow variables, for
+ which a `Variable` object must be created and assigned to an attribute.
+
+ This snippet works both when graph building and when executing eagerly. On
+ save, the NumPy array(s) are fed as strings to be saved in the checkpoint (via
+ a placeholder when graph building, or as a string constant when executing
+ eagerly). When restoring they skip the TensorFlow graph entirely, and so no
+ restore ops need be run. This means that restoration always happens eagerly,
+ rather than waiting for `checkpoint.restore(...).run_restore_ops()` like
+ TensorFlow variables when graph building.
+ """
+
+ def _lookup_dependency(self, name):
+ """Create placeholder NumPy arrays for to-be-restored attributes.
+
+ Typically `_lookup_dependency` is used to check by name whether a dependency
+ exists. We cheat slightly by creating a checkpointable object for `name` if
+ we don't already have one, giving us attribute re-creation behavior when
+ loading a checkpoint.
+
+ Args:
+ name: The name of the dependency being checked.
+ Returns:
+ An existing dependency if one exists, or a new `_NumpyWrapper` placeholder
+ dependency (which will generally be restored immediately).
+ """
+ value = super(NumpyState, self)._lookup_dependency(name)
+ if value is None:
+ value = _NumpyWrapper(numpy.array([]))
+ new_reference = base.CheckpointableReference(name=name, ref=value)
+ self._unconditional_checkpoint_dependencies.append(new_reference)
+ self._unconditional_dependency_names[name] = value
+ super(NumpyState, self).__setattr__(name, value)
+ return value
+
+ def __getattribute__(self, name):
+ """Un-wrap `_NumpyWrapper` objects when accessing attributes."""
+ value = super(NumpyState, self).__getattribute__(name)
+ if isinstance(value, _NumpyWrapper):
+ return value.array
+ return value
+
+ def __setattr__(self, name, value):
+ """Automatically wrap NumPy arrays assigned to attributes."""
+ # TODO(allenl): Consider supporting lists/tuples, either ad-hoc or by making
+ # ndarrays checkpointable natively and using standard checkpointable list
+ # tracking.
+ if isinstance(value, numpy.ndarray):
+ try:
+ existing = super(NumpyState, self).__getattribute__(name)
+ existing.array = value
+ return
+ except AttributeError:
+ value = _NumpyWrapper(value)
+ self._track_checkpointable(value, name=name, overwrite=True)
+ elif (name not in ("_setattr_tracking", "_update_uid")
+ and getattr(self, "_setattr_tracking", True)):
+ # Mixing restore()-created attributes with user-added checkpointable
+ # objects is tricky, since we can't use the `_lookup_dependency` trick to
+ # re-create attributes (we might accidentally steal the restoration for
+ # another checkpointable object). For now `NumpyState` objects must be
+ # leaf nodes. Theoretically we could add some extra arguments to
+ # `_lookup_dependency` to figure out whether we should create a NumPy
+ # array for the attribute or not.
+ raise NotImplementedError(
+ ("Assigned %s to the %s property of %s, which is not a NumPy array. "
+ "Currently mixing NumPy arrays and other checkpointable objects is "
+ "not supported. File a feature request if this limitation bothers "
+ "you.")
+ % (value, name, self))
+ super(NumpyState, self).__setattr__(name, value)
+
+
+class _NumpyWrapper(base.CheckpointableBase):
+ """Wraps a NumPy array for storage in an object-based checkpoint."""
+
+ def __init__(self, array):
+ """Specify a NumPy array to wrap.
+
+ Args:
+ array: The NumPy array to save and restore (may be overwritten).
+ """
+ self.array = array
+
+ def _serialize(self):
+ """Callback for `PythonStringStateSaveable` to serialize the array."""
+ string_file = BytesIO()
+ try:
+ numpy.save(string_file, self.array, allow_pickle=False)
+ serialized = string_file.getvalue()
+ finally:
+ string_file.close()
+ return serialized
+
+ def _deserialize(self, string_value):
+ """Callback for `PythonStringStateSaveable` to deserialize the array."""
+ string_file = BytesIO(string_value)
+ try:
+ self.array = numpy.load(string_file, allow_pickle=False)
+ finally:
+ string_file.close()
+
+ def _gather_saveables_for_checkpoint(self):
+ """Specify callbacks for saving and restoring `array`."""
+ return {
+ "array": functools.partial(
+ base.PythonStringStateSaveable,
+ state_callback=self._serialize,
+ restore_callback=self._deserialize)
+ }
diff --git a/tensorflow/contrib/checkpoint/python/python_state_test.py b/tensorflow/contrib/checkpoint/python/python_state_test.py
new file mode 100644
index 0000000000..0439a4755e
--- /dev/null
+++ b/tensorflow/contrib/checkpoint/python/python_state_test.py
@@ -0,0 +1,101 @@
+# 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.
+# ==============================================================================
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import os
+
+import numpy
+
+from tensorflow.contrib.checkpoint.python import python_state
+from tensorflow.python.client import session
+from tensorflow.python.eager import test
+from tensorflow.python.framework import ops
+from tensorflow.python.framework import test_util
+from tensorflow.python.ops import variables
+from tensorflow.python.training.checkpointable import util
+
+
+class NumpyStateTests(test.TestCase):
+
+ @test_util.run_in_graph_and_eager_modes
+ def testSaveRestoreNumpyState(self):
+ directory = self.get_temp_dir()
+ prefix = os.path.join(directory, "ckpt")
+ save_state = python_state.NumpyState()
+ saver = util.Checkpoint(numpy=save_state)
+ save_state.a = numpy.ones([2, 2])
+ save_state.b = numpy.ones([2, 2])
+ save_state.b = numpy.zeros([2, 2])
+ self.assertAllEqual(numpy.ones([2, 2]), save_state.a)
+ self.assertAllEqual(numpy.zeros([2, 2]), save_state.b)
+ first_save_path = saver.save(prefix)
+ save_state.a[1, 1] = 2.
+ second_save_path = saver.save(prefix)
+
+ load_state = python_state.NumpyState()
+ loader = util.Checkpoint(numpy=load_state)
+ loader.restore(first_save_path).initialize_or_restore()
+ self.assertAllEqual(numpy.ones([2, 2]), load_state.a)
+ self.assertAllEqual(numpy.zeros([2, 2]), load_state.b)
+ load_state.a[0, 0] = 42.
+ self.assertAllEqual([[42., 1.], [1., 1.]], load_state.a)
+ loader.restore(first_save_path).run_restore_ops()
+ self.assertAllEqual(numpy.ones([2, 2]), load_state.a)
+ loader.restore(second_save_path).run_restore_ops()
+ self.assertAllEqual([[1., 1.], [1., 2.]], load_state.a)
+ self.assertAllEqual(numpy.zeros([2, 2]), load_state.b)
+
+ def testNoGraphPollution(self):
+ graph = ops.Graph()
+ with graph.as_default(), session.Session():
+ directory = self.get_temp_dir()
+ prefix = os.path.join(directory, "ckpt")
+ save_state = python_state.NumpyState()
+ saver = util.Checkpoint(numpy=save_state)
+ save_state.a = numpy.ones([2, 2])
+ save_path = saver.save(prefix)
+ saver.restore(save_path)
+ graph.finalize()
+ saver.save(prefix)
+ save_state.a = numpy.zeros([2, 2])
+ saver.save(prefix)
+ saver.restore(save_path)
+
+ @test_util.run_in_graph_and_eager_modes
+ def testNoMixedNumpyStateTF(self):
+ save_state = python_state.NumpyState()
+ save_state.a = numpy.ones([2, 2])
+ with self.assertRaises(NotImplementedError):
+ save_state.v = variables.Variable(1.)
+
+ @test_util.run_in_graph_and_eager_modes
+ def testDocstringExample(self):
+ arrays = python_state.NumpyState()
+ checkpoint = util.Checkpoint(numpy_arrays=arrays)
+ arrays.x = numpy.zeros([3, 4])
+ save_path = checkpoint.save(os.path.join(self.get_temp_dir(), "ckpt"))
+ arrays.x[1, 1] = 4.
+ checkpoint.restore(save_path)
+ self.assertAllEqual(numpy.zeros([3, 4]), arrays.x)
+
+ second_checkpoint = util.Checkpoint(numpy_arrays=python_state.NumpyState())
+ second_checkpoint.restore(save_path)
+ self.assertAllEqual(numpy.zeros([3, 4]), second_checkpoint.numpy_arrays.x)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py b/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py
index 95e7e744d3..cb45e42734 100644
--- a/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py
+++ b/tensorflow/contrib/cloud/python/ops/gcs_config_ops.py
@@ -19,6 +19,7 @@ from __future__ import division
from __future__ import print_function
import json
+import os
from tensorflow.contrib.cloud.python.ops import gen_gcs_config_ops
from tensorflow.python.framework import dtypes
@@ -188,6 +189,8 @@ def configure_colab_session(session):
session: A `tf.Session` session.
"""
# Read from the application default credentials (adc).
- with open('/content/datalab/adc.json') as f:
+ adc_filename = os.environ.get(
+ 'GOOGLE_APPLICATION_CREDENTIALS', '/content/adc.json')
+ with open(adc_filename) as f:
data = json.load(f)
configure_gcs(session, credentials=data)
diff --git a/tensorflow/contrib/cmake/external/nsync.cmake b/tensorflow/contrib/cmake/external/nsync.cmake
index 1d638e6402..479609458c 100644
--- a/tensorflow/contrib/cmake/external/nsync.cmake
+++ b/tensorflow/contrib/cmake/external/nsync.cmake
@@ -16,16 +16,16 @@ include (ExternalProject)
set(nsync_INCLUDE_DIR ${CMAKE_CURRENT_BINARY_DIR}/external/nsync/public)
set(nsync_URL https://github.com/google/nsync)
-set(nsync_TAG 1.20.0)
+set(nsync_TAG 1.20.1)
set(nsync_BUILD ${CMAKE_CURRENT_BINARY_DIR}/nsync/src/nsync)
set(nsync_INSTALL ${CMAKE_CURRENT_BINARY_DIR}/nsync/install)
if(WIN32)
set(nsync_HEADERS "${nsync_BUILD}/public/*.h")
- set(nsync_STATIC_LIBRARIES ${nsync_INSTALL}/lib/nsync.lib)
+ set(nsync_STATIC_LIBRARIES ${nsync_INSTALL}/lib/nsync_cpp.lib)
else()
set(nsync_HEADERS "${nsync_BUILD}/public/*.h")
- set(nsync_STATIC_LIBRARIES ${nsync_INSTALL}/lib/libnsync.a)
+ set(nsync_STATIC_LIBRARIES ${nsync_INSTALL}/lib/libnsync_cpp.a)
endif()
ExternalProject_Add(nsync
@@ -35,12 +35,12 @@ ExternalProject_Add(nsync
DOWNLOAD_DIR "${DOWNLOAD_LOCATION}"
BUILD_IN_SOURCE 1
BUILD_BYPRODUCTS ${nsync_STATIC_LIBRARIES}
- PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/patches/nsync/CMakeLists.txt ${nsync_BUILD}
INSTALL_DIR ${nsync_INSTALL}
CMAKE_CACHE_ARGS
-DCMAKE_BUILD_TYPE:STRING=Release
-DCMAKE_VERBOSE_MAKEFILE:BOOL=OFF
-DCMAKE_INSTALL_PREFIX:STRING=${nsync_INSTALL}
+ -DCMAKE_INSTALL_LIBDIR:STRING=lib
-DNSYNC_LANGUAGE:STRING=c++11)
set(nsync_HEADERS
diff --git a/tensorflow/contrib/cmake/patches/nsync/CMakeLists.txt b/tensorflow/contrib/cmake/patches/nsync/CMakeLists.txt
deleted file mode 100644
index 6f059c7225..0000000000
--- a/tensorflow/contrib/cmake/patches/nsync/CMakeLists.txt
+++ /dev/null
@@ -1,325 +0,0 @@
-cmake_minimum_required (VERSION 2.8.12)
-
-# nsync provides portable synchronization primitives, such as mutexes and
-# condition variables.
-project (nsync)
-
-# Set variable NSYNC_LANGUAGE to "c++11" to build with C++11
-# rather than C.
-
-# Some builds need position-independent code.
-set (CMAKE_POSITION_INDEPENDENT_CODE ON)
-
-# -----------------------------------------------------------------
-# Platform dependencies
-
-# Many platforms use these posix related sources; even Win32.
-set (NSYNC_POSIX_SRC
- "platform/posix/src/nsync_panic.c"
- "platform/posix/src/per_thread_waiter.c"
- "platform/posix/src/time_rep.c"
- "platform/posix/src/yield.c"
-)
-
-if (WIN32)
- # Suppress warnings to reduce build log size.
- add_definitions(/wd4267 /wd4244 /wd4800 /wd4503 /wd4554 /wd4996 /wd4348 /wd4018)
- add_definitions(/wd4099 /wd4146 /wd4267 /wd4305 /wd4307)
- add_definitions(/wd4715 /wd4722 /wd4723 /wd4838 /wd4309 /wd4334)
- add_definitions(/wd4003 /wd4244 /wd4267 /wd4503 /wd4506 /wd4800 /wd4996)
- add_definitions(/wd8029)
-endif()
-
-# Many of the string matches below use a literal "X" suffix on both sides.
-# This is because some versions of cmake treat (for example) "MSVC" (in quotes)
-# as a reference to the variable MSVC, thus the expression
-# "${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC"
-# is false when ${CMAKE_C_COMPILER_ID} has the value "MSVC"! See
-# https://cmake.org/cmake/help/v3.1/policy/CMP0054.html
-
-# Pick the include directory for the operating system.
-if ("${NSYNC_LANGUAGE}X" STREQUAL "c++11X")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/c++11")
- add_definitions ("-DNSYNC_USE_CPP11_TIMEPOINT -DNSYNC_ATOMIC_CPP11")
- set (NSYNC_OS_CPP_SRC
- "platform/c++11/src/per_thread_waiter.cc"
- "platform/c++11/src/yield.cc"
- "platform/c++11/src/time_rep_timespec.cc"
- "platform/c++11/src/nsync_panic.cc"
- )
- if ("${CMAKE_SYSTEM_NAME}X" STREQUAL "WindowsX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/win32")
- add_compile_options ("/TP")
- set (NSYNC_OS_SRC
- "platform/c++11/src/nsync_semaphore_mutex.cc"
- "platform/win32/src/clock_gettime.c"
- "platform/win32/src/pthread_key_win32.cc"
- ${NSYNC_OS_CPP_SRC}
- )
- set (NSYNC_TEST_OS_SRC
- "platform/win32/src/start_thread.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "DarwinX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/macos")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- # Some versions of MacOS, such as Sierra, require _DARWIN_C_SOURCE
- # when including certin C++ standard header files, such as <mutex>.
- add_definitions ("-D_DARWIN_C_SOURCE")
- add_compile_options ("-std=c++11")
- set (NSYNC_OS_SRC
- ${NSYNC_OS_CPP_SRC}
- "platform/c++11/src/nsync_semaphore_mutex.cc"
- "platform/posix/src/clock_gettime.c"
- "platform/posix/src/nsync_semaphore_mutex.c"
- )
- set (NSYNC_TEST_OS_SRC
- "platform/posix/src/start_thread.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "LinuxX")
- include_directories (BEFORE "${PROJECT_SOURCE_DIR}/platform/c++11.futex")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- add_compile_options ("-std=c++11")
- set (NSYNC_OS_SRC
- "platform/linux/src/nsync_semaphore_futex.c"
- ${NSYNC_OS_CPP_SRC}
- )
- set (NSYNC_TEST_OS_SRC
- "platform/posix/src/start_thread.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "NetBSDX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- add_compile_options ("-std=c++11")
- set (NSYNC_OS_SRC
- "platform/c++11/src/nsync_semaphore_mutex.cc"
- ${NSYNC_OS_CPP_SRC}
- )
- set (NSYNC_TEST_OS_SRC
- "platform/posix/src/start_thread.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "FreeBSDX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- add_compile_options ("-std=c++11")
- set (NSYNC_OS_SRC
- "platform/c++11/src/nsync_semaphore_mutex.cc"
- ${NSYNC_OS_CPP_SRC}
- )
- set (NSYNC_TEST_OS_SRC
- "platform/posix/src/start_thread.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "OpenBSDX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- add_compile_options ("-std=c++11")
- set (NSYNC_OS_SRC
- "platform/c++11/src/nsync_semaphore_mutex.cc"
- ${NSYNC_OS_CPP_SRC}
- )
- set (NSYNC_TEST_OS_SRC
- "platform/posix/src/start_thread.c"
- )
- endif ()
-endif ()
-
-# Pick the include directory for the compiler.
-if ("${CMAKE_C_COMPILER_ID}X" STREQUAL "GNUX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/gcc")
- set (THREADS_HAVE_PTHREAD_ARG ON)
-elseif ("${CMAKE_C_COMPILER_ID}X" STREQUAL "ClangX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/clang")
- set (THREADS_HAVE_PTHREAD_ARG ON)
-elseif ("${CMAKE_C_COMPILER_ID}X" STREQUAL "MSVCX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/msvc")
-else ()
- message (WARNING "CMAKE_C_COMPILER_ID (${CMAKE_C_COMPILER_ID}) matched NOTHING")
-endif ()
-
-if (NOT "${NSYNC_LANGUAGE}X" STREQUAL "c++11X")
- if ("${CMAKE_SYSTEM_NAME}X" STREQUAL "WindowsX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/win32")
- set (NSYNC_OS_SRC
- ${NSYNC_POSIX_SRC}
- "platform/win32/src/clock_gettime.c"
- "platform/win32/src/init_callback_win32.c"
- "platform/win32/src/nanosleep.c"
- "platform/win32/src/nsync_semaphore_win32.c"
- "platform/win32/src/pthread_cond_timedwait_win32.c"
- "platform/win32/src/pthread_key_win32.cc"
- )
- set (NSYNC_TEST_OS_SRC
- "platform/win32/src/start_thread.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "DarwinX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/macos")
- set (NSYNC_POSIX ON)
- set (NSYNC_OS_EXTRA_SRC
- "platform/posix/src/clock_gettime.c"
- "platform/posix/src/nsync_semaphore_mutex.c"
- )
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "LinuxX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/linux")
- set (NSYNC_POSIX ON)
- set (NSYNC_OS_EXTRA_SRC
- "platform/linux/src/nsync_semaphore_futex.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "NetBSDX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/netbsd")
- set (NSYNC_POSIX ON)
- set (NSYNC_OS_EXTRA_SRC
- "platform/posix/src/nsync_semaphore_mutex.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "FreeBSDX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/freebsd")
- set (NSYNC_POSIX ON)
- set (NSYNC_OS_EXTRA_SRC
- "platform/posix/src/nsync_semaphore_mutex.c"
- )
- elseif ("${CMAKE_SYSTEM_NAME}X" STREQUAL "OpenBSDX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/openbsd")
- set (NSYNC_POSIX ON)
- set (NSYNC_OS_EXTRA_SRC
- "platform/posix/src/nsync_semaphore_mutex.c"
- )
- endif ()
-endif ()
-
-if (NSYNC_POSIX)
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
- set (NSYNC_OS_SRC
- ${NSYNC_POSIX_SRC}
- ${NSYNC_OS_EXTRA_SRC}
- )
- set (NSYNC_TEST_OS_SRC
- "platform/posix/src/start_thread.c"
- )
-endif ()
-
-# Pick the include directory for the architecture.
-if (("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "x86_64X") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "amd64X") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "AMD64X"))
- include_directories ("${PROJECT_SOURCE_DIR}/platform/x86_64")
-elseif (("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "x86_32X") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "i386X") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "i686X"))
- include_directories ("${PROJECT_SOURCE_DIR}/platform/x86_32")
-elseif (("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "armv6lX") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "armv7lX") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "armX"))
- include_directories ("${PROJECT_SOURCE_DIR}/platform/arm")
-elseif (("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "aarch64X") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "arm64X"))
- include_directories ("${PROJECT_SOURCE_DIR}/platform/aarch64")
-elseif (("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "ppcX") OR
- ("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "ppc32X"))
- include_directories ("${PROJECT_SOURCE_DIR}/platform/ppc32")
-elseif (("${CMAKE_SYSTEM_PROCESSOR}X" STREQUAL "ppc64X"))
- include_directories ("${PROJECT_SOURCE_DIR}/platform/ppc64")
-endif ()
-
-# Windows uses some include files from the posix directory also.
-if ("${CMAKE_SYSTEM_NAME}X" STREQUAL "WindowsX")
- include_directories ("${PROJECT_SOURCE_DIR}/platform/posix")
-endif ()
-
-# -----------------------------------------------------------------
-
-include_directories ("${PROJECT_SOURCE_DIR}/public")
-include_directories ("${PROJECT_SOURCE_DIR}/internal")
-
-set (NSYNC_SRC
- "internal/common.c"
- "internal/counter.c"
- "internal/cv.c"
- "internal/debug.c"
- "internal/dll.c"
- "internal/mu.c"
- "internal/mu_wait.c"
- "internal/note.c"
- "internal/once.c"
- "internal/sem_wait.c"
- "internal/time_internal.c"
- "internal/wait.c"
- ${NSYNC_OS_SRC}
-)
-add_library (nsync ${NSYNC_SRC})
-
-set (NSYNC_TEST_SRC
- "testing/array.c"
- "testing/atm_log.c"
- "testing/closure.c"
- "testing/smprintf.c"
- "testing/testing.c"
- "testing/time_extra.c"
- ${NSYNC_TEST_OS_SRC}
-)
-add_library (nsync_test ${NSYNC_TEST_SRC})
-
-set (NSYNC_TESTS
- "counter_test"
- "cv_mu_timeout_stress_test"
- "cv_test"
- "cv_wait_example_test"
- "dll_test"
- "mu_starvation_test"
- "mu_test"
- "mu_wait_example_test"
- "mu_wait_test"
- "note_test"
- "once_test"
- "pingpong_test"
- "wait_test"
-)
-
-if ("${NSYNC_LANGUAGE}X" STREQUAL "c++11X")
- foreach (s IN ITEMS ${NSYNC_SRC} ${NSYNC_TEST_SRC})
- SET_SOURCE_FILES_PROPERTIES ("${s}" PROPERTIES LANGUAGE CXX)
- endforeach (s)
- foreach (t IN ITEMS ${NSYNC_TESTS})
- SET_SOURCE_FILES_PROPERTIES ("testing/${t}.c" PROPERTIES LANGUAGE CXX)
- endforeach (t)
-endif ()
-
-enable_testing ()
-foreach (t IN ITEMS ${NSYNC_TESTS})
- add_executable (${t} "testing/${t}.c")
-endforeach (t)
-
-find_package (Threads REQUIRED)
-set (THREADS_PREFER_PTHREAD_FLAG ON)
-foreach (t IN ITEMS "nsync" "nsync_test" ${NSYNC_TESTS})
- if (THREADS_HAVE_PTHREAD_ARG)
- target_compile_options (${t} PUBLIC "-pthread")
- endif ()
- if (CMAKE_THREAD_LIBS_INIT)
- target_link_libraries (${t} "${CMAKE_THREAD_LIBS_INIT}")
- endif ()
-endforeach (t)
-
-foreach (t IN ITEMS ${NSYNC_TESTS})
- target_link_libraries (${t} nsync_test nsync)
- add_test (NAME ${t} COMMAND ${t})
-endforeach (t)
-
-install (TARGETS nsync
- LIBRARY DESTINATION lib COMPONENT RuntimeLibraries
- ARCHIVE DESTINATION lib COMPONENT Development)
-
-set (NSYNC_INCLUDES
- "public/nsync.h"
- "public/nsync_atomic.h"
- "public/nsync_counter.h"
- "public/nsync_cpp.h"
- "public/nsync_cv.h"
- "public/nsync_debug.h"
- "public/nsync_mu.h"
- "public/nsync_mu_wait.h"
- "public/nsync_note.h"
- "public/nsync_once.h"
- "public/nsync_time.h"
- "public/nsync_time_internal.h"
- "public/nsync_waiter.h"
-)
-
-foreach (NSYNC_INCLUDE ${NSYNC_INCLUDES})
- install (FILES ${NSYNC_INCLUDE} DESTINATION include COMPONENT Development)
-endforeach ()
diff --git a/tensorflow/contrib/cmake/python_modules.txt b/tensorflow/contrib/cmake/python_modules.txt
index 9045290679..07934ef324 100644
--- a/tensorflow/contrib/cmake/python_modules.txt
+++ b/tensorflow/contrib/cmake/python_modules.txt
@@ -4,6 +4,8 @@ tensorflow
tensorflow/core
tensorflow/core/example
tensorflow/core/framework
+tensorflow/core/kernels
+tensorflow/core/kernels/boosted_trees
tensorflow/core/lib
tensorflow/core/lib/core
tensorflow/core/profiler
@@ -186,6 +188,8 @@ tensorflow/contrib/graph_editor/examples
tensorflow/contrib/grid_rnn
tensorflow/contrib/grid_rnn/python
tensorflow/contrib/grid_rnn/python/ops
+tensorflow/contrib/hadoop/python
+tensorflow/contrib/hadoop/python/ops
tensorflow/contrib/hooks
tensorflow/contrib/hooks/python
tensorflow/contrib/image
diff --git a/tensorflow/contrib/cmake/tf_python.cmake b/tensorflow/contrib/cmake/tf_python.cmake
index 5cb0db6b01..6d86daf5f1 100755
--- a/tensorflow/contrib/cmake/tf_python.cmake
+++ b/tensorflow/contrib/cmake/tf_python.cmake
@@ -198,7 +198,7 @@ function(add_python_module MODULE_NAME)
# so we currently add explicit commands to include those files
# later on in this script.
if (NOT "${script}" MATCHES "_test\.py$")
- add_custom_command(TARGET tf_python_copy_scripts_to_destination PRE_BUILD
+ add_custom_command(TARGET tf_python_copy_scripts_to_destination PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ${tensorflow_source_dir}/${script} ${CMAKE_CURRENT_BINARY_DIR}/tf_python/${script})
endif()
endforeach()
@@ -297,7 +297,7 @@ function(GENERATE_PYTHON_OP_LIB tf_python_op_lib_name)
)
target_link_libraries(${tf_python_op_lib_name}_gen_python PRIVATE
tf_protos_cc
- tf_python_protos_cc
+ tf_python_protos_cc
${tensorflow_EXTERNAL_LIBRARIES}
)
@@ -549,15 +549,15 @@ if(WIN32)
${NUMPY_INCLUDE_DIR}
)
#target_link_libraries(pywrap_tensorflow_internal_static
- # tf_protos_cc
- # tf_python_protos_cc
+ # tf_protos_cc
+ # tf_python_protos_cc
#)
add_dependencies(pywrap_tensorflow_internal_static tf_protos_cc tf_python_protos_cc)
set(pywrap_tensorflow_internal_static_dependencies
$<TARGET_FILE:pywrap_tensorflow_internal_static>
$<TARGET_FILE:tf_protos_cc>
$<TARGET_FILE:tf_python_protos_cc>
- ${nsync_STATIC_LIBRARIES}
+ ${nsync_STATIC_LIBRARIES}
)
if(${CMAKE_GENERATOR} MATCHES "Visual Studio.*")
@@ -763,57 +763,40 @@ file(WRITE "${api_init_list_file}" "${api_init_files}")
# recongnize paths. As CUDA isn't built with MKL, the MKL built directory is the only path to this command to work around that issue.
# To not override the CUDA and system path in other circumstances, `if-else` branch used here to handle this problem,
# and should be removed if the path issue can be resolved.
+# UPDATE: Below block appears to handle multiple items in PATH correctly, but risks command line limits if PATH is large.
+# If you have issues, try `set(PY_RUNTIME_ENV "PATH=${mkl_BIN_DIRS}")` instead.
###
-if (tensorflow_ENABLE_MKL_SUPPORT)
+set(PY_RUNTIME_ENV "")
+if(tensorflow_ENABLE_MKL_SUPPORT)
# add mkl dist dlls to system path for python
- # TODO: In current cmake version, PY_RUNTIME_ENV behaves strange with multiple paths,
- # so we have to specify only one path in it to work around the issue. We need this if/else
- # to protect overwriting CUDA environments
- set(PY_RUNTIME_ENV ${mkl_BIN_DIRS})
- add_custom_command(
- OUTPUT ${api_init_files}
- DEPENDS tf_python_ops tf_python_copy_scripts_to_destination pywrap_tensorflow_internal tf_python_touchup_modules tf_extension_ops
-
- # tensorflow/__init__.py depends on files generated in this step. So, remove it while
- # this step is running since the files aren't there yet.
- COMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/__init__.py
-
- # Run create_python_api.py to generate API init files.
- COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/tf_python PATH=${PY_RUNTIME_ENV} ${PYTHON_EXECUTABLE}
- "${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/python/tools/api/generator/create_python_api.py"
- "--root_init_template=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/api_template.__init__.py"
- "--apidir=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow"
- "--package=tensorflow.python"
- "--apiname=tensorflow"
- "${api_init_list_file}"
-
- COMMENT "Generating __init__.py files for Python API."
- WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tf_python"
- VERBATIM
- )
-else (tensorflow_ENABLE_MKL_SUPPORT)
- add_custom_command(
- OUTPUT ${api_init_files}
- DEPENDS tf_python_ops tf_python_copy_scripts_to_destination pywrap_tensorflow_internal tf_python_touchup_modules tf_extension_ops
-
- # tensorflow/__init__.py depends on files generated in this step. So, remove it while
- # this step is running since the files aren't there yet.
- COMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/__init__.py
-
- # Run create_python_api.py to generate API init files.
- COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/tf_python ${PYTHON_EXECUTABLE}
- "${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/python/tools/api/generator/create_python_api.py"
- "--root_init_template=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/api_template.__init__.py"
- "--apidir=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow"
- "--package=tensorflow.python"
- "--apiname=tensorflow"
- "${api_init_list_file}"
-
- COMMENT "Generating __init__.py files for Python API."
- WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tf_python"
- )
-endif (tensorflow_ENABLE_MKL_SUPPORT)
+ file(TO_CMAKE_PATH "$ENV{PATH}" PY_RUNTIME_ENV)
+ set(PY_RUNTIME_ENV ${mkl_BIN_DIRS} ${PY_RUNTIME_ENV})
+ file(TO_NATIVE_PATH "${PY_RUNTIME_ENV}" PY_RUNTIME_ENV)
+ set(PY_RUNTIME_ENV "PATH=${PY_RUNTIME_ENV}")
+endif(tensorflow_ENABLE_MKL_SUPPORT)
+
+add_custom_command(
+ OUTPUT ${api_init_files}
+ DEPENDS tf_python_ops tf_python_copy_scripts_to_destination pywrap_tensorflow_internal tf_python_touchup_modules tf_extension_ops
+
+ # tensorflow/__init__.py depends on files generated in this step. So, remove it while
+ # this step is running since the files aren't there yet.
+ COMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/__init__.py
+
+ # Run create_python_api.py to generate API init files.
+ COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/tf_python "${PY_RUNTIME_ENV}" ${PYTHON_EXECUTABLE}
+ "${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/python/tools/api/generator/create_python_api.py"
+ "--root_init_template=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/api_template.__init__.py"
+ "--apidir=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow"
+ "--package=tensorflow.python"
+ "--apiname=tensorflow"
+ "${api_init_list_file}"
+
+ COMMENT "Generating __init__.py files for Python API."
+ WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tf_python"
+ VERBATIM
+)
add_custom_target(tf_python_api SOURCES ${api_init_files})
add_dependencies(tf_python_api tf_python_ops)
@@ -848,12 +831,12 @@ add_custom_command(
DEPENDS tf_python_ops tf_python_copy_scripts_to_destination pywrap_tensorflow_internal tf_python_touchup_modules tf_extension_ops
# Run create_python_api.py to generate API init files.
- COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/tf_python ${PYTHON_EXECUTABLE}
+ COMMAND ${CMAKE_COMMAND} -E env PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/tf_python "${PY_RUNTIME_ENV}" ${PYTHON_EXECUTABLE}
"${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/python/tools/api/generator/create_python_api.py"
"--apidir=${CMAKE_CURRENT_BINARY_DIR}/tf_python/tensorflow/python/estimator/api"
"--package=tensorflow.python.estimator"
"--apiname=estimator"
- "--output_package=tensorflow.python.estimator.api"
+ "--output_package=tensorflow.python.estimator.api"
"${estimator_api_init_list_file}"
COMMENT "Generating __init__.py files for Python API."
diff --git a/tensorflow/contrib/cmake/tf_tests.cmake b/tensorflow/contrib/cmake/tf_tests.cmake
index b2330c4e34..2c878c1716 100644
--- a/tensorflow/contrib/cmake/tf_tests.cmake
+++ b/tensorflow/contrib/cmake/tf_tests.cmake
@@ -122,6 +122,17 @@ function(AddPythonTests)
endforeach()
endfunction(AddPythonTests)
+#
+# ensure that every element is an existing file
+#
+function(CheckExists TYPE SOURCES)
+ foreach(source ${SOURCES})
+ if(NOT EXISTS ${source})
+ message(SEND_ERROR "${TYPE} not found: ${source}")
+ endif()
+ endforeach(source)
+endfunction(CheckExists)
+
if (tensorflow_BUILD_PYTHON_TESTS)
#
# python tests. This assumes that the tensorflow wheel is
@@ -145,7 +156,6 @@ if (tensorflow_BUILD_PYTHON_TESTS)
"${tensorflow_source_dir}/tensorflow/python/debug/wrappers/*_test.py"
"${tensorflow_source_dir}/tensorflow/contrib/estimator/python/estimator/*_test.py"
"${tensorflow_source_dir}/tensorflow/python/kernel_tests/*.py"
- "${tensorflow_source_dir}/tensorflow/python/meta_graph_transform/*_test.py"
"${tensorflow_source_dir}/tensorflow/python/ops/quantized_conv_ops_test.py"
"${tensorflow_source_dir}/tensorflow/python/ops/quantized_ops_test.py"
"${tensorflow_source_dir}/tensorflow/python/platform/build_info_test.py"
@@ -198,7 +208,6 @@ if (tensorflow_BUILD_PYTHON_TESTS)
"${tensorflow_source_dir}/tensorflow/python/saved_model/saved_model_test.py"
"${tensorflow_source_dir}/tensorflow/contrib/image/python/kernel_tests/sparse_image_warp_test.py"
# requires scipy
- "${tensorflow_source_dir}/tensorflow/contrib/keras/python/keras/preprocessing/*_test.py"
"${tensorflow_source_dir}/tensorflow/contrib/tfprof/python/tools/tfprof/pprof_profiler_test.py"
"${tensorflow_source_dir}/tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py"
# Takes very long to run without sharding (defined in bazel build file).
@@ -256,10 +265,9 @@ if (tensorflow_BUILD_PYTHON_TESTS)
# Flaky because of local cluster creation.
"${tensorflow_source_dir}/tensorflow/python/training/sync_replicas_optimizer_test.py"
"${tensorflow_source_dir}/tensorflow/python/debug/lib/session_debug_grpc_test.py"
- "${tensorflow_source_dir}tensorflow/python/training/localhost_cluster_performance_test.py"
+ "${tensorflow_source_dir}/tensorflow/python/training/localhost_cluster_performance_test.py"
"${tensorflow_source_dir}/tensorflow/python/data/kernel_tests/iterator_ops_cluster_test.py"
"${tensorflow_source_dir}/tensorflow/python/kernel_tests/functional_ops_test.py"
- "${tensorflow_source_dir}/tensorflow/contrib/data/python/kernel_tests/iterator_ops_cluster_test.py"
# Type error in testRemoteIteratorUsingRemoteCallOpDirectSessionGPUCPU.
"${tensorflow_source_dir}/tensorflow/python/data/kernel_tests/iterator_ops_test.py"
"${tensorflow_source_dir}/tensorflow/python/kernel_tests/self_adjoint_eig_op_test.py"
@@ -329,6 +337,7 @@ if (tensorflow_BUILD_PYTHON_TESTS)
"${tensorflow_source_dir}/tensorflow/python/keras/_impl/keras/utils/io_utils_test.py" # b/72894325
)
endif()
+ CheckExists(${tf_test_src_py_exclude})
list(REMOVE_ITEM tf_test_src_py ${tf_test_src_py_exclude})
AddPythonTests(
@@ -480,6 +489,7 @@ if (tensorflow_BUILD_CC_TESTS)
"${tensorflow_source_dir}/tensorflow/cc/saved_model/*_test.cc"
)
+ CheckExists(${tf_test_src_simple_exclude})
list(REMOVE_ITEM tf_test_src_simple
${tf_test_src_simple_exclude}
${tf_cc_saved_model_test_srcs}
@@ -494,6 +504,7 @@ if (tensorflow_BUILD_CC_TESTS)
${tf_core_profiler_test_srcs}
)
+ CheckExists(${tf_src_testlib})
set(tf_test_lib tf_test_lib)
add_library(${tf_test_lib} STATIC ${tf_src_testlib})
diff --git a/tensorflow/contrib/constrained_optimization/python/candidates.py b/tensorflow/contrib/constrained_optimization/python/candidates.py
index ac86a6741b..66d7ebed74 100644
--- a/tensorflow/contrib/constrained_optimization/python/candidates.py
+++ b/tensorflow/contrib/constrained_optimization/python/candidates.py
@@ -204,7 +204,7 @@ def find_best_candidate_distribution(objective_vector,
assert best_pp is not None
# Throughout this loop, a maximum_violation of "lower" is not achievable,
- # but a maximum_violation of "upper" is achiveable.
+ # but a maximum_violation of "upper" is achievable.
while True:
middle = 0.5 * (lower + upper)
if (middle - lower <= epsilon) or (upper - middle <= epsilon):
diff --git a/tensorflow/contrib/constrained_optimization/python/constrained_minimization_problem.py b/tensorflow/contrib/constrained_optimization/python/constrained_minimization_problem.py
index 70813fb217..41258edd90 100644
--- a/tensorflow/contrib/constrained_optimization/python/constrained_minimization_problem.py
+++ b/tensorflow/contrib/constrained_optimization/python/constrained_minimization_problem.py
@@ -72,7 +72,8 @@ class ConstrainedMinimizationProblem(object):
else:
proxy_constraints_shape = self.proxy_constraints.get_shape()
- if (constraints_shape is None or proxy_constraints_shape is None or
+ if (constraints_shape.ndims is None or
+ proxy_constraints_shape.ndims is None or
any([ii is None for ii in constraints_shape.as_list()]) or
any([ii is None for ii in proxy_constraints_shape.as_list()])):
raise ValueError(
@@ -121,3 +122,19 @@ class ConstrainedMinimizationProblem(object):
A tensor of proxy constraint functions.
"""
return None
+
+ # This is a property, instead of an abstract property, since it doesn't need
+ # to be overridden: if pre_train_ops returns None, then there are no ops to
+ # run before train_op.
+ @property
+ def pre_train_ops(self):
+ """Returns a list of `Operation`s to run before the train_op.
+
+ When a `ConstrainedOptimizer` creates a train_op (in `minimize`
+ `minimize_unconstrained`, or `minimize_constrained`), it will include these
+ ops before the main training step.
+
+ Returns:
+ A list of `Operation`s.
+ """
+ return None
diff --git a/tensorflow/contrib/constrained_optimization/python/constrained_optimizer.py b/tensorflow/contrib/constrained_optimization/python/constrained_optimizer.py
index 8055545366..0b79bdf7c0 100644
--- a/tensorflow/contrib/constrained_optimization/python/constrained_optimizer.py
+++ b/tensorflow/contrib/constrained_optimization/python/constrained_optimizer.py
@@ -55,20 +55,21 @@ class ConstrainedOptimizer(object):
"""Returns the `tf.train.Optimizer` used for optimization."""
return self._optimizer
- def minimize_unconstrained(self,
- minimization_problem,
- global_step=None,
- var_list=None,
- gate_gradients=train_optimizer.Optimizer.GATE_OP,
- aggregation_method=None,
- colocate_gradients_with_ops=False,
- name=None,
- grad_loss=None):
- """Returns an `Op` for minimizing the unconstrained problem.
+ @abc.abstractmethod
+ def _minimize_constrained(self,
+ minimization_problem,
+ global_step=None,
+ var_list=None,
+ gate_gradients=train_optimizer.Optimizer.GATE_OP,
+ aggregation_method=None,
+ colocate_gradients_with_ops=False,
+ name=None,
+ grad_loss=None):
+ """Version of `minimize_constrained` to be overridden by subclasses.
- Unlike `minimize_constrained`, this function ignores the `constraints` (and
- `proxy_constraints`) portion of the minimization problem entirely, and only
- minimizes `objective`.
+ Implementations of this method should ignore the `pre_train_ops` property of
+ the `minimization_problem`. The public `minimize_constrained` method will
+ take care of executing these before the returned train_op.
Args:
minimization_problem: ConstrainedMinimizationProblem, the problem to
@@ -83,19 +84,10 @@ class ConstrainedOptimizer(object):
grad_loss: as in `tf.train.Optimizer`'s `minimize` method.
Returns:
- TensorFlow Op.
+ `Operation`, the train_op.
"""
- return self.optimizer.minimize(
- minimization_problem.objective,
- global_step=global_step,
- var_list=var_list,
- gate_gradients=gate_gradients,
- aggregation_method=aggregation_method,
- colocate_gradients_with_ops=colocate_gradients_with_ops,
- name=name,
- grad_loss=grad_loss)
+ pass
- @abc.abstractmethod
def minimize_constrained(self,
minimization_problem,
global_step=None,
@@ -105,7 +97,7 @@ class ConstrainedOptimizer(object):
colocate_gradients_with_ops=False,
name=None,
grad_loss=None):
- """Returns an `Op` for minimizing the constrained problem.
+ """Returns an `Operation` for minimizing the constrained problem.
Unlike `minimize_unconstrained`, this function attempts to find a solution
that minimizes the `objective` portion of the minimization problem while
@@ -124,9 +116,83 @@ class ConstrainedOptimizer(object):
grad_loss: as in `tf.train.Optimizer`'s `minimize` method.
Returns:
- TensorFlow Op.
+ `Operation`, the train_op.
"""
- pass
+
+ def train_op_callback():
+ return self._minimize_constrained(
+ minimization_problem,
+ global_step=global_step,
+ var_list=var_list,
+ gate_gradients=gate_gradients,
+ aggregation_method=aggregation_method,
+ colocate_gradients_with_ops=colocate_gradients_with_ops,
+ name=name,
+ grad_loss=grad_loss)
+
+ # If we have pre_train_ops, use tf.control_dependencies() to ensure that
+ # they execute before the train_op.
+ pre_train_ops = minimization_problem.pre_train_ops
+ if pre_train_ops:
+ with ops.control_dependencies(pre_train_ops):
+ train_op = train_op_callback()
+ else:
+ train_op = train_op_callback()
+
+ return train_op
+
+ def minimize_unconstrained(self,
+ minimization_problem,
+ global_step=None,
+ var_list=None,
+ gate_gradients=train_optimizer.Optimizer.GATE_OP,
+ aggregation_method=None,
+ colocate_gradients_with_ops=False,
+ name=None,
+ grad_loss=None):
+ """Returns an `Operation` for minimizing the unconstrained problem.
+
+ Unlike `minimize_constrained`, this function ignores the `constraints` (and
+ `proxy_constraints`) portion of the minimization problem entirely, and only
+ minimizes `objective`.
+
+ Args:
+ minimization_problem: ConstrainedMinimizationProblem, the problem to
+ optimize.
+ global_step: as in `tf.train.Optimizer`'s `minimize` method.
+ var_list: as in `tf.train.Optimizer`'s `minimize` method.
+ gate_gradients: as in `tf.train.Optimizer`'s `minimize` method.
+ aggregation_method: as in `tf.train.Optimizer`'s `minimize` method.
+ colocate_gradients_with_ops: as in `tf.train.Optimizer`'s `minimize`
+ method.
+ name: as in `tf.train.Optimizer`'s `minimize` method.
+ grad_loss: as in `tf.train.Optimizer`'s `minimize` method.
+
+ Returns:
+ `Operation`, the train_op.
+ """
+
+ def train_op_callback():
+ return self.optimizer.minimize(
+ minimization_problem.objective,
+ global_step=global_step,
+ var_list=var_list,
+ gate_gradients=gate_gradients,
+ aggregation_method=aggregation_method,
+ colocate_gradients_with_ops=colocate_gradients_with_ops,
+ name=name,
+ grad_loss=grad_loss)
+
+ # If we have pre_train_ops, use tf.control_dependencies() to ensure that
+ # they execute before the train_op.
+ pre_train_ops = minimization_problem.pre_train_ops
+ if pre_train_ops:
+ with ops.control_dependencies(pre_train_ops):
+ train_op = train_op_callback()
+ else:
+ train_op = train_op_callback()
+
+ return train_op
def minimize(self,
minimization_problem,
@@ -138,7 +204,7 @@ class ConstrainedOptimizer(object):
colocate_gradients_with_ops=False,
name=None,
grad_loss=None):
- """Returns an `Op` for minimizing the constrained problem.
+ """Returns an `Operation` for minimizing the constrained problem.
This method combines the functionality of `minimize_unconstrained` and
`minimize_constrained`. If global_step < unconstrained_steps, it will
@@ -164,14 +230,14 @@ class ConstrainedOptimizer(object):
grad_loss: as in `tf.train.Optimizer`'s `minimize` method.
Returns:
- TensorFlow Op.
+ `Operation`, the train_op.
Raises:
ValueError: If unconstrained_steps is provided, but global_step is not.
"""
def unconstrained_fn():
- """Returns an `Op` for minimizing the unconstrained problem."""
+ """Returns an `Operation` for minimizing the unconstrained problem."""
return self.minimize_unconstrained(
minimization_problem=minimization_problem,
global_step=global_step,
@@ -183,7 +249,7 @@ class ConstrainedOptimizer(object):
grad_loss=grad_loss)
def constrained_fn():
- """Returns an `Op` for minimizing the constrained problem."""
+ """Returns an `Operation` for minimizing the constrained problem."""
return self.minimize_constrained(
minimization_problem=minimization_problem,
global_step=global_step,
diff --git a/tensorflow/contrib/constrained_optimization/python/external_regret_optimizer.py b/tensorflow/contrib/constrained_optimization/python/external_regret_optimizer.py
index 01c6e4f08a..d1af15f7e4 100644
--- a/tensorflow/contrib/constrained_optimization/python/external_regret_optimizer.py
+++ b/tensorflow/contrib/constrained_optimization/python/external_regret_optimizer.py
@@ -70,11 +70,13 @@ def _project_multipliers_wrt_euclidean_norm(multipliers, radius):
region w.r.t. the Euclidean norm.
Raises:
- ValueError: if the `multipliers` tensor does not have a fully-known shape,
- or is not one-dimensional.
+ ValueError: if the `multipliers` tensor is not floating-point, does not have
+ a fully-known shape, or is not one-dimensional.
"""
+ if not multipliers.dtype.is_floating:
+ raise ValueError("multipliers must have a floating-point dtype")
multipliers_shape = multipliers.get_shape()
- if multipliers_shape is None:
+ if multipliers_shape.ndims is None:
raise ValueError("multipliers must have known shape")
if multipliers_shape.ndims != 1:
raise ValueError(
@@ -101,12 +103,12 @@ def _project_multipliers_wrt_euclidean_norm(multipliers, radius):
(radius - standard_ops.reduce_sum(multipliers)) / standard_ops.maximum(
1.0, standard_ops.reduce_sum(inactive)))
multipliers += scale * inactive
- new_inactive = standard_ops.to_float(multipliers > 0)
+ new_inactive = standard_ops.cast(multipliers > 0, multipliers.dtype)
multipliers *= new_inactive
return (iteration, multipliers, new_inactive, inactive)
iteration = standard_ops.constant(0)
- inactive = standard_ops.ones_like(multipliers)
+ inactive = standard_ops.ones_like(multipliers, dtype=multipliers.dtype)
# We actually want a do-while loop, so we explicitly call while_loop_body()
# once before tf.while_loop().
@@ -189,16 +191,16 @@ class _ExternalRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
def _projection_op(self, state, name=None):
pass
- def minimize_constrained(self,
- minimization_problem,
- global_step=None,
- var_list=None,
- gate_gradients=train_optimizer.Optimizer.GATE_OP,
- aggregation_method=None,
- colocate_gradients_with_ops=False,
- name=None,
- grad_loss=None):
- """Returns an `Op` for minimizing the constrained problem.
+ def _minimize_constrained(self,
+ minimization_problem,
+ global_step=None,
+ var_list=None,
+ gate_gradients=train_optimizer.Optimizer.GATE_OP,
+ aggregation_method=None,
+ colocate_gradients_with_ops=False,
+ name=None,
+ grad_loss=None):
+ """Returns an `Operation` for minimizing the constrained problem.
The `optimizer` constructor parameter will be used to update the model
parameters, while the Lagrange multipliers will be updated using
@@ -216,8 +218,11 @@ class _ExternalRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
name: as in `tf.train.Optimizer`'s `minimize` method.
grad_loss: as in `tf.train.Optimizer`'s `minimize` method.
+ Raises:
+ ValueError: If the minimization_problem tensors have different dtypes.
+
Returns:
- TensorFlow Op.
+ `Operation`, the train_op.
"""
objective = minimization_problem.objective
@@ -225,6 +230,14 @@ class _ExternalRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
proxy_constraints = minimization_problem.proxy_constraints
if proxy_constraints is None:
proxy_constraints = constraints
+
+ # Make sure that the objective, constraints and proxy constraints all have
+ # the same dtype.
+ if (objective.dtype.base_dtype != constraints.dtype.base_dtype or
+ objective.dtype.base_dtype != proxy_constraints.dtype.base_dtype):
+ raise ValueError("objective, constraints and proxy_constraints must "
+ "have the same dtype")
+
# Flatten both constraints tensors to 1d.
num_constraints = minimization_problem.num_constraints
constraints = standard_ops.reshape(constraints, shape=(num_constraints,))
@@ -241,8 +254,10 @@ class _ExternalRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
multipliers = self._lagrange_multipliers(state)
loss = (
- objective + standard_ops.tensordot(multipliers, proxy_constraints, 1))
- multipliers_gradient = constraints
+ objective + standard_ops.tensordot(
+ standard_ops.cast(multipliers, proxy_constraints.dtype),
+ proxy_constraints, 1))
+ multipliers_gradient = standard_ops.cast(constraints, multipliers.dtype)
update_ops = []
if self.constraint_optimizer is None:
@@ -356,6 +371,8 @@ class AdditiveExternalRegretOptimizer(_ExternalRegretOptimizer):
# For an AdditiveExternalRegretOptimizer, the internal state is simply a
# tensor of Lagrange multipliers with shape (m,), where m is the number of
# constraints.
+ #
+ # FUTURE WORK: make the dtype a parameter.
return standard_ops.zeros((num_constraints,), dtype=dtypes.float32)
def _lagrange_multipliers(self, state):
diff --git a/tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.py b/tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.py
index 3791dae8d7..2c673d9347 100644
--- a/tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.py
+++ b/tensorflow/contrib/constrained_optimization/python/swap_regret_optimizer.py
@@ -79,9 +79,11 @@ def _maximal_eigenvector_power_method(matrix,
The maximal right-eigenvector of `matrix`.
Raises:
- ValueError: If the epsilon or maximum_iterations parameters violate their
- bounds.
+ ValueError: If the `matrix` tensor is not floating-point, or if the
+ `epsilon` or `maximum_iterations` parameters violate their bounds.
"""
+ if not matrix.dtype.is_floating:
+ raise ValueError("multipliers must have a floating-point dtype")
if epsilon <= 0.0:
raise ValueError("epsilon must be strictly positive")
if maximum_iterations <= 0:
@@ -139,18 +141,20 @@ def _project_stochastic_matrix_wrt_euclidean_norm(matrix):
(i.e. the Frobenius norm).
Raises:
- ValueError: if the `matrix` tensor does not have a fully-known shape, or is
- not two-dimensional and square.
+ ValueError: if the `matrix` tensor is not floating-point, does not have a
+ fully-known shape, or is not two-dimensional and square.
"""
+ if not matrix.dtype.is_floating:
+ raise ValueError("multipliers must have a floating-point dtype")
matrix_shape = matrix.get_shape()
- if matrix_shape is None:
+ if matrix_shape.ndims is None:
raise ValueError("matrix must have known shape")
if matrix_shape.ndims != 2:
raise ValueError(
"matrix must be two dimensional (instead is %d-dimensional)" %
matrix_shape.ndims)
if matrix_shape[0] != matrix_shape[1]:
- raise ValueError("matrix must be be square (instead has shape (%d,%d))" %
+ raise ValueError("matrix must be square (instead has shape (%d,%d))" %
(matrix_shape[0], matrix_shape[1]))
dimension = matrix_shape[0].value
if dimension is None:
@@ -172,12 +176,12 @@ def _project_stochastic_matrix_wrt_euclidean_norm(matrix):
matrix, axis=0, keepdims=True)) / standard_ops.maximum(
1.0, standard_ops.reduce_sum(inactive, axis=0, keepdims=True))
matrix += scale * inactive
- new_inactive = standard_ops.to_float(matrix > 0)
+ new_inactive = standard_ops.cast(matrix > 0, matrix.dtype)
matrix *= new_inactive
return (iteration, matrix, new_inactive, inactive)
iteration = standard_ops.constant(0)
- inactive = standard_ops.ones_like(matrix)
+ inactive = standard_ops.ones_like(matrix, dtype=matrix.dtype)
# We actually want a do-while loop, so we explicitly call while_loop_body()
# once before tf.while_loop().
@@ -218,7 +222,7 @@ class _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
"""Base class representing a `_SwapRegretOptimizer`.
This class contains most of the logic for performing constrained optimization,
- minimizing external regret for the constraints player. What it *doesn't* do is
+ minimizing swap regret for the constraints player. What it *doesn't* do is
keep track of the internal state (the stochastic matrix). Instead, the state
is accessed via the _initial_state(), _stochastic_matrix(),
_constraint_grad_and_var() and _projection_op() methods.
@@ -291,16 +295,16 @@ class _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
def _projection_op(self, state, name=None):
pass
- def minimize_constrained(self,
- minimization_problem,
- global_step=None,
- var_list=None,
- gate_gradients=train_optimizer.Optimizer.GATE_OP,
- aggregation_method=None,
- colocate_gradients_with_ops=False,
- name=None,
- grad_loss=None):
- """Returns an `Op` for minimizing the constrained problem.
+ def _minimize_constrained(self,
+ minimization_problem,
+ global_step=None,
+ var_list=None,
+ gate_gradients=train_optimizer.Optimizer.GATE_OP,
+ aggregation_method=None,
+ colocate_gradients_with_ops=False,
+ name=None,
+ grad_loss=None):
+ """Returns an `Operation` for minimizing the constrained problem.
The `optimizer` constructor parameter will be used to update the model
parameters, while the constraint/objective weight matrix (the analogue of
@@ -320,8 +324,11 @@ class _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
name: as in `tf.train.Optimizer`'s `minimize` method.
grad_loss: as in `tf.train.Optimizer`'s `minimize` method.
+ Raises:
+ ValueError: If the minimization_problem tensors have different dtypes.
+
Returns:
- TensorFlow Op.
+ `Operation`, the train_op.
"""
objective = minimization_problem.objective
@@ -329,6 +336,14 @@ class _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
proxy_constraints = minimization_problem.proxy_constraints
if proxy_constraints is None:
proxy_constraints = constraints
+
+ # Make sure that the objective, constraints and proxy constraints all have
+ # the same dtype.
+ if (objective.dtype.base_dtype != constraints.dtype.base_dtype or
+ objective.dtype.base_dtype != proxy_constraints.dtype.base_dtype):
+ raise ValueError("objective, constraints and proxy_constraints must "
+ "have the same dtype")
+
# Flatten both constraints tensors to 1d.
num_constraints = minimization_problem.num_constraints
constraints = standard_ops.reshape(constraints, shape=(num_constraints,))
@@ -344,15 +359,18 @@ class _SwapRegretOptimizer(constrained_optimizer.ConstrainedOptimizer):
name="swap_regret_optimizer_state")
zero_and_constraints = standard_ops.concat(
- (standard_ops.zeros((1,)), constraints), axis=0)
+ (standard_ops.zeros((1,), dtype=constraints.dtype), constraints),
+ axis=0)
objective_and_proxy_constraints = standard_ops.concat(
(standard_ops.expand_dims(objective, 0), proxy_constraints), axis=0)
distribution = self._distribution(state)
- loss = standard_ops.tensordot(distribution, objective_and_proxy_constraints,
- 1)
+ loss = standard_ops.tensordot(
+ standard_ops.cast(distribution, objective_and_proxy_constraints.dtype),
+ objective_and_proxy_constraints, 1)
matrix_gradient = standard_ops.matmul(
- standard_ops.expand_dims(zero_and_constraints, 1),
+ standard_ops.expand_dims(
+ standard_ops.cast(zero_and_constraints, distribution.dtype), 1),
standard_ops.expand_dims(distribution, 0))
update_ops = []
@@ -555,6 +573,7 @@ class MultiplicativeSwapRegretOptimizer(_SwapRegretOptimizer):
log_initial_one = math.log(1.0 - (self._initial_multiplier_radius *
(dimension - 1) / (dimension)))
log_initial_zero = math.log(self._initial_multiplier_radius / dimension)
+ # FUTURE WORK: make the dtype a parameter.
return standard_ops.concat(
(standard_ops.constant(
log_initial_one, dtype=dtypes.float32, shape=(1, dimension)),
diff --git a/tensorflow/contrib/crf/__init__.py b/tensorflow/contrib/crf/__init__.py
index 615e62b16f..fe5e34d258 100644
--- a/tensorflow/contrib/crf/__init__.py
+++ b/tensorflow/contrib/crf/__init__.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""Linear-chain CRF layer.
-See the @{$python/contrib.crf} guide.
+See the [CRF](https://tensorflow.org/api_guides/python/contrib.crf) guide.
@@crf_binary_score
@@crf_decode
diff --git a/tensorflow/contrib/crf/python/kernel_tests/crf_test.py b/tensorflow/contrib/crf/python/kernel_tests/crf_test.py
index f56a973f6f..8cfe142059 100644
--- a/tensorflow/contrib/crf/python/kernel_tests/crf_test.py
+++ b/tensorflow/contrib/crf/python/kernel_tests/crf_test.py
@@ -158,7 +158,7 @@ class CrfTest(test.TestCase):
# Test both the length-1 and regular cases.
sequence_lengths_list = [
np.array(3, dtype=np.int32),
- np.array(1, dtype=np.int32)
+ np.array(1, dtype=np.int64)
]
inputs_list = [
np.array([[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]],
@@ -291,7 +291,7 @@ class CrfTest(test.TestCase):
# Test both the length-1 and regular cases.
sequence_lengths_list = [
np.array(3, dtype=np.int32),
- np.array(1, dtype=np.int32)
+ np.array(1, dtype=np.int64)
]
inputs_list = [
np.array([[4, 5, -3], [3, -1, 3], [-1, 2, 1], [0, 0, 0]],
diff --git a/tensorflow/contrib/crf/python/ops/crf.py b/tensorflow/contrib/crf/python/ops/crf.py
index 8a7ff61bc8..2a91dcb63a 100644
--- a/tensorflow/contrib/crf/python/ops/crf.py
+++ b/tensorflow/contrib/crf/python/ops/crf.py
@@ -548,7 +548,9 @@ def crf_decode(potentials, transition_params, sequence_length):
initial_state = array_ops.squeeze(initial_state, axis=[1]) # [B, O]
inputs = array_ops.slice(potentials, [0, 1, 0], [-1, -1, -1]) # [B, T-1, O]
# Sequence length is not allowed to be less than zero.
- sequence_length_less_one = math_ops.maximum(0, sequence_length - 1)
+ sequence_length_less_one = math_ops.maximum(
+ constant_op.constant(0, dtype=sequence_length.dtype),
+ sequence_length - 1)
backpointers, last_score = rnn.dynamic_rnn( # [B, T - 1, O], [B, O]
crf_fwd_cell,
inputs=inputs,
diff --git a/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py b/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
index d58198faf3..e26d56c857 100644
--- a/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
+++ b/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
@@ -56,7 +56,7 @@ class _CudnnRNN(base_layer.Layer):
Cudnn RNNs have two major differences from other platform-independent RNNs tf
provides:
* Cudnn LSTM and GRU are mathematically different from their tf counterparts.
- (e.g. @{tf.contrib.rnn.LSTMBlockCell} and @{tf.nn.rnn_cell.GRUCell}.
+ (e.g. `tf.contrib.rnn.LSTMBlockCell` and `tf.nn.rnn_cell.GRUCell`.
* Cudnn-trained checkpoints are not directly compatible with tf RNNs:
* They use a single opaque parameter buffer for the entire (possibly)
multi-layer multi-directional RNN; Whereas tf RNN weights are per-cell and
@@ -182,7 +182,7 @@ class _CudnnRNN(base_layer.Layer):
dropout: dropout rate, a number between [0, 1]. Dropout is applied between
each layer (no dropout is applied for a model with a single layer).
When set to 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
dtype: tf.float16, tf.float32 or tf.float64
kernel_initializer: starting value to initialize the weight.
diff --git a/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py b/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
index 748d7cd011..2c92f31788 100644
--- a/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
+++ b/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
@@ -61,8 +61,8 @@ _WEIGHTS_VARIABLE_NAME = rnn_cell_impl._WEIGHTS_VARIABLE_NAME
class CudnnCompatibleLSTMCell(lstm_ops.LSTMBlockCell):
"""Cudnn Compatible LSTMCell.
- A simple wrapper around @{tf.contrib.rnn.LSTMBlockCell} to use along with
- @{tf.contrib.cudnn_rnn.CudnnLSTM}. The latter's params can be used by
+ A simple wrapper around `tf.contrib.rnn.LSTMBlockCell` to use along with
+ `tf.contrib.cudnn_rnn.CudnnLSTM`. The latter's params can be used by
this cell seamlessly.
"""
@@ -76,8 +76,8 @@ class CudnnCompatibleLSTMCell(lstm_ops.LSTMBlockCell):
class CudnnCompatibleGRUCell(rnn_cell_impl.GRUCell):
"""Cudnn Compatible GRUCell.
- A GRU impl akin to @{tf.nn.rnn_cell.GRUCell} to use along with
- @{tf.contrib.cudnn_rnn.CudnnGRU}. The latter's params can be used by
+ A GRU impl akin to `tf.nn.rnn_cell.GRUCell` to use along with
+ `tf.contrib.cudnn_rnn.CudnnGRU`. The latter's params can be used by
it seamlessly.
It differs from platform-independent GRUs in how the new memory gate is
@@ -97,7 +97,7 @@ class CudnnCompatibleGRUCell(rnn_cell_impl.GRUCell):
$$h_t = (1 - u_t) .* h'_t + u_t .* h_t-1$$
```
- Other GRU (see @{tf.nn.rnn_cell.GRUCell} and @{tf.contrib.rnn.GRUBlockCell}):
+ Other GRU (see `tf.nn.rnn_cell.GRUCell` and `tf.contrib.rnn.GRUBlockCell`):
```python
# new memory gate
\\(h'_t = tanh(x_t * W_h + (r_t .* h_t-1) * R_h + b_{Wh})\\)
@@ -891,7 +891,7 @@ def _cudnn_rnn(inputs,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -957,7 +957,7 @@ def cudnn_lstm(inputs,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -998,7 +998,7 @@ def _cudnn_rnn_no_input_c(inputs,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1040,7 +1040,7 @@ def cudnn_gru(inputs,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1079,7 +1079,7 @@ def cudnn_rnn_relu(inputs,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1119,7 +1119,7 @@ def cudnn_rnn_tanh(inputs,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1161,7 +1161,7 @@ def cudnn_rnn_opaque_params_to_canonical(rnn_mode,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1224,7 +1224,7 @@ def cudnn_rnn_canonical_to_opaque_params(rnn_mode,
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1282,7 +1282,7 @@ def cudnn_rnn_opaque_params_size(rnn_mode,
'unidirectional' or 'bidirectional'
dtype: one of tf.float32 or tf.float64.
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
name: name of the operation.
Returns:
@@ -1349,7 +1349,7 @@ class _CudnnRNN(object):
'unidirectional' or 'bidirectional'
dtype: dtype of params, tf.float32 or tf.float64.
dropout: whether to enable dropout. With it is 0, dropout is disabled.
- seed: the op seed used for initializing dropout. See @{tf.set_random_seed}
+ seed: the op seed used for initializing dropout. See `tf.set_random_seed`
for behavior.
Raises:
ValueError: if direction is invalid.
diff --git a/tensorflow/contrib/data/__init__.py b/tensorflow/contrib/data/__init__.py
index 7878e46e88..5821d51bca 100644
--- a/tensorflow/contrib/data/__init__.py
+++ b/tensorflow/contrib/data/__init__.py
@@ -15,12 +15,12 @@
"""Experimental API for building input pipelines.
This module contains experimental `Dataset` sources and transformations that can
-be used in conjunction with the @{tf.data.Dataset} API. Note that the
+be used in conjunction with the `tf.data.Dataset` API. Note that the
`tf.contrib.data` API is not subject to the same backwards compatibility
guarantees as `tf.data`, but we will provide deprecation advice in advance of
removing existing functionality.
-See @{$guide/datasets$Importing Data} for an overview.
+See [Importing Data](https://tensorflow.org/guide/datasets) for an overview.
@@Counter
@@CheckpointInputPipelineHook
diff --git a/tensorflow/contrib/data/kernels/assert_next_dataset_op.cc b/tensorflow/contrib/data/kernels/assert_next_dataset_op.cc
index 95b8e1f7fd..e36c9c0634 100644
--- a/tensorflow/contrib/data/kernels/assert_next_dataset_op.cc
+++ b/tensorflow/contrib/data/kernels/assert_next_dataset_op.cc
@@ -42,13 +42,13 @@ class AssertNextDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const std::vector<string>& transformations,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
transformations_(transformations),
output_types_(output_types),
@@ -76,10 +76,11 @@ class AssertNextDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* transformations_node = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(transformations_, &transformations_node));
TF_RETURN_IF_ERROR(b->AddDataset(
@@ -121,13 +122,13 @@ class AssertNextDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/contrib/data/kernels/csv_dataset_op.cc b/tensorflow/contrib/data/kernels/csv_dataset_op.cc
index f7e3ed886c..d242cfdf49 100644
--- a/tensorflow/contrib/data/kernels/csv_dataset_op.cc
+++ b/tensorflow/contrib/data/kernels/csv_dataset_op.cc
@@ -131,7 +131,7 @@ class CSVDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::vector<string> filenames, bool header,
string compression_type, io::ZlibCompressionOptions options,
@@ -139,7 +139,7 @@ class CSVDatasetOp : public DatasetOpKernel {
const std::vector<PartialTensorShape>& output_shapes,
std::vector<Tensor> record_defaults, std::vector<int64> select_cols,
bool use_quote_delim, char delim, string na_value)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
filenames_(std::move(filenames)),
header_(header),
out_type_(output_types),
@@ -168,7 +168,8 @@ class CSVDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "CSVDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
Node* compression_type = nullptr;
diff --git a/tensorflow/contrib/data/kernels/directed_interleave_dataset_op.cc b/tensorflow/contrib/data/kernels/directed_interleave_dataset_op.cc
index 6a12ca06f4..ccf7ec1f84 100644
--- a/tensorflow/contrib/data/kernels/directed_interleave_dataset_op.cc
+++ b/tensorflow/contrib/data/kernels/directed_interleave_dataset_op.cc
@@ -63,11 +63,11 @@ class DirectedInterleaveDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* selector_input,
std::vector<DatasetBase*> data_inputs)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
selector_input_(selector_input),
data_inputs_(std::move(data_inputs)) {
selector_input_->Ref();
@@ -110,15 +110,16 @@ class DirectedInterleaveDatasetOp : public DatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* selector_input_node;
TF_RETURN_IF_ERROR(
- b->AddParentDataset(ctx, selector_input_, &selector_input_node));
+ b->AddInputDataset(ctx, selector_input_, &selector_input_node));
std::vector<Node*> data_input_nodes(data_inputs_.size());
for (size_t i = 0; i < data_inputs_.size(); ++i) {
TF_RETURN_IF_ERROR(
- b->AddParentDataset(ctx, data_inputs_[i], &data_input_nodes[i]));
+ b->AddInputDataset(ctx, data_inputs_[i], &data_input_nodes[i]));
}
TF_RETURN_IF_ERROR(b->AddDataset(this, {{0, selector_input_node}},
{{1, data_input_nodes}}, {}, output));
@@ -204,7 +205,7 @@ class DirectedInterleaveDatasetOp : public DatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (selector_input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, selector_input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, selector_input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("selector_input_impl_empty"), ""));
@@ -212,7 +213,7 @@ class DirectedInterleaveDatasetOp : public DatasetOpKernel {
for (size_t i = 0; i < data_input_impls_.size(); ++i) {
const auto& data_input_impl = data_input_impls_[i];
if (data_input_impl) {
- TF_RETURN_IF_ERROR(SaveParent(writer, data_input_impl));
+ TF_RETURN_IF_ERROR(SaveInput(writer, data_input_impl));
} else {
TF_RETURN_IF_ERROR(writer->WriteScalar(
full_name(strings::StrCat("data_input_impl_empty[", i, "]")),
@@ -226,15 +227,14 @@ class DirectedInterleaveDatasetOp : public DatasetOpKernel {
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("selector_input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, selector_input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, selector_input_impl_));
} else {
selector_input_impl_.reset();
}
for (size_t i = 0; i < data_input_impls_.size(); ++i) {
if (!reader->Contains(full_name(
strings::StrCat("data_input_impl_empty[", i, "]")))) {
- TF_RETURN_IF_ERROR(
- RestoreParent(ctx, reader, data_input_impls_[i]));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, data_input_impls_[i]));
} else {
data_input_impls_[i].reset();
}
diff --git a/tensorflow/contrib/data/kernels/ignore_errors_dataset_op.cc b/tensorflow/contrib/data/kernels/ignore_errors_dataset_op.cc
index bbec50681c..db24e60846 100644
--- a/tensorflow/contrib/data/kernels/ignore_errors_dataset_op.cc
+++ b/tensorflow/contrib/data/kernels/ignore_errors_dataset_op.cc
@@ -35,10 +35,10 @@ class IgnoreErrorsDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input)
- : GraphDatasetBase(ctx), input_(input) {
+ : DatasetBase(DatasetContext(ctx)), input_(input) {
input_->Ref();
}
@@ -62,10 +62,11 @@ class IgnoreErrorsDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph_node}, output));
return Status::OK();
}
@@ -106,7 +107,7 @@ class IgnoreErrorsDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_)
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
else
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impls_empty"), ""));
@@ -119,7 +120,7 @@ class IgnoreErrorsDatasetOp : public UnaryDatasetOpKernel {
if (reader->Contains(full_name("input_impls_empty")))
input_impl_.reset();
else
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/contrib/data/kernels/prefetching_kernels.cc b/tensorflow/contrib/data/kernels/prefetching_kernels.cc
index 32f03ca683..74df1e42a8 100644
--- a/tensorflow/contrib/data/kernels/prefetching_kernels.cc
+++ b/tensorflow/contrib/data/kernels/prefetching_kernels.cc
@@ -526,6 +526,15 @@ string SanitizeThreadSuffix(string suffix) {
return clean;
}
+struct HostBufferElement {
+ Status status;
+ bool end_of_sequence;
+ std::vector<Tensor> value;
+};
+
+using MultiDeviceIteratorCallback =
+ std::function<void(const HostBufferElement&)>;
+
class MultiDeviceIterator : public ResourceBase {
public:
MultiDeviceIterator(const DataTypeVector& output_types,
@@ -539,83 +548,45 @@ class MultiDeviceIterator : public ResourceBase {
devices_(devices),
flib_def_(std::move(flib_def)),
pflr_(std::move(pflr)),
- lib_(lib) {
- buffer_.resize(devices_.size());
- }
+ lib_(lib) {}
string DebugString() override {
- return strings::StrCat("MultiDeviceIterator");
+ return strings::StrCat("MultiDeviceIterator for ", devices_.size(),
+ " devices");
}
- Status Init(std::unique_ptr<IteratorBase> iterator, int64* incarnation_id) {
- mutex_lock l(mu_);
+ Status Init(std::unique_ptr<IteratorBase> iterator, int64 max_buffer_size,
+ int64* incarnation_id) {
if (iterator) {
TF_RETURN_IF_ERROR(
VerifyTypesMatch(output_types_, iterator->output_dtypes()));
TF_RETURN_IF_ERROR(
VerifyShapesCompatible(output_shapes_, iterator->output_shapes()));
}
- host_iterator_.reset(iterator.release());
- incarnation_id_++;
+
+ mutex_lock l(mu_);
+ if (multi_device_buffer_) {
+ multi_device_buffer_->Reset();
+ }
+
+ ++incarnation_id_;
*incarnation_id = incarnation_id_;
- max_buffer_size_ = 0;
- num_elements_ = 0;
- buffer_.clear();
- buffer_.resize(devices_.size());
+
+ multi_device_buffer_.reset(
+ new MultiDeviceBuffer(devices_.size(), max_buffer_size, incarnation_id_,
+ std::move(iterator)));
return Status::OK();
}
- Status GetNextFromShard(IteratorContext* ctx, int shard_num,
- int64 incarnation_id,
- std::vector<Tensor>* out_tensors,
- bool* end_of_sequence) {
- // TODO(rohanj): This might potentially strand elements in other shards.
- // Opportunity to do smarter locking semantics.
- mutex_lock l(mu_);
- // Make sure we're in the right incarnation.
- if (incarnation_id != incarnation_id_) {
- return errors::InvalidArgument(
- "Current incarnation: ", incarnation_id_,
- "; Supplied incarnation: ", incarnation_id);
- }
- // Then look it up in the buffer.
- if (!buffer_[shard_num].empty()) {
- const HostBufferElement& elem = buffer_[shard_num].front();
- *out_tensors = elem.value;
- *end_of_sequence = elem.end_of_sequence;
- Status s = elem.status;
- buffer_[shard_num].pop_front();
- return s;
- }
- std::shared_ptr<IteratorBase> captured_iterator(host_iterator_);
- if (captured_iterator) {
- if (lib_ != nullptr) {
- ctx->set_lib(lib_);
- }
- while (true) {
- HostBufferElement elem;
- elem.status =
- captured_iterator->GetNext(ctx, &elem.value, &elem.end_of_sequence);
- int buffer_index = num_elements_ % devices_.size();
- num_elements_++;
- if (buffer_index == shard_num) {
- out_tensors->swap(elem.value);
- *end_of_sequence = elem.end_of_sequence;
- return elem.status;
- } else {
- buffer_[buffer_index].push_back(std::move(elem));
- // TODO(rohanj): Put an upper bound to buffer size.
- if (buffer_[buffer_index].size() > max_buffer_size_) {
- max_buffer_size_ = buffer_[buffer_index].size();
- VLOG(1) << "MultiDeviceIterator: Max buffer size increased to: "
- << max_buffer_size_;
- }
- }
- }
- } else {
- return errors::FailedPrecondition("Iterator not initialized");
+ void GetNextFromShard(IteratorContext* ctx, int shard_num,
+ int64 incarnation_id,
+ MultiDeviceIteratorCallback callback) {
+ if (lib_ != nullptr) {
+ ctx->set_lib(lib_);
}
- return Status::OK();
+ tf_shared_lock l(mu_);
+ multi_device_buffer_->GetNextFromShard(ctx, shard_num, incarnation_id,
+ std::move(callback));
}
const DataTypeVector& output_types() const { return output_types_; }
@@ -630,25 +601,218 @@ class MultiDeviceIterator : public ResourceBase {
}
private:
- struct HostBufferElement {
- Status status;
- bool end_of_sequence;
- std::vector<Tensor> value;
+ // A private class that uses a background thread to keep a per device buffer
+ // full.
+ class MultiDeviceBuffer {
+ public:
+ MultiDeviceBuffer(size_t size, int64 max_buffer_size, int64 incarnation_id,
+ std::unique_ptr<IteratorBase> host_iterator)
+ : buffer_(size),
+ size_(size),
+ max_buffer_size_(max_buffer_size),
+ incarnation_id_(incarnation_id),
+ host_iterator_(std::move(host_iterator)) {}
+
+ ~MultiDeviceBuffer() { Reset(); }
+
+ void Reset() LOCKS_EXCLUDED(mu_) {
+ {
+ mutex_lock l(mu_);
+ if (background_thread_finished_) {
+ return;
+ }
+
+ cancelled_ = true;
+ // Wake up the background thread.
+ for (int i = 0; i < size_; ++i) {
+ buffer_[i].cond_var.notify_all();
+ }
+
+ // Make sure background thread has finished first.
+ while (!background_thread_finished_) {
+ shutdown_cond_var_.wait(l);
+ }
+ }
+ RunPendingCallbacks();
+ }
+
+ void GetNextFromShard(IteratorContext* ctx, int shard_num,
+ int64 incarnation_id,
+ MultiDeviceIteratorCallback callback) {
+ HostBufferElement elem;
+ if (incarnation_id_ != incarnation_id) {
+ elem.status = errors::InvalidArgument("Invalid incarnation id");
+ callback(elem);
+ return;
+ }
+
+ bool produced_output = false;
+ {
+ mutex_lock l(mu_);
+ if (cancelled_) {
+ elem.status = errors::Cancelled("Cancelled Multidevice iterator");
+ callback(elem);
+ return;
+ }
+
+ EnsureBackgroundThreadStarted(ctx);
+
+ if (!buffer_[shard_num].data.empty()) {
+ produced_output = true;
+ std::swap(elem, buffer_[shard_num].data.front());
+ buffer_[shard_num].data.pop_front();
+ // Wake up background thread if it is blocked on this element.
+ if (buffer_[shard_num].data.size() == max_buffer_size_ - 1) {
+ buffer_[shard_num].cond_var.notify_all();
+ }
+ } else {
+ if (background_thread_finished_) {
+ produced_output = true;
+ elem.end_of_sequence = true;
+ } else {
+ buffer_[shard_num].callbacks.push_back(std::move(callback));
+ callback = nullptr;
+ }
+ }
+ }
+
+ if (produced_output) {
+ callback(elem);
+ }
+ }
+
+ private:
+ void EnsureBackgroundThreadStarted(IteratorContext* ctx)
+ EXCLUSIVE_LOCKS_REQUIRED(mu_) {
+ if (!background_thread_) {
+ background_thread_.reset(ctx->env()->StartThread(
+ {}, "multi_device_iterator_background_thread",
+ std::bind(&MultiDeviceIterator::MultiDeviceBuffer::BackgroundThread,
+ this, new IteratorContext(*ctx))));
+ }
+ }
+
+ void RunPendingCallbacks() LOCKS_EXCLUDED(mu_) {
+ // Run all remaining callbacks.
+ std::vector<MultiDeviceIteratorCallback> cancellation_callbacks;
+ std::vector<HostBufferElement> cancellation_elements;
+ {
+ mutex_lock l(mu_);
+
+ for (int i = 0; i < size_; ++i) {
+ while (!buffer_[i].callbacks.empty()) {
+ if (buffer_[i].data.empty()) {
+ HostBufferElement elem;
+ elem.status =
+ errors::Cancelled("Cancelled and buffer not filled.");
+ cancellation_elements.push_back(std::move(elem));
+ } else {
+ cancellation_elements.push_back(
+ std::move(buffer_[i].data.front()));
+ buffer_[i].data.pop_front();
+ }
+ cancellation_callbacks.push_back(
+ std::move(buffer_[i].callbacks.front()));
+ buffer_[i].callbacks.pop_front();
+ }
+ }
+ }
+ for (int i = 0; i < cancellation_callbacks.size(); ++i) {
+ cancellation_callbacks[i](cancellation_elements[i]);
+ }
+ }
+
+ void BackgroundThread(IteratorContext* ctx) {
+ std::unique_ptr<IteratorContext> cleanup(ctx);
+ int shard_to_fetch = 0;
+ while (true) {
+ HostBufferElement elem;
+ MultiDeviceIteratorCallback callback = nullptr;
+ bool end_of_iterator = false;
+
+ {
+ mutex_lock l(mu_);
+ while (!cancelled_ &&
+ buffer_[shard_to_fetch].data.size() >= max_buffer_size_) {
+ buffer_[shard_to_fetch].cond_var.wait(l);
+ }
+
+ if (cancelled_) {
+ background_thread_finished_ = true;
+ shutdown_cond_var_.notify_all();
+ return;
+ }
+ }
+
+ elem.status =
+ host_iterator_->GetNext(ctx, &elem.value, &elem.end_of_sequence);
+
+ if (elem.status.ok() && elem.end_of_sequence) {
+ end_of_iterator = true;
+ }
+
+ {
+ mutex_lock l(mu_);
+ // Try to find a callback, else just push stuff into buffer.
+ if (!buffer_[shard_to_fetch].callbacks.empty()) {
+ callback = buffer_[shard_to_fetch].callbacks.front();
+ buffer_[shard_to_fetch].callbacks.pop_front();
+ } else {
+ buffer_[shard_to_fetch].data.push_back(std::move(elem));
+ elem = HostBufferElement();
+ }
+ }
+
+ if (callback) {
+ (*ctx->runner())(std::bind(std::move(callback), std::move(elem)));
+ }
+
+ // Finish off the thread if we reach the end of the iterator. Runs
+ // pending callbacks.
+ if (end_of_iterator) {
+ {
+ mutex_lock l(mu_);
+ background_thread_finished_ = true;
+ shutdown_cond_var_.notify_all();
+ }
+ RunPendingCallbacks();
+ return;
+ }
+ shard_to_fetch = (shard_to_fetch + 1) % size_;
+ }
+ }
+
+ struct HostBuffer {
+ condition_variable cond_var;
+ std::deque<HostBufferElement> data;
+ std::deque<MultiDeviceIteratorCallback> callbacks;
+ };
+
+ mutex mu_;
+ std::unique_ptr<Thread> background_thread_ GUARDED_BY(mu_);
+ bool background_thread_finished_ GUARDED_BY(mu_) = false;
+ bool cancelled_ GUARDED_BY(mu_) = false;
+ condition_variable shutdown_cond_var_ GUARDED_BY(mu_);
+
+ std::vector<HostBuffer> buffer_;
+
+ const size_t size_;
+ const int64 max_buffer_size_;
+ const int64 incarnation_id_;
+ const std::unique_ptr<IteratorBase> host_iterator_;
};
mutex mu_;
const DataTypeVector output_types_;
const std::vector<PartialTensorShape> output_shapes_;
const std::vector<string> devices_;
- int64 num_elements_ GUARDED_BY(mu_) = 0;
- int64 max_buffer_size_ GUARDED_BY(mu_) = 0;
- int64 incarnation_id_ GUARDED_BY(mu_) = 0;
- std::vector<std::deque<HostBufferElement>> buffer_ GUARDED_BY(mu_);
- std::unique_ptr<FunctionLibraryDefinition> flib_def_;
- std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_;
- FunctionLibraryRuntime* lib_ = nullptr; // not owned.
- std::shared_ptr<IteratorBase> host_iterator_;
+ const std::unique_ptr<FunctionLibraryDefinition> flib_def_;
+ const std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_;
+ FunctionLibraryRuntime* const lib_ = nullptr; // not owned.
std::shared_ptr<const FunctionLibraryDefinition> lib_def_ GUARDED_BY(mu_);
+
+ int64 incarnation_id_ GUARDED_BY(mu_) = 0;
+ std::unique_ptr<MultiDeviceBuffer> multi_device_buffer_ GUARDED_BY(mu_);
};
// Just creates a MultiDeviceIterator and returns it.
@@ -754,6 +918,10 @@ class MultiDeviceIteratorInitOp : public OpKernel {
: OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
+ const Tensor* tensor_max_buffer_size;
+ OP_REQUIRES_OK(ctx, ctx->input("max_buffer_size", &tensor_max_buffer_size));
+ int64 max_buffer_size = tensor_max_buffer_size->scalar<int64>()();
+
DatasetBase* dataset;
OP_REQUIRES_OK(ctx, GetDatasetFromVariantTensor(ctx->input(0), &dataset));
MultiDeviceIterator* resource;
@@ -761,12 +929,12 @@ class MultiDeviceIteratorInitOp : public OpKernel {
LookupResource(ctx, HandleFromInput(ctx, 1), &resource));
core::ScopedUnref unref(resource);
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iterator;
- OP_REQUIRES_OK(ctx,
- dataset->MakeIterator(&iter_ctx, "Iterator", &iterator));
+ OP_REQUIRES_OK(ctx, dataset->MakeIterator(IteratorContext(ctx), "Iterator",
+ &iterator));
int64 incarnation_id;
- OP_REQUIRES_OK(ctx, resource->Init(std::move(iterator), &incarnation_id));
+ OP_REQUIRES_OK(ctx, resource->Init(std::move(iterator), max_buffer_size,
+ &incarnation_id));
Tensor tensor_incarnation_id(DT_INT64, TensorShape({}));
tensor_incarnation_id.scalar<int64>()() = incarnation_id;
OP_REQUIRES_OK(ctx,
@@ -804,9 +972,6 @@ class MultiDeviceIteratorGetNextFromShardOp : public AsyncOpKernel {
ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &iterator), done);
thread_pool_->Schedule(std::bind(
[ctx, iterator, shard_num, incarnation_id](DoneCallback done) {
- std::vector<Tensor> components;
- bool end_of_sequence = false;
-
IteratorContext::Params params;
params.env = ctx->env();
params.runner = *(ctx->runner());
@@ -817,22 +982,26 @@ class MultiDeviceIteratorGetNextFromShardOp : public AsyncOpKernel {
};
IteratorContext iter_ctx(std::move(params));
- Status s =
- iterator->GetNextFromShard(&iter_ctx, shard_num, incarnation_id,
- &components, &end_of_sequence);
- iterator->Unref();
+ MultiDeviceIteratorCallback callback = std::bind(
+ [ctx](const HostBufferElement& elem, DoneCallback done) {
+ // iterator->Unref();
+ Status s = elem.status;
+ if (!s.ok()) {
+ ctx->SetStatus(s);
+ } else if (elem.end_of_sequence) {
+ ctx->SetStatus(errors::OutOfRange("End of sequence"));
+ } else {
+ for (int i = 0; i < elem.value.size(); ++i) {
+ ctx->set_output(i, elem.value[i]);
+ }
+ }
+ done();
+ },
+ std::placeholders::_1, std::move(done));
- if (!s.ok()) {
- ctx->SetStatus(s);
- } else if (end_of_sequence) {
- ctx->SetStatus(errors::OutOfRange("End of sequence"));
- } else {
- for (int i = 0; i < components.size(); ++i) {
- // TODO(mrry): Check that the shapes match the shape attrs.
- ctx->set_output(i, components[i]);
- }
- }
- done();
+ iterator->GetNextFromShard(&iter_ctx, shard_num, incarnation_id,
+ callback);
+ iterator->Unref();
},
std::move(done)));
}
diff --git a/tensorflow/contrib/data/kernels/threadpool_dataset_op.cc b/tensorflow/contrib/data/kernels/threadpool_dataset_op.cc
index 141706f393..ab584504a0 100644
--- a/tensorflow/contrib/data/kernels/threadpool_dataset_op.cc
+++ b/tensorflow/contrib/data/kernels/threadpool_dataset_op.cc
@@ -130,11 +130,13 @@ class ThreadPoolDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
ThreadPoolResource* threadpool)
- : GraphDatasetBase(ctx), input_(input), threadpool_(threadpool) {
+ : DatasetBase(DatasetContext(ctx)),
+ input_(input),
+ threadpool_(threadpool) {
input_->Ref();
threadpool_->Ref();
}
@@ -162,11 +164,11 @@ class ThreadPoolDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- return errors::Unimplemented(
- "Cannot currently serialize the thread pool for a "
- "ThreadPoolDataset.");
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
}
private:
diff --git a/tensorflow/contrib/data/kernels/unique_dataset_op.cc b/tensorflow/contrib/data/kernels/unique_dataset_op.cc
index 67c237799c..6fbf5d2ebb 100644
--- a/tensorflow/contrib/data/kernels/unique_dataset_op.cc
+++ b/tensorflow/contrib/data/kernels/unique_dataset_op.cc
@@ -47,10 +47,10 @@ class UniqueDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input)
- : GraphDatasetBase(ctx), input_(input) {
+ : DatasetBase(DatasetContext(ctx)), input_(input) {
input_->Ref();
}
@@ -75,10 +75,11 @@ class UniqueDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph_node}, output));
return Status::OK();
}
@@ -116,7 +117,7 @@ class UniqueDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
@@ -135,7 +136,7 @@ class UniqueDatasetOp : public UnaryDatasetOpKernel {
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/contrib/data/ops/dataset_ops.cc b/tensorflow/contrib/data/ops/dataset_ops.cc
index 66a7c7fdcd..cc5e250ea1 100644
--- a/tensorflow/contrib/data/ops/dataset_ops.cc
+++ b/tensorflow/contrib/data/ops/dataset_ops.cc
@@ -168,9 +168,11 @@ output_shapes: The list of shapes being produced.
REGISTER_OP("MultiDeviceIteratorInit")
.Input("dataset: variant")
.Input("multi_device_iterator: resource")
+ .Input("max_buffer_size: int64")
.Output("incarnation_id: int64")
.Doc(R"doc(
Initializes the multi device iterator with the given dataset.
+max_buffer_size: The maximum size of the host side per device buffer to keep.
incarnation_id: An int64 indicating which incarnation of the MultiDeviceIterator
is running.
dataset: Dataset to be iterated upon.
diff --git a/tensorflow/contrib/data/python/kernel_tests/BUILD b/tensorflow/contrib/data/python/kernel_tests/BUILD
index ea92191f3e..2b75aa2ca5 100644
--- a/tensorflow/contrib/data/python/kernel_tests/BUILD
+++ b/tensorflow/contrib/data/python/kernel_tests/BUILD
@@ -175,7 +175,7 @@ py_test(
"//tensorflow/python:variables",
"//tensorflow/python/data/ops:dataset_ops",
"//tensorflow/python/estimator",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
],
)
diff --git a/tensorflow/contrib/data/python/kernel_tests/interleave_dataset_op_test.py b/tensorflow/contrib/data/python/kernel_tests/interleave_dataset_op_test.py
index 44c3325a3d..7a3215f6cc 100644
--- a/tensorflow/contrib/data/python/kernel_tests/interleave_dataset_op_test.py
+++ b/tensorflow/contrib/data/python/kernel_tests/interleave_dataset_op_test.py
@@ -777,6 +777,34 @@ class ParallelInterleaveDatasetTest(test.TestCase):
with self.assertRaises(errors.OutOfRangeError):
sess.run(self.next_element)
+ def testShutdownRace(self):
+ dataset = dataset_ops.Dataset.range(20)
+ map_fn = lambda x: dataset_ops.Dataset.range(20 * x, 20 * (x + 1))
+ dataset = dataset.apply(
+ interleave_ops.parallel_interleave(
+ map_fn,
+ cycle_length=3,
+ sloppy=False,
+ buffer_output_elements=1,
+ prefetch_input_elements=0))
+ dataset = dataset.batch(32)
+ iterator = dataset.make_initializable_iterator()
+ next_element = iterator.get_next()
+
+ results = []
+ with self.test_session() as sess:
+ for _ in range(2):
+ elements = []
+ sess.run(iterator.initializer)
+ try:
+ while True:
+ elements.extend(sess.run(next_element))
+ except errors.OutOfRangeError:
+ pass
+ results.append(elements)
+
+ self.assertAllEqual(results[0], results[1])
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/data/python/kernel_tests/prefetching_ops_test.py b/tensorflow/contrib/data/python/kernel_tests/prefetching_ops_test.py
index d66305d732..361fe0dd39 100644
--- a/tensorflow/contrib/data/python/kernel_tests/prefetching_ops_test.py
+++ b/tensorflow/contrib/data/python/kernel_tests/prefetching_ops_test.py
@@ -1021,7 +1021,7 @@ class MultiDeviceIteratorTest(test.TestCase):
def testUneven(self):
dataset = dataset_ops.Dataset.range(10)
multi_device_iterator = prefetching_ops.MultiDeviceIterator(
- dataset, ["/cpu:1", "/cpu:2"])
+ dataset, ["/cpu:1", "/cpu:2"], max_buffer_size=4)
elem_on_1, elem_on_2 = multi_device_iterator.get_next()
config = config_pb2.ConfigProto(device_count={"CPU": 3})
@@ -1079,7 +1079,7 @@ class MultiDeviceIteratorTest(test.TestCase):
with compat.forward_compatibility_horizon(2018, 8, 4):
dataset = dataset_ops.Dataset.range(10)
multi_device_iterator = prefetching_ops.MultiDeviceIterator(
- dataset, ["/cpu:1", "/gpu:0"])
+ dataset, ["/cpu:1", "/gpu:0"], max_buffer_size=4)
elem_on_1, elem_on_2 = multi_device_iterator.get_next()
config = config_pb2.ConfigProto(device_count={"CPU": 2, "GPU": 1})
diff --git a/tensorflow/contrib/data/python/ops/batching.py b/tensorflow/contrib/data/python/ops/batching.py
index 4835c4e5bd..9f059942a6 100644
--- a/tensorflow/contrib/data/python/ops/batching.py
+++ b/tensorflow/contrib/data/python/ops/batching.py
@@ -185,7 +185,7 @@ def dense_to_sparse_batch(batch_size, row_shape):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -401,7 +401,7 @@ def unbatch():
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -443,7 +443,7 @@ def unbatch():
def batch_and_drop_remainder(batch_size):
"""A batching transformation that omits the final small batch (if present).
- Like @{tf.data.Dataset.batch}, this transformation combines
+ Like `tf.data.Dataset.batch`, this transformation combines
consecutive elements of this dataset into batches. However, if the batch
size does not evenly divide the input dataset size, this transformation will
drop the final smaller element.
@@ -467,7 +467,7 @@ def batch_and_drop_remainder(batch_size):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}
+ `tf.data.Dataset.apply`
"""
def _apply_fn(dataset):
@@ -484,25 +484,25 @@ def padded_batch_and_drop_remainder(batch_size,
padding_values=None):
"""A batching and padding transformation that omits the final small batch.
- Like @{tf.data.Dataset.padded_batch}, this transformation combines
+ Like `tf.data.Dataset.padded_batch`, this transformation combines
consecutive elements of this dataset into batches. However, if the batch
size does not evenly divide the input dataset size, this transformation will
drop the final smaller element.
- See `@{tf.contrib.data.batch_and_drop_remainder}` for more details.
+ See `tf.contrib.data.batch_and_drop_remainder` for more details.
Args:
batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of
consecutive elements of this dataset to combine in a single batch.
padded_shapes: A nested structure of `tf.TensorShape` or
`tf.int64` vector tensor-like objects. See
- @{tf.data.Dataset.padded_batch} for details.
+ `tf.data.Dataset.padded_batch` for details.
padding_values: (Optional.) A nested structure of scalar-shaped
- `tf.Tensor`. See @{tf.data.Dataset.padded_batch} for details.
+ `tf.Tensor`. See `tf.data.Dataset.padded_batch` for details.
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}
+ `tf.data.Dataset.apply`
"""
def _apply_fn(dataset):
@@ -661,7 +661,7 @@ def assert_element_shape(expected_shapes):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}
+ `tf.data.Dataset.apply`
"""
def _check_shape(*elements):
@@ -760,7 +760,7 @@ def map_and_batch(map_func,
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
Raises:
ValueError: If both `num_parallel_batches` and `num_parallel_calls` are
diff --git a/tensorflow/contrib/data/python/ops/enumerate_ops.py b/tensorflow/contrib/data/python/ops/enumerate_ops.py
index ac2b386b81..490281e0d2 100644
--- a/tensorflow/contrib/data/python/ops/enumerate_ops.py
+++ b/tensorflow/contrib/data/python/ops/enumerate_ops.py
@@ -47,7 +47,7 @@ def enumerate_dataset(start=0):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
diff --git a/tensorflow/contrib/data/python/ops/error_ops.py b/tensorflow/contrib/data/python/ops/error_ops.py
index d46d96c461..b4a7521e08 100644
--- a/tensorflow/contrib/data/python/ops/error_ops.py
+++ b/tensorflow/contrib/data/python/ops/error_ops.py
@@ -42,7 +42,7 @@ def ignore_errors():
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
diff --git a/tensorflow/contrib/data/python/ops/get_single_element.py b/tensorflow/contrib/data/python/ops/get_single_element.py
index ef9284456e..a6713b017a 100644
--- a/tensorflow/contrib/data/python/ops/get_single_element.py
+++ b/tensorflow/contrib/data/python/ops/get_single_element.py
@@ -29,8 +29,8 @@ from tensorflow.python.ops import gen_dataset_ops
def get_single_element(dataset):
"""Returns the single element in `dataset` as a nested structure of tensors.
- This function enables you to use a @{tf.data.Dataset} in a stateless
- "tensor-in tensor-out" expression, without creating a @{tf.data.Iterator}.
+ This function enables you to use a `tf.data.Dataset` in a stateless
+ "tensor-in tensor-out" expression, without creating a `tf.data.Iterator`.
This can be useful when your preprocessing transformations are expressed
as a `Dataset`, and you want to use the transformation at serving time.
For example:
@@ -50,10 +50,10 @@ def get_single_element(dataset):
```
Args:
- dataset: A @{tf.data.Dataset} object containing a single element.
+ dataset: A `tf.data.Dataset` object containing a single element.
Returns:
- A nested structure of @{tf.Tensor} objects, corresponding to the single
+ A nested structure of `tf.Tensor` objects, corresponding to the single
element of `dataset`.
Raises:
@@ -77,11 +77,11 @@ def reduce_dataset(dataset, reducer):
"""Returns the result of reducing the `dataset` using `reducer`.
Args:
- dataset: A @{tf.data.Dataset} object.
- reducer: A @{tf.contrib.data.Reducer} object representing the reduce logic.
+ dataset: A `tf.data.Dataset` object.
+ reducer: A `tf.contrib.data.Reducer` object representing the reduce logic.
Returns:
- A nested structure of @{tf.Tensor} objects, corresponding to the result
+ A nested structure of `tf.Tensor` objects, corresponding to the result
of reducing `dataset` using `reducer`.
Raises:
diff --git a/tensorflow/contrib/data/python/ops/grouping.py b/tensorflow/contrib/data/python/ops/grouping.py
index bd8d398c58..6edc1d7990 100644
--- a/tensorflow/contrib/data/python/ops/grouping.py
+++ b/tensorflow/contrib/data/python/ops/grouping.py
@@ -50,7 +50,7 @@ def group_by_reducer(key_func, reducer):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -92,7 +92,7 @@ def group_by_window(key_func,
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
Raises:
ValueError: if neither or both of {`window_size`, `window_size_func`} are
@@ -142,11 +142,11 @@ def bucket_by_sequence_length(element_length_func,
bucket_batch_sizes: `list<int>`, batch size per bucket. Length should be
`len(bucket_boundaries) + 1`.
padded_shapes: Nested structure of `tf.TensorShape` to pass to
- @{tf.data.Dataset.padded_batch}. If not provided, will use
+ `tf.data.Dataset.padded_batch`. If not provided, will use
`dataset.output_shapes`, which will result in variable length dimensions
being padded out to the maximum length in each batch.
padding_values: Values to pad with, passed to
- @{tf.data.Dataset.padded_batch}. Defaults to padding with 0.
+ `tf.data.Dataset.padded_batch`. Defaults to padding with 0.
pad_to_bucket_boundary: bool, if `False`, will pad dimensions with unknown
size to maximum length in batch. If `True`, will pad dimensions with
unknown size to bucket boundary minus 1 (i.e., the maximum length in each
@@ -155,7 +155,7 @@ def bucket_by_sequence_length(element_length_func,
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
Raises:
ValueError: if `len(bucket_batch_sizes) != len(bucket_boundaries) + 1`.
diff --git a/tensorflow/contrib/data/python/ops/interleave_ops.py b/tensorflow/contrib/data/python/ops/interleave_ops.py
index bcc959594a..5a1a35199a 100644
--- a/tensorflow/contrib/data/python/ops/interleave_ops.py
+++ b/tensorflow/contrib/data/python/ops/interleave_ops.py
@@ -42,7 +42,7 @@ def parallel_interleave(map_func,
`parallel_interleave()` maps `map_func` across its input to produce nested
datasets, and outputs their elements interleaved. Unlike
- @{tf.data.Dataset.interleave}, it gets elements from `cycle_length` nested
+ `tf.data.Dataset.interleave`, it gets elements from `cycle_length` nested
datasets in parallel, which increases the throughput, especially in the
presence of stragglers. Furthermore, the `sloppy` argument can be used to
improve performance, by relaxing the requirement that the outputs are produced
@@ -79,7 +79,7 @@ def parallel_interleave(map_func,
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
return readers.ParallelInterleaveDataset(
@@ -138,7 +138,7 @@ def sloppy_interleave(map_func, cycle_length, block_length=1):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
return readers.ParallelInterleaveDataset(
@@ -196,15 +196,15 @@ def sample_from_datasets(datasets, weights=None, seed=None):
"""Samples elements at random from the datasets in `datasets`.
Args:
- datasets: A list of @{tf.data.Dataset} objects with compatible structure.
+ datasets: A list of `tf.data.Dataset` objects with compatible structure.
weights: (Optional.) A list of `len(datasets)` floating-point values where
`weights[i]` represents the probability with which an element should be
- sampled from `datasets[i]`, or a @{tf.data.Dataset} object where each
+ sampled from `datasets[i]`, or a `tf.data.Dataset` object where each
element is such a list. Defaults to a uniform distribution across
`datasets`.
seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
random seed that will be used to create the distribution. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
Returns:
A dataset that interleaves elements from `datasets` at random, according to
@@ -262,8 +262,8 @@ def choose_from_datasets(datasets, choice_dataset):
```
Args:
- datasets: A list of @{tf.data.Dataset} objects with compatible structure.
- choice_dataset: A @{tf.data.Dataset} of scalar `tf.int64` tensors between
+ datasets: A list of `tf.data.Dataset` objects with compatible structure.
+ choice_dataset: A `tf.data.Dataset` of scalar `tf.int64` tensors between
`0` and `len(datasets) - 1`.
Returns:
diff --git a/tensorflow/contrib/data/python/ops/iterator_ops.py b/tensorflow/contrib/data/python/ops/iterator_ops.py
index d2c1d0d362..18515e21ed 100644
--- a/tensorflow/contrib/data/python/ops/iterator_ops.py
+++ b/tensorflow/contrib/data/python/ops/iterator_ops.py
@@ -118,7 +118,7 @@ class CheckpointInputPipelineHook(session_run_hook.SessionRunHook):
pipeline.
For saving the input pipeline checkpoint alongside the model weights use
- @{tf.contrib.data.make_saveable_from_iterator} directly to create a
+ `tf.contrib.data.make_saveable_from_iterator` directly to create a
`SaveableObject` and add to the `SAVEABLE_OBJECTS` collection. Note, however,
that you will need to be careful not to restore the training iterator during
eval. You can do that by not adding the iterator to the SAVEABLE_OBJECTS
diff --git a/tensorflow/contrib/data/python/ops/optimization.py b/tensorflow/contrib/data/python/ops/optimization.py
index 018c5115e1..fa1b851ad7 100644
--- a/tensorflow/contrib/data/python/ops/optimization.py
+++ b/tensorflow/contrib/data/python/ops/optimization.py
@@ -36,7 +36,7 @@ def assert_next(transformations):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -56,7 +56,7 @@ def optimize(optimizations=None):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
diff --git a/tensorflow/contrib/data/python/ops/prefetching_ops.py b/tensorflow/contrib/data/python/ops/prefetching_ops.py
index 0243c72c70..5222011d04 100644
--- a/tensorflow/contrib/data/python/ops/prefetching_ops.py
+++ b/tensorflow/contrib/data/python/ops/prefetching_ops.py
@@ -92,7 +92,7 @@ def function_buffering_resource_reset(function_buffer_resource, name=None):
# pylint: disable=protected-access
class _PrefetchToDeviceIterator(object):
- """A replacement for @{tf.data.Iterator} that prefetches to another device.
+ """A replacement for `tf.data.Iterator` that prefetches to another device.
Args:
input_dataset: The input dataset
@@ -158,7 +158,7 @@ class _PrefetchToDeviceIterator(object):
self._input_dataset)
def get_next(self, name=None):
- """See @{tf.data.Iterator.get_next}."""
+ """See `tf.data.Iterator.get_next`."""
self._get_next_call_count += 1
if self._get_next_call_count > iterator_ops.GET_NEXT_CALL_WARNING_THRESHOLD:
warnings.warn(iterator_ops.GET_NEXT_CALL_WARNING_MESSAGE)
@@ -199,7 +199,7 @@ class _PrefetchToDeviceIterator(object):
class _PrefetchToDeviceEagerIterator(iterator_ops.EagerIterator):
- """A replacement for @{tf.data.Iterator} that prefetches to another device.
+ """A replacement for `tf.data.Iterator` that prefetches to another device.
Args:
input_dataset: The input dataset
@@ -334,7 +334,7 @@ class _PrefetchToDeviceDataset(dataset_ops.Dataset):
def prefetch_to_device(device, buffer_size=None):
"""A transformation that prefetches dataset values to the given `device`.
- NOTE: Although the transformation creates a @{tf.data.Dataset}, the
+ NOTE: Although the transformation creates a `tf.data.Dataset`, the
transformation must be the final `Dataset` in the input pipeline.
Args:
@@ -344,7 +344,7 @@ def prefetch_to_device(device, buffer_size=None):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
return _PrefetchToDeviceDataset(dataset, device, buffer_size)
@@ -361,7 +361,7 @@ def copy_to_device(target_device, source_device="/cpu:0"):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -631,6 +631,7 @@ class MultiDeviceIterator(object):
def __init__(self,
dataset,
devices,
+ max_buffer_size=1,
prefetch_buffer_size=1,
source_device="/cpu:0"):
"""Constructs a MultiDeviceIterator.
@@ -638,6 +639,7 @@ class MultiDeviceIterator(object):
Args:
dataset: The input dataset to be iterated over.
devices: The list of devices to fetch data to.
+ max_buffer_size: Maximum size of the host side per device buffer to keep.
prefetch_buffer_size: if > 1, then we setup a buffer on each device
to prefetch into.
source_device: The host device to place the `dataset` on.
@@ -668,7 +670,8 @@ class MultiDeviceIterator(object):
# iterators and the multi-device iterator.
self._incarnation_id = gen_dataset_ops.multi_device_iterator_init(
self._dataset._as_variant_tensor(), # pylint: disable=protected-access
- self._multi_device_iterator_resource)
+ self._multi_device_iterator_resource,
+ max_buffer_size=max_buffer_size)
# TODO(rohanj): Explore the possibility of the MultiDeviceIterator to
# initialize the device side of the pipeline. This would allow the
diff --git a/tensorflow/contrib/data/python/ops/readers.py b/tensorflow/contrib/data/python/ops/readers.py
index 14d69f8d5b..3882d4bfdb 100644
--- a/tensorflow/contrib/data/python/ops/readers.py
+++ b/tensorflow/contrib/data/python/ops/readers.py
@@ -234,7 +234,7 @@ def make_tf_record_dataset(
Args:
file_pattern: List of files or patterns of TFRecord file paths.
- See @{tf.gfile.Glob} for pattern rules.
+ See `tf.gfile.Glob` for pattern rules.
batch_size: An int representing the number of records to combine
in a single batch.
parser_fn: (Optional.) A function accepting string input to parse
@@ -340,7 +340,7 @@ def make_csv_dataset(
Args:
file_pattern: List of files or patterns of file paths containing CSV
- records. See @{tf.gfile.Glob} for pattern rules.
+ records. See `tf.gfile.Glob` for pattern rules.
batch_size: An int representing the number of records to combine
in a single batch.
column_names: An optional list of strings that corresponds to the CSV
diff --git a/tensorflow/contrib/data/python/ops/resampling.py b/tensorflow/contrib/data/python/ops/resampling.py
index 182a5c6ff3..75642f143e 100644
--- a/tensorflow/contrib/data/python/ops/resampling.py
+++ b/tensorflow/contrib/data/python/ops/resampling.py
@@ -50,7 +50,7 @@ def rejection_resample(class_func, target_dist, initial_dist=None, seed=None):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
"""Function from `Dataset` to `Dataset` that applies the transformation."""
diff --git a/tensorflow/contrib/data/python/ops/scan_ops.py b/tensorflow/contrib/data/python/ops/scan_ops.py
index ea9dcfe68f..6b002b4a53 100644
--- a/tensorflow/contrib/data/python/ops/scan_ops.py
+++ b/tensorflow/contrib/data/python/ops/scan_ops.py
@@ -151,7 +151,7 @@ class _ScanDataset(dataset_ops.Dataset):
def scan(initial_state, scan_func):
"""A transformation that scans a function across an input dataset.
- This transformation is a stateful relative of @{tf.data.Dataset.map}.
+ This transformation is a stateful relative of `tf.data.Dataset.map`.
In addition to mapping `scan_func` across the elements of the input dataset,
`scan()` accumulates one or more state tensors, whose initial values are
`initial_state`.
@@ -166,7 +166,7 @@ def scan(initial_state, scan_func):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
return _ScanDataset(dataset, initial_state, scan_func)
diff --git a/tensorflow/contrib/data/python/ops/shuffle_ops.py b/tensorflow/contrib/data/python/ops/shuffle_ops.py
index d7f8a73fe3..4356721704 100644
--- a/tensorflow/contrib/data/python/ops/shuffle_ops.py
+++ b/tensorflow/contrib/data/python/ops/shuffle_ops.py
@@ -92,11 +92,11 @@ def shuffle_and_repeat(buffer_size, count=None, seed=None):
indefinitely.
seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
random seed that will be used to create the distribution. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset): # pylint: disable=missing-docstring
diff --git a/tensorflow/contrib/data/python/ops/sliding.py b/tensorflow/contrib/data/python/ops/sliding.py
index e9dd74530a..8025dcdd16 100644
--- a/tensorflow/contrib/data/python/ops/sliding.py
+++ b/tensorflow/contrib/data/python/ops/sliding.py
@@ -109,7 +109,7 @@ def sliding_window_batch(window_size,
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
Raises:
ValueError: if invalid arguments are provided.
diff --git a/tensorflow/contrib/data/python/ops/stats_ops.py b/tensorflow/contrib/data/python/ops/stats_ops.py
index 97931f75bd..3b4e981402 100644
--- a/tensorflow/contrib/data/python/ops/stats_ops.py
+++ b/tensorflow/contrib/data/python/ops/stats_ops.py
@@ -29,7 +29,7 @@ class StatsAggregator(object):
"""A stateful resource that aggregates statistics from one or more iterators.
To record statistics, use one of the custom transformation functions defined
- in this module when defining your @{tf.data.Dataset}. All statistics will be
+ in this module when defining your `tf.data.Dataset`. All statistics will be
aggregated by the `StatsAggregator` that is associated with a particular
iterator (see below). For example, to record the total number of bytes
produced by iterating over a dataset:
@@ -39,7 +39,7 @@ class StatsAggregator(object):
dataset = dataset.apply(stats_ops.bytes_produced_stats("total_bytes"))
```
- To associate a `StatsAggregator` with a @{tf.data.Iterator} object, use
+ To associate a `StatsAggregator` with a `tf.data.Iterator` object, use
the following pattern:
```python
@@ -55,7 +55,7 @@ class StatsAggregator(object):
To get a protocol buffer summary of the currently aggregated statistics,
use the `StatsAggregator.get_summary()` tensor. The easiest way to do this
- is to add the returned tensor to the @{tf.GraphKeys.SUMMARIES} collection,
+ is to add the returned tensor to the `tf.GraphKeys.SUMMARIES` collection,
so that the summaries will be included with any existing summaries.
```python
@@ -74,13 +74,13 @@ class StatsAggregator(object):
self._resource = gen_dataset_ops.stats_aggregator_handle()
def get_summary(self):
- """Returns a string @{tf.Tensor} that summarizes the aggregated statistics.
+ """Returns a string `tf.Tensor` that summarizes the aggregated statistics.
- The returned tensor will contain a serialized @{tf.summary.Summary} protocol
+ The returned tensor will contain a serialized `tf.summary.Summary` protocol
buffer, which can be used with the standard TensorBoard logging facilities.
Returns:
- A scalar string @{tf.Tensor} that summarizes the aggregated statistics.
+ A scalar string `tf.Tensor` that summarizes the aggregated statistics.
"""
return gen_dataset_ops.stats_aggregator_summary(self._resource)
@@ -122,7 +122,7 @@ def set_stats_aggregator(stats_aggregator):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -145,7 +145,7 @@ def bytes_produced_stats(tag):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -169,7 +169,7 @@ def latency_stats(tag):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
@@ -192,7 +192,7 @@ def feature_stats(tag):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
diff --git a/tensorflow/contrib/data/python/ops/threadpool.py b/tensorflow/contrib/data/python/ops/threadpool.py
index 9af1e784ff..dc67accdcf 100644
--- a/tensorflow/contrib/data/python/ops/threadpool.py
+++ b/tensorflow/contrib/data/python/ops/threadpool.py
@@ -100,6 +100,6 @@ def override_threadpool(dataset, thread_pool):
Returns:
A dataset containing the same values as `dataset`, but which uses
`thread_pool` to compute any of its parallel operations (such as
- @{tf.data.Dataset.map}).
+ `tf.data.Dataset.map`).
"""
return _ThreadPoolDataset(dataset, thread_pool)
diff --git a/tensorflow/contrib/data/python/ops/unique.py b/tensorflow/contrib/data/python/ops/unique.py
index e0ce0a4ef1..e0d606311c 100644
--- a/tensorflow/contrib/data/python/ops/unique.py
+++ b/tensorflow/contrib/data/python/ops/unique.py
@@ -38,7 +38,7 @@ def unique():
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
diff --git a/tensorflow/contrib/data/python/ops/writers.py b/tensorflow/contrib/data/python/ops/writers.py
index f53bd3f738..c455fdcba6 100644
--- a/tensorflow/contrib/data/python/ops/writers.py
+++ b/tensorflow/contrib/data/python/ops/writers.py
@@ -38,13 +38,13 @@ class TFRecordWriter(object):
argument_dtype=dtypes.string)
def write(self, dataset):
- """Returns a @{tf.Operation} to write a dataset to a file.
+ """Returns a `tf.Operation` to write a dataset to a file.
Args:
- dataset: a @{tf.data.Dataset} whose elements are to be written to a file
+ dataset: a `tf.data.Dataset` whose elements are to be written to a file
Returns:
- A @{tf.Operation} that, when run, writes contents of `dataset` to a file.
+ A `tf.Operation` that, when run, writes contents of `dataset` to a file.
"""
if not isinstance(dataset, dataset_ops.Dataset):
raise TypeError("`dataset` must be a `tf.data.Dataset` object.")
diff --git a/tensorflow/contrib/distribute/BUILD b/tensorflow/contrib/distribute/BUILD
index d3628d480d..c16f1d6035 100644
--- a/tensorflow/contrib/distribute/BUILD
+++ b/tensorflow/contrib/distribute/BUILD
@@ -29,7 +29,6 @@ py_library(
"//tensorflow/contrib/distribute/python:cross_tower_ops",
"//tensorflow/contrib/distribute/python:mirrored_strategy",
"//tensorflow/contrib/distribute/python:monitor",
- "//tensorflow/contrib/distribute/python:multi_worker_strategy",
"//tensorflow/contrib/distribute/python:one_device_strategy",
"//tensorflow/contrib/distribute/python:parameter_server_strategy",
"//tensorflow/contrib/distribute/python:step_fn",
diff --git a/tensorflow/contrib/distribute/__init__.py b/tensorflow/contrib/distribute/__init__.py
index 9123ca749b..588a4f2898 100644
--- a/tensorflow/contrib/distribute/__init__.py
+++ b/tensorflow/contrib/distribute/__init__.py
@@ -22,13 +22,13 @@ from __future__ import print_function
from tensorflow.contrib.distribute.python.collective_all_reduce_strategy import CollectiveAllReduceStrategy
from tensorflow.contrib.distribute.python.cross_tower_ops import *
from tensorflow.contrib.distribute.python.mirrored_strategy import MirroredStrategy
-from tensorflow.contrib.distribute.python.multi_worker_strategy import MultiWorkerMirroredStrategy
from tensorflow.contrib.distribute.python.monitor import Monitor
from tensorflow.contrib.distribute.python.one_device_strategy import OneDeviceStrategy
from tensorflow.contrib.distribute.python.parameter_server_strategy import ParameterServerStrategy
from tensorflow.contrib.distribute.python.step_fn import *
from tensorflow.contrib.distribute.python.tpu_strategy import TPUStrategy
from tensorflow.python.training.distribute import *
+from tensorflow.python.training.distribution_strategy_context import *
from tensorflow.python.util.all_util import remove_undocumented
@@ -39,7 +39,6 @@ _allowed_symbols = [
'CrossTowerOps',
'DistributionStrategy',
'MirroredStrategy',
- 'MultiWorkerMirroredStrategy',
'Monitor',
'OneDeviceStrategy',
'ParameterServerStrategy',
@@ -55,6 +54,7 @@ _allowed_symbols = [
'get_tower_context',
'has_distribution_strategy',
'require_tower_context',
+ 'UpdateContext',
]
remove_undocumented(__name__, _allowed_symbols)
diff --git a/tensorflow/contrib/distribute/python/BUILD b/tensorflow/contrib/distribute/python/BUILD
index 3159dd154a..59efd17746 100644
--- a/tensorflow/contrib/distribute/python/BUILD
+++ b/tensorflow/contrib/distribute/python/BUILD
@@ -57,7 +57,7 @@ cuda_py_test(
"//tensorflow/python/eager:context",
"//tensorflow/python:device_util",
"//tensorflow/python/eager:test",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
],
tags = [
"no_pip",
@@ -72,31 +72,21 @@ py_library(
":cross_tower_ops",
":shared_variable_creator",
":values",
+ "//tensorflow/core:protos_all_py",
"//tensorflow/python:array_ops",
+ "//tensorflow/python:constant_op",
+ "//tensorflow/python:control_flow_ops",
"//tensorflow/python:device",
"//tensorflow/python:device_util",
"//tensorflow/python:distribute",
"//tensorflow/python:framework_ops",
- "//tensorflow/python:math_ops",
"//tensorflow/python:pywrap_tensorflow",
"//tensorflow/python:training",
+ "//tensorflow/python:util",
"//tensorflow/python:variable_scope",
+ "//tensorflow/python:variables",
"//tensorflow/python/eager:context",
"//tensorflow/python/eager:tape",
- "@six_archive//:six",
- ],
-)
-
-py_library(
- name = "multi_worker_strategy",
- srcs = ["multi_worker_strategy.py"],
- visibility = ["//tensorflow:internal"],
- deps = [
- ":mirrored_strategy",
- ":values",
- "//tensorflow/core:protos_all_py",
- "//tensorflow/python:training",
- "//tensorflow/python:util",
],
)
@@ -114,6 +104,7 @@ py_library(
"//tensorflow/python:resource_variable_ops",
"//tensorflow/python:training",
"//tensorflow/python:util",
+ "//tensorflow/python/distribute:multi_worker_util",
],
)
@@ -184,7 +175,6 @@ py_library(
],
deps = [
":mirrored_strategy",
- ":multi_worker_strategy",
":one_device_strategy",
":tpu_strategy",
"//tensorflow/contrib/cluster_resolver:cluster_resolver_pip",
@@ -219,9 +209,13 @@ py_test(
],
deps = [
":mirrored_strategy",
+ ":multi_worker_test_base",
":strategy_test_lib",
+ "//tensorflow/python:constant_op",
"//tensorflow/python:distribute",
+ "//tensorflow/python:framework_ops",
"//tensorflow/python:framework_test_lib",
+ "//tensorflow/python:training",
"//tensorflow/python:variable_scope",
"//tensorflow/python/eager:context",
"//tensorflow/python/eager:test",
@@ -267,7 +261,7 @@ py_test(
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
"//tensorflow/python/eager:context",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
"@absl_py//absl/testing:parameterized",
],
)
@@ -315,7 +309,7 @@ py_library(
"//tensorflow/python:client_testlib",
"//tensorflow/python:distributed_framework_test_lib",
"//tensorflow/python:session",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
"//third_party/py/numpy",
],
)
@@ -370,7 +364,7 @@ py_test(
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
"//tensorflow/python/eager:context",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
"//third_party/py/numpy",
"@absl_py//absl/testing:parameterized",
],
@@ -440,11 +434,7 @@ cuda_py_test(
"//tensorflow/contrib/optimizer_v2:training",
"//tensorflow/python/data/ops:dataset_ops",
"//tensorflow/python/eager:test",
- "//tensorflow/python/estimator:dnn_linear_combined",
- "//tensorflow/python/estimator:export_export",
- "//tensorflow/python/estimator:numpy_io",
- "//tensorflow/python/estimator:prediction_keys",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/feature_column",
"//tensorflow/python:framework_ops",
"//tensorflow/python:platform",
@@ -470,17 +460,27 @@ py_library(
],
)
-cuda_py_test(
- name = "step_fn_test",
+py_library(
+ name = "step_fn_test_lib",
+ testonly = 1,
srcs = ["step_fn_test.py"],
- additional_deps = [
- ":single_loss_example",
+ deps = [
":combinations",
- "@absl_py//absl/testing:parameterized",
- "//third_party/py/numpy",
+ ":single_loss_example",
+ "//tensorflow/contrib/tpu:tpu_lib",
"//tensorflow/python:variables",
"//tensorflow/python/eager:context",
"//tensorflow/python/eager:test",
+ "//third_party/py/numpy",
+ "@absl_py//absl/testing:parameterized",
+ ],
+)
+
+cuda_py_test(
+ name = "step_fn_test",
+ srcs = ["step_fn_test.py"],
+ additional_deps = [
+ ":step_fn_test_lib",
],
tags = [
"multi_and_single_gpu",
@@ -681,8 +681,7 @@ cuda_py_test(
"//tensorflow/contrib/distribute/python:mirrored_strategy",
"//tensorflow/python:client_testlib",
"//tensorflow/python:training",
- "//tensorflow/python/estimator:keras",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/keras",
],
tags = [
diff --git a/tensorflow/contrib/distribute/python/combinations.py b/tensorflow/contrib/distribute/python/combinations.py
index 120349481f..2fbadfe0f5 100644
--- a/tensorflow/contrib/distribute/python/combinations.py
+++ b/tensorflow/contrib/distribute/python/combinations.py
@@ -48,7 +48,6 @@ import six
from tensorflow.contrib.cluster_resolver import TPUClusterResolver
from tensorflow.contrib.distribute.python import mirrored_strategy as mirrored_lib
-from tensorflow.contrib.distribute.python import multi_worker_strategy
from tensorflow.contrib.distribute.python import one_device_strategy as one_device_lib
from tensorflow.contrib.distribute.python import tpu_strategy as tpu_lib
from tensorflow.contrib.optimizer_v2 import adam as adam_v2
@@ -56,7 +55,7 @@ from tensorflow.contrib.optimizer_v2 import gradient_descent as gradient_descent
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.training import adam
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import gradient_descent
from tensorflow.python.util import tf_inspect
@@ -320,13 +319,14 @@ class NamedDistribution(object):
# pylint: disable=g-long-lambda
default_strategy = NamedDistribution(
"Default",
- lambda: distribute_lib._default_distribution_strategy, # pylint: disable=protected-access
+ distribution_strategy_context._get_default_distribution_strategy, # pylint: disable=protected-access
required_gpus=None)
one_device_strategy = NamedDistribution(
"OneDeviceCPU", lambda: one_device_lib.OneDeviceStrategy("/cpu:0"),
required_gpus=None)
tpu_strategy = NamedDistribution(
- "TPU", lambda: tpu_lib.TPUStrategy(TPUClusterResolver("")),
+ "TPU", lambda: tpu_lib.TPUStrategy(
+ TPUClusterResolver(""), steps_per_run=5),
required_tpu=True)
# Note that we disable prefetching for testing since prefetching makes
# the input non-deterministic.
@@ -343,42 +343,44 @@ mirrored_strategy_with_two_gpus = NamedDistribution(
multi_worker_strategy_with_cpu = NamedDistribution(
"MultiWorkerCPU",
- lambda: multi_worker_strategy.MultiWorkerMirroredStrategy(
- cluster={
+ lambda: mirrored_lib.MirroredStrategy(
+ cluster_spec={
"worker": [
"/job:worker/replica:0/task:0", "/job:worker/replica:0/task:1"
]
},
- num_gpus_per_worker=0), 0)
+ num_gpus=0), 0)
multi_worker_strategy_with_one_gpu = NamedDistribution(
"MultiWorker1GPU",
- lambda: multi_worker_strategy.MultiWorkerMirroredStrategy(
- cluster={
+ lambda: mirrored_lib.MirroredStrategy(
+ cluster_spec={
"worker": [
"/job:worker/replica:0/task:0", "/job:worker/replica:0/task:1"
]
},
- num_gpus_per_worker=1), 1)
+ num_gpus=1), 1)
multi_worker_strategy_with_two_gpus = NamedDistribution(
"MultiWorker2GPUs",
- lambda: multi_worker_strategy.MultiWorkerMirroredStrategy(
- cluster={
+ lambda: mirrored_lib.MirroredStrategy(
+ cluster_spec={
"worker": [
"/job:worker/replica:0/task:0", "/job:worker/replica:0/task:1"
]
},
- num_gpus_per_worker=2), 2)
+ num_gpus=2), 2)
adam_optimizer_v1_fn = NamedObject(
"AdamV1", lambda: adam.AdamOptimizer(0.2, epsilon=1))
gradient_descent_optimizer_v1_fn = NamedObject(
"GradientDescentV1", lambda: gradient_descent.GradientDescentOptimizer(0.2))
+optimizers_v1 = [adam_optimizer_v1_fn, gradient_descent_optimizer_v1_fn]
adam_optimizer_v2_fn = NamedObject(
"AdamV2", lambda: adam_v2.AdamOptimizer(0.2, epsilon=1))
gradient_descent_optimizer_v2_fn = NamedObject(
"GradientDescentV2",
lambda: gradient_descent_v2.GradientDescentOptimizer(0.2))
+optimizers_v2 = [adam_optimizer_v2_fn, gradient_descent_optimizer_v2_fn]
graph_and_eager_modes = ["graph", "eager"]
@@ -390,7 +392,7 @@ def distributions_and_v1_optimizers():
one_device_strategy, mirrored_strategy_with_gpu_and_cpu,
mirrored_strategy_with_two_gpus
],
- optimizer_fn=[adam_optimizer_v1_fn, gradient_descent_optimizer_v1_fn])
+ optimizer_fn=optimizers_v1)
def distributions_and_v2_optimizers():
@@ -400,4 +402,4 @@ def distributions_and_v2_optimizers():
one_device_strategy, mirrored_strategy_with_gpu_and_cpu,
mirrored_strategy_with_two_gpus
],
- optimizer_fn=[adam_optimizer_v2_fn, gradient_descent_optimizer_v2_fn])
+ optimizer_fn=optimizers_v2)
diff --git a/tensorflow/contrib/distribute/python/cross_tower_ops.py b/tensorflow/contrib/distribute/python/cross_tower_ops.py
index 9b5534393e..dd74d5eed7 100644
--- a/tensorflow/contrib/distribute/python/cross_tower_ops.py
+++ b/tensorflow/contrib/distribute/python/cross_tower_ops.py
@@ -157,7 +157,7 @@ class CrossTowerOps(object):
Args:
aggregation: Indicates how a variable will be aggregated. Accepted values
- are @{tf.VariableAggregation.SUM}, @{tf.VariableAggregation.MEAN}.
+ are `tf.VariableAggregation.SUM`, `tf.VariableAggregation.MEAN`.
per_device_value: a PerDevice object.
destinations: the reduction destinations.
@@ -181,7 +181,7 @@ class CrossTowerOps(object):
Args:
aggregation: Indicates how a variable will be aggregated. Accepted values
- are @{tf.VariableAggregation.SUM}, @{tf.VariableAggregation.MEAN}.
+ are `tf.VariableAggregation.SUM`, `tf.VariableAggregation.MEAN`.
value_destination_pairs: a list or a tuple of tuples of PerDevice objects
and destinations. If a destination is None, then the destinations
are set to match the devices of the input PerDevice object.
@@ -305,7 +305,7 @@ def _ungroup_and_make_mirrored(grouped_reduced,
cross_tower_utils.aggregate_gradients_using*.
destinations: a list of device strings for returned Mirrored objects.
aggregation: Indicates how a variable will be aggregated. Accepted values
- are @{tf.VariableAggregation.SUM}, @{tf.VariableAggregation.MEAN}.
+ are `tf.VariableAggregation.SUM`, `tf.VariableAggregation.MEAN`.
num_between_graph_workers: number of workers in the between-graph
replication.
@@ -756,7 +756,7 @@ class CollectiveAllReduce(CrossTowerOps):
)
super(CollectiveAllReduce, self).__init__()
- # TODO(yuefengz, tucker): is index slices supported by collective ops?
+ # TODO(yuefengz, tucker): is indexed slices supported by collective ops?
def _reduce(self, aggregation, per_device_value, destinations):
all_reduced = self._batch_all_reduce(aggregation, [per_device_value])[0]
if destinations is None or _devices_match(per_device_value, destinations):
@@ -768,8 +768,10 @@ class CollectiveAllReduce(CrossTowerOps):
if d in all_reduced._index:
index[d] = all_reduced._index[d]
else:
- with ops.device(d):
+ with ops.control_dependencies(list(
+ all_reduced._index.values())), ops.device(d):
index[d] = array_ops.identity(list(all_reduced._index.values())[0])
+
return value_lib.Mirrored(index)
def _batch_reduce(self, aggregation, value_destination_pairs):
diff --git a/tensorflow/contrib/distribute/python/cross_tower_ops_test.py b/tensorflow/contrib/distribute/python/cross_tower_ops_test.py
index aec53b01d7..3508c9d599 100644
--- a/tensorflow/contrib/distribute/python/cross_tower_ops_test.py
+++ b/tensorflow/contrib/distribute/python/cross_tower_ops_test.py
@@ -417,7 +417,7 @@ class MultiWorkerCollectiveAllReduceTest(
devices = ["/device:GPU:%d" % i for i in range(num_gpus)]
else:
devices = ["/device:CPU:0"]
- return collective_all_reduce_ops, devices, "local"
+ return collective_all_reduce_ops, devices, ""
else:
collective_all_reduce_ops = cross_tower_ops_lib.CollectiveAllReduce(
3, num_gpus, collective_keys=collective_keys)
@@ -476,7 +476,7 @@ class MultiWorkerCollectiveAllReduceTest(
destination_list = devices
all_destinations = [
- None, destination_mirrored, destination_different, destination_str,
+ destination_different, None, destination_mirrored, destination_str,
destination_list
]
@@ -540,6 +540,12 @@ class MultiWorkerCollectiveAllReduceTest(
self._run_between_graph_clients(self._test_reduction, self._cluster_spec,
num_gpus)
+ # Collective ops doesn't support strategy with one device.
+ def testReductionLocal(self, num_gpus=2):
+ if context.num_gpus() < num_gpus:
+ return
+ self._test_reduction(None, None, num_gpus, local_mode=True)
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/distribute/python/estimator_integration_test.py b/tensorflow/contrib/distribute/python/estimator_integration_test.py
index a0bb144b7c..cc626c33bf 100644
--- a/tensorflow/contrib/distribute/python/estimator_integration_test.py
+++ b/tensorflow/contrib/distribute/python/estimator_integration_test.py
@@ -29,6 +29,7 @@ from tensorflow.contrib.optimizer_v2 import adagrad
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import test
from tensorflow.python.estimator import run_config
+from tensorflow.python.estimator import training
from tensorflow.python.estimator.canned import dnn_linear_combined
from tensorflow.python.estimator.canned import prediction_keys
from tensorflow.python.estimator.export import export
@@ -63,8 +64,9 @@ class DNNLinearCombinedClassifierIntegrationTest(test.TestCase,
combinations.one_device_strategy,
combinations.mirrored_strategy_with_gpu_and_cpu,
combinations.mirrored_strategy_with_two_gpus
- ]))
- def test_complete_flow_with_mode(self, distribution):
+ ],
+ use_train_and_evaluate=[True, False]))
+ def test_complete_flow_with_mode(self, distribution, use_train_and_evaluate):
label_dimension = 2
input_dimension = label_dimension
batch_size = 10
@@ -75,8 +77,11 @@ class DNNLinearCombinedClassifierIntegrationTest(test.TestCase,
y=data,
batch_size=batch_size // len(distribution.worker_devices),
shuffle=True)
- eval_input_fn = numpy_io.numpy_input_fn(
- x={'x': data}, y=data, batch_size=batch_size, shuffle=False)
+ eval_input_fn = self.dataset_input_fn(
+ x={'x': data},
+ y=data,
+ batch_size=batch_size // len(distribution.worker_devices),
+ shuffle=False)
predict_input_fn = numpy_io.numpy_input_fn(
x={'x': data}, batch_size=batch_size, shuffle=False)
@@ -100,9 +105,15 @@ class DNNLinearCombinedClassifierIntegrationTest(test.TestCase,
train_distribute=distribution, eval_distribute=distribution))
num_steps = 10
- estimator.train(train_input_fn, steps=num_steps)
+ if use_train_and_evaluate:
+ scores, _ = training.train_and_evaluate(
+ estimator,
+ training.TrainSpec(train_input_fn, max_steps=num_steps),
+ training.EvalSpec(eval_input_fn))
+ else:
+ estimator.train(train_input_fn, steps=num_steps)
+ scores = estimator.evaluate(eval_input_fn)
- scores = estimator.evaluate(eval_input_fn)
self.assertEqual(num_steps, scores[ops.GraphKeys.GLOBAL_STEP])
self.assertIn('loss', six.iterkeys(scores))
diff --git a/tensorflow/contrib/distribute/python/keras_test.py b/tensorflow/contrib/distribute/python/keras_test.py
index ec0ca6879c..a262d7666e 100644
--- a/tensorflow/contrib/distribute/python/keras_test.py
+++ b/tensorflow/contrib/distribute/python/keras_test.py
@@ -241,6 +241,47 @@ class TestWithDistributionStrategy(test.TestCase):
validation_data=dataset, validation_steps=2)
model.predict(dataset, steps=2)
+ def test_fit_with_tuple_and_dict_dataset_inputs(self):
+ with self.test_session():
+ a = keras.layers.Input(shape=(3,), name='input_a')
+ b = keras.layers.Input(shape=(3,), name='input_b')
+
+ dense = keras.layers.Dense(4, name='dense')
+ c = dense(a)
+ d = dense(b)
+ e = keras.layers.Dropout(0.5, name='dropout')(c)
+
+ model = keras.models.Model([a, b], [d, e])
+
+ optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.001)
+ loss = 'mse'
+ metrics = ['mae']
+ strategy = mirrored_strategy.MirroredStrategy(['/device:GPU:0',
+ '/device:CPU:0'])
+ model.compile(optimizer, loss, metrics=metrics, distribute=strategy)
+
+ input_a_np = np.random.random((10, 3))
+ input_b_np = np.random.random((10, 3))
+ output_d_np = np.random.random((10, 4))
+ output_e_np = np.random.random((10, 4))
+
+ # Test with tuples
+ dataset_tuple = dataset_ops.Dataset.from_tensor_slices((
+ (input_a_np, input_b_np), (output_d_np, output_e_np)))
+ dataset_tuple = dataset_tuple.repeat(100)
+ dataset_tuple = dataset_tuple.batch(10)
+
+ model.fit(dataset_tuple, epochs=1, steps_per_epoch=2, verbose=1)
+
+ # Test with dict
+ dataset_dict = dataset_ops.Dataset.from_tensor_slices((
+ {'input_a': input_a_np, 'input_b': input_b_np},
+ (output_d_np, output_e_np)))
+ dataset_dict = dataset_dict.repeat(100)
+ dataset_dict = dataset_dict.batch(10)
+
+ model.fit(dataset_dict, epochs=1, steps_per_epoch=2, verbose=1)
+
def test_fit_eval_and_predict_methods_on_dataset(self):
with self.test_session():
x = keras.layers.Input(shape=(3,), name='input')
@@ -326,8 +367,8 @@ class TestWithDistributionStrategy(test.TestCase):
# Test with sample weight.
sample_weight = np.random.random((10,))
with self.assertRaisesRegexp(
- NotImplementedError, 'sample_weight is currently not supported when '
- 'using DistributionStrategy.'):
+ NotImplementedError, '`sample_weight` is currently not supported '
+ 'when using DistributionStrategy.'):
model.fit(
dataset,
epochs=1,
diff --git a/tensorflow/contrib/distribute/python/metrics_v1_test.py b/tensorflow/contrib/distribute/python/metrics_v1_test.py
index 2f3d6bdd3f..8163494c8e 100644
--- a/tensorflow/contrib/distribute/python/metrics_v1_test.py
+++ b/tensorflow/contrib/distribute/python/metrics_v1_test.py
@@ -68,6 +68,8 @@ def _regression_dataset_fn():
"predictions": [1., .75, .25, 0.]}).repeat()
+# TODO(priyag): Add TPU Strategy to this once metrics aggregate correctly using
+# TowerLocalVariables on TPUs. Submit http://cl/208914352.
def all_combinations():
return combinations.combine(
distribution=[combinations.default_strategy,
diff --git a/tensorflow/contrib/distribute/python/minimize_loss_test.py b/tensorflow/contrib/distribute/python/minimize_loss_test.py
index aeeb9553e6..516ede7ade 100644
--- a/tensorflow/contrib/distribute/python/minimize_loss_test.py
+++ b/tensorflow/contrib/distribute/python/minimize_loss_test.py
@@ -25,11 +25,13 @@ from tensorflow.contrib.distribute.python import combinations
from tensorflow.contrib.distribute.python import mirrored_strategy
from tensorflow.contrib.distribute.python.single_loss_example import batchnorm_example
from tensorflow.contrib.distribute.python.single_loss_example import minimize_loss_example
-from tensorflow.contrib.tpu.python.tpu import tpu
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.eager import test
+from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
+from tensorflow.python.layers import core
+from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
@@ -43,32 +45,60 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
combinations.times(
combinations.distributions_and_v1_optimizers(),
combinations.combine(mode=["graph"], use_callable_loss=[True, False])
- + combinations.combine(mode=["eager"], use_callable_loss=[True]),
- combinations.combine(is_tpu=[False])) + combinations.combine(
- distribution=[combinations.tpu_strategy],
- optimizer_fn=[
- combinations.adam_optimizer_v1_fn,
- # TODO(isaprykin): Make Adam v2 work with while_loops
- # and TPUs.
- ],
- mode=["graph"],
- use_callable_loss=[False],
- is_tpu=[True]))
- def testTrainNetwork(self, distribution, optimizer_fn, use_callable_loss,
- is_tpu):
- # TODO(priyag): Remove this once the step TPU Strategy is stable.
- if is_tpu:
- self.skipTest("TPU tests are WIP.")
+ + combinations.combine(mode=["eager"], use_callable_loss=[True])) +
+ combinations.combine(
+ distribution=[combinations.tpu_strategy],
+ optimizer_fn=combinations.optimizers_v1,
+ mode=["graph"],
+ use_callable_loss=[True, False]))
+ def testTrainNetwork(self, distribution, optimizer_fn, use_callable_loss):
+ with distribution.scope():
+ model_fn, dataset_fn, layer = minimize_loss_example(
+ optimizer_fn, use_bias=True, use_callable_loss=use_callable_loss)
+
+ def step_fn(ctx, *inputs):
+ del ctx # Unused
+ return distribution.group(
+ distribution.call_for_each_tower(
+ model_fn, *inputs, run_concurrently=layer.built))
+
+ iterator = distribution.distribute_dataset(
+ dataset_fn).make_one_shot_iterator()
+
+ def run_step():
+ return distribution.run_steps_on_dataset(
+ step_fn, iterator, iterations=2).run_op
+
+ self.evaluate(distribution.initialize())
+ if not context.executing_eagerly():
+ with self.test_session() as sess:
+ run_step = sess.make_callable(run_step())
+ self.evaluate(variables_lib.global_variables_initializer())
+
+ weights, biases = [], []
+ for _ in range(5):
+ run_step()
+ weights.append(self.evaluate(layer.kernel))
+ biases.append(self.evaluate(layer.bias))
+
+ self.evaluate(distribution.finalize())
+
+ error = abs(numpy.add(numpy.squeeze(weights), numpy.squeeze(biases)) - 1)
+ is_not_increasing = all(y <= x for x, y in zip(error, error[1:]))
+ self.assertTrue(is_not_increasing)
+
+ @combinations.generate(
+ combinations.times(
+ combinations.distributions_and_v1_optimizers(),
+ combinations.combine(mode=["graph"], use_callable_loss=[True, False])
+ + combinations.combine(mode=["eager"], use_callable_loss=[True])))
+ def testTrainNetworkByCallForEachTower(self, distribution, optimizer_fn,
+ use_callable_loss):
with distribution.scope():
model_fn, dataset_fn, layer = minimize_loss_example(
optimizer_fn, use_bias=True, use_callable_loss=use_callable_loss)
- # TODO(isaprykin): Eliminate `is_tpu`. Probably add a
- # `DistributionStrategy.create_monitor` so that each DistributionStrategy
- # could influence its training loop. That method would return an instance
- # of Monitor. TPUMonitor would execute tpu.initialize_system() and
- # tpu.shutdown_system().
iterator = distribution.distribute_dataset(
dataset_fn).make_one_shot_iterator()
@@ -79,8 +109,6 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
if not context.executing_eagerly():
with self.test_session() as sess:
- if is_tpu:
- sess.run(tpu.initialize_system())
run_step = sess.make_callable(run_step())
self.evaluate(variables_lib.global_variables_initializer())
@@ -91,10 +119,6 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
weights.append(self.evaluate(layer.kernel))
biases.append(self.evaluate(layer.bias))
- if is_tpu:
- with self.test_session() as sess:
- sess.run(tpu.shutdown_system())
-
error = abs(numpy.add(numpy.squeeze(weights), numpy.squeeze(biases)) - 1)
is_not_increasing = all(y <= x for x, y in zip(error, error[1:]))
self.assertTrue(is_not_increasing)
@@ -103,22 +127,12 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
combinations.times(
combinations.distributions_and_v1_optimizers() +
combinations.distributions_and_v2_optimizers(),
- combinations.combine(mode=["graph", "eager"], is_tpu=[False])) +
+ combinations.combine(mode=["graph", "eager"])) +
combinations.combine(
distribution=[combinations.tpu_strategy],
- optimizer_fn=[
- combinations.adam_optimizer_v1_fn,
- combinations.gradient_descent_optimizer_v1_fn,
- combinations.gradient_descent_optimizer_v2_fn,
- ],
- mode=["graph"],
- is_tpu=[True]))
-
- def testOptimizerInsideModelFn(self, distribution, optimizer_fn, is_tpu):
- # TODO(priyag): Remove this once the step TPU Strategy is stable.
- if is_tpu:
- self.skipTest("TPU tests are WIP.")
-
+ optimizer_fn=combinations.optimizers_v1+combinations.optimizers_v2,
+ mode=["graph"]))
+ def testOptimizerInsideModelFn(self, distribution, optimizer_fn):
created_variables = []
trainable_variables = []
@@ -139,26 +153,28 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
use_callable_loss=True,
create_optimizer_inside_model_fn=True)
+ def step_fn(ctx, *inputs):
+ del ctx # Unused
+ return distribution.group(
+ distribution.call_for_each_tower(
+ model_fn, *inputs, run_concurrently=layer.built))
+
iterator = distribution.distribute_dataset(
dataset_fn).make_one_shot_iterator()
def run_step():
- return distribution.group(
- distribution.call_for_each_tower(
- model_fn, iterator.get_next(), run_concurrently=layer.built))
+ return distribution.run_steps_on_dataset(
+ step_fn, iterator, iterations=1).run_op
+ self.evaluate(distribution.initialize())
if not context.executing_eagerly():
with self.test_session() as sess:
- if is_tpu:
- sess.run(tpu.initialize_system())
run_step = sess.make_callable(run_step())
- self.evaluate(variables_lib.global_variables_initializer())
+ self.evaluate(variables_lib.global_variables_initializer())
run_step()
- if is_tpu:
- with self.test_session() as sess:
- sess.run(tpu.shutdown_system())
+ self.evaluate(distribution.finalize())
def get_expected_variables(optimizer_fn, num_parameter_devices):
variables_map = {
@@ -189,27 +205,17 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
combinations.distributions_and_v1_optimizers(),
combinations.combine(
mode=["graph", "eager"],
- is_tpu=[False],
# TODO(isaprykin): Allow False here. Currently subsequent
# towers will re-execute UPDATE_OPS of previous towers.
update_ops_in_cross_tower_mode=[True])) +
combinations.combine(
distribution=[combinations.tpu_strategy],
- optimizer_fn=[
- combinations.gradient_descent_optimizer_v1_fn,
- combinations.gradient_descent_optimizer_v2_fn
- ],
+ optimizer_fn=combinations.optimizers_v1,
mode=["graph"],
- is_tpu=[True],
update_ops_in_cross_tower_mode=[False])))
def testTrainNetworkWithBatchNorm(self, distribution, optimizer_fn, momentum,
- renorm, is_tpu,
- update_ops_in_cross_tower_mode):
+ renorm, update_ops_in_cross_tower_mode):
"""Verifies that moving mean updates are reduced across towers."""
- # TODO(priyag): Remove this once the step TPU Strategy is stable.
- if is_tpu:
- self.skipTest("TPU tests are WIP.")
-
with distribution.scope():
num_towers = len(distribution.worker_devices)
model_fn, dataset_fn, batchnorm = batchnorm_example(
@@ -224,24 +230,28 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
# this test relies on specific input being on each device.
if isinstance(distribution, mirrored_strategy.MirroredStrategy):
self.assertFalse(distribution._prefetch_on_device)
- iterator = distribution.distribute_dataset(
- dataset_fn).make_one_shot_iterator()
- def run_step():
+ def step_fn(ctx, *inputs):
+ del ctx # Unused
fetches = distribution.unwrap(
distribution.call_for_each_tower(
- model_fn, iterator.get_next(),
- run_concurrently=batchnorm.built))
+ model_fn, *inputs, run_concurrently=batchnorm.built))
if update_ops_in_cross_tower_mode:
fetches += ops.get_collection(ops.GraphKeys.UPDATE_OPS)
return control_flow_ops.group(fetches)
+ iterator = distribution.distribute_dataset(
+ dataset_fn).make_one_shot_iterator()
+
+ def run_step():
+ return distribution.run_steps_on_dataset(
+ step_fn, iterator, iterations=1).run_op
+
+ self.evaluate(distribution.initialize())
if not context.executing_eagerly():
with self.test_session() as sess:
- if is_tpu:
- sess.run(tpu.initialize_system())
run_step = sess.make_callable(run_step())
- self.evaluate(variables_lib.global_variables_initializer())
+ self.evaluate(variables_lib.global_variables_initializer())
expected_moving_means = [0.] * 8
@@ -263,9 +273,7 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
expected_moving_mean - averaged_batch_mean(i)) * (1.0 - momentum))
self.assertNear(expected_moving_means[i], moving_means[i], 0.0001)
- if is_tpu:
- with self.test_session() as sess:
- sess.run(tpu.shutdown_system())
+ self.evaluate(distribution.finalize())
@combinations.generate(
combinations.times(
@@ -285,22 +293,16 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
combinations.one_device_strategy,
combinations.mirrored_strategy_with_gpu_and_cpu,
combinations.mirrored_strategy_with_two_gpus
- ],
- is_tpu=[False]),
+ ]),
combinations.combine(
mode=["graph"], use_callable_loss=[True, False]) +
combinations.combine(mode=["eager"], use_callable_loss=[True])) +
combinations.combine(
distribution=[combinations.tpu_strategy],
- is_tpu=[True],
mode=["graph"],
use_callable_loss=[True, False])))
def testMeanVsSum(self, distribution, optimizer_fn, loss_reduction,
- use_callable_loss, is_tpu):
- # TODO(priyag): Remove this once the step TPU Strategy is stable.
- if is_tpu:
- self.skipTest("TPU tests are WIP.")
-
+ use_callable_loss):
with distribution.scope():
all_vars = []
@@ -326,20 +328,24 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
labels = dataset_ops.Dataset.from_tensors([[6.], [21.]])
return dataset_ops.Dataset.zip((features, labels)).repeat()
+ def step_fn(ctx, x, y):
+ del ctx # Unused
+ return distribution.group(
+ distribution.call_for_each_tower(
+ model_fn, x, y, run_concurrently=False))
+
iterator = distribution.distribute_dataset(
dataset_fn).make_one_shot_iterator()
def run_step():
- return distribution.group(
- distribution.call_for_each_tower(
- model_fn, *iterator.get_next(), run_concurrently=False))
+ return distribution.run_steps_on_dataset(
+ step_fn, iterator, iterations=1).run_op
+ self.evaluate(distribution.initialize())
if not context.executing_eagerly():
with self.test_session() as sess:
- if is_tpu:
- sess.run(tpu.initialize_system())
run_step = sess.make_callable(run_step())
- self.evaluate(variables_lib.global_variables_initializer())
+ self.evaluate(variables_lib.global_variables_initializer())
run_step()
@@ -369,10 +375,132 @@ class MinimizeLossStepTest(test.TestCase, parameterized.TestCase):
# One of the mean loss reductions.
self.assertNear(weight, 2 + 10.6, 0.0001)
- if is_tpu:
+ self.evaluate(distribution.finalize())
+
+ @combinations.generate(
+ combinations.times(
+ combinations.distributions_and_v1_optimizers(),
+ combinations.combine(mode=["graph", "eager"]),
+ combinations.combine(is_tpu=[False])) +
+ combinations.combine(
+ distribution=[combinations.tpu_strategy],
+ optimizer_fn=combinations.optimizers_v1,
+ mode=["graph"],
+ is_tpu=[True]))
+ def testRunStepsWithOutputContext(self, distribution, optimizer_fn, is_tpu):
+ with distribution.scope():
+ def dataset_fn():
+ dataset = dataset_ops.Dataset.from_tensors([[1.]]).repeat()
+ # TODO(priyag): batch with drop_remainder=True causes shapes to be
+ # fully defined for TPU. Remove this when XLA supports dynamic shapes.
+ return dataset.batch(batch_size=1, drop_remainder=True)
+
+ optimizer = optimizer_fn()
+ layer = core.Dense(1, use_bias=True)
+
+ key1 = "foo"
+ value1 = "bar"
+
+ def model_fn(output_context, x):
+ """A very simple model written by the user."""
+ def loss_fn():
+ y = array_ops.reshape(layer(x), []) - constant_op.constant(1.)
+ return y * y
+
+ train_op = optimizer.minimize(loss_fn)
+ loss = loss_fn()
+ output_context.set_last_step_output(
+ name="tower_loss_agg",
+ output=loss,
+ aggregation=variables_lib.VariableAggregation.MEAN)
+ output_context.set_non_tensor_output(key1, value1)
+ return (train_op, loss)
+
+ def step_fn(output_context, *inputs):
+ (train_op, loss) = distribution.call_for_each_tower(
+ model_fn, output_context, *inputs, run_concurrently=False)
+ output_context.set_last_step_output(
+ name="cross_tower_loss_agg",
+ output=loss,
+ aggregation=variables_lib.VariableAggregation.MEAN)
+ output_context.set_last_step_output(
+ name="cross_tower_loss_noagg",
+ output=loss)
+ return distribution.group(train_op)
+
+ iterator = distribution.distribute_dataset(
+ dataset_fn).make_one_shot_iterator()
+
+ def run_step():
+ initial_loss = lambda: constant_op.constant(1e7)
+ # Initial values corresponding to aggregated losses are just single
+ # tensors. But for non aggregated losses, we need to have initial
+ # values that are of the same structure as non reduced losses. In
+ # MirroredStrategy, this will be a list of losses, in TPUStrategy
+ # it will be single tensor. Using `broadcast` followed by `unwrap`
+ # gives us the desired initial value structure.
+ initial_loop_values = {
+ "tower_loss_agg": initial_loss(),
+ "cross_tower_loss_agg": initial_loss(),
+ "cross_tower_loss_noagg":
+ distribution.unwrap(distribution.broadcast(initial_loss()))
+ }
+ ctx = distribution.run_steps_on_dataset(
+ step_fn, iterator, iterations=2,
+ initial_loop_values=initial_loop_values)
+
+ self.assertEqual({key1: [value1]}, ctx.non_tensor_outputs)
+ self._verify_loss_output(
+ initial_loss(),
+ loss_output=ctx.last_step_outputs["tower_loss_agg"],
+ aggregated=True, distribution=distribution)
+ self._verify_loss_output(
+ initial_loss(),
+ loss_output=ctx.last_step_outputs["cross_tower_loss_agg"],
+ aggregated=True, distribution=distribution)
+ self._verify_loss_output(
+ initial_loss(),
+ loss_output=ctx.last_step_outputs["cross_tower_loss_noagg"],
+ aggregated=False, distribution=distribution)
+ return (ctx.run_op, ctx.last_step_outputs["tower_loss_agg"])
+
+ self.evaluate(distribution.initialize())
+ if not context.executing_eagerly():
with self.test_session() as sess:
- sess.run(tpu.shutdown_system())
+ run_step = sess.make_callable(run_step())
+ self.evaluate(variables_lib.global_variables_initializer())
+
+ weights, biases, losses = [], [], []
+ for _ in range(5):
+ _, loss = run_step()
+ losses.append(loss)
+ weights.append(self.evaluate(layer.kernel))
+ biases.append(self.evaluate(layer.bias))
+ self.evaluate(distribution.finalize())
+
+ loss_is_not_increasing = all(y <= x for x, y in zip(losses, losses[1:]))
+ self.assertTrue(loss_is_not_increasing)
+
+ error = abs(
+ numpy.add(numpy.squeeze(weights), numpy.squeeze(biases)) - 1)
+ error_is_not_increasing = all(y <= x for x, y in zip(error, error[1:]))
+ self.assertTrue(error_is_not_increasing)
+
+ def _verify_loss_output(self, initial_loss, loss_output, aggregated,
+ distribution):
+ if not aggregated:
+ self.assertEqual(distribution.num_towers,
+ len(distribution.unwrap(loss_output)))
+ loss_output = distribution.reduce(
+ aggregation=variables_lib.VariableAggregation.MEAN,
+ value=loss_output, destinations="/device:CPU:0")
+
+ unwrapped_output = distribution.unwrap(loss_output)
+ self.assertEqual(1, len(unwrapped_output))
+ loss_tensor = unwrapped_output[0]
+ self.assertEqual(initial_loss.dtype, loss_tensor.dtype)
+ self.assertEqual(initial_loss.shape, loss_tensor.shape)
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/distribute/python/mirrored_strategy.py b/tensorflow/contrib/distribute/python/mirrored_strategy.py
index 3c1760c03c..6981449a4c 100644
--- a/tensorflow/contrib/distribute/python/mirrored_strategy.py
+++ b/tensorflow/contrib/distribute/python/mirrored_strategy.py
@@ -19,11 +19,13 @@ from __future__ import division
from __future__ import print_function
import contextlib
+from functools import partial
import threading
from tensorflow.contrib.distribute.python import cross_tower_ops as cross_tower_ops_lib
from tensorflow.contrib.distribute.python import shared_variable_creator
from tensorflow.contrib.distribute.python import values
+from tensorflow.core.protobuf import cluster_pb2
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.eager import tape
@@ -37,6 +39,7 @@ from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.training import coordinator
from tensorflow.python.training import device_util
from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import server_lib
from tensorflow.python.util import nest
@@ -291,24 +294,112 @@ def _create_mirrored_variable(devices, real_mirrored_creator, *args, **kwargs):
class MirroredStrategy(distribute_lib.DistributionStrategy):
- """Mirrors vars to distribute across multiple devices on a single machine.
+ """Mirrors vars to distribute across multiple devices and machines.
+
+ This strategy uses one tower per device and sync replication for its multi-GPU
+ version.
+
+ When `cluster_spec` is given, it turns into the mulit-worker version that
+ works on multiple workers with in-graph replication.
+
+ There are several important concepts for distributed TensorFlow, e.g.
+ `client`, `job`, 'task', `cluster`, `in-graph replication` and
+ 'synchronous training' and they have already been defined in the
+ [TensorFlow's documentation](https://www.tensorflow.org/deploy/distributed).
+ The distribution strategy inherits these concepts as well and in addition to
+ that we also clarify several more concepts:
+ * **In-graph replication**: the `client` creates a single `tf.Graph` that
+ specifies tasks for devices on all workers. The `client` then creates a
+ client session which will talk to the `master` service of a `worker`. Then
+ the `master` will partition the graph and distribute the work to all
+ participating workers.
+ * **Worker**: A `worker` is a TensorFlow `task` that usually maps to one
+ physical machine. We will have multiple `worker`s with different `task`
+ index. They all do similar things except for one worker checkpointing model
+ variables, writing summaries, etc. in addition to its ordinary work.
+
+ The multi-worker version of this class maps one tower to one device on a
+ worker. It mirrors all model variables on all towers. For example, if you have
+ two `worker`s and each `worker` has 4 GPUs, it will create 8 copies of the
+ model variables on these 8 GPUs. Then like in MirroredStrategy, each tower
+ performs their computation with their own copy of variables unless in
+ cross-tower model where variable or tensor reduction happens.
- This strategy uses one tower per device and sync replication.
+ Args:
+ devices: a list of device strings.
+ num_gpus: number of GPUs. For local training, either specify `devices` or
+ `num_gpus`. In distributed training, this must be specified as number of
+ GPUs on each worker.
+ cluster_spec: if this is set, it turns into the multi-worker version and
+ `devices` must not be set but `num_gpus` must be set.
+ cross_tower_ops: optional, a descedant of `CrossTowerOps`. If this is not
+ set, the `configure` method will try to find the best one.
+ prefetch_on_device: optional boolean to specify whether to prefetch input
+ data to devices.
"""
def __init__(self,
devices=None,
num_gpus=None,
+ cluster_spec=None,
cross_tower_ops=None,
prefetch_on_device=None):
super(MirroredStrategy, self).__init__()
- # Convert `num_gpus` into `devices`, shouldn't specify both.
- if devices is None:
+
+ if cluster_spec:
+ if devices is not None:
+ raise ValueError("Specifying devices when `cluster_spec` is also given "
+ "is not supported in MirroredStrategy.")
+
+ # TODO(yuefengz): use the utility method to normalize cluster_spec.
+ if isinstance(cluster_spec, (dict, cluster_pb2.ClusterDef)):
+ cluster_spec = server_lib.ClusterSpec(cluster_spec)
+ elif not isinstance(cluster_spec, server_lib.ClusterSpec):
+ raise ValueError(
+ "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a "
+ "`tf.train.ClusterDef` object")
+ self._cluster_spec = cluster_spec
+
+ self._workers = []
+ for job in sorted(cluster_spec.jobs):
+ for task in range(cluster_spec.num_tasks(job)):
+ self._workers.append("/job:%s/task:%d" % (job, task))
+
if num_gpus is None:
- num_gpus = context.num_gpus()
- devices = ["/device:GPU:%d" % d for d in range(num_gpus)]
- elif num_gpus is not None:
- raise ValueError("Must only specify one of `devices` and `num_gpus`.")
+ raise ValueError("`num_gpus` is required if `cluster_spec` is given.")
+ self._num_gpus = num_gpus
+ if num_gpus > 0:
+ self._worker_device_map = {
+ worker: [
+ device_util.canonicalize(worker + "/device:GPU:%d" % gpu)
+ for gpu in range(num_gpus)
+ ] for worker in self._workers
+ }
+ else:
+ self._worker_device_map = {
+ worker: [device_util.canonicalize(worker, "/device:CPU:0")]
+ for worker in self._workers
+ }
+ devices = nest.flatten(self._worker_device_map)
+
+ # Setting `_default_device` will add a device scope in the
+ # distribution.scope. We set the default device to the first worker. When
+ # users specify device under distribution.scope by
+ # with tf.device("/cpu:0"):
+ # ...
+ # their ops will end up on the cpu device of its first worker, e.g.
+ # "/job:worker/task:0/device:CPU:0". Note this is not used in tower mode.
+ self._default_device = self._workers[0]
+ else:
+ self._cluster_spec = None
+ # Convert `num_gpus` into `devices`, shouldn't specify both.
+ if devices is None:
+ if num_gpus is None:
+ num_gpus = context.num_gpus()
+ devices = ["/device:GPU:%d" % d for d in range(num_gpus)]
+ elif num_gpus is not None:
+ raise ValueError("Must only specify one of `devices` and `num_gpus`.")
+ # TODO(yuefengz): consider setting the default device.
assert devices, "Must specify at least one device."
assert len(set(devices)) == len(devices), (
@@ -317,10 +408,9 @@ class MirroredStrategy(distribute_lib.DistributionStrategy):
self._devices = [device_util.resolve(d) for d in devices]
self._canonical_device_set = set(self._devices)
self._device_index = values.PerDevice(
- dict((d, i) for i, d in enumerate(devices)))
+ {d: i for i, d in enumerate(devices)})
self._cross_tower_ops = cross_tower_ops
self._prefetch_on_device = prefetch_on_device
- # TODO(yuefengz): consider setting the default device.
def _create_variable(self, next_creator, *args, **kwargs):
"""Create a mirrored variable. See `DistributionStrategy.scope`."""
@@ -357,9 +447,14 @@ class MirroredStrategy(distribute_lib.DistributionStrategy):
**kwargs)
def distribute_dataset(self, dataset_fn):
- return values.PerDeviceDataset(
- self._call_dataset_fn(dataset_fn), self._devices,
- self._prefetch_on_device)
+ if self._cluster_spec:
+ return values.MultiWorkerDataset(
+ partial(self._call_dataset_fn, dataset_fn), self._worker_device_map,
+ self._prefetch_on_device)
+ else:
+ return values.PerDeviceDataset(
+ self._call_dataset_fn(dataset_fn), self._devices,
+ self._prefetch_on_device)
# TODO(priyag): Deal with OutOfRange errors once b/111349762 is fixed.
def _run_steps_on_dataset(self, fn, iterator, iterations,
@@ -372,7 +467,10 @@ class MirroredStrategy(distribute_lib.DistributionStrategy):
def body(i, *args):
"""A wrapper around `fn` to create the while loop body."""
del args
- fn_result = fn(ctx, iterator.get_next())
+ fn_inputs = iterator.get_next()
+ if not isinstance(fn_inputs, tuple):
+ fn_inputs = (fn_inputs,)
+ fn_result = fn(ctx, *fn_inputs)
for (name, output) in ctx.last_step_outputs.items():
# Convert all outputs to tensors, potentially from `DistributedValues`.
ctx.last_step_outputs[name] = self.unwrap(output)
@@ -380,12 +478,21 @@ class MirroredStrategy(distribute_lib.DistributionStrategy):
with ops.control_dependencies([fn_result]):
return [i + 1] + flat_last_step_outputs
+ # We capture the control_flow_context at this point, before we run `fn`
+ # inside a while_loop. This is useful in cases where we might need to exit
+ # these contexts and get back to the outer context to do some things, for
+ # e.g. create an op which should be evaluated only once at the end of the
+ # loop on the host. One such usage is in creating metrics' value op.
+ self._outer_control_flow_context = (
+ ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access
+
cond = lambda i, *args: i < iterations
i = constant_op.constant(0)
loop_result = control_flow_ops.while_loop(
cond, body, [i] + initial_loop_values, name="",
parallel_iterations=1, back_prop=False, swap_memory=False,
return_same_structure=True)
+ del self._outer_control_flow_context
ctx.run_op = control_flow_ops.group(loop_result)
@@ -432,10 +539,19 @@ class MirroredStrategy(distribute_lib.DistributionStrategy):
# in addition to PerDevice data.
return values.PerDevice({k: values.MapOutput(v) for k, v in index.items()})
- def configure(self, session_config=None):
+ def configure(self,
+ session_config=None,
+ cluster_spec=None,
+ task_type=None,
+ task_id=None):
+ del cluster_spec, task_type, task_id
if self._cross_tower_ops is None:
- self._cross_tower_ops = cross_tower_ops_lib.choose_the_best(
- self._devices, session_config=session_config)
+ if self._cluster_spec:
+ self._cross_tower_ops = cross_tower_ops_lib.MultiWorkerAllReduce(
+ self._workers, self._num_gpus)
+ else:
+ self._cross_tower_ops = cross_tower_ops_lib.choose_the_best(
+ self._devices, session_config=session_config)
def _get_cross_tower_ops(self):
if self._cross_tower_ops is None:
diff --git a/tensorflow/contrib/distribute/python/mirrored_strategy_multigpu_test.py b/tensorflow/contrib/distribute/python/mirrored_strategy_multigpu_test.py
index e064cfe37d..9a4cc0a897 100644
--- a/tensorflow/contrib/distribute/python/mirrored_strategy_multigpu_test.py
+++ b/tensorflow/contrib/distribute/python/mirrored_strategy_multigpu_test.py
@@ -40,7 +40,7 @@ from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.training import device_util
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
GPU_TEST = "test_gpu" in sys.argv[0]
@@ -164,7 +164,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
# This variable should be created only once across the threads because of
# special variable_creator functions used by `dist.call_for_each_tower`.
v = variable_scope.variable(1.0, name="foo")
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return v
dist = mirrored_strategy.MirroredStrategy(
@@ -181,7 +181,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn():
v = variable_scope.variable(1.0)
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return v
dist = mirrored_strategy.MirroredStrategy(
@@ -201,7 +201,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
vs = []
for i in range(5):
vs.append(variable_scope.variable(1.0, name="foo" + str(i)))
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return vs
dist = mirrored_strategy.MirroredStrategy(
@@ -223,7 +223,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
vs.append(variable_scope.variable(1.0, name="foo_1/bar"))
vs.append(variable_scope.variable(1.0, name="foo_1/bar_1"))
vs.append(variable_scope.variable(1.0, name="foo/bar_1"))
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return vs
dist = mirrored_strategy.MirroredStrategy(
@@ -245,7 +245,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn(device_id):
v = variable_scope.variable(1.0, name="foo_" + str(device_id))
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return v
dist = mirrored_strategy.MirroredStrategy(
@@ -268,7 +268,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
layer2 = core.Dense(1)
layer2(features)
# This will pause the current thread, and execute the other thread.
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(
+ lambda _: _)
layer3 = core.Dense(1)
layer3(features)
return [(layer1.kernel, layer1.bias),
@@ -300,7 +301,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
with variable_scope.variable_scope("common"):
v1 = variable_scope.variable(1.0, name="var1")
# This will pause the current thread, and execute the other thread.
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(
+ lambda _: _)
v2 = variable_scope.variable(
1.0,
name="var2",
@@ -343,7 +345,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
with variable_scope.variable_scope("common"):
v1 = variable_scope.get_variable("var1", [1])
# This will pause the current thread, and execute the other thread.
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(
+ lambda _: _)
v2 = variable_scope.get_variable(
"var2", [1],
synchronization=variable_scope.VariableSynchronization.ON_READ,
@@ -453,7 +456,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn():
v = variable_scope.variable(1.0, name="foo")
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return v
dist = mirrored_strategy.MirroredStrategy(
@@ -470,7 +473,7 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn(name):
v = variable_scope.variable(1.0, name=name)
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(lambda _: _)
return v
dist = mirrored_strategy.MirroredStrategy(
@@ -570,7 +573,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn():
with ops.name_scope("foo"):
a = constant_op.constant(1.0, name="a")
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(
+ lambda _: _)
b = constant_op.constant(1.0, name="b")
return a, b
@@ -591,7 +595,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn():
with ops.name_scope(None, "foo"):
a = constant_op.constant(1.0, name="a")
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(
+ lambda _: _)
b = constant_op.constant(2.0, name="b")
return a, b
@@ -619,7 +624,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn():
b = variable_scope.variable(1.0, name="b")
with ops.name_scope("foo"):
- c = distribute_lib.get_tower_context().merge_call(in_cross_tower)
+ c = distribution_strategy_context.get_tower_context().merge_call(
+ in_cross_tower)
return b, c
dist = mirrored_strategy.MirroredStrategy(
@@ -651,7 +657,8 @@ class MirroredStrategyVariableCreationTest(test.TestCase):
def model_fn():
b = variable_scope.get_variable("b", [1])
with ops.name_scope("foo"):
- c = distribute_lib.get_tower_context().merge_call(in_cross_tower)
+ c = distribution_strategy_context.get_tower_context().merge_call(
+ in_cross_tower)
return b, c
dist = mirrored_strategy.MirroredStrategy(
@@ -833,8 +840,9 @@ class MirroredVariableUpdateTest(test.TestCase):
self.assertEquals(1.0, self.evaluate(mirrored_var))
def model_fn():
- value = math_ops.cast(distribute_lib.get_tower_context().tower_id,
- mirrored_var.dtype)
+ value = math_ops.cast(
+ distribution_strategy_context.get_tower_context().tower_id,
+ mirrored_var.dtype)
return mirrored_var.assign(value)
self.evaluate(dist.unwrap(dist.call_for_each_tower(
@@ -898,8 +906,9 @@ class MirroredVariableUpdateTest(test.TestCase):
self.assertEquals(1.0, self.evaluate(mirrored_var))
def model_fn():
- value = math_ops.cast(distribute_lib.get_tower_context().tower_id,
- mirrored_var.dtype)
+ value = math_ops.cast(
+ distribution_strategy_context.get_tower_context().tower_id,
+ mirrored_var.dtype)
return mirrored_var.assign_add(value)
self.evaluate(dist.unwrap(dist.call_for_each_tower(
@@ -963,8 +972,9 @@ class MirroredVariableUpdateTest(test.TestCase):
self.assertEquals(5.0, self.evaluate(mirrored_var))
def model_fn():
- value = math_ops.cast(distribute_lib.get_tower_context().tower_id,
- mirrored_var.dtype)
+ value = math_ops.cast(
+ distribution_strategy_context.get_tower_context().tower_id,
+ mirrored_var.dtype)
return mirrored_var.assign_sub(value)
self.evaluate(dist.unwrap(dist.call_for_each_tower(
diff --git a/tensorflow/contrib/distribute/python/mirrored_strategy_test.py b/tensorflow/contrib/distribute/python/mirrored_strategy_test.py
index a066adf124..55d59adc07 100644
--- a/tensorflow/contrib/distribute/python/mirrored_strategy_test.py
+++ b/tensorflow/contrib/distribute/python/mirrored_strategy_test.py
@@ -19,12 +19,16 @@ from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distribute.python import mirrored_strategy
+from tensorflow.contrib.distribute.python import multi_worker_test_base
from tensorflow.contrib.distribute.python import strategy_test_lib
from tensorflow.python.eager import context
from tensorflow.python.eager import test
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import variable_scope
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
+from tensorflow.python.training import server_lib
class MirroredOneCPUDistributionTest(strategy_test_lib.DistributionTestBase):
@@ -68,7 +72,8 @@ class VariableCreatorStackTest(test.TestCase):
v = variable_scope.variable(1.0)
# This will pause the current thread, and execute the other thread.
- distribute_lib.get_tower_context().merge_call(lambda _: _)
+ distribution_strategy_context.get_tower_context().merge_call(
+ lambda _: _)
return v
def main_thread_creator(next_creator, *args, **kwargs):
@@ -85,5 +90,33 @@ class VariableCreatorStackTest(test.TestCase):
self.assertEquals(expected, result)
+class MultiWorkerMirroredStrategyTest(
+ multi_worker_test_base.MultiWorkerTestBase,
+ strategy_test_lib.DistributionTestBase):
+
+ def _get_distribution_strategy(self):
+ return mirrored_strategy.MirroredStrategy(
+ cluster_spec=server_lib.ClusterSpec({
+ 'worker': ['/job:worker/task:0', '/job:worker/task:1']
+ }),
+ num_gpus=context.num_gpus())
+
+ def testMinimizeLossGraph(self):
+ self._test_minimize_loss_graph(self._get_distribution_strategy())
+
+ def testDeviceScope(self):
+ """Test the device scope of multi-worker MirroredStrategy."""
+ with context.graph_mode():
+ strategy = mirrored_strategy.MirroredStrategy(
+ cluster_spec={'worker': ['/job:worker/task:0', '/job:worker/task:1']},
+ num_gpus=context.num_gpus())
+ with strategy.scope():
+ a = constant_op.constant(1.)
+ with ops.device('/cpu:0'):
+ b = constant_op.constant(1.)
+ self.assertEqual(a.device, '/job:worker/task:0')
+ self.assertEqual(b.device, '/job:worker/task:0/device:CPU:0')
+
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/distribute/python/multi_worker_strategy.py b/tensorflow/contrib/distribute/python/multi_worker_strategy.py
deleted file mode 100644
index cbfe5df61d..0000000000
--- a/tensorflow/contrib/distribute/python/multi_worker_strategy.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# 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.
-# ==============================================================================
-"""Classes implementing a mirrored DistributionStrategy for multiple workers."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from functools import partial
-
-from tensorflow.contrib.distribute.python import values
-from tensorflow.contrib.distribute.python.mirrored_strategy import MirroredStrategy
-from tensorflow.core.protobuf import cluster_pb2
-from tensorflow.python.training import device_util
-from tensorflow.python.training import server_lib
-from tensorflow.python.util import nest
-
-
-# TODO(yuefengz): support between-graph replication.
-# TODO(yuefengz): merge this class into its base class.
-# TODO(yuefengz): in some cases, we probably want to use configure method to
-# configure this class.
-# TODO(yuefengz): MirroredStrategy.worker_devices may be confusing after the
-# class is introduced.
-class MultiWorkerMirroredStrategy(MirroredStrategy):
- """Mirrored strategy that works on multiple workers with in-graph replication.
-
- There are several important concepts for distributed TensorFlow, e.g.
- `client`, `job`, 'task', `cluster`, `in-graph replication` and
- 'synchronous training' and they have already been defined in the
- [TensorFlow's documentation](https://www.tensorflow.org/deploy/distributed).
- The distribution strategy inherits these concepts as well and in addition to
- that we also clarify several more concepts:
- * **In-graph replication**: the `client` creates a single `tf.Graph` that
- specifies tasks for devices on all workers. The `client` then creates a
- client session which will talk to the `master` service of a `worker`. Then
- the `master` will partition the graph and distribute the work to all
- participating workers.
- * **Worker**: A `worker` is a TensorFlow `task` that usually maps to one
- physical machine. We will have multiple `worker`s with different `task`
- index. They all do similar things except for one worker checkpointing model
- variables, writing summaries, etc. in addition to its ordinary work.
-
- This class maps one tower to one device on a worker. It mirrors all model
- variables on all towers. For example, if you have two `worker`s and each
- `worker` has 4 GPUs, it will create 8 copies of the model variables on these 8
- GPUs. Then like in MirroredStrategy, each tower performs their computation
- with their own copy of variables unless in cross-tower model where variable or
- tensor reduction happens.
- """
-
- def __init__(self,
- num_gpus_per_worker=1,
- worker_job_name=None,
- num_workers=None,
- cluster=None,
- cross_tower_ops=None,
- prefetch_on_device=None):
- """Initialize the strategy object.
-
- Args:
- num_gpus_per_worker: number of GPUs per work. If it is zero, the local
- CPU will be used.
- worker_job_name: the job name for `worker`, typically just 'worker'.
- num_workers: the number of workers. If it is 0, it regenerates to
- single-worker MirroredStrategy.
- cluster: a `tf.train.ClusterSpec` object or a dict that can be used to
- construct a `tf.train.ClusterSpec` object or a `tf.train.ClusterDef`
- proto buffer. It is an alternative way to initialize this object.
- cross_tower_ops: the cross tower ops to use. If None, a default one will
- be used. If configure method is called, a best one for the configuration
- will be chosen.
- prefetch_on_device: a boolean to specify whether to prefetech input to
- each worker's devices.
-
- Raises:
- ValueError: if got an unexpected `cluster`.
- """
- if cluster is None:
- self._workers = [
- '/job:%s/task:%d' % (worker_job_name, task_index)
- for task_index in range(num_workers)
- ]
- else:
- if isinstance(cluster, (dict, cluster_pb2.ClusterDef)):
- cluster_spec = server_lib.ClusterSpec(cluster)
- elif isinstance(cluster, server_lib.ClusterSpec):
- cluster_spec = cluster
- else:
- raise ValueError(
- "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a "
- '`tf.train.ClusterDef` object')
-
- self._workers = []
- for job in sorted(cluster_spec.jobs):
- for task in range(cluster_spec.num_tasks(job)):
- self._workers.append('/job:%s/task:%d' % (job, task))
-
- self._num_gpus_per_worker = num_gpus_per_worker
- if num_gpus_per_worker > 0:
- self._worker_device_map = {
- worker: [
- device_util.canonicalize(worker + '/device:GPU:%d' % gpu)
- for gpu in range(num_gpus_per_worker)
- ] for worker in self._workers
- }
- else:
- self._worker_device_map = {
- worker: [device_util.canonicalize(worker, '/device:CPU:0')]
- for worker in self._workers
- }
- self._devices = nest.flatten(self._worker_device_map)
-
- super(MultiWorkerMirroredStrategy, self).__init__(
- devices=self._devices, prefetch_on_device=prefetch_on_device)
-
- # Setting `_default_device` will add a device scope in the
- # distribution.scope. We set the default device to the first worker. When
- # users specify device under distribution.scope by
- # with tf.device("/cpu:0"):
- # ...
- # their ops will end up on the cpu device of its first worker, e.g.
- # "/job:worker/task:0/device:CPU:0". Note this is not used in tower mode.
- self._default_device = self._workers[0]
-
- def distribute_dataset(self, dataset_fn):
- return values.MultiWorkerDataset(
- partial(self._call_dataset_fn, dataset_fn), self._worker_device_map,
- self._prefetch_on_device)
diff --git a/tensorflow/contrib/distribute/python/multi_worker_strategy_test.py b/tensorflow/contrib/distribute/python/multi_worker_strategy_test.py
deleted file mode 100644
index 09c859b32a..0000000000
--- a/tensorflow/contrib/distribute/python/multi_worker_strategy_test.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# 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 MultiWorkerMirroredStrategy."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.contrib.distribute.python import multi_worker_strategy
-from tensorflow.contrib.distribute.python import multi_worker_test_base
-from tensorflow.contrib.distribute.python import strategy_test_lib
-from tensorflow.python.eager import context
-from tensorflow.python.eager import test
-from tensorflow.python.framework import constant_op
-from tensorflow.python.framework import ops
-from tensorflow.python.training import server_lib
-
-
-class MultiWorkerStrategyTest(multi_worker_test_base.MultiWorkerTestBase,
- strategy_test_lib.DistributionTestBase):
-
- def _get_distribution_strategy(self):
- return multi_worker_strategy.MultiWorkerMirroredStrategy(
- cluster=server_lib.ClusterSpec({
- 'worker': ['/job:worker/task:0', '/job:worker/task:1']
- }),
- num_gpus_per_worker=context.num_gpus())
-
- def testMinimizeLossGraph(self):
- self._test_minimize_loss_graph(self._get_distribution_strategy())
-
-
-class DeviceScopeTest(test.TestCase):
- """Test the device scope of MultiWorkerMirroredStrategy."""
-
- def testDeviceScope(self):
- with context.graph_mode():
- strategy = multi_worker_strategy.MultiWorkerMirroredStrategy(
- cluster={'worker': ['/job:worker/task:0', '/job:worker/task:1']},
- num_gpus_per_worker=context.num_gpus())
- with strategy.scope():
- a = constant_op.constant(1.)
- with ops.device('/cpu:0'):
- b = constant_op.constant(1.)
- self.assertEqual(a.device, '/job:worker/task:0')
- self.assertEqual(b.device, '/job:worker/task:0/device:CPU:0')
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/contrib/distribute/python/one_device_strategy.py b/tensorflow/contrib/distribute/python/one_device_strategy.py
index 016978cdb3..68561b5bbf 100644
--- a/tensorflow/contrib/distribute/python/one_device_strategy.py
+++ b/tensorflow/contrib/distribute/python/one_device_strategy.py
@@ -80,18 +80,30 @@ class OneDeviceStrategy(distribute_lib.DistributionStrategy):
def body(i, *args):
"""A wrapper around `fn` to create the while loop body."""
del args
- fn_result = fn(ctx, iterator.get_next())
+ fn_inputs = iterator.get_next()
+ if not isinstance(fn_inputs, tuple):
+ fn_inputs = (fn_inputs,)
+ fn_result = fn(ctx, *fn_inputs)
flat_last_step_outputs = nest.flatten(ctx.last_step_outputs)
with ops.control_dependencies([fn_result]):
return [i + 1] + flat_last_step_outputs
+ # We capture the control_flow_context at this point, before we run `fn`
+ # inside a while_loop. This is useful in cases where we might need to exit
+ # these contexts and get back to the outer context to do some things, for
+ # e.g. create an op which should be evaluated only once at the end of the
+ # loop on the host. One such usage is in creating metrics' value op.
+ self._outer_control_flow_context = (
+ ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access
+
+ # TODO(priyag): Use max_iterations instead of an explicit counter.
cond = lambda i, *args: i < iterations
i = constant_op.constant(0)
- # TODO(priyag): Use max_iterations instead of an explicit counter.
loop_result = control_flow_ops.while_loop(
cond, body, [i] + initial_loop_values, name="",
parallel_iterations=1, back_prop=False, swap_memory=False,
return_same_structure=True)
+ del self._outer_control_flow_context
ctx.run_op = control_flow_ops.group(loop_result)
diff --git a/tensorflow/contrib/distribute/python/parameter_server_strategy.py b/tensorflow/contrib/distribute/python/parameter_server_strategy.py
index f2c7fd556a..8041eb0f34 100644
--- a/tensorflow/contrib/distribute/python/parameter_server_strategy.py
+++ b/tensorflow/contrib/distribute/python/parameter_server_strategy.py
@@ -18,13 +18,10 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import json
-import os
-
from tensorflow.contrib.distribute.python import cross_tower_ops as cross_tower_ops_lib
from tensorflow.contrib.distribute.python import mirrored_strategy
from tensorflow.contrib.distribute.python import values
-from tensorflow.core.protobuf import cluster_pb2
+from tensorflow.python.distribute import multi_worker_util
from tensorflow.python.framework import device as tf_device
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
@@ -32,24 +29,12 @@ from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.training import device_setter
from tensorflow.python.training import device_util
from tensorflow.python.training import distribute as distribute_lib
-from tensorflow.python.training import server_lib
from tensorflow.python.util import nest
_LOCAL_CPU = "/device:CPU:0"
_LOCAL_GPU_0 = "/device:GPU:0"
-def _normalize_cluster_spec(cluster_spec):
- """Makes `cluster_spec` into a `ClusterSpec` object."""
- if isinstance(cluster_spec, (dict, cluster_pb2.ClusterDef)):
- return server_lib.ClusterSpec(cluster_spec)
- elif not isinstance(cluster_spec, server_lib.ClusterSpec):
- raise ValueError(
- "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a "
- "`tf.train.ClusterDef` object")
- return cluster_spec
-
-
# TODO(yuefengz): maybe cache variables on local CPU.
# TODO(yuefengz): we may want to set session options to disallow communication
# between workers.
@@ -77,16 +62,16 @@ class ParameterServerStrategy(distribute_lib.DistributionStrategy):
GPUs) even if there is only CPU or one GPU. When defining the `fn`, extra
caution needs to be taken:
- 1) Always use @{tf.get_variable} instead of @{tf.Variable} which is not able
+ 1) Always use `tf.get_variable` instead of `tf.Variable` which is not able
to refer to the same variable on different towers.
2) It is generally not recommended to open a device scope under the strategy's
- scope. A device scope (i.e. calling @{tf.device}) will be merged with or
+ scope. A device scope (i.e. calling `tf.device`) will be merged with or
override the device for operations but will not change the device for
variables.
3) It is also not recommended to open a colocation scope (i.e. calling
- @{tf.colocate_with}) under the strategy's scope. For colocating variables,
+ `tf.colocate_with`) under the strategy's scope. For colocating variables,
use `distribution.colocate_vars_with` instead. Colocation of ops will possibly
create conflicts of device assignement.
"""
@@ -108,7 +93,7 @@ class ParameterServerStrategy(distribute_lib.DistributionStrategy):
super(ParameterServerStrategy, self).__init__()
self._num_gpus_per_worker = num_gpus_per_worker
if cluster_spec:
- cluster_spec = _normalize_cluster_spec(cluster_spec)
+ cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec)
self._cluster_spec = cluster_spec
# We typically don't need to do all-reduce in this strategy.
@@ -216,6 +201,9 @@ class ParameterServerStrategy(distribute_lib.DistributionStrategy):
else:
self._default_device = self._worker_device
+ self._is_chief = cluster_spec is None or multi_worker_util.is_chief(
+ cluster_spec, task_type, task_id)
+
def distribute_dataset(self, dataset_fn):
"""Distributes the dataset to each local GPU."""
return values.PerDeviceDataset(
@@ -319,26 +307,31 @@ class ParameterServerStrategy(distribute_lib.DistributionStrategy):
# No need to distinguish between normal variables and tower-local variables.
return array_ops.identity(var)
- def configure(self, session_config=None):
- del session_config
+ def configure(self,
+ session_config=None,
+ cluster_spec=None,
+ task_type=None,
+ task_id=None):
+ """Configures the strategy class.
- # Use TF_CONFIG to get the cluster spec and the current job.
- tf_config = json.loads(os.environ.get("TF_CONFIG", "{}"))
- cluster_spec = _normalize_cluster_spec(tf_config.get("cluster", {}))
+ The strategy object will be re-initialized if `cluster_spec` is given but
+ was not passed in the constructor.
- task_env = tf_config.get("task", {})
- if task_env:
- task_type = task_env.get("type", "worker")
- task_id = int(task_env.get("index", "0"))
- else:
- task_type = "worker"
- task_id = None
+ Args:
+ session_config: not used currently.
+ cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the
+ cluster configurations.
+ task_type: the current task type.
+ task_id: the current task id.
+ """
+ del session_config
# Set the devices if cluster_spec is defined in TF_CONFIG but not passed in
# the constructor.
if not self._cluster_spec and cluster_spec:
- self._cluster_spec = cluster_spec
- self._initialize_devices(self._num_gpus_per_worker, cluster_spec,
+ self._cluster_spec = multi_worker_util.normalize_cluster_spec(
+ cluster_spec)
+ self._initialize_devices(self._num_gpus_per_worker, self._cluster_spec,
task_type, task_id)
@property
@@ -356,3 +349,19 @@ class ParameterServerStrategy(distribute_lib.DistributionStrategy):
def non_slot_devices(self, var_list):
return min(var_list, key=lambda x: x.name)
+
+ @property
+ def between_graph(self):
+ return True
+
+ @property
+ def should_init(self):
+ return self._is_chief
+
+ @property
+ def should_checkpoint(self):
+ return self._is_chief
+
+ @property
+ def should_save_summary(self):
+ return self._is_chief
diff --git a/tensorflow/contrib/distribute/python/parameter_server_strategy_test.py b/tensorflow/contrib/distribute/python/parameter_server_strategy_test.py
index cf29c0ed91..0df65714fb 100644
--- a/tensorflow/contrib/distribute/python/parameter_server_strategy_test.py
+++ b/tensorflow/contrib/distribute/python/parameter_server_strategy_test.py
@@ -18,7 +18,6 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import json
import threading
from absl.testing import parameterized
@@ -37,7 +36,7 @@ from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import device_util
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
class ParameterServerStrategyTest(multi_worker_test_base.MultiWorkerTestBase,
@@ -69,19 +68,8 @@ class ParameterServerStrategyTest(multi_worker_test_base.MultiWorkerTestBase,
if not task_type:
return distribution, ''
- tf_config = {
- 'cluster': self._cluster_spec,
- 'task': {
- 'type': task_type,
- 'index': task_id
- }
- }
- with self._lock:
- # Accessing environment variables should be protected by locks because
- # environment variables are shared by all threads.
- with test.mock.patch.dict('os.environ',
- {'TF_CONFIG': json.dumps(tf_config)}):
- distribution.configure()
+ distribution.configure(
+ cluster_spec=self._cluster_spec, task_type=task_type, task_id=task_id)
return distribution, self._workers[task_id].target
def _test_device_assignment_distributed(self, task_type, task_id, num_gpus):
@@ -101,7 +89,8 @@ class ParameterServerStrategyTest(multi_worker_test_base.MultiWorkerTestBase,
last_part_device = 'device:CPU:0'
else:
last_part_device = (
- 'device:GPU:%d' % distribute_lib.get_tower_context().tower_id)
+ 'device:GPU:%d' %
+ distribution_strategy_context.get_tower_context().tower_id)
a = constant_op.constant(1.0)
b = constant_op.constant(2.0)
@@ -192,14 +181,16 @@ class ParameterServerStrategyTest(multi_worker_test_base.MultiWorkerTestBase,
tower_compute_device = '/device:CPU:0'
else:
tower_compute_device = (
- '/device:GPU:%d' % distribute_lib.get_tower_context().tower_id)
+ '/device:GPU:%d' %
+ distribution_strategy_context.get_tower_context().tower_id)
tower_compute_device = device_util.canonicalize(tower_compute_device)
if 'CPU' in variable_device:
tower_variable_device = '/device:CPU:0'
else:
tower_variable_device = (
- '/device:GPU:%d' % distribute_lib.get_tower_context().tower_id)
+ '/device:GPU:%d' %
+ distribution_strategy_context.get_tower_context().tower_id)
tower_variable_device = device_util.canonicalize(tower_variable_device)
a = constant_op.constant(1.0)
diff --git a/tensorflow/contrib/distribute/python/prefetching_ops_v2.py b/tensorflow/contrib/distribute/python/prefetching_ops_v2.py
index 24cdc627a3..1ff60c0762 100644
--- a/tensorflow/contrib/distribute/python/prefetching_ops_v2.py
+++ b/tensorflow/contrib/distribute/python/prefetching_ops_v2.py
@@ -35,7 +35,7 @@ from tensorflow.python.util import nest
# pylint: disable=protected-access
class _PrefetchToDeviceIterator(object):
- """A replacement for @{tf.data.Iterator} that prefetches to another device.
+ """A replacement for `tf.data.Iterator` that prefetches to another device.
Args:
input_dataset: The input dataset.
@@ -108,7 +108,7 @@ class _PrefetchToDeviceIterator(object):
self._input_dataset)
def get_next(self, name=None):
- """See @{tf.data.Iterator.get_next}."""
+ """See `tf.data.Iterator.get_next`."""
self._get_next_call_count += 1
if self._get_next_call_count > iterator_ops.GET_NEXT_CALL_WARNING_THRESHOLD:
warnings.warn(iterator_ops.GET_NEXT_CALL_WARNING_MESSAGE)
@@ -209,7 +209,7 @@ class _PrefetchToDeviceDataset(dataset_ops.Dataset):
def prefetch_to_devices(devices, buffer_size=None):
"""A transformation that prefetches dataset values to the given `devices`.
- NOTE: Although the transformation creates a @{tf.data.Dataset}, the
+ NOTE: Although the transformation creates a `tf.data.Dataset`, the
transformation must be the final `Dataset` in the input pipeline.
Args:
@@ -220,7 +220,7 @@ def prefetch_to_devices(devices, buffer_size=None):
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
return _PrefetchToDeviceDataset(dataset, devices, buffer_size)
diff --git a/tensorflow/contrib/distribute/python/single_loss_example.py b/tensorflow/contrib/distribute/python/single_loss_example.py
index d1fdb3279c..5aa19cf6a9 100644
--- a/tensorflow/contrib/distribute/python/single_loss_example.py
+++ b/tensorflow/contrib/distribute/python/single_loss_example.py
@@ -29,7 +29,8 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
-def single_loss_example(optimizer_fn, distribution, use_bias=False):
+def single_loss_example(optimizer_fn, distribution, use_bias=False,
+ iterations_per_step=1):
"""Build a very simple network to use in tests and examples."""
def dataset_fn():
@@ -38,12 +39,13 @@ def single_loss_example(optimizer_fn, distribution, use_bias=False):
optimizer = optimizer_fn()
layer = core.Dense(1, use_bias=use_bias)
- def loss_fn(x):
+ def loss_fn(ctx, x):
+ del ctx
y = array_ops.reshape(layer(x), []) - constant_op.constant(1.)
return y * y
- single_loss_step = step_fn.StandardSingleLossStep(dataset_fn, loss_fn,
- optimizer, distribution)
+ single_loss_step = step_fn.StandardSingleLossStep(
+ dataset_fn, loss_fn, optimizer, distribution, iterations_per_step)
# Layer is returned for inspecting the kernels in tests.
return single_loss_step, layer
diff --git a/tensorflow/contrib/distribute/python/step_fn.py b/tensorflow/contrib/distribute/python/step_fn.py
index d1910622b3..1b5a4f64e5 100644
--- a/tensorflow/contrib/distribute/python/step_fn.py
+++ b/tensorflow/contrib/distribute/python/step_fn.py
@@ -34,15 +34,9 @@ class Step(object):
def __call__(self):
"""Perform one step of this training algorithm."""
- return self.step(self.inputs())
-
- def inputs(self):
- """For the generating the input to be passed to `step()`."""
raise NotImplementedError("must be implemented in descendants")
- def step(self, inputs):
- """Perform the main computation of this training algorithm."""
- raise NotImplementedError("must be implemented in descendants")
+ # TODO(priyag): Add an method to access initialization and finalize ops.
class StandardInputStep(Step):
@@ -54,12 +48,9 @@ class StandardInputStep(Step):
"""
def __init__(self, dataset_fn, distribution):
- Step.__init__(self, distribution)
- self._distributed_input = distribution.distribute_dataset(
- dataset_fn).make_one_shot_iterator()
-
- def inputs(self):
- return self._distributed_input.get_next()
+ super(StandardInputStep, self).__init__(distribution)
+ self._distributed_input = distribution.distribute_dataset(dataset_fn)
+ self._iterator = self._distributed_input.make_one_shot_iterator()
class StandardSingleLossStep(StandardInputStep):
@@ -69,8 +60,8 @@ class StandardSingleLossStep(StandardInputStep):
```python
...
- step = step_fn.StandardSingleLossStep(dataset, loss_fn, optimizer)
- step.initialize(distribution)
+ step = step_fn.StandardSingleLossStep(
+ dataset, loss_fn, optimizer, distribution)
# Run a single training step on a given DistributionStrategy:
step(distribution)
@@ -80,27 +71,43 @@ class StandardSingleLossStep(StandardInputStep):
Args:
dataset_fn: a function that returns a tf.data Dataset that produces the
input for the model.
- loss_fn: a function that returns loss.
+ loss_fn: a function that takes a context and inputs as arguments. It returns
+ the loss for those inputs. `context` is an instance of
+ `values.MultiStepContext` that will be passed when `loss_fn` is run.
+ `context` can be used to specify the outputs to be returned from
+ `loss_fn`, among other things.
optimizer: an optimizer that implements an update rule.
distribution: a `DistributionStrategy` object.
"""
- def __init__(self, dataset_fn, loss_fn, optimizer, distribution):
- StandardInputStep.__init__(self, dataset_fn, distribution)
+ def __init__(self, dataset_fn, loss_fn, optimizer, distribution,
+ iterations_per_step=1):
+ super(StandardSingleLossStep, self).__init__(dataset_fn, distribution)
self._loss_fn = loss_fn
self._optimizer = optimizer
self._is_run_concurrently = False
+ self._iterations_per_step = iterations_per_step
- def step(self, inputs):
+ def __call__(self):
with self._distribution.scope():
- gradients_fn = backprop.implicit_grad(self._loss_fn)
- gradients_fn = optimizer_lib.get_filtered_grad_fn(gradients_fn)
-
- grads_and_vars = self.distribution.call_for_each_tower(
- gradients_fn, inputs, run_concurrently=self._is_run_concurrently)
- # If threads use layers, then we need to run the first step sequentially,
- # so that layers.build() is not executed in parallel. Otherwise, multiple
- # sets of mirrored variables are going to be created.
- self._is_run_concurrently = True
- return self._optimizer._distributed_apply( # pylint: disable=protected-access
- self.distribution, grads_and_vars)
+ def step_fn(ctx, *inputs):
+ """Function to run one iteration with one input."""
+ gradients_fn = backprop.implicit_grad(self._loss_fn)
+ gradients_fn = optimizer_lib.get_filtered_grad_fn(gradients_fn)
+
+ grads_and_vars = self.distribution.call_for_each_tower(
+ gradients_fn,
+ ctx, *inputs,
+ run_concurrently=self._is_run_concurrently)
+ # If threads use layers, then we need to run the first step
+ # sequentially, so that layers.build() is not executed in parallel.
+ # Otherwise, multiple sets of mirrored variables are going to be
+ # created.
+ self._is_run_concurrently = True
+ return self._optimizer._distributed_apply( # pylint: disable=protected-access
+ self.distribution, grads_and_vars)
+
+ # TODO(priyag): Return the outputs, context, etc as well.
+ ctx = self.distribution.run_steps_on_dataset(
+ step_fn, self._iterator, self._iterations_per_step)
+ return ctx.run_op
diff --git a/tensorflow/contrib/distribute/python/step_fn_test.py b/tensorflow/contrib/distribute/python/step_fn_test.py
index 2ee94d8f70..8605ab1f7d 100644
--- a/tensorflow/contrib/distribute/python/step_fn_test.py
+++ b/tensorflow/contrib/distribute/python/step_fn_test.py
@@ -33,12 +33,19 @@ class SingleLossStepTest(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.times(
combinations.distributions_and_v1_optimizers(),
- combinations.combine(mode=combinations.graph_and_eager_modes)))
- def testTrainNetwork(self, distribution, optimizer_fn):
+ combinations.combine(mode=combinations.graph_and_eager_modes),
+ combinations.combine(is_tpu=[False])) +
+ combinations.combine(
+ distribution=[combinations.tpu_strategy],
+ optimizer_fn=combinations.optimizers_v1,
+ mode=["graph"],
+ is_tpu=[True]))
+ def testTrainNetwork(self, distribution, optimizer_fn, is_tpu):
with distribution.scope():
single_loss_step, layer = single_loss_example(
- optimizer_fn, distribution, use_bias=True)
+ optimizer_fn, distribution, use_bias=True, iterations_per_step=2)
+ self.evaluate(distribution.initialize())
if context.executing_eagerly():
run_step = single_loss_step
else:
@@ -47,12 +54,14 @@ class SingleLossStepTest(test.TestCase, parameterized.TestCase):
self.evaluate(variables.global_variables_initializer())
weights, biases = [], []
- for _ in range(10):
+ for _ in range(5):
run_step()
weights.append(self.evaluate(layer.kernel))
biases.append(self.evaluate(layer.bias))
+ self.evaluate(distribution.finalize())
+
error = abs(numpy.add(numpy.squeeze(weights), numpy.squeeze(biases)) - 1)
is_not_increasing = all(y <= x for x, y in zip(error, error[1:]))
self.assertTrue(is_not_increasing)
diff --git a/tensorflow/contrib/distribute/python/strategy_test_lib.py b/tensorflow/contrib/distribute/python/strategy_test_lib.py
index baed0ebaae..371b97ba96 100644
--- a/tensorflow/contrib/distribute/python/strategy_test_lib.py
+++ b/tensorflow/contrib/distribute/python/strategy_test_lib.py
@@ -28,7 +28,7 @@ from tensorflow.python.layers import core
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import optimizer
@@ -45,7 +45,8 @@ def _raise_exception_fn(_=None):
# Must be the argument to a distribution.call_for_each_tower() call, calls a
# get_tower_context().merge_call() that raises an exception.
def _merge_raises_fn():
- distribute_lib.get_tower_context().merge_call(_raise_exception_fn)
+ distribution_strategy_context.get_tower_context().merge_call(
+ _raise_exception_fn)
# Must be the argument to a get_tower_context().merge_call() call, calls
@@ -58,7 +59,7 @@ def _call_raises_fn(dist):
# calls a get_tower_context().merge_call() that calls a
# call_for_each_tower() that raises an exception.
def _merge_call_raises_fn():
- distribute_lib.get_tower_context().merge_call(_call_raises_fn)
+ distribution_strategy_context.get_tower_context().merge_call(_call_raises_fn)
# Must be the argument to a get_tower_context().merge_call() call, calls
@@ -72,7 +73,8 @@ def _call_merge_raises_fn(dist):
# get_tower_context().merge_call() that calls a call_for_each_tower() that
# calls a get_tower_context().merge_call() that raises an exception.
def _merge_call_merge_raises_fn():
- distribute_lib.get_tower_context().merge_call(_call_merge_raises_fn)
+ distribution_strategy_context.get_tower_context().merge_call(
+ _call_merge_raises_fn)
class DistributionTestBase(test.TestCase):
@@ -208,7 +210,7 @@ class DistributionTestBase(test.TestCase):
expected_devices = [False] * len(d.worker_devices)
def mark_devices_fn():
- tower_id = distribute_lib.get_tower_context().tower_id
+ tower_id = distribution_strategy_context.get_tower_context().tower_id
self.assertLess(tower_id, len(d.worker_devices))
self.assertFalse(expected_devices[tower_id])
expected_devices[tower_id] = True
diff --git a/tensorflow/contrib/distribute/python/tpu_strategy.py b/tensorflow/contrib/distribute/python/tpu_strategy.py
index 83af37fc81..77fc56de36 100644
--- a/tensorflow/contrib/distribute/python/tpu_strategy.py
+++ b/tensorflow/contrib/distribute/python/tpu_strategy.py
@@ -37,7 +37,6 @@ from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.training import device_util
-from tensorflow.python.training import server_lib
from tensorflow.python.util import nest
@@ -46,8 +45,8 @@ def get_tpu_system_metadata(tpu_cluster_resolver):
master = tpu_cluster_resolver.master()
# pylint: disable=protected-access
- cluster_def = (tpu_cluster_resolver.cluster_spec()
- or server_lib.ClusterSpec({})).as_cluster_def()
+ cluster_spec = tpu_cluster_resolver.cluster_spec()
+ cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None
tpu_system_metadata = (
tpu_system_metadata_lib._query_tpu_system_metadata(
master,
@@ -60,12 +59,17 @@ def get_tpu_system_metadata(tpu_cluster_resolver):
class TPUStrategy(one_device_strategy.OneDeviceStrategy):
"""Experimental TPU distribution strategy implementation."""
- def __init__(self, tpu_cluster_resolver):
+ def __init__(self, tpu_cluster_resolver, steps_per_run):
"""Initializes the TPUStrategy object.
Args:
tpu_cluster_resolver: A tf.contrib.cluster_resolver.TPUClusterResolver,
which provides information about the TPU cluster.
+ steps_per_run: Number of steps to run on device before returning to the
+ host. Note that this can have side-effects on performance, hooks,
+ metrics, summaries etc.
+ This parameter is only used when Distribution Strategy is used with
+ estimator or keras.
"""
# TODO(isaprykin): Generalize the defaults. They are currently tailored for
# the unit test.
@@ -76,6 +80,9 @@ class TPUStrategy(one_device_strategy.OneDeviceStrategy):
# TODO(priyag): This should not be hardcoded here.
self._host = '/device:CPU:0'
+ # TODO(sourabhbajaj): Remove this once performance of running one step
+ # at a time is comparable to multiple steps.
+ self.steps_per_run = steps_per_run
def distribute_dataset(self, dataset_fn):
# TODO(priyag): Perhaps distribute across cores here.
@@ -136,7 +143,10 @@ class TPUStrategy(one_device_strategy.OneDeviceStrategy):
ctx = values.MultiStepContext()
def run_fn(*args, **kwargs):
del args, kwargs
- fn_result = fn(ctx, dequeue_fn())
+ fn_inputs = dequeue_fn()
+ if not isinstance(fn_inputs, tuple):
+ fn_inputs = (fn_inputs,)
+ fn_result = fn(ctx, *fn_inputs)
flat_last_step_outputs = nest.flatten(ctx.last_step_outputs)
if flat_last_step_outputs:
with ops.control_dependencies([fn_result]):
@@ -149,8 +159,18 @@ class TPUStrategy(one_device_strategy.OneDeviceStrategy):
def iterate_on_tpu():
return training_loop.repeat(iterations, run_fn, initial_loop_values)
+ # We capture the control_flow_context at this point, before we run `fn`
+ # inside a while_loop and TPU replicate context. This is useful in cases
+ # where we might need to exit these contexts and get back to the outer
+ # context to do some things, for e.g. create an op which should be
+ # evaluated only once at the end of the loop on the host. One such usage
+ # is in creating metrics' value op.
+ self._outer_control_flow_context = (
+ ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access
+
replicate_inputs = [[]] * self.num_towers
replicate_outputs = tpu.replicate(iterate_on_tpu, replicate_inputs)
+ del self._outer_control_flow_context
ctx.run_op = control_flow_ops.group(replicate_outputs, enqueue_ops)
# Filter out any ops from the outputs, typically this would be the case
diff --git a/tensorflow/contrib/distribute/python/values.py b/tensorflow/contrib/distribute/python/values.py
index 5fd4c9de69..8548a86421 100644
--- a/tensorflow/contrib/distribute/python/values.py
+++ b/tensorflow/contrib/distribute/python/values.py
@@ -38,6 +38,7 @@ from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.training import device_util
from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import saver
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.util import nest
@@ -56,7 +57,7 @@ class DistributedValues(object):
def get(self, device=None):
"""Returns the value for the current device or raises a ValueError."""
if device is None:
- tower_context = distribute_lib.get_tower_context()
+ tower_context = distribution_strategy_context.get_tower_context()
if tower_context:
device = tower_context.device
else:
@@ -289,14 +290,15 @@ class DistributedVariable(DistributedDelegate):
# We want cross-tower code that does some var.op.X calls
# to work (even if the current device isn't in self.devices), but
# other uses of var.op in a cross-tower context to fail.
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
return DistributedVarOp(self._primary_var.op.name,
self._primary_var.op.graph,
self._primary_var.op.type)
return self.get().op
def read_value(self):
- return distribute_lib.get_distribution_strategy().read_var(self)
+ return distribution_strategy_context.get_distribution_strategy().read_var(
+ self)
def _should_act_as_resource_variable(self):
"""Pass resource_variable_ops.is_resource_variable check."""
@@ -362,7 +364,7 @@ class MirroredVariable(DistributedVariable, Mirrored,
# update several non-slot variables in one call.
def _assign_func(self, *args, **kwargs):
f = kwargs.pop("f")
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
update_device = distribute_lib.get_update_device()
# We are calling update on the mirrored variable in cross tower context.
if update_device is not None:
@@ -371,7 +373,7 @@ class MirroredVariable(DistributedVariable, Mirrored,
v = self.get(device=update_device)
return f(v, *args, **kwargs)
- return distribute_lib.get_distribution_strategy().update(
+ return distribution_strategy_context.get_distribution_strategy().update(
self, f, *args, **kwargs)
else:
_assert_tower_context()
@@ -392,8 +394,8 @@ class MirroredVariable(DistributedVariable, Mirrored,
aggregation=self._aggregation, value=value, destinations=self),
*other_args, **other_kwargs)
- return distribute_lib.get_tower_context().merge_call(merge_fn, *args,
- **kwargs)
+ return distribution_strategy_context.get_tower_context().merge_call(
+ merge_fn, *args, **kwargs)
def assign_sub(self, *args, **kwargs):
assign_sub_fn = lambda var, *a, **kw: var.assign_sub(*a, **kw)
@@ -419,7 +421,7 @@ class MirroredVariable(DistributedVariable, Mirrored,
def _as_graph_element(self):
# pylint: disable=protected-access
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
return self._primary_var._as_graph_element()
return self.get()._as_graph_element()
@@ -459,7 +461,7 @@ class _TowerLocalSaveable(saver.BaseSaverBuilder.SaveableObject):
# We use a callable so that we don't have to evaluate this expression
# in the case where we are trying to restore instead of save.
def tensor():
- return distribute_lib.get_distribution_strategy().read_var(
+ return distribution_strategy_context.get_distribution_strategy().read_var(
tower_local_variable)
spec = saver.BaseSaverBuilder.SaveSpec(
tensor=tensor,
@@ -475,7 +477,7 @@ class _TowerLocalSaveable(saver.BaseSaverBuilder.SaveableObject):
def _assert_tower_context():
- if not distribute_lib.get_tower_context():
+ if not distribution_strategy_context.get_tower_context():
raise RuntimeError(
"Tower-local variables may only be assigned in a tower context.")
@@ -498,7 +500,7 @@ class TowerLocalVariable(DistributedVariable, PerDevice,
return self.get().assign_add(*args, **kwargs)
def assign(self, *args, **kwargs):
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
# To preserve the sum across save and restore, we have to divide the
# total across all devices when restoring a variable that was summed
# when saving.
@@ -526,7 +528,7 @@ class TowerLocalVariable(DistributedVariable, PerDevice,
def _as_graph_element(self):
# pylint: disable=protected-access
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
return self._get_cross_tower()
return self.get()._as_graph_element()
@@ -994,12 +996,12 @@ class MultiStepContext(object):
outputs as already reduced or not.
"""
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
self._last_step_outputs_aggregations[name] = aggregation
if aggregation is variables_lib.VariableAggregation.NONE:
self._last_step_outputs[name] = output
else:
- distribution = distribute_lib.get_distribution_strategy()
+ distribution = distribution_strategy_context.get_distribution_strategy()
self._last_step_outputs[name] = distribution.reduce(
aggregation, output, destinations="/device:CPU:0")
else:
@@ -1011,7 +1013,9 @@ class MultiStepContext(object):
# context object, so it's more robust to set it only once (even if all
# the towers are trying to set the same value).
self._last_step_outputs_aggregations[name] = aggregation
- distribute_lib.get_tower_context().merge_call(merge_fn, output)
+
+ distribution_strategy_context.get_tower_context().merge_call(
+ merge_fn, output)
@property
def non_tensor_outputs(self):
@@ -1020,14 +1024,15 @@ class MultiStepContext(object):
def set_non_tensor_output(self, name, output):
"""Set `output` with `name` to be captured as a non tensor output."""
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
self._non_tensor_outputs[name] = output
else:
def merge_fn(distribution, value):
# NOTE(priyag): For non tensor outputs, we simply return all the values
# in a list as aggregation doesn't make sense on non tensors.
self._non_tensor_outputs[name] = distribution.unwrap(value)
- distribute_lib.get_tower_context().merge_call(merge_fn, output)
+ distribution_strategy_context.get_tower_context().merge_call(
+ merge_fn, output)
def value_container(val):
diff --git a/tensorflow/contrib/distributions/python/kernel_tests/bijectors/matrix_inverse_tril_test.py b/tensorflow/contrib/distributions/python/kernel_tests/bijectors/matrix_inverse_tril_test.py
index 85d604e34a..49a9afe3f6 100644
--- a/tensorflow/contrib/distributions/python/kernel_tests/bijectors/matrix_inverse_tril_test.py
+++ b/tensorflow/contrib/distributions/python/kernel_tests/bijectors/matrix_inverse_tril_test.py
@@ -29,6 +29,17 @@ from tensorflow.python.platform import test
class MatrixInverseTriLBijectorTest(test.TestCase):
"""Tests the correctness of the Y = inv(tril) transformation."""
+ #The inverse of 0 is undefined, as the numbers above the main
+ #diagonal must be zero, we zero out these numbers after running inverse.
+ #See: https://github.com/numpy/numpy/issues/11445
+ def _inv(self, x):
+ y = np.linalg.inv(x)
+ #triu_indices only works on 2d arrays
+ #need to iterate over all the 2d arrays in a x-dimensional array.
+ for idx in np.ndindex(y.shape[0:-2]):
+ y[idx][np.triu_indices(y[idx].shape[-1], 1)] = 0
+ return y
+
@test_util.run_in_graph_and_eager_modes
def testComputesCorrectValues(self):
inv = bijectors.MatrixInverseTriL(validate_args=True)
@@ -98,7 +109,7 @@ class MatrixInverseTriLBijectorTest(test.TestCase):
[2., 3.]]],
[[[4., 0.],
[5., -6.]]]], dtype=np.float32)
- x_inv_ = np.linalg.inv(x_)
+ x_inv_ = self._inv(x_)
expected_fldj_ = -4. * np.sum(
np.log(np.abs(np.diagonal(x_, axis1=-2, axis2=-1))), axis=-1)
diff --git a/tensorflow/contrib/distributions/python/kernel_tests/deterministic_test.py b/tensorflow/contrib/distributions/python/kernel_tests/deterministic_test.py
index 90910f3839..200310bc41 100644
--- a/tensorflow/contrib/distributions/python/kernel_tests/deterministic_test.py
+++ b/tensorflow/contrib/distributions/python/kernel_tests/deterministic_test.py
@@ -173,6 +173,13 @@ class DeterministicTest(test.TestCase):
self.assertAllClose(
np.zeros(sample_shape_ + (2,)).astype(np.float32), sample_)
+ def testEntropy(self):
+ loc = np.array([-0.1, -3.2, 7.])
+ deterministic = deterministic_lib.Deterministic(loc=loc)
+ with self.test_session() as sess:
+ entropy_ = sess.run(deterministic.entropy())
+ self.assertAllEqual(np.zeros(3), entropy_)
+
class VectorDeterministicTest(test.TestCase):
@@ -290,6 +297,13 @@ class VectorDeterministicTest(test.TestCase):
self.assertAllClose(
np.zeros(sample_shape_ + (2, 1)).astype(np.float32), sample_)
+ def testEntropy(self):
+ loc = np.array([[8.3, 1.2, 3.3], [-0.1, -3.2, 7.]])
+ deterministic = deterministic_lib.VectorDeterministic(loc=loc)
+ with self.test_session() as sess:
+ entropy_ = sess.run(deterministic.entropy())
+ self.assertAllEqual(np.zeros(2), entropy_)
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/distributions/python/ops/deterministic.py b/tensorflow/contrib/distributions/python/ops/deterministic.py
index ad853ee293..affc64a14f 100644
--- a/tensorflow/contrib/distributions/python/ops/deterministic.py
+++ b/tensorflow/contrib/distributions/python/ops/deterministic.py
@@ -152,6 +152,9 @@ class _BaseDeterministic(distribution.Distribution):
"""Relative tolerance for comparing points to `self.loc`."""
return self._rtol
+ def _entropy(self):
+ return array_ops.zeros(self.batch_shape_tensor(), dtype=self.dtype)
+
def _mean(self):
return array_ops.identity(self.loc)
diff --git a/tensorflow/contrib/distributions/python/ops/sample_stats.py b/tensorflow/contrib/distributions/python/ops/sample_stats.py
index f5aaa5cf34..aa680a92be 100644
--- a/tensorflow/contrib/distributions/python/ops/sample_stats.py
+++ b/tensorflow/contrib/distributions/python/ops/sample_stats.py
@@ -134,7 +134,7 @@ def auto_correlation(
x_len = util.prefer_static_shape(x_rotated)[-1]
# TODO(langmore) Investigate whether this zero padding helps or hurts. At
- # the moment is is necessary so that all FFT implementations work.
+ # the moment is necessary so that all FFT implementations work.
# Zero pad to the next power of 2 greater than 2 * x_len, which equals
# 2**(ceil(Log_2(2 * x_len))). Note: Log_2(X) = Log_e(X) / Log_e(2).
x_len_float64 = math_ops.cast(x_len, np.float64)
@@ -198,7 +198,7 @@ def auto_correlation(
# Recall R[m] is a sum of N / 2 - m nonzero terms x[n] Conj(x[n - m]). The
# other terms were zeros arising only due to zero padding.
# `denominator = (N / 2 - m)` (defined below) is the proper term to
- # divide by by to make this an unbiased estimate of the expectation
+ # divide by to make this an unbiased estimate of the expectation
# E[X[n] Conj(X[n - m])].
x_len = math_ops.cast(x_len, dtype.real_dtype)
max_lags = math_ops.cast(max_lags, dtype.real_dtype)
diff --git a/tensorflow/contrib/eager/python/BUILD b/tensorflow/contrib/eager/python/BUILD
index 0cc764d220..fa3f1bb7ad 100644
--- a/tensorflow/contrib/eager/python/BUILD
+++ b/tensorflow/contrib/eager/python/BUILD
@@ -104,7 +104,6 @@ cuda_py_test(
"//tensorflow/python:array_ops",
"//tensorflow/python:client",
"//tensorflow/python:client_testlib",
- "//tensorflow/python/eager:graph_callable",
"//tensorflow/python/eager:test",
"//tensorflow/python:variables",
],
@@ -199,7 +198,7 @@ py_library(
"//tensorflow/python:training",
"//tensorflow/python:variable_scope",
"//tensorflow/python/eager:context",
- "//tensorflow/python/estimator:util",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -223,3 +222,17 @@ py_test(
"//tensorflow/python/eager:test",
],
)
+
+py_test(
+ name = "remote_test",
+ srcs = ["remote_test.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ "//tensorflow/contrib/eager/python:tfe",
+ "//tensorflow/python:array_ops",
+ "//tensorflow/python:client",
+ "//tensorflow/python:framework",
+ "//tensorflow/python:math_ops",
+ "//tensorflow/python/eager:function",
+ ],
+)
diff --git a/tensorflow/contrib/eager/python/datasets.py b/tensorflow/contrib/eager/python/datasets.py
index 16844e0d68..135095a979 100644
--- a/tensorflow/contrib/eager/python/datasets.py
+++ b/tensorflow/contrib/eager/python/datasets.py
@@ -28,7 +28,7 @@ class Iterator(iterator_ops.EagerIterator):
"""An iterator producing tf.Tensor objects from a tf.data.Dataset.
NOTE: Unlike the iterator created by the
- @{tf.data.Dataset.make_one_shot_iterator} method, this class enables
+ `tf.data.Dataset.make_one_shot_iterator` method, this class enables
additional experimental functionality, such as prefetching to the GPU.
"""
diff --git a/tensorflow/contrib/eager/python/examples/densenet/densenet_test.py b/tensorflow/contrib/eager/python/examples/densenet/densenet_test.py
index 0736ed02b7..e5058bfd94 100644
--- a/tensorflow/contrib/eager/python/examples/densenet/densenet_test.py
+++ b/tensorflow/contrib/eager/python/examples/densenet/densenet_test.py
@@ -218,7 +218,7 @@ class DensenetBenchmark(tf.test.Benchmark):
tf.constant(1.).cpu()
def _benchmark_eager_apply(self, label, device_and_format, defun=False,
- execution_mode=None, compiled=False):
+ execution_mode=None):
with tfe.execution_mode(execution_mode):
device, data_format = device_and_format
model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks,
@@ -228,7 +228,7 @@ class DensenetBenchmark(tf.test.Benchmark):
weight_decay=1e-4, dropout_rate=0,
pool_initial=True, include_top=True)
if defun:
- model.call = tfe.defun(model.call, compiled=compiled)
+ model.call = tfe.defun(model.call)
batch_size = 64
num_burn = 5
num_iters = 30
@@ -264,8 +264,7 @@ class DensenetBenchmark(tf.test.Benchmark):
make_iterator,
device_and_format,
defun=False,
- execution_mode=None,
- compiled=False):
+ execution_mode=None):
with tfe.execution_mode(execution_mode):
device, data_format = device_and_format
for batch_size in self._train_batch_sizes():
@@ -279,8 +278,8 @@ class DensenetBenchmark(tf.test.Benchmark):
optimizer = tf.train.GradientDescentOptimizer(0.1)
apply_grads = apply_gradients
if defun:
- model.call = tfe.defun(model.call, compiled=compiled)
- apply_grads = tfe.defun(apply_gradients, compiled=compiled)
+ model.call = tfe.defun(model.call)
+ apply_grads = tfe.defun(apply_gradients)
num_burn = 3
num_iters = 10
diff --git a/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb b/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb
new file mode 100644
index 0000000000..ca27a85a22
--- /dev/null
+++ b/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb
@@ -0,0 +1,649 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "0TD5ZrvEMbhZ"
+ },
+ "source": [
+ "##### Copyright 2018 The TensorFlow Authors.\n",
+ "\n",
+ "Licensed under the Apache License, Version 2.0 (the \"License\").\n",
+ "\n",
+ "# Convolutional VAE: An example with tf.keras and eager\n",
+ "\n",
+ "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\u003ctd\u003e\n",
+ "\u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb\"\u003e\n",
+ " \u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e \n",
+ "\u003c/td\u003e\u003ctd\u003e\n",
+ "\u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb\"\u003e\u003cimg width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\u003c/td\u003e\u003c/table\u003e"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "ITZuApL56Mny"
+ },
+ "source": [
+ "![evolution of output during training](https://tensorflow.org/images/autoencoders/cvae.gif)\n",
+ "\n",
+ "This notebook demonstrates how to generate images of handwritten digits using [tf.keras](https://www.tensorflow.org/programmers_guide/keras) and [eager execution](https://www.tensorflow.org/programmers_guide/eager) by training a Variational Autoencoder. (VAE, [[1]](https://arxiv.org/abs/1312.6114), [[2]](https://arxiv.org/abs/1401.4082)).\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "P-JuIu2N_SQf"
+ },
+ "outputs": [],
+ "source": [
+ "# to generate gifs\n",
+ "!pip install imageio"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "e1_Y75QXJS6h"
+ },
+ "source": [
+ "## Import TensorFlow and enable Eager execution"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "YfIk2es3hJEd"
+ },
+ "outputs": [],
+ "source": [
+ "from __future__ import absolute_import, division, print_function\n",
+ "\n",
+ "# Import TensorFlow \u003e= 1.9 and enable eager execution\n",
+ "import tensorflow as tf\n",
+ "tfe = tf.contrib.eager\n",
+ "tf.enable_eager_execution()\n",
+ "\n",
+ "import os\n",
+ "import time\n",
+ "import numpy as np\n",
+ "import glob\n",
+ "import matplotlib.pyplot as plt\n",
+ "import PIL\n",
+ "import imageio\n",
+ "from IPython import display"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "iYn4MdZnKCey"
+ },
+ "source": [
+ "## Load the MNIST dataset\n",
+ "Each MNIST image is originally a vector of 784 integers, each of which is between 0-255 and represents the intensity of a pixel. We model each pixel with a Bernoulli distribution in our model, and we statically binarize the dataset."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "a4fYMGxGhrna"
+ },
+ "outputs": [],
+ "source": [
+ "(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "NFC2ghIdiZYE"
+ },
+ "outputs": [],
+ "source": [
+ "train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')\n",
+ "test_images = test_images.reshape(test_images.shape[0], 28, 28, 1).astype('float32')\n",
+ "\n",
+ "# Normalizing the images to the range of [0., 1.]\n",
+ "train_images /= 255.\n",
+ "test_images /= 255.\n",
+ "\n",
+ "# Binarization\n",
+ "train_images[train_images \u003e= .5] = 1.\n",
+ "train_images[train_images \u003c .5] = 0.\n",
+ "test_images[test_images \u003e= .5] = 1.\n",
+ "test_images[test_images \u003c .5] = 0."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "S4PIDhoDLbsZ"
+ },
+ "outputs": [],
+ "source": [
+ "TRAIN_BUF = 60000\n",
+ "BATCH_SIZE = 100\n",
+ "\n",
+ "TEST_BUF = 10000"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "PIGN6ouoQxt3"
+ },
+ "source": [
+ "## Use *tf.data* to create batches and shuffle the dataset"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "-yKCCQOoJ7cn"
+ },
+ "outputs": [],
+ "source": [
+ "train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(TRAIN_BUF).batch(BATCH_SIZE)\n",
+ "test_dataset = tf.data.Dataset.from_tensor_slices(test_images).shuffle(TEST_BUF).batch(BATCH_SIZE)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "THY-sZMiQ4UV"
+ },
+ "source": [
+ "## Wire up the generative and inference network with *tf.keras.Sequential*\n",
+ "\n",
+ "In our VAE example, we use two small ConvNets for the generative and inference network. Since these neural nets are small, we use `tf.keras.Sequential` to simplify our code. Let $x$ and $z$ denote the observation and latent variable respectively in the following descriptions. \n",
+ "\n",
+ "### Generative Network\n",
+ "This defines the generative model which takes a latent encoding as input, and outputs the parameters for a conditional distribution of the observation, i.e. $p(x|z)$. Additionally, we use a unit Gaussian prior $p(z)$ for the latent variable.\n",
+ "\n",
+ "### Inference Network\n",
+ "This defines an approximate posterior distribution $q(z|x)$, which takes as input an observation and outputs a set of parameters for the conditional distribution of the latent representation. In this example, we simply model this distribution as a diagonal Gaussian. In this case, the inference network outputs the mean and log-variance parameters of a factorized Gaussian (log-variance instead of the variance directly is for numerical stability).\n",
+ "\n",
+ "### Reparameterization Trick\n",
+ "During optimization, we can sample from $q(z|x)$ by first sampling from a unit Gaussian, and then multiplying by the standard deviation and adding the mean. This ensures the gradients could pass through the sample to the inference network parameters.\n",
+ "\n",
+ "### Network architecture\n",
+ "For the inference network, we use two convolutional layers followed by a fully-connected layer. In the generative network, we mirror this architecture by using a fully-connected layer followed by three convolution transpose layers (a.k.a. deconvolutional layers in some contexts). Note, it's common practice to avoid using batch normalization when training VAEs, since the additional stochasticity due to using mini-batches may aggravate instability on top of the stochasticity from sampling."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "VGLbvBEmjK0a"
+ },
+ "outputs": [],
+ "source": [
+ "class CVAE(tf.keras.Model):\n",
+ " def __init__(self, latent_dim):\n",
+ " super(CVAE, self).__init__()\n",
+ " self.latent_dim = latent_dim\n",
+ " self.inference_net = tf.keras.Sequential(\n",
+ " [\n",
+ " tf.keras.layers.InputLayer(input_shape=(28, 28, 1)),\n",
+ " tf.keras.layers.Conv2D(\n",
+ " filters=32, kernel_size=3, strides=(2, 2), activation=tf.nn.relu),\n",
+ " tf.keras.layers.Conv2D(\n",
+ " filters=64, kernel_size=3, strides=(2, 2), activation=tf.nn.relu),\n",
+ " tf.keras.layers.Flatten(),\n",
+ " # No activation\n",
+ " tf.keras.layers.Dense(latent_dim + latent_dim),\n",
+ " ]\n",
+ " )\n",
+ "\n",
+ " self.generative_net = tf.keras.Sequential(\n",
+ " [\n",
+ " tf.keras.layers.InputLayer(input_shape=(latent_dim,)),\n",
+ " tf.keras.layers.Dense(units=7*7*32, activation=tf.nn.relu),\n",
+ " tf.keras.layers.Reshape(target_shape=(7, 7, 32)),\n",
+ " tf.keras.layers.Conv2DTranspose(\n",
+ " filters=64,\n",
+ " kernel_size=3,\n",
+ " strides=(2, 2),\n",
+ " padding=\"SAME\",\n",
+ " activation=tf.nn.relu),\n",
+ " tf.keras.layers.Conv2DTranspose(\n",
+ " filters=32,\n",
+ " kernel_size=3,\n",
+ " strides=(2, 2),\n",
+ " padding=\"SAME\",\n",
+ " activation=tf.nn.relu),\n",
+ " # No activation\n",
+ " tf.keras.layers.Conv2DTranspose(\n",
+ " filters=1, kernel_size=3, strides=(1, 1), padding=\"SAME\"),\n",
+ " ]\n",
+ " )\n",
+ "\n",
+ " def sample(self, eps=None):\n",
+ " if eps is None:\n",
+ " eps = tf.random_normal(shape=(100, self.latent_dim))\n",
+ " return self.decode(eps, apply_sigmoid=True)\n",
+ "\n",
+ " def encode(self, x):\n",
+ " mean, logvar = tf.split(self.inference_net(x), num_or_size_splits=2, axis=1)\n",
+ " return mean, logvar\n",
+ "\n",
+ " def reparameterize(self, mean, logvar):\n",
+ " eps = tf.random_normal(shape=mean.shape)\n",
+ " return eps * tf.exp(logvar * .5) + mean\n",
+ "\n",
+ " def decode(self, z, apply_sigmoid=False):\n",
+ " logits = self.generative_net(z)\n",
+ " if apply_sigmoid:\n",
+ " probs = tf.sigmoid(logits)\n",
+ " return probs\n",
+ "\n",
+ " return logits"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "0FMYgY_mPfTi"
+ },
+ "source": [
+ "## Define the loss function and the optimizer\n",
+ "\n",
+ "VAEs train by maximizing the evidence lower bound (ELBO) on the marginal log-likelihood:\n",
+ "\n",
+ "$$\\log p(x) \\ge \\text{ELBO} = \\mathbb{E}_{q(z|x)}\\left[\\log \\frac{p(x, z)}{q(z|x)}\\right].$$\n",
+ "\n",
+ "In practice, we optimize the single sample Monte Carlo estimate of this expectation:\n",
+ "\n",
+ "$$\\log p(x| z) + \\log p(z) - \\log q(z|x),$$\n",
+ "where $z$ is sampled from $q(z|x)$.\n",
+ "\n",
+ "**Note**: we could also analytically compute the KL term, but here we incorporate all three terms in the Monte Carlo estimator for simplicity."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "iWCn_PVdEJZ7"
+ },
+ "outputs": [],
+ "source": [
+ "def log_normal_pdf(sample, mean, logvar, raxis=1):\n",
+ " log2pi = tf.log(2. * np.pi)\n",
+ " return tf.reduce_sum(\n",
+ " -.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),\n",
+ " axis=raxis)\n",
+ "\n",
+ "def compute_loss(model, x):\n",
+ " mean, logvar = model.encode(x)\n",
+ " z = model.reparameterize(mean, logvar)\n",
+ " x_logit = model.decode(z)\n",
+ "\n",
+ " cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logit, labels=x)\n",
+ " logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2, 3])\n",
+ " logpz = log_normal_pdf(z, 0., 0.)\n",
+ " logqz_x = log_normal_pdf(z, mean, logvar)\n",
+ " return -tf.reduce_mean(logpx_z + logpz - logqz_x)\n",
+ "\n",
+ "def compute_gradients(model, x):\n",
+ " with tf.GradientTape() as tape:\n",
+ " loss = compute_loss(model, x)\n",
+ " return tape.gradient(loss, model.trainable_variables), loss\n",
+ "\n",
+ "optimizer = tf.train.AdamOptimizer(1e-4)\n",
+ "def apply_gradients(optimizer, gradients, variables, global_step=None):\n",
+ " optimizer.apply_gradients(zip(gradients, variables), global_step=global_step)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "Rw1fkAczTQYh"
+ },
+ "source": [
+ "## Training\n",
+ "\n",
+ "* We start by iterating over the dataset\n",
+ "* During each iteration, we pass the image to the encoder to obtain a set of mean and log-variance parameters of the approximate posterior $q(z|x)$\n",
+ "* We then apply the *reparameterization trick* to sample from $q(z|x)$\n",
+ "* Finally, we pass the reparameterized samples to the decoder to obtain the logits of the generative distribution $p(x|z)$\n",
+ "* **Note:** Since we use the dataset loaded by keras with 60k datapoints in the training set and 10k datapoints in the test set, our resulting ELBO on the test set is slightly higher than reported results in the literature which uses dynamic binarization of Larochelle's MNIST.\n",
+ "\n",
+ "## Generate Images\n",
+ "\n",
+ "* After training, it is time to generate some images\n",
+ "* We start by sampling a set of latent vectors from the unit Gaussian prior distribution $p(z)$\n",
+ "* The generator will then convert the latent sample $z$ to logits of the observation, giving a distribution $p(x|z)$\n",
+ "* Here we plot the probabilities of Bernoulli distributions\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "NS2GWywBbAWo"
+ },
+ "outputs": [],
+ "source": [
+ "epochs = 100\n",
+ "latent_dim = 50\n",
+ "num_examples_to_generate = 16\n",
+ "\n",
+ "# keeping the random vector constant for generation (prediction) so\n",
+ "# it will be easier to see the improvement.\n",
+ "random_vector_for_generation = tf.random_normal(\n",
+ " shape=[num_examples_to_generate, latent_dim])\n",
+ "model = CVAE(latent_dim)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "RmdVsmvhPxyy"
+ },
+ "outputs": [],
+ "source": [
+ "def generate_and_save_images(model, epoch, test_input):\n",
+ " predictions = model.sample(test_input)\n",
+ " fig = plt.figure(figsize=(4,4))\n",
+ "\n",
+ " for i in range(predictions.shape[0]):\n",
+ " plt.subplot(4, 4, i+1)\n",
+ " plt.imshow(predictions[i, :, :, 0], cmap='gray')\n",
+ " plt.axis('off')\n",
+ "\n",
+ " # tight_layout minimizes the overlap between 2 sub-plots\n",
+ " plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "2M7LmLtGEMQJ"
+ },
+ "outputs": [],
+ "source": [
+ "generate_and_save_images(model, 0, random_vector_for_generation)\n",
+ "\n",
+ "for epoch in range(1, epochs + 1):\n",
+ " start_time = time.time()\n",
+ " for train_x in train_dataset:\n",
+ " gradients, loss = compute_gradients(model, train_x)\n",
+ " apply_gradients(optimizer, gradients, model.trainable_variables)\n",
+ " end_time = time.time()\n",
+ "\n",
+ " if epoch % 1 == 0:\n",
+ " loss = tfe.metrics.Mean()\n",
+ " for test_x in test_dataset.make_one_shot_iterator():\n",
+ " loss(compute_loss(model, test_x))\n",
+ " elbo = -loss.result()\n",
+ " display.clear_output(wait=False)\n",
+ " print('Epoch: {}, Test set ELBO: {}, '\n",
+ " 'time elapse for current epoch {}'.format(epoch,\n",
+ " elbo,\n",
+ " end_time - start_time))\n",
+ " generate_and_save_images(\n",
+ " model, epoch, random_vector_for_generation)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "P4M_vIbUi7c0"
+ },
+ "source": [
+ "### Display an image using the epoch number"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "WfO5wCdclHGL"
+ },
+ "outputs": [],
+ "source": [
+ "def display_image(epoch_no):\n",
+ " return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "5x3q9_Oe5q0A"
+ },
+ "outputs": [],
+ "source": [
+ "display_image(epochs) # Display images"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "NywiH3nL8guF"
+ },
+ "source": [
+ "### Generate a GIF of all the saved images."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "IGKQgENQ8lEI"
+ },
+ "outputs": [],
+ "source": [
+ "with imageio.get_writer('cvae.gif', mode='I') as writer:\n",
+ " filenames = glob.glob('image*.png')\n",
+ " filenames = sorted(filenames)\n",
+ " last = -1\n",
+ " for i,filename in enumerate(filenames):\n",
+ " frame = 2*(i**0.5)\n",
+ " if round(frame) \u003e round(last):\n",
+ " last = frame\n",
+ " else:\n",
+ " continue\n",
+ " image = imageio.imread(filename)\n",
+ " writer.append_data(image)\n",
+ " image = imageio.imread(filename)\n",
+ " writer.append_data(image)\n",
+ " \n",
+ "# this is a hack to display the gif inside the notebook\n",
+ "os.system('cp cvae.gif cvae.gif.png')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "uV0yiKpzNP1b"
+ },
+ "outputs": [],
+ "source": [
+ "display.Image(filename=\"cvae.gif.png\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "yQXO_dlXkKsT"
+ },
+ "source": [
+ "To downlod the animation from Colab uncomment the code below:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "colab_type": "code",
+ "id": "4fSJS3m5HLFM"
+ },
+ "outputs": [],
+ "source": [
+ "#from google.colab import files\n",
+ "#files.download('cvae.gif')"
+ ]
+ }
+ ],
+ "metadata": {
+ "accelerator": "GPU",
+ "colab": {
+ "collapsed_sections": [],
+ "default_view": {},
+ "name": "cvae.ipynb",
+ "private_outputs": true,
+ "provenance": [
+ {
+ "file_id": "1eb0NOTQapkYs3X0v-zL1x5_LFKgDISnp",
+ "timestamp": 1527173385672
+ }
+ ],
+ "toc_visible": true,
+ "version": "0.3.2",
+ "views": {}
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
diff --git a/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb b/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb
index 44ff43a111..5621d6a358 100644
--- a/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb
+++ b/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb
@@ -40,12 +40,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "u_2z-B3piVsw"
},
@@ -69,12 +64,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "YfIk2es3hJEd"
},
@@ -82,7 +72,7 @@
"source": [
"from __future__ import absolute_import, division, print_function\n",
"\n",
- "# Import TensorFlow \u003e= 1.9 and enable eager execution\n",
+ "# Import TensorFlow \u003e= 1.10 and enable eager execution\n",
"import tensorflow as tf\n",
"tf.enable_eager_execution()\n",
"\n",
@@ -112,12 +102,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "a4fYMGxGhrna"
},
@@ -130,12 +115,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "NFC2ghIdiZYE"
},
@@ -150,12 +130,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "S4PIDhoDLbsZ"
},
@@ -179,12 +154,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "-yKCCQOoJ7cn"
},
@@ -217,12 +187,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "VGLbvBEmjK0a"
},
@@ -265,12 +230,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "bkOfJxk5j5Hi"
},
@@ -299,12 +259,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "gDkA05NE6QMs"
},
@@ -318,12 +273,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "k1HpMSLImuRi"
},
@@ -360,12 +310,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "wkMNfBWlT-PV"
},
@@ -388,12 +333,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "90BIcCKcDMxz"
},
@@ -407,12 +347,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "iWCn_PVdEJZ7"
},
@@ -426,6 +361,34 @@
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
+ "id": "mWtinsGDPJlV"
+ },
+ "source": [
+ "## Checkpoints (Object-based saving)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "CA1w-7s2POEy"
+ },
+ "outputs": [],
+ "source": [
+ "checkpoint_dir = './training_checkpoints'\n",
+ "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n",
+ "checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n",
+ " discriminator_optimizer=discriminator_optimizer,\n",
+ " generator=generator,\n",
+ " discriminator=discriminator)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
"id": "Rw1fkAczTQYh"
},
"source": [
@@ -449,12 +412,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "NS2GWywBbAWo"
},
@@ -462,7 +420,7 @@
"source": [
"EPOCHS = 150\n",
"noise_dim = 100\n",
- "num_examples_to_generate = 100\n",
+ "num_examples_to_generate = 16\n",
"\n",
"# keeping the random vector constant for generation (prediction) so\n",
"# it will be easier to see the improvement of the gan.\n",
@@ -474,12 +432,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "RmdVsmvhPxyy"
},
@@ -490,15 +443,13 @@
" # don't want to train the batchnorm layer when doing inference.\n",
" predictions = model(test_input, training=False)\n",
"\n",
- " fig = plt.figure(figsize=(10,10))\n",
+ " fig = plt.figure(figsize=(4,4))\n",
" \n",
" for i in range(predictions.shape[0]):\n",
- " plt.subplot(10, 10, i+1)\n",
+ " plt.subplot(4, 4, i+1)\n",
" plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n",
" plt.axis('off')\n",
" \n",
- " # tight_layout minimizes the overlap between 2 sub-plots\n",
- " plt.tight_layout()\n",
" plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n",
" plt.show()"
]
@@ -507,12 +458,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "2M7LmLtGEMQJ"
},
@@ -542,15 +488,20 @@
" discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.variables))\n",
"\n",
" \n",
- " if epoch % 10 == 0:\n",
+ " if epoch % 1 == 0:\n",
" display.clear_output(wait=True)\n",
" generate_and_save_images(generator,\n",
" epoch + 1,\n",
" random_vector_for_generation)\n",
- "\n",
+ " \n",
+ " # saving (checkpoint) the model every 15 epochs\n",
+ " if (epoch + 1) % 15 == 0:\n",
+ " checkpoint.save(file_prefix = checkpoint_prefix)\n",
+ " \n",
" print ('Time taken for epoch {} is {} sec'.format(epoch + 1,\n",
" time.time()-start))\n",
" # generating after the final epoch\n",
+ " display.clear_output(wait=True)\n",
" generate_and_save_images(generator,\n",
" epochs,\n",
" random_vector_for_generation)"
@@ -560,12 +511,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "Ly3UN0SLLY2l"
},
@@ -578,43 +524,55 @@
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
+ "id": "rfM4YcPVPkNO"
+ },
+ "source": [
+ "## Restore the latest checkpoint"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "XhXsd0srPo8c"
+ },
+ "outputs": [],
+ "source": [
+ "# restoring the latest checkpoint in checkpoint_dir\n",
+ "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
"id": "P4M_vIbUi7c0"
},
"source": [
- "# Display an image using the epoch number"
+ "## Display an image using the epoch number"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "WfO5wCdclHGL"
},
"outputs": [],
"source": [
"def display_image(epoch_no):\n",
- " plt.figure(figsize=(15,15))\n",
- " plt.imshow(np.array(PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))))\n",
- " plt.axis('off')"
+ " return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "5x3q9_Oe5q0A"
},
@@ -647,12 +605,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "IGKQgENQ8lEI"
},
@@ -661,23 +614,27 @@
"with imageio.get_writer('dcgan.gif', mode='I') as writer:\n",
" filenames = glob.glob('image*.png')\n",
" filenames = sorted(filenames)\n",
- " for filename in filenames:\n",
+ " last = -1\n",
+ " for i,filename in enumerate(filenames):\n",
+ " frame = 2*(i**0.5)\n",
+ " if round(frame) \u003e round(last):\n",
+ " last = frame\n",
+ " else:\n",
+ " continue\n",
" image = imageio.imread(filename)\n",
" writer.append_data(image)\n",
- " # this is a hack to display the gif inside the notebook\n",
- " os.system('mv dcgan.gif dcgan.gif.png')"
+ " image = imageio.imread(filename)\n",
+ " writer.append_data(image)\n",
+ " \n",
+ "# this is a hack to display the gif inside the notebook\n",
+ "os.system('cp dcgan.gif dcgan.gif.png')"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "uV0yiKpzNP1b"
},
@@ -687,21 +644,27 @@
]
},
{
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "6EEG-wePkmJQ"
+ },
+ "source": [
+ "To downlod the animation from Colab uncomment the code below:"
+ ]
+ },
+ {
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "4UJjSnIMOzOJ"
},
"outputs": [],
"source": [
- ""
+ "#from google.colab import files\n",
+ "#files.download('dcgan.gif')"
]
}
],
@@ -709,7 +672,6 @@
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
- "default_view": {},
"name": "dcgan.ipynb",
"private_outputs": true,
"provenance": [
@@ -719,8 +681,7 @@
}
],
"toc_visible": true,
- "version": "0.3.2",
- "views": {}
+ "version": "0.3.2"
},
"kernelspec": {
"display_name": "Python 3",
diff --git a/tensorflow/contrib/eager/python/examples/generative_examples/text_generation.ipynb b/tensorflow/contrib/eager/python/examples/generative_examples/text_generation.ipynb
index b173f856c6..027097908f 100644
--- a/tensorflow/contrib/eager/python/examples/generative_examples/text_generation.ipynb
+++ b/tensorflow/contrib/eager/python/examples/generative_examples/text_generation.ipynb
@@ -96,12 +96,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "wZ6LOM12wKGH"
},
@@ -124,24 +119,20 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "yG_n40gFzf9s"
},
"outputs": [],
"source": [
- "# Import TensorFlow \u003e= 1.9 and enable eager execution\n",
+ "# Import TensorFlow \u003e= 1.10 and enable eager execution\n",
"import tensorflow as tf\n",
"\n",
"# Note: Once you enable eager execution, it cannot be disabled. \n",
"tf.enable_eager_execution()\n",
"\n",
"import numpy as np\n",
+ "import os\n",
"import re\n",
"import random\n",
"import unidecode\n",
@@ -165,12 +156,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "pD_55cOxLkAb"
},
@@ -194,12 +180,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "-E5JvY3wzf94"
},
@@ -224,12 +205,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "IalZLbvOzf-F"
},
@@ -247,12 +223,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "1v_qUYfAzf-I"
},
@@ -302,12 +273,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "0UHJDA39zf-O"
},
@@ -341,19 +307,14 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "p2pGotuNzf-S"
},
"outputs": [],
"source": [
"dataset = tf.data.Dataset.from_tensor_slices((input_text, target_text)).shuffle(BUFFER_SIZE)\n",
- "dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(BATCH_SIZE))"
+ "dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)"
]
},
{
@@ -376,12 +337,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "P3KTiiInzf-a"
},
@@ -445,12 +401,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "7t2XrzEOzf-e"
},
@@ -463,12 +414,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "dkjWIATszf-h"
},
@@ -485,6 +431,32 @@
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
+ "id": "3K6s6F79P7za"
+ },
+ "source": [
+ "## Checkpoints (Object-based saving)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "oAGisDdfP9rL"
+ },
+ "outputs": [],
+ "source": [
+ "checkpoint_dir = './training_checkpoints'\n",
+ "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n",
+ "checkpoint = tf.train.Checkpoint(optimizer=optimizer,\n",
+ " model=model)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
"id": "lPrP0XMUzf-p"
},
"source": [
@@ -514,12 +486,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "d4tSNwymzf-q"
},
@@ -527,7 +494,7 @@
"source": [
"# Training step\n",
"\n",
- "EPOCHS = 30\n",
+ "EPOCHS = 20\n",
"\n",
"for epoch in range(EPOCHS):\n",
" start = time.time()\n",
@@ -547,13 +514,16 @@
" loss = loss_function(target, predictions)\n",
" \n",
" grads = tape.gradient(loss, model.variables)\n",
- " optimizer.apply_gradients(zip(grads, model.variables), global_step=tf.train.get_or_create_global_step())\n",
+ " optimizer.apply_gradients(zip(grads, model.variables))\n",
"\n",
" if batch % 100 == 0:\n",
" print ('Epoch {} Batch {} Loss {:.4f}'.format(epoch+1,\n",
" batch,\n",
" loss))\n",
- " \n",
+ " # saving (checkpoint) the model every 5 epochs\n",
+ " if (epoch + 1) % 5 == 0:\n",
+ " checkpoint.save(file_prefix = checkpoint_prefix)\n",
+ "\n",
" print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss))\n",
" print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))"
]
@@ -562,6 +532,30 @@
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
+ "id": "01AR9vpNQMFF"
+ },
+ "source": [
+ "## Restore the latest checkpoint"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "tyvpYomYQQkF"
+ },
+ "outputs": [],
+ "source": [
+ "# restoring the latest checkpoint in checkpoint_dir\n",
+ "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
"id": "DjGz1tDkzf-u"
},
"source": [
@@ -584,12 +578,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "WvuwZBX5Ogfd"
},
@@ -651,12 +640,7 @@
"cell_type": "code",
"execution_count": 0,
"metadata": {
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- },
+ "colab": {},
"colab_type": "code",
"id": "gtEd86sX5cB2"
},
@@ -670,13 +654,11 @@
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
- "default_view": {},
"name": "text_generation.ipynb",
"private_outputs": true,
"provenance": [],
"toc_visible": true,
- "version": "0.3.2",
- "views": {}
+ "version": "0.3.2"
},
"kernelspec": {
"display_name": "Python 3",
diff --git a/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb b/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb
index 1ab1b71bd0..08d8364978 100644
--- a/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb
+++ b/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb
@@ -1,39 +1,11 @@
{
- "nbformat": 4,
- "nbformat_minor": 0,
- "metadata": {
- "colab": {
- "name": "nmt_with_attention.ipynb",
- "version": "0.3.2",
- "views": {},
- "default_view": {},
- "provenance": [
- {
- "file_id": "1C4fpM7_7IL8ZzF7Gc5abywqQjeQNS2-U",
- "timestamp": 1527858391290
- },
- {
- "file_id": "1pExo6aUuw0S6MISFWoinfJv0Ftm9V4qv",
- "timestamp": 1527776041613
- }
- ],
- "private_outputs": true,
- "collapsed_sections": [],
- "toc_visible": true
- },
- "kernelspec": {
- "name": "python3",
- "display_name": "Python 3"
- },
- "accelerator": "GPU"
- },
"cells": [
{
+ "cell_type": "markdown",
"metadata": {
- "id": "AOpGoE2T-YXS",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "AOpGoE2T-YXS"
},
- "cell_type": "markdown",
"source": [
"##### Copyright 2018 The TensorFlow Authors.\n",
"\n",
@@ -41,19 +13,19 @@
"\n",
"# Neural Machine Translation with Attention\n",
"\n",
- "<table class=\"tfo-notebook-buttons\" align=\"left\"><td>\n",
- "<a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb\">\n",
- " <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a> \n",
- "</td><td>\n",
- "<a target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a></td></table>"
+ "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\u003ctd\u003e\n",
+ "\u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb\"\u003e\n",
+ " \u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e \n",
+ "\u003c/td\u003e\u003ctd\u003e\n",
+ "\u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb\"\u003e\u003cimg width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\u003c/td\u003e\u003c/table\u003e"
]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "CiwtNgENbx2g",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "CiwtNgENbx2g"
},
- "cell_type": "markdown",
"source": [
"This notebook trains a sequence to sequence (seq2seq) model for Spanish to English translation using [tf.keras](https://www.tensorflow.org/programmers_guide/keras) and [eager execution](https://www.tensorflow.org/programmers_guide/eager). This is an advanced example that assumes some knowledge of sequence to sequence models.\n",
"\n",
@@ -61,27 +33,24 @@
"\n",
"The translation quality is reasonable for a toy example, but the generated attention plot is perhaps more interesting. This shows which parts of the input sentence has the model's attention while translating:\n",
"\n",
- "<img src=\"https://tensorflow.org/images/spanish-english.png\" alt=\"spanish-english attention plot\">\n",
+ "\u003cimg src=\"https://tensorflow.org/images/spanish-english.png\" alt=\"spanish-english attention plot\"\u003e\n",
"\n",
"Note: This example takes approximately 10 mintues to run on a single P100 GPU."
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "tnxXKDjq3jEL",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "tnxXKDjq3jEL"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"from __future__ import absolute_import, division, print_function\n",
"\n",
- "# Import TensorFlow >= 1.9 and enable eager execution\n",
+ "# Import TensorFlow \u003e= 1.10 and enable eager execution\n",
"import tensorflow as tf\n",
"\n",
"tf.enable_eager_execution()\n",
@@ -96,16 +65,14 @@
"import time\n",
"\n",
"print(tf.__version__)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "wfodePkj3jEa",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "wfodePkj3jEa"
},
- "cell_type": "markdown",
"source": [
"## Download and prepare the dataset\n",
"\n",
@@ -124,17 +91,14 @@
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "kRVATYOgJs1b",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "kRVATYOgJs1b"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# Download the file\n",
"path_to_zip = tf.keras.utils.get_file(\n",
@@ -142,22 +106,17 @@
" extract=True)\n",
"\n",
"path_to_file = os.path.dirname(path_to_zip)+\"/spa-eng/spa.txt\""
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "rd0jw-eC3jEh",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "rd0jw-eC3jEh"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# Converts the unicode file to ascii\n",
"def unicode_to_ascii(s):\n",
@@ -169,7 +128,7 @@
" w = unicode_to_ascii(w.lower().strip())\n",
" \n",
" # creating a space between a word and the punctuation following it\n",
- " # eg: \"he is a boy.\" => \"he is a boy .\" \n",
+ " # eg: \"he is a boy.\" =\u003e \"he is a boy .\" \n",
" # Reference:- https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation\n",
" w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n",
" w = re.sub(r'[\" \"]+', \" \", w)\n",
@@ -181,24 +140,19 @@
" \n",
" # adding a start and an end token to the sentence\n",
" # so that the model know when to start and stop predicting.\n",
- " w = '<start> ' + w + ' <end>'\n",
+ " w = '\u003cstart\u003e ' + w + ' \u003cend\u003e'\n",
" return w"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "OHn4Dct23jEm",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "OHn4Dct23jEm"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# 1. Remove the accents\n",
"# 2. Clean the sentences\n",
@@ -209,25 +163,20 @@
" word_pairs = [[preprocess_sentence(w) for w in l.split('\\t')] for l in lines[:num_examples]]\n",
" \n",
" return word_pairs"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "9xbqO7Iie9bb",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "9xbqO7Iie9bb"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
- "# This class creates a word -> index mapping (e.g,. \"dad\" -> 5) and vice-versa \n",
- "# (e.g., 5 -> \"dad\") for each language,\n",
+ "# This class creates a word -\u003e index mapping (e.g,. \"dad\" -\u003e 5) and vice-versa \n",
+ "# (e.g., 5 -\u003e \"dad\") for each language,\n",
"class LanguageIndex():\n",
" def __init__(self, lang):\n",
" self.lang = lang\n",
@@ -243,28 +192,23 @@
" \n",
" self.vocab = sorted(self.vocab)\n",
" \n",
- " self.word2idx['<pad>'] = 0\n",
+ " self.word2idx['\u003cpad\u003e'] = 0\n",
" for index, word in enumerate(self.vocab):\n",
" self.word2idx[word] = index + 1\n",
" \n",
" for word, index in self.word2idx.items():\n",
" self.idx2word[index] = word"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "eAY9k49G3jE_",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "eAY9k49G3jE_"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"def max_length(tensor):\n",
" return max(len(t) for t in tensor)\n",
@@ -300,86 +244,71 @@
" padding='post')\n",
" \n",
" return input_tensor, target_tensor, inp_lang, targ_lang, max_length_inp, max_length_tar"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "GOi42V79Ydlr",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "GOi42V79Ydlr"
},
- "cell_type": "markdown",
"source": [
"### Limit the size of the dataset to experiment faster (optional)\n",
"\n",
- "Training on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data):"
+ "Training on the complete dataset of \u003e100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data):"
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "cnxC7q-j3jFD",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "cnxC7q-j3jFD"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# Try experimenting with the size of that dataset\n",
"num_examples = 30000\n",
"input_tensor, target_tensor, inp_lang, targ_lang, max_length_inp, max_length_targ = load_dataset(path_to_file, num_examples)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "4QILQkOs3jFG",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "4QILQkOs3jFG"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# Creating training and validation sets using an 80-20 split\n",
"input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n",
"\n",
"# Show length\n",
"len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "rgCLkfv5uO3d",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "rgCLkfv5uO3d"
},
- "cell_type": "markdown",
"source": [
"### Create a tf.data dataset"
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "TqHsArVZ3jFS",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "TqHsArVZ3jFS"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"BUFFER_SIZE = len(input_tensor_train)\n",
"BATCH_SIZE = 64\n",
@@ -390,30 +319,28 @@
"vocab_tar_size = len(targ_lang.word2idx)\n",
"\n",
"dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)\n",
- "dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(BATCH_SIZE))"
- ],
- "execution_count": 0,
- "outputs": []
+ "dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)"
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "TNfHIF71ulLu",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "TNfHIF71ulLu"
},
- "cell_type": "markdown",
"source": [
"## Write the encoder and decoder model\n",
"\n",
"Here, we'll implement an encoder-decoder model with attention which you can read about in the TensorFlow [Neural Machine Translation (seq2seq) tutorial](https://www.tensorflow.org/tutorials/seq2seq). This example uses a more recent set of APIs. This notebook implements the [attention equations](https://www.tensorflow.org/tutorials/seq2seq#background_on_the_attention_mechanism) from the seq2seq tutorial. The following diagram shows that each input words is assigned a weight by the attention mechanism which is then used by the decoder to predict the next word in the sentence.\n",
"\n",
- "<img src=\"https://www.tensorflow.org/images/seq2seq/attention_mechanism.jpg\" width=\"500\" alt=\"attention mechanism\">\n",
+ "\u003cimg src=\"https://www.tensorflow.org/images/seq2seq/attention_mechanism.jpg\" width=\"500\" alt=\"attention mechanism\"\u003e\n",
"\n",
"The input is put through an encoder model which gives us the encoder output of shape *(batch_size, max_length, hidden_size)* and the encoder hidden state of shape *(batch_size, hidden_size)*. \n",
"\n",
"Here are the equations that are implemented:\n",
"\n",
- "<img src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_0.jpg\" alt=\"attention equation 0\" width=\"800\">\n",
- "<img src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_1.jpg\" alt=\"attention equation 1\" width=\"800\">\n",
+ "\u003cimg src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_0.jpg\" alt=\"attention equation 0\" width=\"800\"\u003e\n",
+ "\u003cimg src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_1.jpg\" alt=\"attention equation 1\" width=\"800\"\u003e\n",
"\n",
"We're using *Bahdanau attention*. Lets decide on notation before writing the simplified form:\n",
"\n",
@@ -435,17 +362,14 @@
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "avyJ_4VIUoHb",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "avyJ_4VIUoHb"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"def gru(units):\n",
" # If you have a GPU, we recommend using CuDNNGRU(provides a 3x speedup than GRU)\n",
@@ -461,22 +385,17 @@
" return_state=True, \n",
" recurrent_activation='sigmoid', \n",
" recurrent_initializer='glorot_uniform')"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "nZ2rI24i3jFg",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "nZ2rI24i3jFg"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"class Encoder(tf.keras.Model):\n",
" def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):\n",
@@ -493,22 +412,17 @@
" \n",
" def initialize_hidden_state(self):\n",
" return tf.zeros((self.batch_sz, self.enc_units))"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "yJ_B3mhW3jFk",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "yJ_B3mhW3jFk"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"class Decoder(tf.keras.Model):\n",
" def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):\n",
@@ -562,51 +476,41 @@
" \n",
" def initialize_hidden_state(self):\n",
" return tf.zeros((self.batch_sz, self.dec_units))"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "P5UY8wko3jFp",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "P5UY8wko3jFp"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n",
"decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "_ch_71VbIRfK",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "_ch_71VbIRfK"
},
- "cell_type": "markdown",
"source": [
"## Define the optimizer and the loss function"
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "WmTHr5iV3jFr",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "WmTHr5iV3jFr"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"optimizer = tf.train.AdamOptimizer()\n",
"\n",
@@ -615,16 +519,41 @@
" mask = 1 - np.equal(real, 0)\n",
" loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=real, logits=pred) * mask\n",
" return tf.reduce_mean(loss_)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "hpObfY22IddU",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "DMVWzzsfNl4e"
},
+ "source": [
+ "## Checkpoints (Object-based saving)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "Zj8bXQTgNwrF"
+ },
+ "outputs": [],
+ "source": [
+ "checkpoint_dir = './training_checkpoints'\n",
+ "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n",
+ "checkpoint = tf.train.Checkpoint(optimizer=optimizer,\n",
+ " encoder=encoder,\n",
+ " decoder=decoder)"
+ ]
+ },
+ {
"cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "hpObfY22IddU"
+ },
"source": [
"## Training\n",
"\n",
@@ -638,17 +567,14 @@
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "ddefjBMa3jF0",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "ddefjBMa3jF0"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"EPOCHS = 10\n",
"\n",
@@ -666,7 +592,7 @@
" \n",
" dec_hidden = enc_hidden\n",
" \n",
- " dec_input = tf.expand_dims([targ_lang.word2idx['<start>']] * BATCH_SIZE, 1) \n",
+ " dec_input = tf.expand_dims([targ_lang.word2idx['\u003cstart\u003e']] * BATCH_SIZE, 1) \n",
" \n",
" # Teacher forcing - feeding the target as the next input\n",
" for t in range(1, targ.shape[1]):\n",
@@ -686,26 +612,27 @@
" \n",
" gradients = tape.gradient(loss, variables)\n",
" \n",
- " optimizer.apply_gradients(zip(gradients, variables), tf.train.get_or_create_global_step())\n",
+ " optimizer.apply_gradients(zip(gradients, variables))\n",
" \n",
" if batch % 100 == 0:\n",
" print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,\n",
" batch,\n",
" batch_loss.numpy()))\n",
+ " # saving (checkpoint) the model every 2 epochs\n",
+ " if (epoch + 1) % 2 == 0:\n",
+ " checkpoint.save(file_prefix = checkpoint_prefix)\n",
" \n",
" print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n",
" total_loss / N_BATCH))\n",
" print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "mU3Ce8M6I3rz",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "mU3Ce8M6I3rz"
},
- "cell_type": "markdown",
"source": [
"## Translate\n",
"\n",
@@ -717,17 +644,14 @@
]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "EbQpyYs13jF_",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "EbQpyYs13jF_"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"def evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ):\n",
" attention_plot = np.zeros((max_length_targ, max_length_inp))\n",
@@ -744,7 +668,7 @@
" enc_out, enc_hidden = encoder(inputs, hidden)\n",
"\n",
" dec_hidden = enc_hidden\n",
- " dec_input = tf.expand_dims([targ_lang.word2idx['<start>']], 0)\n",
+ " dec_input = tf.expand_dims([targ_lang.word2idx['\u003cstart\u003e']], 0)\n",
"\n",
" for t in range(max_length_targ):\n",
" predictions, dec_hidden, attention_weights = decoder(dec_input, dec_hidden, enc_out)\n",
@@ -757,29 +681,24 @@
"\n",
" result += targ_lang.idx2word[predicted_id] + ' '\n",
"\n",
- " if targ_lang.idx2word[predicted_id] == '<end>':\n",
+ " if targ_lang.idx2word[predicted_id] == '\u003cend\u003e':\n",
" return result, sentence, attention_plot\n",
" \n",
" # the predicted ID is fed back into the model\n",
" dec_input = tf.expand_dims([predicted_id], 0)\n",
"\n",
" return result, sentence, attention_plot"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "s5hQWlbN3jGF",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "s5hQWlbN3jGF"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# function for plotting the attention weights\n",
"def plot_attention(attention, sentence, predicted_sentence):\n",
@@ -793,22 +712,17 @@
" ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)\n",
"\n",
" plt.show()"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "sl9zUHzg3jGI",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "sl9zUHzg3jGI"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"def translate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ):\n",
" result, sentence, attention_plot = evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)\n",
@@ -818,89 +732,91 @@
" \n",
" attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]\n",
" plot_attention(attention_plot, sentence.split(' '), result.split(' '))"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "WrAM0FDomq3E",
+ "colab_type": "text",
+ "id": "n250XbnjOaqP"
+ },
+ "source": [
+ "## Restore the latest checkpoint and test"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "UJpT9D5_OgP6"
},
+ "outputs": [],
+ "source": [
+ "# restoring the latest checkpoint in checkpoint_dir\n",
+ "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))"
+ ]
+ },
+ {
"cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "WrAM0FDomq3E"
+ },
+ "outputs": [],
"source": [
"translate('hace mucho frio aqui.', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "zSx2iM36EZQZ",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "zSx2iM36EZQZ"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"translate('esta es mi vida.', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "A3LLCx3ZE0Ls",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "A3LLCx3ZE0Ls"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"translate('¿todavia estan en casa?', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "code",
+ "execution_count": 0,
"metadata": {
- "id": "DUQVLVqUE1YW",
+ "colab": {},
"colab_type": "code",
- "colab": {
- "autoexec": {
- "startup": false,
- "wait_interval": 0
- }
- }
+ "id": "DUQVLVqUE1YW"
},
- "cell_type": "code",
+ "outputs": [],
"source": [
"# wrong translation\n",
"translate('trata de averiguarlo.', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)"
- ],
- "execution_count": 0,
- "outputs": []
+ ]
},
{
+ "cell_type": "markdown",
"metadata": {
- "id": "RTe5P5ioMJwN",
- "colab_type": "text"
+ "colab_type": "text",
+ "id": "RTe5P5ioMJwN"
},
- "cell_type": "markdown",
"source": [
"## Next steps\n",
"\n",
@@ -908,5 +824,31 @@
"* Experiment with training on a larger dataset, or using more epochs\n"
]
}
- ]
+ ],
+ "metadata": {
+ "accelerator": "GPU",
+ "colab": {
+ "collapsed_sections": [],
+ "name": "nmt_with_attention.ipynb",
+ "private_outputs": true,
+ "provenance": [
+ {
+ "file_id": "1C4fpM7_7IL8ZzF7Gc5abywqQjeQNS2-U",
+ "timestamp": 1527858391290
+ },
+ {
+ "file_id": "1pExo6aUuw0S6MISFWoinfJv0Ftm9V4qv",
+ "timestamp": 1527776041613
+ }
+ ],
+ "toc_visible": true,
+ "version": "0.3.2"
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "name": "python3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
}
diff --git a/tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb b/tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb
new file mode 100644
index 0000000000..ee25d25b52
--- /dev/null
+++ b/tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb
@@ -0,0 +1,810 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "0TD5ZrvEMbhZ"
+ },
+ "source": [
+ "##### Copyright 2018 The TensorFlow Authors.\n",
+ "\n",
+ "Licensed under the Apache License, Version 2.0 (the \"License\").\n",
+ "\n",
+ "# Pix2Pix: An example with tf.keras and eager\n",
+ "\n",
+ "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\u003ctd\u003e\n",
+ "\u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb\"\u003e\n",
+ " \u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e \n",
+ "\u003c/td\u003e\u003ctd\u003e\n",
+ "\u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb\"\u003e\u003cimg width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\u003c/td\u003e\u003c/table\u003e"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "ITZuApL56Mny"
+ },
+ "source": [
+ "This notebook demonstrates image to image translation using conditional GAN's, as described in [Image-to-Image Translation with Conditional Adversarial Networks](https://arxiv.org/abs/1611.07004). Using this technique we can colorize black and white photos, convert google maps to google earth, etc. Here, we convert building facades to real buildings. We use [tf.keras](https://www.tensorflow.org/programmers_guide/keras) and [eager execution](https://www.tensorflow.org/programmers_guide/eager) to achieve this.\n",
+ "\n",
+ "In example, we will use the [CMP Facade Database](http://cmp.felk.cvut.cz/~tylecr1/facade/), helpfully provided by the [Center for Machine Perception](http://cmp.felk.cvut.cz/) at the [Czech Technical University in Prague](https://www.cvut.cz/). To keep our example short, we will use a preprocessed [copy](https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets/) of this dataset, created by the authors of the [paper](https://arxiv.org/abs/1611.07004) above.\n",
+ "\n",
+ "Each epoch takes around 58 seconds on a single P100 GPU.\n",
+ "\n",
+ "Below is the output generated after training the model for 200 epochs.\n",
+ "\n",
+ "\n",
+ "![sample output_1](https://www.tensorflow.org/images/gan/pix2pix_1.png)\n",
+ "![sample output_2](https://www.tensorflow.org/images/gan/pix2pix_2.png)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "e1_Y75QXJS6h"
+ },
+ "source": [
+ "## Import TensorFlow and enable eager execution"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "YfIk2es3hJEd"
+ },
+ "outputs": [],
+ "source": [
+ "# Import TensorFlow \u003e= 1.10 and enable eager execution\n",
+ "import tensorflow as tf\n",
+ "tf.enable_eager_execution()\n",
+ "\n",
+ "import os\n",
+ "import time\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import PIL\n",
+ "from IPython.display import clear_output"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "iYn4MdZnKCey"
+ },
+ "source": [
+ "## Load the dataset\n",
+ "\n",
+ "You can download this dataset and similar datasets from [here](https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets). As mentioned in the [paper](https://arxiv.org/abs/1611.07004) we apply random jittering and mirroring to the training dataset.\n",
+ "* In random jittering, the image is resized to `286 x 286` and then randomly cropped to `256 x 256`\n",
+ "* In random mirroring, the image is randomly flipped horizontally i.e left to right."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "Kn-k8kTXuAlv"
+ },
+ "outputs": [],
+ "source": [
+ "path_to_zip = tf.keras.utils.get_file('facades.tar.gz',\n",
+ " cache_subdir=os.path.abspath('.'),\n",
+ " origin='https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets/facades.tar.gz', \n",
+ " extract=True)\n",
+ "\n",
+ "PATH = os.path.join(os.path.dirname(path_to_zip), 'facades/')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "2CbTEt448b4R"
+ },
+ "outputs": [],
+ "source": [
+ "BUFFER_SIZE = 400\n",
+ "BATCH_SIZE = 1\n",
+ "IMG_WIDTH = 256\n",
+ "IMG_HEIGHT = 256"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "tyaP4hLJ8b4W"
+ },
+ "outputs": [],
+ "source": [
+ "def load_image(image_file, is_train):\n",
+ " image = tf.read_file(image_file)\n",
+ " image = tf.image.decode_jpeg(image)\n",
+ "\n",
+ " w = tf.shape(image)[1]\n",
+ "\n",
+ " w = w // 2\n",
+ " real_image = image[:, :w, :]\n",
+ " input_image = image[:, w:, :]\n",
+ "\n",
+ " input_image = tf.cast(input_image, tf.float32)\n",
+ " real_image = tf.cast(real_image, tf.float32)\n",
+ "\n",
+ " if is_train:\n",
+ " # random jittering\n",
+ " \n",
+ " # resizing to 286 x 286 x 3\n",
+ " # method = 2 indicates using \"ResizeMethod.NEAREST_NEIGHBOR\"\n",
+ " input_image = tf.image.resize_images(input_image, [286, 286], \n",
+ " align_corners=True, method=2)\n",
+ " real_image = tf.image.resize_images(real_image, [286, 286], \n",
+ " align_corners=True, method=2)\n",
+ " \n",
+ " # randomly cropping to 256 x 256 x 3\n",
+ " stacked_image = tf.stack([input_image, real_image], axis=0)\n",
+ " cropped_image = tf.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])\n",
+ " input_image, real_image = cropped_image[0], cropped_image[1]\n",
+ "\n",
+ " if np.random.random() \u003e 0.5:\n",
+ " # random mirroring\n",
+ " input_image = tf.image.flip_left_right(input_image)\n",
+ " real_image = tf.image.flip_left_right(real_image)\n",
+ " else:\n",
+ " input_image = tf.image.resize_images(input_image, size=[IMG_HEIGHT, IMG_WIDTH], \n",
+ " align_corners=True, method=2)\n",
+ " real_image = tf.image.resize_images(real_image, size=[IMG_HEIGHT, IMG_WIDTH], \n",
+ " align_corners=True, method=2)\n",
+ " \n",
+ " # normalizing the images to [-1, 1]\n",
+ " input_image = (input_image / 127.5) - 1\n",
+ " real_image = (real_image / 127.5) - 1\n",
+ "\n",
+ " return input_image, real_image"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "PIGN6ouoQxt3"
+ },
+ "source": [
+ "## Use tf.data to create batches, map(do preprocessing) and shuffle the dataset"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "SQHmYSmk8b4b"
+ },
+ "outputs": [],
+ "source": [
+ "train_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')\n",
+ "train_dataset = train_dataset.shuffle(BUFFER_SIZE)\n",
+ "train_dataset = train_dataset.map(lambda x: load_image(x, True))\n",
+ "train_dataset = train_dataset.batch(1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "MS9J0yA58b4g"
+ },
+ "outputs": [],
+ "source": [
+ "test_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')\n",
+ "test_dataset = test_dataset.map(lambda x: load_image(x, False))\n",
+ "test_dataset = test_dataset.batch(1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "THY-sZMiQ4UV"
+ },
+ "source": [
+ "## Write the generator and discriminator models\n",
+ "\n",
+ "* **Generator** \n",
+ " * The architecture of generator is a modified U-Net.\n",
+ " * Each block in the encoder is (Conv -\u003e Batchnorm -\u003e Leaky ReLU)\n",
+ " * Each block in the decoder is (Transposed Conv -\u003e Batchnorm -\u003e Dropout(applied to the first 3 blocks) -\u003e ReLU)\n",
+ " * There are skip connections between the encoder and decoder (as in U-Net).\n",
+ " \n",
+ "* **Discriminator**\n",
+ " * The Discriminator is a PatchGAN.\n",
+ " * Each block in the discriminator is (Conv -\u003e BatchNorm -\u003e Leaky ReLU)\n",
+ " * The shape of the output after the last layer is (batch_size, 30, 30, 1)\n",
+ " * Each 30x30 patch of the output classifies a 70x70 portion of the input image (such an architecture is called a PatchGAN).\n",
+ " * Discriminator receives 2 inputs.\n",
+ " * Input image and the target image, which it should classify as real.\n",
+ " * Input image and the generated image (output of generator), which it should classify as fake. \n",
+ " * We concatenate these 2 inputs together in the code (`tf.concat([inp, tar], axis=-1)`)\n",
+ "\n",
+ "* Shape of the input travelling through the generator and the discriminator is in the comments in the code.\n",
+ "\n",
+ "To learn more about the architecture and the hyperparameters you can refer the [paper](https://arxiv.org/abs/1611.07004).\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "tqqvWxlw8b4l"
+ },
+ "outputs": [],
+ "source": [
+ "OUTPUT_CHANNELS = 3"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "lFPI4Nu-8b4q"
+ },
+ "outputs": [],
+ "source": [
+ "class Downsample(tf.keras.Model):\n",
+ " \n",
+ " def __init__(self, filters, size, apply_batchnorm=True):\n",
+ " super(Downsample, self).__init__()\n",
+ " self.apply_batchnorm = apply_batchnorm\n",
+ " initializer = tf.random_normal_initializer(0., 0.02)\n",
+ "\n",
+ " self.conv1 = tf.keras.layers.Conv2D(filters, \n",
+ " (size, size), \n",
+ " strides=2, \n",
+ " padding='same',\n",
+ " kernel_initializer=initializer,\n",
+ " use_bias=False)\n",
+ " if self.apply_batchnorm:\n",
+ " self.batchnorm = tf.keras.layers.BatchNormalization()\n",
+ " \n",
+ " def call(self, x, training):\n",
+ " x = self.conv1(x)\n",
+ " if self.apply_batchnorm:\n",
+ " x = self.batchnorm(x, training=training)\n",
+ " x = tf.nn.leaky_relu(x)\n",
+ " return x \n",
+ "\n",
+ "\n",
+ "class Upsample(tf.keras.Model):\n",
+ " \n",
+ " def __init__(self, filters, size, apply_dropout=False):\n",
+ " super(Upsample, self).__init__()\n",
+ " self.apply_dropout = apply_dropout\n",
+ " initializer = tf.random_normal_initializer(0., 0.02)\n",
+ "\n",
+ " self.up_conv = tf.keras.layers.Conv2DTranspose(filters, \n",
+ " (size, size), \n",
+ " strides=2, \n",
+ " padding='same',\n",
+ " kernel_initializer=initializer,\n",
+ " use_bias=False)\n",
+ " self.batchnorm = tf.keras.layers.BatchNormalization()\n",
+ " if self.apply_dropout:\n",
+ " self.dropout = tf.keras.layers.Dropout(0.5)\n",
+ "\n",
+ " def call(self, x1, x2, training):\n",
+ " x = self.up_conv(x1)\n",
+ " x = self.batchnorm(x, training=training)\n",
+ " if self.apply_dropout:\n",
+ " x = self.dropout(x, training=training)\n",
+ " x = tf.nn.relu(x)\n",
+ " x = tf.concat([x, x2], axis=-1)\n",
+ " return x\n",
+ "\n",
+ "\n",
+ "class Generator(tf.keras.Model):\n",
+ " \n",
+ " def __init__(self):\n",
+ " super(Generator, self).__init__()\n",
+ " initializer = tf.random_normal_initializer(0., 0.02)\n",
+ " \n",
+ " self.down1 = Downsample(64, 4, apply_batchnorm=False)\n",
+ " self.down2 = Downsample(128, 4)\n",
+ " self.down3 = Downsample(256, 4)\n",
+ " self.down4 = Downsample(512, 4)\n",
+ " self.down5 = Downsample(512, 4)\n",
+ " self.down6 = Downsample(512, 4)\n",
+ " self.down7 = Downsample(512, 4)\n",
+ " self.down8 = Downsample(512, 4)\n",
+ "\n",
+ " self.up1 = Upsample(512, 4, apply_dropout=True)\n",
+ " self.up2 = Upsample(512, 4, apply_dropout=True)\n",
+ " self.up3 = Upsample(512, 4, apply_dropout=True)\n",
+ " self.up4 = Upsample(512, 4)\n",
+ " self.up5 = Upsample(256, 4)\n",
+ " self.up6 = Upsample(128, 4)\n",
+ " self.up7 = Upsample(64, 4)\n",
+ "\n",
+ " self.last = tf.keras.layers.Conv2DTranspose(OUTPUT_CHANNELS, \n",
+ " (4, 4), \n",
+ " strides=2, \n",
+ " padding='same',\n",
+ " kernel_initializer=initializer)\n",
+ " \n",
+ " @tf.contrib.eager.defun\n",
+ " def call(self, x, training):\n",
+ " # x shape == (bs, 256, 256, 3) \n",
+ " x1 = self.down1(x, training=training) # (bs, 128, 128, 64)\n",
+ " x2 = self.down2(x1, training=training) # (bs, 64, 64, 128)\n",
+ " x3 = self.down3(x2, training=training) # (bs, 32, 32, 256)\n",
+ " x4 = self.down4(x3, training=training) # (bs, 16, 16, 512)\n",
+ " x5 = self.down5(x4, training=training) # (bs, 8, 8, 512)\n",
+ " x6 = self.down6(x5, training=training) # (bs, 4, 4, 512)\n",
+ " x7 = self.down7(x6, training=training) # (bs, 2, 2, 512)\n",
+ " x8 = self.down8(x7, training=training) # (bs, 1, 1, 512)\n",
+ "\n",
+ " x9 = self.up1(x8, x7, training=training) # (bs, 2, 2, 1024)\n",
+ " x10 = self.up2(x9, x6, training=training) # (bs, 4, 4, 1024)\n",
+ " x11 = self.up3(x10, x5, training=training) # (bs, 8, 8, 1024)\n",
+ " x12 = self.up4(x11, x4, training=training) # (bs, 16, 16, 1024)\n",
+ " x13 = self.up5(x12, x3, training=training) # (bs, 32, 32, 512)\n",
+ " x14 = self.up6(x13, x2, training=training) # (bs, 64, 64, 256)\n",
+ " x15 = self.up7(x14, x1, training=training) # (bs, 128, 128, 128)\n",
+ "\n",
+ " x16 = self.last(x15) # (bs, 256, 256, 3)\n",
+ " x16 = tf.nn.tanh(x16)\n",
+ "\n",
+ " return x16"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "ll6aNeQx8b4v"
+ },
+ "outputs": [],
+ "source": [
+ "class DiscDownsample(tf.keras.Model):\n",
+ " \n",
+ " def __init__(self, filters, size, apply_batchnorm=True):\n",
+ " super(DiscDownsample, self).__init__()\n",
+ " self.apply_batchnorm = apply_batchnorm\n",
+ " initializer = tf.random_normal_initializer(0., 0.02)\n",
+ "\n",
+ " self.conv1 = tf.keras.layers.Conv2D(filters, \n",
+ " (size, size), \n",
+ " strides=2, \n",
+ " padding='same',\n",
+ " kernel_initializer=initializer,\n",
+ " use_bias=False)\n",
+ " if self.apply_batchnorm:\n",
+ " self.batchnorm = tf.keras.layers.BatchNormalization()\n",
+ " \n",
+ " def call(self, x, training):\n",
+ " x = self.conv1(x)\n",
+ " if self.apply_batchnorm:\n",
+ " x = self.batchnorm(x, training=training)\n",
+ " x = tf.nn.leaky_relu(x)\n",
+ " return x \n",
+ "\n",
+ "class Discriminator(tf.keras.Model):\n",
+ " \n",
+ " def __init__(self):\n",
+ " super(Discriminator, self).__init__()\n",
+ " initializer = tf.random_normal_initializer(0., 0.02)\n",
+ " \n",
+ " self.down1 = DiscDownsample(64, 4, False)\n",
+ " self.down2 = DiscDownsample(128, 4)\n",
+ " self.down3 = DiscDownsample(256, 4)\n",
+ " \n",
+ " # we are zero padding here with 1 because we need our shape to \n",
+ " # go from (batch_size, 32, 32, 256) to (batch_size, 31, 31, 512)\n",
+ " self.zero_pad1 = tf.keras.layers.ZeroPadding2D()\n",
+ " self.conv = tf.keras.layers.Conv2D(512, \n",
+ " (4, 4), \n",
+ " strides=1, \n",
+ " kernel_initializer=initializer, \n",
+ " use_bias=False)\n",
+ " self.batchnorm1 = tf.keras.layers.BatchNormalization()\n",
+ " \n",
+ " # shape change from (batch_size, 31, 31, 512) to (batch_size, 30, 30, 1)\n",
+ " self.zero_pad2 = tf.keras.layers.ZeroPadding2D()\n",
+ " self.last = tf.keras.layers.Conv2D(1, \n",
+ " (4, 4), \n",
+ " strides=1,\n",
+ " kernel_initializer=initializer)\n",
+ " \n",
+ " @tf.contrib.eager.defun\n",
+ " def call(self, inp, tar, training):\n",
+ " # concatenating the input and the target\n",
+ " x = tf.concat([inp, tar], axis=-1) # (bs, 256, 256, channels*2)\n",
+ " x = self.down1(x, training=training) # (bs, 128, 128, 64)\n",
+ " x = self.down2(x, training=training) # (bs, 64, 64, 128)\n",
+ " x = self.down3(x, training=training) # (bs, 32, 32, 256)\n",
+ "\n",
+ " x = self.zero_pad1(x) # (bs, 34, 34, 256)\n",
+ " x = self.conv(x) # (bs, 31, 31, 512)\n",
+ " x = self.batchnorm1(x, training=training)\n",
+ " x = tf.nn.leaky_relu(x)\n",
+ " \n",
+ " x = self.zero_pad2(x) # (bs, 33, 33, 512)\n",
+ " # don't add a sigmoid activation here since\n",
+ " # the loss function expects raw logits.\n",
+ " x = self.last(x) # (bs, 30, 30, 1)\n",
+ "\n",
+ " return x"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "gDkA05NE6QMs"
+ },
+ "outputs": [],
+ "source": [
+ "# The call function of Generator and Discriminator have been decorated\n",
+ "# with tf.contrib.eager.defun()\n",
+ "# We get a performance speedup if defun is used (~25 seconds per epoch)\n",
+ "generator = Generator()\n",
+ "discriminator = Discriminator()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "0FMYgY_mPfTi"
+ },
+ "source": [
+ "## Define the loss functions and the optimizer\n",
+ "\n",
+ "* **Discriminator loss**\n",
+ " * The discriminator loss function takes 2 inputs; **real images, generated images**\n",
+ " * real_loss is a sigmoid cross entropy loss of the **real images** and an **array of ones(since these are the real images)**\n",
+ " * generated_loss is a sigmoid cross entropy loss of the **generated images** and an **array of zeros(since these are the fake images)**\n",
+ " * Then the total_loss is the sum of real_loss and the generated_loss\n",
+ " \n",
+ "* **Generator loss**\n",
+ " * It is a sigmoid cross entropy loss of the generated images and an **array of ones**.\n",
+ " * The [paper](https://arxiv.org/abs/1611.07004) also includes L1 loss which is MAE (mean absolute error) between the generated image and the target image.\n",
+ " * This allows the generated image to become structurally similar to the target image.\n",
+ " * The formula to calculate the total generator loss = gan_loss + LAMBDA * l1_loss, where LAMBDA = 100. This value was decided by the authors of the [paper](https://arxiv.org/abs/1611.07004)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "cyhxTuvJyIHV"
+ },
+ "outputs": [],
+ "source": [
+ "LAMBDA = 100"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "wkMNfBWlT-PV"
+ },
+ "outputs": [],
+ "source": [
+ "def discriminator_loss(disc_real_output, disc_generated_output):\n",
+ " real_loss = tf.losses.sigmoid_cross_entropy(multi_class_labels = tf.ones_like(disc_real_output), \n",
+ " logits = disc_real_output)\n",
+ " generated_loss = tf.losses.sigmoid_cross_entropy(multi_class_labels = tf.zeros_like(disc_generated_output), \n",
+ " logits = disc_generated_output)\n",
+ "\n",
+ " total_disc_loss = real_loss + generated_loss\n",
+ "\n",
+ " return total_disc_loss"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "90BIcCKcDMxz"
+ },
+ "outputs": [],
+ "source": [
+ "def generator_loss(disc_generated_output, gen_output, target):\n",
+ " gan_loss = tf.losses.sigmoid_cross_entropy(multi_class_labels = tf.ones_like(disc_generated_output),\n",
+ " logits = disc_generated_output) \n",
+ " # mean absolute error\n",
+ " l1_loss = tf.reduce_mean(tf.abs(target - gen_output))\n",
+ "\n",
+ " total_gen_loss = gan_loss + (LAMBDA * l1_loss)\n",
+ "\n",
+ " return total_gen_loss"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "iWCn_PVdEJZ7"
+ },
+ "outputs": [],
+ "source": [
+ "generator_optimizer = tf.train.AdamOptimizer(2e-4, beta1=0.5)\n",
+ "discriminator_optimizer = tf.train.AdamOptimizer(2e-4, beta1=0.5)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "aKUZnDiqQrAh"
+ },
+ "source": [
+ "## Checkpoints (Object-based saving)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "WJnftd5sQsv6"
+ },
+ "outputs": [],
+ "source": [
+ "checkpoint_dir = './training_checkpoints'\n",
+ "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n",
+ "checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n",
+ " discriminator_optimizer=discriminator_optimizer,\n",
+ " generator=generator,\n",
+ " discriminator=discriminator)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "Rw1fkAczTQYh"
+ },
+ "source": [
+ "## Training\n",
+ "\n",
+ "* We start by iterating over the dataset\n",
+ "* The generator gets the input image and we get a generated output.\n",
+ "* The discriminator receives the input_image and the generated image as the first input. The second input is the input_image and the target_image.\n",
+ "* Next, we calculate the generator and the discriminator loss.\n",
+ "* Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables(inputs) and apply those to the optimizer.\n",
+ "\n",
+ "## Generate Images\n",
+ "\n",
+ "* After training, its time to generate some images!\n",
+ "* We pass images from the test dataset to the generator.\n",
+ "* The generator will then translate the input image into the output we expect.\n",
+ "* Last step is to plot the predictions and **voila!**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "NS2GWywBbAWo"
+ },
+ "outputs": [],
+ "source": [
+ "EPOCHS = 200"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "RmdVsmvhPxyy"
+ },
+ "outputs": [],
+ "source": [
+ "def generate_images(model, test_input, tar):\n",
+ " # the training=True is intentional here since\n",
+ " # we want the batch statistics while running the model\n",
+ " # on the test dataset. If we use training=False, we will get \n",
+ " # the accumulated statistics learned from the training dataset\n",
+ " # (which we don't want)\n",
+ " prediction = model(test_input, training=True)\n",
+ " plt.figure(figsize=(15,15))\n",
+ "\n",
+ " display_list = [test_input[0], tar[0], prediction[0]]\n",
+ " title = ['Input Image', 'Ground Truth', 'Predicted Image']\n",
+ "\n",
+ " for i in range(3):\n",
+ " plt.subplot(1, 3, i+1)\n",
+ " plt.title(title[i])\n",
+ " # getting the pixel values between [0, 1] to plot it.\n",
+ " plt.imshow(display_list[i] * 0.5 + 0.5)\n",
+ " plt.axis('off')\n",
+ " plt.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "2M7LmLtGEMQJ"
+ },
+ "outputs": [],
+ "source": [
+ "def train(dataset, epochs): \n",
+ " for epoch in range(epochs):\n",
+ " start = time.time()\n",
+ "\n",
+ " for input_image, target in dataset:\n",
+ "\n",
+ " with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n",
+ " gen_output = generator(input_image, training=True)\n",
+ "\n",
+ " disc_real_output = discriminator(input_image, target, training=True)\n",
+ " disc_generated_output = discriminator(input_image, gen_output, training=True)\n",
+ "\n",
+ " gen_loss = generator_loss(disc_generated_output, gen_output, target)\n",
+ " disc_loss = discriminator_loss(disc_real_output, disc_generated_output)\n",
+ "\n",
+ " generator_gradients = gen_tape.gradient(gen_loss, \n",
+ " generator.variables)\n",
+ " discriminator_gradients = disc_tape.gradient(disc_loss, \n",
+ " discriminator.variables)\n",
+ "\n",
+ " generator_optimizer.apply_gradients(zip(generator_gradients, \n",
+ " generator.variables))\n",
+ " discriminator_optimizer.apply_gradients(zip(discriminator_gradients, \n",
+ " discriminator.variables))\n",
+ "\n",
+ " if epoch % 1 == 0:\n",
+ " clear_output(wait=True)\n",
+ " for inp, tar in test_dataset.take(1):\n",
+ " generate_images(generator, inp, tar)\n",
+ " \n",
+ " # saving (checkpoint) the model every 20 epochs\n",
+ " if (epoch + 1) % 20 == 0:\n",
+ " checkpoint.save(file_prefix = checkpoint_prefix)\n",
+ "\n",
+ " print ('Time taken for epoch {} is {} sec\\n'.format(epoch + 1,\n",
+ " time.time()-start))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "a1zZmKmvOH85"
+ },
+ "outputs": [],
+ "source": [
+ "train(train_dataset, EPOCHS)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "kz80bY3aQ1VZ"
+ },
+ "source": [
+ "## Restore the latest checkpoint and test"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "4t4x69adQ5xb"
+ },
+ "outputs": [],
+ "source": [
+ "# restoring the latest checkpoint in checkpoint_dir\n",
+ "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "1RGysMU_BZhx"
+ },
+ "source": [
+ "## Testing on the entire test dataset"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "KUgSnmy2nqSP"
+ },
+ "outputs": [],
+ "source": [
+ "# Run the trained model on the entire test dataset\n",
+ "for inp, tar in test_dataset:\n",
+ " generate_images(generator, inp, tar)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 0,
+ "metadata": {
+ "colab": {},
+ "colab_type": "code",
+ "id": "3AJXOByaZVOf"
+ },
+ "outputs": [],
+ "source": [
+ ""
+ ]
+ }
+ ],
+ "metadata": {
+ "accelerator": "GPU",
+ "colab": {
+ "collapsed_sections": [],
+ "name": "pix2pix_eager.ipynb",
+ "private_outputs": true,
+ "provenance": [
+ {
+ "file_id": "1eb0NOTQapkYs3X0v-zL1x5_LFKgDISnp",
+ "timestamp": 1527173385672
+ }
+ ],
+ "toc_visible": true,
+ "version": "0.3.2"
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
diff --git a/tensorflow/contrib/eager/python/examples/resnet50/resnet50_test.py b/tensorflow/contrib/eager/python/examples/resnet50/resnet50_test.py
index 07d8788882..d265169b5e 100644
--- a/tensorflow/contrib/eager/python/examples/resnet50/resnet50_test.py
+++ b/tensorflow/contrib/eager/python/examples/resnet50/resnet50_test.py
@@ -216,12 +216,12 @@ class ResNet50Benchmarks(tf.test.Benchmark):
tf.constant(1.).cpu()
def _benchmark_eager_apply(self, label, device_and_format, defun=False,
- execution_mode=None, compiled=False):
+ execution_mode=None):
with tfe.execution_mode(execution_mode):
device, data_format = device_and_format
model = resnet50.ResNet50(data_format)
if defun:
- model.call = tfe.defun(model.call, compiled=compiled)
+ model.call = tfe.defun(model.call)
batch_size = 64
num_burn = 5
num_iters = 30
@@ -257,8 +257,7 @@ class ResNet50Benchmarks(tf.test.Benchmark):
make_iterator,
device_and_format,
defun=False,
- execution_mode=None,
- compiled=False):
+ execution_mode=None):
with tfe.execution_mode(execution_mode):
device, data_format = device_and_format
for batch_size in self._train_batch_sizes():
@@ -267,8 +266,8 @@ class ResNet50Benchmarks(tf.test.Benchmark):
optimizer = tf.train.GradientDescentOptimizer(0.1)
apply_grads = apply_gradients
if defun:
- model.call = tfe.defun(model.call, compiled=compiled)
- apply_grads = tfe.defun(apply_gradients, compiled=compiled)
+ model.call = tfe.defun(model.call)
+ apply_grads = tfe.defun(apply_gradients)
num_burn = 3
num_iters = 10
diff --git a/tensorflow/contrib/eager/python/examples/revnet/revnet_test.py b/tensorflow/contrib/eager/python/examples/revnet/revnet_test.py
index 84b2ddf0de..6a921e1997 100644
--- a/tensorflow/contrib/eager/python/examples/revnet/revnet_test.py
+++ b/tensorflow/contrib/eager/python/examples/revnet/revnet_test.py
@@ -226,14 +226,13 @@ class RevNetBenchmark(tf.test.Benchmark):
label,
device_and_format,
defun=False,
- execution_mode=None,
- compiled=False):
+ execution_mode=None):
config = config_.get_hparams_imagenet_56()
with tfe.execution_mode(execution_mode):
device, data_format = device_and_format
model = revnet.RevNet(config=config)
if defun:
- model.call = tfe.defun(model.call, compiled=compiled)
+ model.call = tfe.defun(model.call)
batch_size = 64
num_burn = 5
num_iters = 10
@@ -271,8 +270,7 @@ class RevNetBenchmark(tf.test.Benchmark):
make_iterator,
device_and_format,
defun=False,
- execution_mode=None,
- compiled=False):
+ execution_mode=None):
config = config_.get_hparams_imagenet_56()
with tfe.execution_mode(execution_mode):
device, data_format = device_and_format
diff --git a/tensorflow/contrib/eager/python/remote_test.py b/tensorflow/contrib/eager/python/remote_test.py
new file mode 100644
index 0000000000..76f48eeb1c
--- /dev/null
+++ b/tensorflow/contrib/eager/python/remote_test.py
@@ -0,0 +1,178 @@
+# 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 remote eager execution."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import functools
+import os
+
+import numpy as np
+
+from tensorflow.core.protobuf import cluster_pb2
+from tensorflow.core.protobuf import tensorflow_server_pb2
+from tensorflow.python.eager import backprop
+from tensorflow.python.eager import context
+from tensorflow.python.eager import function
+from tensorflow.python.framework import ops
+from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import resource_variable_ops
+from tensorflow.python.platform import test
+from tensorflow.python.training import server_lib
+
+JOB_NAME = "remote_device"
+ALT_JOB_NAME = "alt_remote_device"
+
+
+def run_sync_and_async(f):
+ """Execute all test methods in the given class in sync and async modes."""
+
+ @functools.wraps(f)
+ def decorator(self, *args, **kwargs):
+ with context.execution_mode(context.ASYNC):
+ f(self, *args, **kwargs)
+
+ with context.execution_mode(context.SYNC):
+ f(self, *args, **kwargs)
+
+ return decorator
+
+
+def get_server_def(job_name, local_server_port, remote_server_addresses,
+ task_index):
+ """Returns a server def with a single job + multiple tasks."""
+ cluster_def = cluster_pb2.ClusterDef()
+ job_def = cluster_def.job.add()
+ job_def.name = job_name
+ job_def.tasks[0] = "localhost:%d" % local_server_port
+
+ for i, remote_server_address in enumerate(remote_server_addresses, start=1):
+ job_def.tasks[i] = remote_server_address
+
+ server_def = tensorflow_server_pb2.ServerDef(
+ cluster=cluster_def,
+ job_name=job_name,
+ task_index=task_index,
+ protocol="grpc")
+
+ return server_def
+
+
+class RemoteExecutionTest(test.TestCase):
+
+ def __init__(self, methodName="runTest"): # pylint: disable=invalid-name
+ super(RemoteExecutionTest, self).__init__(methodName)
+ self._cached_server1 = server_lib.Server.create_local_server()
+ self._cached_server2 = server_lib.Server.create_local_server()
+
+ os.environ["TF_EAGER_REMOTE_USE_SEND_TENSOR_RPC"] = "1"
+
+ self._cached_server1_target = self._cached_server1.target[len("grpc://"):]
+ self._cached_server2_target = self._cached_server2.target[len("grpc://"):]
+
+ # Start the local server.
+ context.set_server_def(
+ server_def=get_server_def(
+ JOB_NAME,
+ local_server_port=0,
+ remote_server_addresses=[
+ self._cached_server1_target, self._cached_server2_target
+ ],
+ task_index=0))
+
+ @run_sync_and_async
+ def testDefunMatmul(self):
+ """Basic remote eager execution with defun."""
+
+ mm_defun = function.defun(math_ops.matmul)
+ with ops.device("job:%s/replica:0/task:1/device:CPU:0" % JOB_NAME):
+ x1 = array_ops.ones([2, 2])
+ with ops.device("job:%s/replica:0/task:2/device:CPU:0" % JOB_NAME):
+ x2 = array_ops.ones([2, 2])
+ y = mm_defun(x1, x2)
+ np.testing.assert_array_equal([[2, 2], [2, 2]], y.numpy())
+
+ @run_sync_and_async
+ def testSimpleMatmul(self):
+ """Basic remote eager execution."""
+
+ with ops.device("job:%s/replica:0/task:1/device:CPU:0" % JOB_NAME):
+ x1 = array_ops.ones([2, 2])
+ with ops.device("job:%s/replica:0/task:2/device:CPU:0" % JOB_NAME):
+ x2 = array_ops.ones([2, 2])
+ y = math_ops.matmul(x1, x2)
+ np.testing.assert_array_equal([[2, 2], [2, 2]], y.numpy())
+
+ @run_sync_and_async
+ def testSimpleWeightRead(self):
+ """Basic remote eager weight read."""
+
+ with ops.device("job:%s/replica:0/task:1/device:CPU:0" % JOB_NAME):
+ w = resource_variable_ops.ResourceVariable([[2.0]])
+ loss = w * w
+ np.testing.assert_array_equal([[4.0]], loss.numpy())
+
+ @run_sync_and_async
+ def testTapeWeightRead(self):
+ """Remote eager weight read in a tape."""
+
+ with ops.device("job:%s/replica:0/task:1/device:CPU:0" % JOB_NAME):
+ w = resource_variable_ops.ResourceVariable([[3.0]])
+ with backprop.GradientTape() as tape:
+ loss = w * w
+
+ grad = tape.gradient(loss, w)
+ np.testing.assert_array_equal([[9.0]], loss.numpy())
+ np.testing.assert_array_equal([[6.0]], grad.numpy())
+
+ @run_sync_and_async
+ def testServerDefChanged(self):
+ """Update server def, and run ops on new cluster."""
+ context.set_server_def(
+ server_def=get_server_def(
+ ALT_JOB_NAME,
+ local_server_port=0,
+ remote_server_addresses=[
+ self._cached_server1_target, self._cached_server2_target
+ ],
+ task_index=0))
+
+ with ops.device("job:%s/replica:0/task:1/device:CPU:0" % ALT_JOB_NAME):
+ x1 = array_ops.ones([2, 2])
+ y = math_ops.matmul(x1, x1)
+ np.testing.assert_array_equal([[2, 2], [2, 2]], y.numpy())
+
+ # Set the server def back to JOB_NAME
+ context.set_server_def(
+ server_def=get_server_def(
+ JOB_NAME,
+ local_server_port=0,
+ remote_server_addresses=[
+ self._cached_server1_target, self._cached_server2_target
+ ],
+ task_index=0))
+
+ with ops.device("job:%s/replica:0/task:1/device:CPU:0" % JOB_NAME):
+ x1 = array_ops.ones([2, 2])
+ y = math_ops.matmul(x1, x1)
+ np.testing.assert_array_equal([[2, 2], [2, 2]], y.numpy())
+
+
+if __name__ == "__main__":
+ ops.enable_eager_execution()
+ test.main()
diff --git a/tensorflow/contrib/eager/python/saver.py b/tensorflow/contrib/eager/python/saver.py
index d709308647..f9c716360c 100644
--- a/tensorflow/contrib/eager/python/saver.py
+++ b/tensorflow/contrib/eager/python/saver.py
@@ -161,7 +161,7 @@ class Saver(object):
Args:
file_prefix: Path prefix where parameters were previously saved.
Typically obtained from a previous `save()` call, or from
- @{tf.train.latest_checkpoint}.
+ `tf.train.latest_checkpoint`.
"""
with ops.device("/device:CPU:0"):
self._saver.restore(None, file_prefix)
diff --git a/tensorflow/contrib/eager/python/saver_test.py b/tensorflow/contrib/eager/python/saver_test.py
index 90a3711475..91bc75213c 100644
--- a/tensorflow/contrib/eager/python/saver_test.py
+++ b/tensorflow/contrib/eager/python/saver_test.py
@@ -21,15 +21,11 @@ import os
from tensorflow.contrib.eager.python import saver as _saver
from tensorflow.python.eager import context
-from tensorflow.python.eager import graph_callable
from tensorflow.python.eager import test
-from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
-from tensorflow.python.ops import init_ops
from tensorflow.python.ops import resource_variable_ops
-from tensorflow.python.ops import variable_scope
from tensorflow.python.training import adam
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import momentum
@@ -142,53 +138,6 @@ class SaverTest(test.TestCase):
with _saver.restore_variables_on_create(ckpt_prefix):
_ = model(resource_variable_ops.ResourceVariable(1.0, name='v2'))
- def testSaveRestoreGraphCallable(self):
- with ops.device(self._dev()):
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def model(x):
- v = variable_scope.get_variable(
- 'v', initializer=init_ops.zeros_initializer(), shape=())
- return v + x
-
- # Default 2 + 0 = 2
- self.assertEqual(
- 2, model(array_ops.constant(2, dtype=dtypes.float32)).numpy())
-
- # Save the variable value 0.
- ckpt_prefix = os.path.join(test.get_temp_dir(), 'ckpt')
- _saver.Saver(model.variables).save(ckpt_prefix)
-
- # update variable to 1, so that 2 + 1 = 3
- model.variables[0].assign(1.)
- self.assertEqual(
- 3, model(array_ops.constant(2, dtype=dtypes.float32)).numpy())
-
- # load the variable value 0, so that 2 + 0 = 2
- _saver.Saver(model.variables).restore(ckpt_prefix)
- self.assertEqual(
- 2, model(array_ops.constant(2, dtype=dtypes.float32)).numpy())
-
- # update checkpoint variable to 1 and memory value to 2.
- model.variables[0].assign(1.)
- _saver.Saver(model.variables).save(ckpt_prefix)
- model.variables[0].assign(2.)
- self.assertEqual(
- 4, model(array_ops.constant(2, dtype=dtypes.float32)).numpy())
-
- # reset the graph and reload on create, so that 1 + 2 = 3
- ops.reset_default_graph()
- with _saver.restore_variables_on_create(ckpt_prefix):
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def model2(x):
- v = variable_scope.get_variable(
- 'v', initializer=init_ops.zeros_initializer(), shape=())
- return v + x
-
- self.assertEqual(
- 3, model2(array_ops.constant(2, dtype=dtypes.float32)).numpy())
-
class GetOptimizerTests(test.TestCase):
diff --git a/tensorflow/contrib/eager/python/tfe.py b/tensorflow/contrib/eager/python/tfe.py
index de11d00a1a..4dfd083443 100644
--- a/tensorflow/contrib/eager/python/tfe.py
+++ b/tensorflow/contrib/eager/python/tfe.py
@@ -16,7 +16,7 @@
EXPERIMENTAL: APIs here are unstable and likely to change without notice.
-To use, at program startup, call `tfe.enable_eager_execution()`.
+To use, at program startup, call `tf.enable_eager_execution()`.
@@metrics
@@ -67,6 +67,7 @@ To use, at program startup, call `tfe.enable_eager_execution()`.
@@execution_mode
@@async_wait
@@async_clear_error
+@@set_server_def
@@run_test_in_graph_and_eager_modes
@@run_all_tests_in_graph_and_eager_modes
@@ -110,6 +111,7 @@ from tensorflow.python.eager.context import async_clear_error
from tensorflow.python.eager.context import SYNC
from tensorflow.python.eager.context import ASYNC
from tensorflow.python.eager.context import num_gpus
+from tensorflow.python.eager.context import set_server_def
from tensorflow.python.eager.execution_callbacks import add_execution_callback
from tensorflow.python.eager.execution_callbacks import clear_execution_callbacks
from tensorflow.python.eager.execution_callbacks import inf_callback
diff --git a/tensorflow/contrib/estimator/BUILD b/tensorflow/contrib/estimator/BUILD
index 349f48f7f7..77f62df99d 100644
--- a/tensorflow/contrib/estimator/BUILD
+++ b/tensorflow/contrib/estimator/BUILD
@@ -20,6 +20,7 @@ py_library(
":dnn_linear_combined",
":early_stopping",
":export",
+ ":exporter",
":extenders",
":head",
":hooks",
@@ -220,6 +221,33 @@ py_test(
)
py_library(
+ name = "exporter",
+ srcs = [
+ "python/estimator/exporter.py",
+ ],
+ srcs_version = "PY2AND3",
+ deps = [
+ "//tensorflow/python:framework_ops",
+ "//tensorflow/python:platform",
+ "//tensorflow/python:summary",
+ "//tensorflow/python/estimator:exporter",
+ ],
+)
+
+py_test(
+ name = "exporter_test",
+ size = "medium",
+ srcs = ["python/estimator/exporter_test.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":exporter",
+ "//tensorflow/python:platform",
+ "//tensorflow/python/estimator",
+ "//tensorflow/python/estimator:exporter",
+ ],
+)
+
+py_library(
name = "head",
srcs = [
"python/estimator/head.py",
@@ -487,6 +515,9 @@ py_test(
size = "medium",
srcs = ["python/estimator/saved_model_estimator_test.py"],
srcs_version = "PY2AND3",
+ tags = [
+ "notsan",
+ ],
deps = [
":export",
":saved_model_estimator",
diff --git a/tensorflow/contrib/estimator/__init__.py b/tensorflow/contrib/estimator/__init__.py
index e1453ae1d0..258860f263 100644
--- a/tensorflow/contrib/estimator/__init__.py
+++ b/tensorflow/contrib/estimator/__init__.py
@@ -45,6 +45,7 @@ _allowed_symbols = [
'clip_gradients_by_norm',
'forward_features',
'InMemoryEvaluatorHook',
+ 'make_stop_at_checkpoint_step_hook',
'logistic_regression_head',
'multi_class_head',
'multi_head',
diff --git a/tensorflow/contrib/estimator/python/estimator/dnn_linear_combined.py b/tensorflow/contrib/estimator/python/estimator/dnn_linear_combined.py
index 2eef60c39f..724bc2c82f 100644
--- a/tensorflow/contrib/estimator/python/estimator/dnn_linear_combined.py
+++ b/tensorflow/contrib/estimator/python/estimator/dnn_linear_combined.py
@@ -147,7 +147,7 @@ class DNNLinearCombinedEstimator(estimator.Estimator):
if a categorical column is multivalent. One of "mean", "sqrtn", and
"sum" -- these are effectively different ways to do example-level
normalization, which can be useful for bag-of-words features. For more
- details, see @{tf.feature_column.linear_model$linear_model}.
+ details, see `tf.feature_column.linear_model`.
Raises:
ValueError: If both linear_feature_columns and dnn_features_columns are
diff --git a/tensorflow/contrib/estimator/python/estimator/export.py b/tensorflow/contrib/estimator/python/estimator/export.py
index 03cf6f107c..b0deb9b494 100644
--- a/tensorflow/contrib/estimator/python/estimator/export.py
+++ b/tensorflow/contrib/estimator/python/estimator/export.py
@@ -31,8 +31,8 @@ def export_saved_model_for_mode(
# pylint: disable=line-too-long
"""Exports a single train/eval/predict graph as a SavedModel.
- For a detailed guide, see
- @{$saved_model#using_savedmodel_with_estimators$Using SavedModel with Estimators}.
+ For a detailed guide, see [Using SavedModel with Estimators](
+ https://tensorflow.org/guide/saved_model#using_savedmodel_with_estimators).
Sample usage:
```python
diff --git a/tensorflow/contrib/estimator/python/estimator/exporter.py b/tensorflow/contrib/estimator/python/estimator/exporter.py
new file mode 100644
index 0000000000..09d7440605
--- /dev/null
+++ b/tensorflow/contrib/estimator/python/estimator/exporter.py
@@ -0,0 +1,280 @@
+# 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.
+# ==============================================================================
+"""Implements StepsExporter to export the model in user specified steps."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import os
+
+from tensorflow.python.estimator import exporter
+from tensorflow.python.framework import ops
+from tensorflow.python.platform import gfile
+from tensorflow.python.platform import tf_logging
+from tensorflow.python.summary import summary_iterator
+
+DEFAULT_GLOBAL_STEP_KEY = ops.GraphKeys.GLOBAL_STEP
+
+
+class StepsExporter(exporter.Exporter):
+ """This class exports the model in user specified steps.
+
+ This class exports the model at the steps given by the `steps_to_keep`
+ argument. Each number in the list is treated as a lower bound for model
+ exports, to handle the case when evaluation is performed at different steps.
+
+ Consider this example:
+
+ ```
+ steps_to_keep = [1, 2, 3, 6, 7, 10, 12, 25]
+ ```
+
+ The model is evaluated at step increments of 5: `[5, 10, 15, 20, 25, 30]`.
+ The `StepsExporter` will export the model when it has reached steps
+ `[5, 10, 15, 25]`.
+
+ This example illustrates the two cases when the model is exported:
+
+ 1. Model is evaluated on a step defined in the list `steps_to_keep`.
+
+ In the example, the model is exported on step `10` and `25`.
+
+ 2. Model is evaluated on a step not defined in the list `steps_to_keep`, but
+ is still exported because a step in `steps_to_keep` was missed.
+
+ In the example, when the model reaches step `5`, the model is exported even
+ though `steps_to_keep` does not contain `5`. Step `5` is exported to make
+ up for step `3`, which was missed. Steps `1` and `2` in `steps_to_keep` are
+ skipped completely (e.g. say the model is evaluated at step `6`. It will
+ **not** be exported to make up for step `2`).
+
+ Using the `steps_to_keep` list as a lower bound allows users to define
+ approximate step boundaries for exporting their models, and avoid frustrating
+ off-by-one calculation errors.
+
+ Sample Use Cases:
+ There are specific points during the training when having a saved version of
+ the model would be useful. One example is at the end of each training phase
+ when the set of freezed weights is changed.
+ Another good use case is saving the model at the end of each epoch for
+ visualization or retraining.
+ """
+
+ def __init__(self,
+ steps_to_keep,
+ name='steps_exporter',
+ serving_input_receiver_fn=None,
+ event_file_pattern='eval/*.tfevents.*',
+ assets_extra=None,
+ as_text=False):
+ """Create an `StepsExporter` to use with `tf.estimator.EvalSpec`.
+
+ Example of creating a StepsExporter for training and evaluation:
+
+ ```python
+ categorical_feature_a = categorical_column_with_hash_bucket(...)
+ categorical_feature_b = categorical_column_with_hash_bucket(...)
+
+ categorical_feature_a_emb = embedding_column(
+ categorical_column=categorical_feature_a, ...)
+ categorical_feature_b_emb = embedding_column(
+ categorical_column=categorical_feature_b, ...)
+
+ estimator = tf.estimator.DNNClassifier(
+ feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
+ hidden_units=[1024, 512, 256])
+
+ # Input pipeline for train and evaluate.
+ def train_input_fn: # returns x, y
+ # please shuffle the data.
+ pass
+ def eval_input_fn_eval: # returns x, y
+ pass
+
+ exporter = tf.contrib.estimator.exporter.StepsExporter(
+ name="steps_exporter",
+ serving_input_receiver_fn=serving_input_receiver_fn,
+ event_file_pattern='eval/*.tfevents.*'
+ steps_to_keep=[...])
+
+ train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=1000)
+
+ eval_spec = [tf.estimator.EvalSpec(
+ input_fn=eval_input_fn,
+ steps=1,
+ exporters=exporter,
+ start_delay_secs=0,
+ throttle_secs=5)]
+
+ tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
+
+ # Models will be exported to estimator.model_dir in timestamped directories,
+ # which can be used for serving, analysis with TFMA, or directly loaded in.
+ # For example:
+ export_dir = os.path.join(estimator.model_dir,
+ <timestamped directory name>)
+
+ with ops.Graph().as_default() as graph:
+ with session.Session(graph=graph) as sess:
+ tf.saved_model.loader.load(
+ sess, [tf.saved_model.tag_constants.SERVING], export_dir)
+
+ ```
+
+ Args:
+ steps_to_keep: Non-empty list of positive integers containing
+ the step numbers at which the model should be exported. All the exports
+ will be kept, so there is no garbage collection.
+ name: Unique name of this `Exporter` that is going to be used in the
+ export path.
+ serving_input_receiver_fn: A function that takes no arguments and returns
+ a `ServingInputReceiver`.
+ event_file_pattern: Event file name pattern relative to model_dir. If
+ None, however, the exporter would not be preemption-safe. To be
+ preemption-safe, event_file_pattern should be specified.
+ assets_extra: An optional dict specifying how to populate the assets.extra
+ directory within the exported SavedModel. Each key should give the
+ destination path (including the filename) relative to the assets.extra
+ directory. The corresponding value gives the full path of the source
+ file to be copied. For example, the simple case of copying a single
+ file without renaming it is specified as `{'my_asset_file.txt':
+ '/path/to/my_asset_file.txt'}`.
+ as_text: Whether to write the SavedModel proto in text format. Defaults to
+ `False`.
+
+ Raises:
+ ValueError: If any arguments is invalid.
+ """
+ # pylint: disable=protected-access
+ self._saved_model_exporter = exporter._SavedModelExporter(
+ name, serving_input_receiver_fn, assets_extra, as_text)
+ # pylint: enable=protected-access
+
+ self._event_file_pattern = event_file_pattern
+ self._model_dir = None
+
+ self._input_steps_to_keep = steps_to_keep
+ steps_to_keep = [step for step in steps_to_keep if isinstance(step, int)]
+ steps_to_keep = [step for step in steps_to_keep if step > 0]
+ if not steps_to_keep:
+ raise ValueError(
+ '`steps_to_keep` list must have at least one positive integer')
+ elif self._input_steps_to_keep != steps_to_keep:
+ tf_logging.warn('Changed `steps_to_keep`, by omitting non-integer or'
+ ' less than 1 elements, to [%s]',
+ ', '.join(str(step) for step in steps_to_keep))
+ self._steps_to_keep = sorted(steps_to_keep)
+ self._steps_kept = []
+
+ @property
+ def name(self):
+ return self._saved_model_exporter.name
+
+ def export(self, estimator, export_path, checkpoint_path, eval_result,
+ is_the_final_export):
+ """Exports the given Estimator to a specific format.
+
+ Args:
+ estimator: A `tf.estimator.Estimator` instance to export.
+ export_path: A string containing a directory where to write the export.
+ checkpoint_path: The checkpoint path to export.
+ eval_result: The output of Estimator.evaluate on this checkpoint.
+ is_the_final_export: This boolean is True when this is an export in the
+ end of training. It is False for the intermediate exports during the
+ training. When passing Exporter to tf.estimator.train_and_evaluate
+ is_the_final_export is always False if TrainSpec.max_steps is None.
+
+ Returns:
+ The string path to the exported directory or None if export is skipped.
+
+ Raises:
+ ValueError: If `eval_result` is None or doesn't have
+ `ops.GraphKeys.GLOBAL_STEP` as a key.
+ """
+ export_result = None
+
+ if not eval_result or DEFAULT_GLOBAL_STEP_KEY not in eval_result:
+ raise ValueError(
+ '`eval_result` is empty, or does not have global step. This'
+ ' should never happen as Estimator always sets the global step in '
+ '`eval_result`. Please file a bug report. Got eval_result: %s'
+ % str(eval_result))
+
+ if self._model_dir != estimator.model_dir and self._event_file_pattern:
+ tf_logging.info('Loads the steps that the model was already evaluated at,'
+ 'from event files')
+ self._model_dir = estimator.model_dir
+ full_event_file_pattern = os.path.join(self._model_dir,
+ self._event_file_pattern)
+ self._steps_kept = self._get_kept_steps(full_event_file_pattern)
+
+ if self._steps_kept:
+ self._steps_kept = sorted(self._steps_kept)
+ self._steps_to_keep = [step for step in self._steps_to_keep if
+ step > self._steps_kept[-1]]
+ # It is assumed that the model is exported at any evaluated step 'n' if
+ # there is any `steps_missed` lower than 'n'. As a result, all the steps in
+ # `_steps_to_keep` lower than the last evaluated step will be removed.
+ steps_missed = [step for step in self._steps_to_keep
+ if step <= eval_result[DEFAULT_GLOBAL_STEP_KEY]]
+
+ if steps_missed:
+ # update the `_steps_to_keep` list by omitting all steps smaller than the
+ # current global step which are missed to be exported
+ export_result = self._saved_model_exporter.export(estimator, export_path,
+ checkpoint_path,
+ eval_result,
+ is_the_final_export)
+ self._steps_to_keep = [step for step in self._steps_to_keep if step
+ not in steps_missed]
+ # contains all the steps in which export has happened.
+ self._steps_kept.append(eval_result[DEFAULT_GLOBAL_STEP_KEY])
+ # Show warning for all the missed steps except the last one
+ if steps_missed[:-1]:
+ tf_logging.warn('Missed steps [%s] for exporting, as no evaluation'
+ ' took place at them.', ', '.join(str(step) for step in
+ steps_missed[:-1]))
+ # Log model export if the last missed step is the same as the current step
+ if steps_missed[-1] == eval_result[DEFAULT_GLOBAL_STEP_KEY]:
+ tf_logging.info('Performing model export at step %d.',
+ eval_result[DEFAULT_GLOBAL_STEP_KEY])
+ # Show warning for exporting model at another step instead of the user
+ # specified one
+ else:
+ tf_logging.warn('Performing model export at step %d instead of %d, as'
+ ' no evaluation took place at step %d.',
+ eval_result[DEFAULT_GLOBAL_STEP_KEY], steps_missed[-1],
+ steps_missed[-1])
+ return export_result
+
+ def _get_kept_steps(self, event_files):
+ """Get the steps that the model was evaluated at, from event files.
+
+ Args:
+ event_files: Absolute pattern of event files.
+
+ Returns:
+ steps_kept: A list of steps in which the model was evaluated.
+ """
+ if not event_files:
+ return None
+
+ steps_kept = []
+ for event_file in gfile.Glob(os.path.join(event_files)):
+ for event in summary_iterator.summary_iterator(event_file):
+ if event.step not in steps_kept:
+ steps_kept.append(event.step)
+ return steps_kept
diff --git a/tensorflow/contrib/estimator/python/estimator/exporter_test.py b/tensorflow/contrib/estimator/python/estimator/exporter_test.py
new file mode 100644
index 0000000000..0d009b945e
--- /dev/null
+++ b/tensorflow/contrib/estimator/python/estimator/exporter_test.py
@@ -0,0 +1,206 @@
+# 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 `StepsExporter`."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import os
+import shutil
+import tempfile
+
+from tensorflow.contrib.estimator.python.estimator import exporter as exporter_lib
+from tensorflow.python.estimator import estimator as estimator_lib
+from tensorflow.python.platform import gfile
+from tensorflow.python.platform import test
+
+
+class StepsExporterTest(test.TestCase):
+
+ def test_error_out_if_steps_to_keep_has_no_positive_integers(self):
+
+ def _serving_input_receiver_fn():
+ pass
+
+ with self.assertRaisesRegexp(ValueError, "positive integer"):
+ exporter = exporter_lib.StepsExporter(
+ name="specified_steps_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ steps_to_keep=[-1, 0, 1.1])
+ self.assertEqual("specified_steps_exporter", exporter.name)
+
+ def test_steps_exporter(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")
+
+ exporter = exporter_lib.StepsExporter(
+ name="steps_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ assets_extra={"from/path": "to/path"},
+ as_text=False,
+ steps_to_keep=[1])
+ estimator = test.mock.Mock(spec=estimator_lib.Estimator)
+ estimator.export_savedmodel.return_value = "export_result_path"
+ estimator.model_dir = export_dir_base
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 1},
+ False)
+
+ self.assertEqual("export_result_path", export_result)
+ estimator.export_savedmodel.assert_called_with(
+ export_dir_base,
+ _serving_input_receiver_fn,
+ assets_extra={"from/path": "to/path"},
+ as_text=False,
+ checkpoint_path="checkpoint_path",
+ strip_default_attrs=True)
+
+ shutil.rmtree(export_dir_base, ignore_errors=True)
+
+ def test_steps_exporter_with_preemption(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, {}, 2)
+
+ exporter = exporter_lib.StepsExporter(
+ name="steps_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ event_file_pattern="eval_continuous/*.tfevents.*",
+ assets_extra={"from/path": "to/path"},
+ as_text=False,
+ steps_to_keep=[1, 2, 6, 8])
+
+ 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", {"global_step": 3},
+ False)
+ self.assertEqual(None, export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 6},
+ False)
+ self.assertEqual("export_result_path", export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 7},
+ False)
+ self.assertEqual(None, export_result)
+
+ shutil.rmtree(export_dir_base, ignore_errors=True)
+
+ def test_specified_step_is_saved(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")
+
+ exporter = exporter_lib.StepsExporter(
+ name="steps_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ assets_extra={"from/path": "to/path"},
+ as_text=False,
+ steps_to_keep=[1, 5, 8, 10, 11])
+ estimator = test.mock.Mock(spec=estimator_lib.Estimator)
+ estimator.export_savedmodel.return_value = "export_result_path"
+ estimator.model_dir = export_dir_base
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 1},
+ False)
+
+ self.assertTrue(estimator.export_savedmodel.called)
+ self.assertEqual("export_result_path", export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 2},
+ False)
+ self.assertEqual(None, export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 5},
+ False)
+ self.assertTrue(estimator.export_savedmodel.called)
+ self.assertEqual("export_result_path", export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 10},
+ False)
+ self.assertTrue(estimator.export_savedmodel.called)
+ self.assertEqual("export_result_path", export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 15},
+ False)
+ self.assertTrue(estimator.export_savedmodel.called)
+ self.assertEqual("export_result_path", export_result)
+
+ export_result = exporter.export(estimator, export_dir_base,
+ "checkpoint_path", {"global_step": 20},
+ False)
+ self.assertEqual(None, export_result)
+
+ shutil.rmtree(export_dir_base, ignore_errors=True)
+
+ def test_steps_exporter_with_no_global_step_key(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")
+
+ exporter = exporter_lib.StepsExporter(
+ name="steps_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ assets_extra={"from/path": "to/path"},
+ as_text=False,
+ steps_to_keep=[1])
+ estimator = test.mock.Mock(spec=estimator_lib.Estimator)
+ estimator.export_savedmodel.return_value = "export_result_path"
+ estimator.model_dir = export_dir_base
+
+ with self.assertRaisesRegexp(ValueError, "does not have global step"):
+ exporter.export(estimator, export_dir_base, "checkpoint_path", {}, False)
+
+ shutil.rmtree(export_dir_base, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/contrib/estimator/python/estimator/extenders.py b/tensorflow/contrib/estimator/python/estimator/extenders.py
index bf08be09e7..26449b4651 100644
--- a/tensorflow/contrib/estimator/python/estimator/extenders.py
+++ b/tensorflow/contrib/estimator/python/estimator/extenders.py
@@ -34,7 +34,7 @@ _VALID_METRIC_FN_ARGS = set(['features', 'labels', 'predictions', 'config'])
def add_metrics(estimator, metric_fn):
- """Creates a new @{tf.estimator.Estimator} which has given metrics.
+ """Creates a new `tf.estimator.Estimator` which has given metrics.
Example:
@@ -61,7 +61,7 @@ def add_metrics(estimator, metric_fn):
```
Args:
- estimator: A @{tf.estimator.Estimator} object.
+ estimator: A `tf.estimator.Estimator` object.
metric_fn: A function which should obey the following signature:
- Args: can only have following four arguments in any order:
* predictions: Predictions `Tensor` or dict of `Tensor` created by given
@@ -79,7 +79,7 @@ def add_metrics(estimator, metric_fn):
function, namely a `(metric_tensor, update_op)` tuple.
Returns:
- A new @{tf.estimator.Estimator} which has a union of original metrics with
+ A new `tf.estimator.Estimator` which has a union of original metrics with
given ones.
"""
_verify_metric_fn_args(metric_fn)
@@ -165,14 +165,14 @@ def forward_features(estimator, keys=None):
```
Args:
- estimator: A @{tf.estimator.Estimator} object.
+ estimator: A `tf.estimator.Estimator` object.
keys: a `string` or a `list` of `string`. If it is `None`, all of the
`features` in `dict` is forwarded to the `predictions`. If it is a
`string`, only given key is forwarded. If it is a `list` of strings, all
the given `keys` are forwarded.
Returns:
- A new @{tf.estimator.Estimator} which forwards features to predictions.
+ A new `tf.estimator.Estimator` which forwards features to predictions.
Raises:
ValueError:
diff --git a/tensorflow/contrib/estimator/python/estimator/hooks.py b/tensorflow/contrib/estimator/python/estimator/hooks.py
index caadafdfa6..66c46e66b7 100644
--- a/tensorflow/contrib/estimator/python/estimator/hooks.py
+++ b/tensorflow/contrib/estimator/python/estimator/hooks.py
@@ -19,6 +19,7 @@ from __future__ import division
from __future__ import print_function
import os
+import time
from tensorflow.python.estimator import estimator as estimator_lib
from tensorflow.python.framework import ops
@@ -26,6 +27,7 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.training import training
+from tensorflow.python.training import training_util
# pylint: disable=protected-access
@@ -72,8 +74,9 @@ class InMemoryEvaluatorHook(training.SessionRunHook):
estimator: A `tf.estimator.Estimator` instance to call evaluate.
input_fn: Equivalent to the `input_fn` arg to `estimator.evaluate`. A
function that constructs the input data for evaluation.
- See @{$premade_estimators#create_input_functions} for more
- information. The function should construct and return one of
+ See [Createing input functions](
+ https://tensorflow.org/guide/premade_estimators#create_input_functions)
+ for more information. The function should construct and return one of
the following:
* A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
@@ -210,4 +213,72 @@ class InMemoryEvaluatorHook(training.SessionRunHook):
self._evaluate(session)
+class _StopAtCheckpointStepHook(training.SessionRunHook):
+ """Hook that requests stop at a specified step based on checkpoint.
+
+ Note: We recommend using 'make_stop_at_checkpoint_step_hook` to get the proper
+ hook.
+ """
+
+ def __init__(self, model_dir, last_step,
+ wait_after_file_check_secs=30):
+ """Initializes a `StopAtCheckpointStepHook`.
+
+ This hook requests stop after a last step has been reached. It checks latest
+ checkpoint to verify last step is written on disk or not.
+
+ Args:
+ model_dir: Directory to read global step from latest checkpoint.
+ last_step: Step after which to stop.
+ wait_after_file_check_secs: Reading same file by many workers may create
+ I/O issues. To throttle that we will wait given secs after each read of
+ the file.
+
+ Raises:
+ ValueError: If one of the arguments is invalid.
+ """
+ if last_step is None:
+ raise ValueError('last_step must be specified.')
+ if model_dir is None:
+ raise ValueError('model_dir must be specified.')
+
+ self._model_dir = model_dir
+ self._last_step = last_step
+ self._wait_after_file_check_secs = wait_after_file_check_secs
+
+ def begin(self):
+ self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
+ if self._global_step_tensor is None:
+ raise RuntimeError(
+ 'Global step should be created to use StopAtCheckpointStepHook.')
+
+ def before_run(self, run_context): # pylint: disable=unused-argument
+ return training.SessionRunArgs(self._global_step_tensor)
+
+ def after_run(self, run_context, run_values):
+ global_step = run_values.results + 1
+ if global_step >= self._last_step:
+ # Check latest global step in the checkpoint to ensure that the targeted
+ # last step is written on disk.
+
+ step = estimator_lib._load_global_step_from_checkpoint_dir(
+ self._model_dir)
+ if step >= self._last_step:
+ run_context.request_stop()
+ else:
+ time.sleep(self._wait_after_file_check_secs)
+
+
+def make_stop_at_checkpoint_step_hook(estimator,
+ last_step,
+ wait_after_file_check_secs=30):
+ """Creates a proper StopAtCheckpointStepHook based on chief status."""
+
+ if estimator.config.is_chief:
+ return training.StopAtStepHook(last_step=last_step)
+ return _StopAtCheckpointStepHook(
+ model_dir=estimator.model_dir,
+ last_step=last_step,
+ wait_after_file_check_secs=wait_after_file_check_secs)
+
# pylint: enable=protected-access
diff --git a/tensorflow/contrib/estimator/python/estimator/hooks_test.py b/tensorflow/contrib/estimator/python/estimator/hooks_test.py
index ee88d5ecf5..c6c6cad95a 100644
--- a/tensorflow/contrib/estimator/python/estimator/hooks_test.py
+++ b/tensorflow/contrib/estimator/python/estimator/hooks_test.py
@@ -21,8 +21,11 @@ from __future__ import print_function
import glob
import json
import os
+import tempfile
+import time
from tensorflow.contrib.estimator.python.estimator import hooks as hooks_lib
+from tensorflow.python.client import session as tf_session
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.estimator import estimator_lib
from tensorflow.python.estimator import run_config as run_config_lib
@@ -316,5 +319,85 @@ class InMemoryEvaluatorHookTest(test.TestCase):
estimator.train(input_fn, hooks=[evaluator])
+class StopAtCheckpointStepHookTest(test.TestCase):
+
+ def test_do_not_stop_if_checkpoint_is_not_there(self):
+ with ops.Graph().as_default():
+ step = training.create_global_step()
+ assign_ten = step.assign(10)
+ no_op = control_flow_ops.no_op()
+ hook = hooks_lib._StopAtCheckpointStepHook(
+ model_dir=tempfile.mkdtemp(), last_step=10)
+ with training.SingularMonitoredSession(hooks=[hook]) as mon_sess:
+ mon_sess.raw_session().run(assign_ten)
+ with test.mock.patch.object(time, 'sleep') as mock_sleep:
+ mon_sess.run(no_op)
+ self.assertTrue(mock_sleep.called)
+ self.assertFalse(mon_sess.should_stop())
+
+ def test_do_not_stop_if_checkpoint_step_is_smaller(self):
+ model_dir = tempfile.mkdtemp()
+ with ops.Graph().as_default():
+ step = training.create_global_step()
+ assign_nine = step.assign(9)
+ assign_ten = step.assign(10)
+ no_op = control_flow_ops.no_op()
+ hook = hooks_lib._StopAtCheckpointStepHook(
+ model_dir=model_dir, last_step=10)
+ with tf_session.Session() as sess:
+ sess.run(assign_nine)
+ training.Saver().save(sess, os.path.join(model_dir, 'model.ckpt'))
+ with training.SingularMonitoredSession(hooks=[hook]) as mon_sess:
+ mon_sess.raw_session().run(assign_ten)
+ with test.mock.patch.object(time, 'sleep') as mock_sleep:
+ mon_sess.run(no_op)
+ self.assertTrue(mock_sleep.called)
+ self.assertFalse(mon_sess.should_stop())
+
+ def test_stop_if_checkpoint_step_is_laststep(self):
+ model_dir = tempfile.mkdtemp()
+ with ops.Graph().as_default():
+ step = training.create_global_step()
+ assign_ten = step.assign(10)
+ no_op = control_flow_ops.no_op()
+ hook = hooks_lib._StopAtCheckpointStepHook(
+ model_dir=model_dir, last_step=10)
+ with tf_session.Session() as sess:
+ sess.run(assign_ten)
+ training.Saver().save(sess, os.path.join(model_dir, 'model.ckpt'))
+ with training.SingularMonitoredSession(hooks=[hook]) as mon_sess:
+ mon_sess.raw_session().run(assign_ten)
+ with test.mock.patch.object(time, 'sleep') as mock_sleep:
+ mon_sess.run(no_op)
+ self.assertFalse(mock_sleep.called)
+ self.assertTrue(mon_sess.should_stop())
+
+ def test_creates_regular_stop_at_step_hook_for_chief(self):
+ # by default an estimator is in chief mode
+ dnn = estimator_lib.DNNClassifier(
+ feature_columns=[feature_column_lib.numeric_column('x')],
+ hidden_units=[3, 1])
+ hook = hooks_lib.make_stop_at_checkpoint_step_hook(dnn, 300)
+ self.assertIsInstance(hook, training.StopAtStepHook)
+ self.assertEqual(300, hook._last_step)
+
+ def test_creates_checkpoint_hook_for_workers(self):
+
+ class FakeWorkerConfig(estimator_lib.RunConfig):
+
+ @property
+ def is_chief(self):
+ return False
+
+ dnn = estimator_lib.DNNClassifier(
+ feature_columns=[feature_column_lib.numeric_column('x')],
+ hidden_units=[3, 1],
+ config=FakeWorkerConfig())
+ hook = hooks_lib.make_stop_at_checkpoint_step_hook(dnn, 300)
+ self.assertIsInstance(hook, hooks_lib._StopAtCheckpointStepHook)
+ self.assertEqual(300, hook._last_step)
+ self.assertEqual(dnn.model_dir, hook._model_dir)
+
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/contrib/estimator/python/estimator/linear.py b/tensorflow/contrib/estimator/python/estimator/linear.py
index 62a37abefb..2b68f24eb2 100644
--- a/tensorflow/contrib/estimator/python/estimator/linear.py
+++ b/tensorflow/contrib/estimator/python/estimator/linear.py
@@ -121,7 +121,7 @@ class LinearEstimator(estimator.Estimator):
is multivalent. One of "mean", "sqrtn", and "sum" -- these are
effectively different ways to do example-level normalization, which can
be useful for bag-of-words features. for more details, see
- @{tf.feature_column.linear_model$linear_model}.
+ `tf.feature_column.linear_model`.
"""
def _model_fn(features, labels, mode, config):
return linear_lib._linear_model_fn( # pylint: disable=protected-access
diff --git a/tensorflow/contrib/factorization/BUILD b/tensorflow/contrib/factorization/BUILD
index effec42f02..9e1f14f990 100644
--- a/tensorflow/contrib/factorization/BUILD
+++ b/tensorflow/contrib/factorization/BUILD
@@ -65,7 +65,7 @@ tf_custom_op_py_library(
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
"//tensorflow/python/estimator",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/feature_column:feature_column_py",
"//third_party/py/numpy",
],
@@ -242,7 +242,7 @@ py_test(
"//tensorflow/python:platform_benchmark",
"//tensorflow/python:random_ops",
"//tensorflow/python:training",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/feature_column:feature_column_py",
"//third_party/py/numpy",
],
diff --git a/tensorflow/contrib/factorization/python/ops/kmeans.py b/tensorflow/contrib/factorization/python/ops/kmeans.py
index 9ffdd3ba5e..f384d761a8 100644
--- a/tensorflow/contrib/factorization/python/ops/kmeans.py
+++ b/tensorflow/contrib/factorization/python/ops/kmeans.py
@@ -158,12 +158,12 @@ class _ModelFn(object):
return either `features` or, equivalently, `(features, None)`.
Args:
- features: The input points. See @{tf.estimator.Estimator}.
- mode: See @{tf.estimator.Estimator}.
- config: See @{tf.estimator.Estimator}.
+ features: The input points. See `tf.estimator.Estimator`.
+ mode: See `tf.estimator.Estimator`.
+ config: See `tf.estimator.Estimator`.
Returns:
- A @{tf.estimator.EstimatorSpec} (see @{tf.estimator.Estimator}) specifying
+ A `tf.estimator.EstimatorSpec` (see `tf.estimator.Estimator`) specifying
this behavior:
* `train_op`: Execute one mini-batch or full-batch run of Lloyd's
algorithm.
@@ -188,7 +188,6 @@ class _ModelFn(object):
# center.
# is_initialized: scalar indicating whether the initial cluster centers
# have been chosen; see init_op.
- # cluster_centers_var: a Variable containing the cluster centers.
# init_op: an op to choose the initial cluster centers. A single worker
# repeatedly executes init_op until is_initialized becomes True.
# training_op: an op that runs an iteration of training, either an entire
@@ -394,7 +393,7 @@ class KMeansClustering(estimator.Estimator):
relative_tolerance: A relative tolerance of change in the loss between
iterations. Stops learning if the loss changes less than this amount.
This may not work correctly if `use_mini_batch=True`.
- config: See @{tf.estimator.Estimator}.
+ config: See `tf.estimator.Estimator`.
feature_columns: An optionable iterable containing all the feature columns
used by the model. All items in the set should be feature column
instances that can be passed to `tf.feature_column.input_layer`. If this
@@ -431,7 +430,7 @@ class KMeansClustering(estimator.Estimator):
"""Finds the index of the closest cluster center to each input point.
Args:
- input_fn: Input points. See @{tf.estimator.Estimator.predict}.
+ input_fn: Input points. See `tf.estimator.Estimator.predict`.
Yields:
The index of the closest cluster center for each input point.
@@ -447,7 +446,7 @@ class KMeansClustering(estimator.Estimator):
which returns the negative sum.
Args:
- input_fn: Input points. See @{tf.estimator.Estimator.evaluate}. Only one
+ input_fn: Input points. See `tf.estimator.Estimator.evaluate`. Only one
batch is retrieved.
Returns:
@@ -465,7 +464,7 @@ class KMeansClustering(estimator.Estimator):
sklearn function returns the Euclidean distance.
Args:
- input_fn: Input points. See @{tf.estimator.Estimator.predict}.
+ input_fn: Input points. See `tf.estimator.Estimator.predict`.
Yields:
The distances from each input point to each cluster center.
diff --git a/tensorflow/contrib/ffmpeg/__init__.py b/tensorflow/contrib/ffmpeg/__init__.py
index 484ffee3e7..3a756da932 100644
--- a/tensorflow/contrib/ffmpeg/__init__.py
+++ b/tensorflow/contrib/ffmpeg/__init__.py
@@ -15,7 +15,7 @@
# pylint: disable=g-short-docstring-punctuation
"""Working with audio using FFmpeg.
-See the @{$python/contrib.ffmpeg} guide.
+See the [FFMPEG](https://tensorflow.org/api_guides/python/contrib.ffmpeg) guide.
@@decode_audio
@@encode_audio
diff --git a/tensorflow/contrib/framework/__init__.py b/tensorflow/contrib/framework/__init__.py
index 918a7e2bc7..95f5ba90ab 100644
--- a/tensorflow/contrib/framework/__init__.py
+++ b/tensorflow/contrib/framework/__init__.py
@@ -15,7 +15,9 @@
"""Framework utilities.
-See the @{$python/contrib.framework} guide.
+See the
+[Contrib Framework](https://tensorflow.org/api_guides/python/contrib.framework)
+guide.
@@assert_same_float_dtype
@@assert_scalar
@@ -100,6 +102,8 @@ See the @{$python/contrib.framework} guide.
@@BoundedTensorSpec
@@TensorSpec
+
+@@RecordInput
"""
from __future__ import absolute_import
@@ -119,6 +123,7 @@ from tensorflow.python.framework.smart_cond import smart_cond
from tensorflow.python.framework.smart_cond import smart_constant_value
from tensorflow.python.framework.tensor_spec import BoundedTensorSpec
from tensorflow.python.framework.tensor_spec import TensorSpec
+from tensorflow.python.ops.data_flow_ops import RecordInput
from tensorflow.python.ops.init_ops import convolutional_delta_orthogonal
from tensorflow.python.ops.init_ops import convolutional_orthogonal_1d
from tensorflow.python.ops.init_ops import convolutional_orthogonal_2d
diff --git a/tensorflow/contrib/framework/python/ops/arg_scope.py b/tensorflow/contrib/framework/python/ops/arg_scope.py
index 5b15033995..0a02e76a26 100644
--- a/tensorflow/contrib/framework/python/ops/arg_scope.py
+++ b/tensorflow/contrib/framework/python/ops/arg_scope.py
@@ -103,9 +103,8 @@ def _kwarg_names(func):
def _add_op(op):
- key = arg_scope_func_key(op)
- if key not in _DECORATED_OPS:
- _DECORATED_OPS[key] = _kwarg_names(op)
+ key_op = arg_scope_func_key(op)
+ _DECORATED_OPS[key_op] = _kwarg_names(op)
@tf_contextlib.contextmanager
diff --git a/tensorflow/contrib/framework/python/ops/arg_scope_test.py b/tensorflow/contrib/framework/python/ops/arg_scope_test.py
index 4c3879d4fc..bcafc1a328 100644
--- a/tensorflow/contrib/framework/python/ops/arg_scope_test.py
+++ b/tensorflow/contrib/framework/python/ops/arg_scope_test.py
@@ -38,6 +38,12 @@ def func3(args, a=None, b=1, c=2):
"""Some cool doc string."""
return (args, a, b, c)
+@add_arg_scope
+def func4(x='x', y='y'):
+ if x:
+ pass
+ if y:
+ pass
def _key_op(op):
return getattr(op, '_key_op', str(op))
@@ -231,6 +237,15 @@ class ArgScopeTest(test.TestCase):
self.assertTupleEqual(args, func2_args)
self.assertDictEqual(kwargs, func2_kwargs)
+ def testAddArgScopeRaceCondition(self):
+ func4_kwargs = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
+ for i in range(4):
+ # redefine the function with different args
+ @add_arg_scope
+ def func4(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8):
+ pass
+ self.assertTupleEqual(arg_scoped_arguments(func4), func4_kwargs)
+
def testDocString(self):
self.assertEqual(func3.__doc__, 'Some cool doc string.')
diff --git a/tensorflow/contrib/framework/python/ops/critical_section_ops.py b/tensorflow/contrib/framework/python/ops/critical_section_ops.py
index 72835c3ad8..71ab755aa2 100644
--- a/tensorflow/contrib/framework/python/ops/critical_section_ops.py
+++ b/tensorflow/contrib/framework/python/ops/critical_section_ops.py
@@ -325,6 +325,8 @@ class CriticalSection(object):
def _is_self_handle(self, x):
"""Check if the tensor `x` is the same Mutex as `self._handle`."""
+ if isinstance(x, ops.EagerTensor):
+ return x is self._handle
return (x.op.type == "MutexV2"
# blank shared_name means the op will create a unique one.
and x.op.get_attr("shared_name")
@@ -365,8 +367,7 @@ class CriticalSection(object):
"(CriticalSection: %s) requested exclusive resource access "
"of this resource. Did you mean to call execute with keyword "
"argument exclusive_resource_access=False?" %
- (list(resource_intersection), self._handle.name,
- sg.op.name, sg.handle.name))
+ (list(resource_intersection), self._handle, sg, sg.handle))
# TODO(ebrevdo): Re-enable once CriticalSection is in core.
diff --git a/tensorflow/contrib/framework/python/ops/script_ops.py b/tensorflow/contrib/framework/python/ops/script_ops.py
index 5d269fefdc..d5cb679e2c 100644
--- a/tensorflow/contrib/framework/python/ops/script_ops.py
+++ b/tensorflow/contrib/framework/python/ops/script_ops.py
@@ -13,7 +13,7 @@
# limitations under the License.
# ==============================================================================
-"""Script Language Operators. See the @{$python/script_ops} guide.
+"""Script Language Operators.
@@py_func
"""
diff --git a/tensorflow/contrib/framework/python/ops/variables.py b/tensorflow/contrib/framework/python/ops/variables.py
index 322d5c335e..a7acae804a 100644
--- a/tensorflow/contrib/framework/python/ops/variables.py
+++ b/tensorflow/contrib/framework/python/ops/variables.py
@@ -241,13 +241,13 @@ def variable(name,
use_resource: If `True` use a ResourceVariable instead of a Variable.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
Returns:
The created or existing variable.
@@ -320,13 +320,13 @@ def model_variable(name,
use_resource: If `True` use a ResourceVariable instead of a Variable.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
Returns:
The created or existing variable.
diff --git a/tensorflow/contrib/fused_conv/kernels/fused_conv2d_bias_activation_op.h b/tensorflow/contrib/fused_conv/kernels/fused_conv2d_bias_activation_op.h
index 7534f5797c..869e899ac8 100644
--- a/tensorflow/contrib/fused_conv/kernels/fused_conv2d_bias_activation_op.h
+++ b/tensorflow/contrib/fused_conv/kernels/fused_conv2d_bias_activation_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef THIRDPARTY_TENSORFLOW_CONTRIB_KERNELS_FUSED_CONV2D_BIAS_ACTIVATION_OP_H_
-#define THIRDPARTY_TENSORFLOW_CONTRIB_KERNELS_FUSED_CONV2D_BIAS_ACTIVATION_OP_H_
+#ifndef TENSORFLOW_CONTRIB_FUSED_CONV_KERNELS_FUSED_CONV2D_BIAS_ACTIVATION_OP_H_
+#define TENSORFLOW_CONTRIB_FUSED_CONV_KERNELS_FUSED_CONV2D_BIAS_ACTIVATION_OP_H_
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor_types.h"
@@ -62,4 +62,4 @@ class LaunchFusedConv2DBiasActivationOp<Eigen::GpuDevice, T, BiasType,
} // namespace tensorflow
-#endif
+#endif // TENSORFLOW_CONTRIB_FUSED_CONV_KERNELS_FUSED_CONV2D_BIAS_ACTIVATION_OP_H_
diff --git a/tensorflow/contrib/gan/BUILD b/tensorflow/contrib/gan/BUILD
index 053d4e3e97..9866fccfba 100644
--- a/tensorflow/contrib/gan/BUILD
+++ b/tensorflow/contrib/gan/BUILD
@@ -424,9 +424,11 @@ py_library(
":namedtuples",
"//tensorflow/python:array_ops",
"//tensorflow/python:framework_ops",
+ "//tensorflow/python:functional_ops",
"//tensorflow/python:math_ops",
"//tensorflow/python:summary",
"//tensorflow/python:util",
+ "//tensorflow/python:variable_scope",
"//tensorflow/python/ops/losses",
],
)
@@ -459,8 +461,7 @@ py_library(
":train",
"//tensorflow/python:framework_ops",
"//tensorflow/python:util",
- "//tensorflow/python/estimator:head",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -477,7 +478,7 @@ py_test(
"//tensorflow/python:math_ops",
"//tensorflow/python:training",
"//tensorflow/python:variable_scope",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -497,8 +498,7 @@ py_library(
"//tensorflow/python:metrics",
"//tensorflow/python:util",
"//tensorflow/python:variable_scope",
- "//tensorflow/python/estimator",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -526,8 +526,7 @@ py_test(
"//tensorflow/python:training",
"//tensorflow/python:training_util",
"//tensorflow/python:variable_scope",
- "//tensorflow/python/estimator:model_fn",
- "//tensorflow/python/estimator:numpy_io",
+ "//tensorflow/python/estimator:estimator_py",
"//third_party/py/numpy",
"@absl_py//absl/testing:parameterized",
"@six_archive//:six",
diff --git a/tensorflow/contrib/gan/python/eval/python/summaries_impl.py b/tensorflow/contrib/gan/python/eval/python/summaries_impl.py
index 508f487722..f9995bb19d 100644
--- a/tensorflow/contrib/gan/python/eval/python/summaries_impl.py
+++ b/tensorflow/contrib/gan/python/eval/python/summaries_impl.py
@@ -22,7 +22,9 @@ from tensorflow.contrib.gan.python import namedtuples
from tensorflow.contrib.gan.python.eval.python import eval_utils
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import variable_scope
from tensorflow.python.ops.losses import util as loss_util
from tensorflow.python.summary import summary
@@ -32,6 +34,7 @@ __all__ = [
'add_gan_model_summaries',
'add_regularization_loss_summaries',
'add_cyclegan_image_summaries',
+ 'add_stargan_image_summaries'
]
@@ -179,6 +182,94 @@ def add_image_comparison_summaries(gan_model, num_comparisons=2,
max_outputs=1)
+def add_stargan_image_summaries(stargan_model,
+ num_images=2,
+ display_diffs=False):
+ """Adds image summaries to see StarGAN image results.
+
+ If display_diffs is True, each image result has `2` rows and `num_domains + 1`
+ columns.
+ The first row looks like:
+ [original_image, transformed_to_domain_0, transformed_to_domain_1, ...]
+ The second row looks like:
+ [no_modification_baseline, transformed_to_domain_0-original_image, ...]
+ If display_diffs is False, only the first row is shown.
+
+ IMPORTANT:
+ Since the model originally does not transformed the image to every domains,
+ we will transform them on-the-fly within this function in parallel.
+
+ Args:
+ stargan_model: A StarGANModel tuple.
+ num_images: The number of examples/images to be transformed and shown.
+ display_diffs: Also display the difference between generated and target.
+
+ Raises:
+ ValueError: If input_data is not images.
+ ValueError: If input_data_domain_label is not rank 2.
+ ValueError: If dimension 2 of input_data_domain_label is not fully defined.
+ """
+
+ _assert_is_image(stargan_model.input_data)
+ stargan_model.input_data_domain_label.shape.assert_has_rank(2)
+ stargan_model.input_data_domain_label.shape[1:].assert_is_fully_defined()
+
+ num_domains = stargan_model.input_data_domain_label.get_shape().as_list()[-1]
+
+ def _build_image(image):
+ """Helper function to create a result for each image on the fly."""
+
+ # Expand the first dimension as batch_size = 1.
+ images = array_ops.expand_dims(image, axis=0)
+
+ # Tile the image num_domains times, so we can get all transformed together.
+ images = array_ops.tile(images, [num_domains, 1, 1, 1])
+
+ # Create the targets to 0, 1, 2, ..., num_domains-1.
+ targets = array_ops.one_hot(list(range(num_domains)), num_domains)
+
+ with variable_scope.variable_scope(
+ stargan_model.generator_scope, reuse=True):
+
+ # Add the original image.
+ output_images_list = [image]
+
+ # Generate the image and add to the list.
+ gen_images = stargan_model.generator_fn(images, targets)
+ gen_images_list = array_ops.split(gen_images, num_domains)
+ gen_images_list = [
+ array_ops.squeeze(img, axis=0) for img in gen_images_list
+ ]
+ output_images_list.extend(gen_images_list)
+
+ # Display diffs.
+ if display_diffs:
+ diff_images = gen_images - images
+ diff_images_list = array_ops.split(diff_images, num_domains)
+ diff_images_list = [
+ array_ops.squeeze(img, axis=0) for img in diff_images_list
+ ]
+ output_images_list.append(array_ops.zeros_like(image))
+ output_images_list.extend(diff_images_list)
+
+ # Create the final image.
+ final_image = eval_utils.image_reshaper(
+ output_images_list, num_cols=num_domains + 1)
+
+ # Reduce the first rank.
+ return array_ops.squeeze(final_image, axis=0)
+
+ summary.image(
+ 'stargan_image_generation',
+ functional_ops.map_fn(
+ _build_image,
+ stargan_model.input_data[:num_images],
+ parallel_iterations=num_images,
+ back_prop=False,
+ swap_memory=True),
+ max_outputs=num_images)
+
+
def add_gan_model_summaries(gan_model):
"""Adds typical GANModel summaries.
diff --git a/tensorflow/contrib/gan/python/eval/python/summaries_test.py b/tensorflow/contrib/gan/python/eval/python/summaries_test.py
index 33d51bfc21..54a6f8d4d9 100644
--- a/tensorflow/contrib/gan/python/eval/python/summaries_test.py
+++ b/tensorflow/contrib/gan/python/eval/python/summaries_test.py
@@ -18,7 +18,6 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-
from tensorflow.contrib.gan.python import namedtuples
from tensorflow.contrib.gan.python.eval.python import summaries_impl as summaries
from tensorflow.python.framework import ops
@@ -37,6 +36,10 @@ def discriminator_model(inputs, _):
return variable_scope.get_variable('dummy_d', initializer=2.0) * inputs
+def stargan_generator_model(inputs, _):
+ return generator_model(inputs)
+
+
def get_gan_model():
# TODO(joelshor): Find a better way of creating a variable scope.
with variable_scope.variable_scope('generator') as gen_scope:
@@ -57,6 +60,31 @@ def get_gan_model():
discriminator_fn=discriminator_model)
+def get_stargan_model():
+ """Similar to get_gan_model()."""
+ # TODO(joelshor): Find a better way of creating a variable scope.
+ with variable_scope.variable_scope('discriminator') as dis_scope:
+ pass
+ with variable_scope.variable_scope('generator') as gen_scope:
+ return namedtuples.StarGANModel(
+ input_data=array_ops.ones([1, 2, 2, 3]),
+ input_data_domain_label=array_ops.ones([1, 2]),
+ generated_data=stargan_generator_model(
+ array_ops.ones([1, 2, 2, 3]), None),
+ generated_data_domain_target=array_ops.ones([1, 2]),
+ reconstructed_data=array_ops.ones([1, 2, 2, 3]),
+ discriminator_input_data_source_predication=array_ops.ones([1]),
+ discriminator_generated_data_source_predication=array_ops.ones([1]),
+ discriminator_input_data_domain_predication=array_ops.ones([1, 2]),
+ discriminator_generated_data_domain_predication=array_ops.ones([1, 2]),
+ generator_variables=None,
+ generator_scope=gen_scope,
+ generator_fn=stargan_generator_model,
+ discriminator_variables=None,
+ discriminator_scope=dis_scope,
+ discriminator_fn=discriminator_model)
+
+
def get_cyclegan_model():
with variable_scope.variable_scope('x2y'):
model_x2y = get_gan_model()
@@ -143,6 +171,16 @@ class SummariesTest(test.TestCase):
with self.test_session(use_gpu=True):
summary.merge_all().eval()
+ def test_add_image_comparison_summaries_for_stargan(self):
+
+ summaries.add_stargan_image_summaries(get_stargan_model())
+
+ self.assertEquals(1, len(ops.get_collection(ops.GraphKeys.SUMMARIES)))
+
+ with self.test_session(use_gpu=True) as sess:
+ sess.run(variables.global_variables_initializer())
+ summary.merge_all().eval()
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/contrib/gan/python/train.py b/tensorflow/contrib/gan/python/train.py
index 03f52d214b..9e5aea1498 100644
--- a/tensorflow/contrib/gan/python/train.py
+++ b/tensorflow/contrib/gan/python/train.py
@@ -52,7 +52,6 @@ from tensorflow.python.training import session_run_hook
from tensorflow.python.training import sync_replicas_optimizer
from tensorflow.python.training import training_util
-
__all__ = [
'gan_model',
'infogan_model',
@@ -61,6 +60,7 @@ __all__ = [
'stargan_model',
'gan_loss',
'cyclegan_loss',
+ 'stargan_loss',
'gan_train_ops',
'gan_train',
'get_sequential_train_hooks',
@@ -646,8 +646,9 @@ def gan_loss(
type(model))
# Optionally create pooled model.
- pooled_model = (_tensor_pool_adjusted_model(model, tensor_pool_fn) if
- tensor_pool_fn else model)
+ pooled_model = (
+ _tensor_pool_adjusted_model(model, tensor_pool_fn)
+ if tensor_pool_fn else model)
# Create standard losses.
gen_loss = generator_loss_fn(model, add_summaries=add_summaries)
@@ -665,9 +666,10 @@ def gan_loss(
if _use_aux_loss(mutual_information_penalty_weight):
gen_info_loss = tfgan_losses.mutual_information_penalty(
model, add_summaries=add_summaries)
- dis_info_loss = (gen_info_loss if tensor_pool_fn is None else
- tfgan_losses.mutual_information_penalty(
- pooled_model, add_summaries=add_summaries))
+ dis_info_loss = (
+ gen_info_loss
+ if tensor_pool_fn is None else tfgan_losses.mutual_information_penalty(
+ pooled_model, add_summaries=add_summaries))
gen_loss += mutual_information_penalty_weight * gen_info_loss
dis_loss += mutual_information_penalty_weight * dis_info_loss
if _use_aux_loss(aux_cond_generator_weight):
diff --git a/tensorflow/contrib/graph_editor/__init__.py b/tensorflow/contrib/graph_editor/__init__.py
index 51b7f45274..b2de2b9a69 100644
--- a/tensorflow/contrib/graph_editor/__init__.py
+++ b/tensorflow/contrib/graph_editor/__init__.py
@@ -14,7 +14,9 @@
# ==============================================================================
"""TensorFlow Graph Editor.
-See the @{$python/contrib.graph_editor} guide.
+See the
+[Graph Editor](https://tensorflow.org/api_guides/python/contrib.graph_editor)
+guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/contrib/graph_editor/transform.py b/tensorflow/contrib/graph_editor/transform.py
index 026a3d1200..e79ccd8da1 100644
--- a/tensorflow/contrib/graph_editor/transform.py
+++ b/tensorflow/contrib/graph_editor/transform.py
@@ -129,7 +129,7 @@ def transform_op_if_inside_handler(info, op, keep_if_possible=True):
return None
-def copy_op_handler(info, op, new_inputs, copy_shape=True, nodedef_fn=None):
+def copy_op_handler(info, op, new_inputs, copy_shape=False, nodedef_fn=None):
"""Copy a `tf.Operation`.
Args:
diff --git a/tensorflow/contrib/hadoop/BUILD b/tensorflow/contrib/hadoop/BUILD
new file mode 100644
index 0000000000..ccad31efa1
--- /dev/null
+++ b/tensorflow/contrib/hadoop/BUILD
@@ -0,0 +1,117 @@
+package(default_visibility = ["//tensorflow:internal"])
+
+licenses(["notice"]) # Apache 2.0
+
+exports_files(["LICENSE"])
+
+load(
+ "//tensorflow:tensorflow.bzl",
+ "tf_custom_op_library",
+ "tf_custom_op_py_library",
+ "tf_gen_op_libs",
+ "tf_gen_op_wrapper_py",
+ "tf_kernel_library",
+ "tf_py_test",
+)
+
+filegroup(
+ name = "test_data",
+ srcs = glob(["python/kernel_tests/testdata/*"]),
+)
+
+py_library(
+ name = "hadoop",
+ srcs = ["__init__.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":dataset_ops",
+ ],
+)
+
+tf_custom_op_library(
+ name = "_dataset_ops.so",
+ srcs = ["ops/dataset_ops.cc"],
+ deps = [
+ ":dataset_kernels",
+ ],
+)
+
+tf_gen_op_libs(
+ op_lib_names = ["dataset_ops"],
+)
+
+cc_library(
+ name = "dataset_kernels",
+ srcs = ["kernels/hadoop_dataset_ops.cc"],
+ deps = [
+ "//tensorflow/core:framework_headers_lib",
+ "//third_party/eigen3",
+ "@protobuf_archive//:protobuf_headers",
+ ],
+ alwayslink = 1,
+)
+
+py_library(
+ name = "dataset_ops",
+ srcs = [
+ "python/ops/hadoop_dataset_ops.py",
+ ],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":hadoop_op_loader",
+ "//tensorflow/python:dataset_ops_gen",
+ "//tensorflow/python:util",
+ "//tensorflow/python/data/ops:dataset_ops",
+ "//tensorflow/python/data/util:nest",
+ ],
+)
+
+tf_gen_op_wrapper_py(
+ name = "gen_dataset_ops",
+ out = "python/ops/gen_dataset_ops.py",
+ deps = ["//tensorflow/contrib/hadoop:dataset_ops_op_lib"],
+)
+
+tf_kernel_library(
+ name = "dataset_ops_kernels",
+ deps = [
+ ":dataset_kernels",
+ "//tensorflow/core:framework",
+ ],
+ alwayslink = 1,
+)
+
+tf_custom_op_py_library(
+ name = "hadoop_op_loader",
+ srcs = ["python/ops/hadoop_op_loader.py"],
+ dso = ["//tensorflow/contrib/hadoop:_dataset_ops.so"],
+ kernels = [
+ ":dataset_ops_kernels",
+ "//tensorflow/contrib/hadoop:dataset_ops_op_lib",
+ ],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":gen_dataset_ops",
+ "//tensorflow/contrib/util:util_py",
+ "//tensorflow/python:platform",
+ ],
+)
+
+tf_py_test(
+ name = "hadoop_test",
+ srcs = ["python/kernel_tests/hadoop_test.py"],
+ additional_deps = [
+ ":hadoop",
+ "//third_party/py/numpy",
+ "//tensorflow/python:client_testlib",
+ "//tensorflow/python:framework",
+ "//tensorflow/python:framework_test_lib",
+ "//tensorflow/python:platform_test",
+ ],
+ data = [
+ ":test_data",
+ ],
+ tags = [
+ "notap",
+ ],
+)
diff --git a/tensorflow/contrib/hadoop/__init__.py b/tensorflow/contrib/hadoop/__init__.py
new file mode 100644
index 0000000000..abf8cd4845
--- /dev/null
+++ b/tensorflow/contrib/hadoop/__init__.py
@@ -0,0 +1,32 @@
+# 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.
+# ==============================================================================
+"""Sequence File Dataset.
+
+@@SequenceFileDataset
+"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.contrib.hadoop.python.ops.hadoop_dataset_ops import SequenceFileDataset
+
+from tensorflow.python.util.all_util import remove_undocumented
+
+_allowed_symbols = [
+ "SequenceFileDataset",
+]
+
+remove_undocumented(__name__)
diff --git a/tensorflow/contrib/hadoop/kernels/hadoop_dataset_ops.cc b/tensorflow/contrib/hadoop/kernels/hadoop_dataset_ops.cc
new file mode 100644
index 0000000000..80b2d3e08b
--- /dev/null
+++ b/tensorflow/contrib/hadoop/kernels/hadoop_dataset_ops.cc
@@ -0,0 +1,340 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/core/framework/dataset.h"
+#include "tensorflow/core/lib/io/buffered_inputstream.h"
+#include "tensorflow/core/platform/file_system.h"
+
+namespace tensorflow {
+namespace {
+
+static const size_t kSyncMarkerSize = 16;
+static const size_t kSequenceFileBufferSize = 1024 * 1024;
+
+class SequenceFileReader {
+ public:
+ explicit SequenceFileReader(RandomAccessFile* file)
+ : input_stream_(
+ new io::BufferedInputStream(file, kSequenceFileBufferSize)) {}
+
+ Status ReadHeader() {
+ string version;
+ TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(4, &version));
+ if (version.substr(0, 3) != "SEQ" || version[3] != 6) {
+ return errors::InvalidArgument(
+ "sequence file header must starts with `SEQ6`, received \"",
+ version.substr(0, 3), static_cast<int>(version[3]), "\"");
+ }
+ TF_RETURN_IF_ERROR(ReadString(&key_class_name_));
+ TF_RETURN_IF_ERROR(ReadString(&value_class_name_));
+
+ // At the moment we only support `org.apache.hadoop.io.Text` for key/value.
+ // TODO (yongtang): Add more class name support.
+ if (key_class_name_ != "org.apache.hadoop.io.Text" ||
+ value_class_name_ != "org.apache.hadoop.io.Text") {
+ return errors::Unimplemented("key/value of '", key_class_name_, "/",
+ value_class_name_,
+ "' is currently not supported");
+ }
+
+ string buffer;
+ TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(2, &buffer));
+ compression_ = buffer[0];
+ block_compression_ = buffer[1];
+ if (compression_ || block_compression_) {
+ TF_RETURN_IF_ERROR(ReadString(&compression_codec_class_name_));
+ }
+
+ // At the moment no compression is supported.
+ // TODO (yongtang): Add compression support.
+ if (compression_ || block_compression_) {
+ return errors::Unimplemented("compression is currently not supported");
+ }
+
+ // Not interested in metadata for now.
+ uint32 num_metadata_pairs = 0;
+ TF_RETURN_IF_ERROR(ReadUInt32(&num_metadata_pairs));
+ if (num_metadata_pairs > 1024) {
+ return errors::InvalidArgument(
+ "sequence file metadata should have key value pairs < 1024, "
+ "received ",
+ num_metadata_pairs);
+ }
+ for (int i = 0; i < num_metadata_pairs; i++) {
+ TF_RETURN_IF_ERROR(ReadString(nullptr));
+ TF_RETURN_IF_ERROR(ReadString(nullptr));
+ }
+
+ TF_RETURN_IF_ERROR(
+ input_stream_->ReadNBytes(kSyncMarkerSize, &sync_marker_));
+
+ return Status::OK();
+ }
+
+ Status ReadRecord(string* key, string* value) {
+ uint32 length = 0;
+ TF_RETURN_IF_ERROR(ReadUInt32(&length));
+ if (length == static_cast<uint32>(-1)) {
+ // Sync marker.
+ string sync_marker;
+ TF_RETURN_IF_ERROR(
+ input_stream_->ReadNBytes(kSyncMarkerSize, &sync_marker));
+ if (sync_marker != sync_marker_) {
+ return errors::InvalidArgument(
+ "sequence file should have sync marker \"", sync_marker_,
+ "\" at pos ", input_stream_->Tell() - kSyncMarkerSize,
+ ", received \"", sync_marker, "\"");
+ }
+ return ReadRecord(key, value);
+ }
+ uint32 key_length = 0;
+ TF_RETURN_IF_ERROR(ReadUInt32(&key_length));
+ if (key_length > length) {
+ return errors::InvalidArgument("key length (", key_length,
+ ") should be < record length (", length,
+ ")");
+ }
+ // At the moment we only support `org.apache.hadoop.io.Text` for key/value.
+ // TODO (yongtang): Expand supported format.
+ TF_RETURN_IF_ERROR(ReadString(key));
+ TF_RETURN_IF_ERROR(ReadString(value));
+ return Status::OK();
+ }
+
+ Status ReadString(string* value) {
+ int64 length = 0;
+ TF_RETURN_IF_ERROR(ReadVInt(&length));
+ if (value == nullptr) {
+ return input_stream_->SkipNBytes(length);
+ }
+ return input_stream_->ReadNBytes(length, value);
+ }
+
+ Status ReadUInt32(uint32* value) {
+ string buffer;
+ TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(4, &buffer));
+ *value = ((static_cast<uint32>(buffer[0]) << 24) |
+ static_cast<uint32>(buffer[1]) << 16) |
+ (static_cast<uint32>(buffer[2]) << 8) |
+ static_cast<uint32>(buffer[3]);
+ return Status::OK();
+ }
+
+ Status ReadVInt(int64* value) {
+ string buffer;
+ TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(1, &buffer));
+ if (buffer[0] >= -112) {
+ *value = static_cast<int64>(buffer[0]);
+ return Status::OK();
+ }
+
+ int64 remaining = 0;
+ bool negative = false;
+ if (buffer[0] >= -120) {
+ remaining = static_cast<int64>(-112) - static_cast<int64>(buffer[0]);
+ } else {
+ remaining = static_cast<int64>(-120) - static_cast<int64>(buffer[0]);
+ negative = true;
+ }
+ buffer.clear();
+ TF_RETURN_IF_ERROR(input_stream_->ReadNBytes(remaining, &buffer));
+
+ uint64 v = 0;
+ for (int i = 0; i < buffer.size(); i++) {
+ v = (v << 8) | static_cast<uint64>(buffer[i]);
+ }
+ if (negative) {
+ v = ~v;
+ }
+ *value = static_cast<int64>(v);
+ return Status::OK();
+ }
+
+ virtual ~SequenceFileReader() = default;
+
+ private:
+ std::unique_ptr<io::InputStreamInterface> input_stream_;
+ string key_class_name_;
+ string value_class_name_;
+ string sync_marker_;
+ bool compression_;
+ bool block_compression_;
+ string compression_codec_class_name_;
+ TF_DISALLOW_COPY_AND_ASSIGN(SequenceFileReader);
+};
+class SequenceFileDatasetOp : public DatasetOpKernel {
+ public:
+ using DatasetOpKernel::DatasetOpKernel;
+ explicit SequenceFileDatasetOp(OpKernelConstruction* ctx)
+ : DatasetOpKernel(ctx) {
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
+ for (const DataType& dt : output_types_) {
+ OP_REQUIRES(ctx, dt == DT_STRING,
+ errors::InvalidArgument(
+ "Each element of `output_types_` must be one of: "
+ "DT_STRING"));
+ }
+ }
+ void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override {
+ const Tensor* filenames_tensor;
+ OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor));
+ OP_REQUIRES(
+ ctx, filenames_tensor->dims() <= 1,
+ errors::InvalidArgument("`filenames` must be a scalar or a vector."));
+
+ std::vector<string> filenames;
+ filenames.reserve(filenames_tensor->NumElements());
+ for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
+ filenames.push_back(filenames_tensor->flat<string>()(i));
+ }
+
+ *output = new Dataset(ctx, filenames, output_types_);
+ }
+
+ private:
+ class Dataset : public DatasetBase {
+ public:
+ Dataset(OpKernelContext* ctx, const std::vector<string>& filenames,
+ const DataTypeVector& output_types)
+ : DatasetBase(DatasetContext(ctx)),
+ filenames_(filenames),
+ output_types_(output_types) {}
+
+ std::unique_ptr<IteratorBase> MakeIteratorInternal(
+ const string& prefix) const override {
+ return std::unique_ptr<IteratorBase>(
+ new Iterator({this, strings::StrCat(prefix, "::SequenceFile")}));
+ }
+
+ const DataTypeVector& output_dtypes() const override {
+ return output_types_;
+ }
+
+ const std::vector<PartialTensorShape>& output_shapes() const override {
+ static std::vector<PartialTensorShape>* shapes =
+ new std::vector<PartialTensorShape>({{}, {}});
+ return *shapes;
+ }
+
+ string DebugString() const override {
+ return "SequenceFileDatasetOp::Dataset";
+ }
+
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ Node* filenames = nullptr;
+ TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
+ TF_RETURN_IF_ERROR(b->AddDataset(this, {filenames}, output));
+ return Status::OK();
+ }
+
+ private:
+ class Iterator : public DatasetIterator<Dataset> {
+ public:
+ explicit Iterator(const Params& params)
+ : DatasetIterator<Dataset>(params) {}
+
+ Status GetNextInternal(IteratorContext* ctx,
+ std::vector<Tensor>* out_tensors,
+ bool* end_of_sequence) override {
+ mutex_lock l(mu_);
+ do {
+ // We are currently processing a file, so try to read the next record.
+ if (reader_) {
+ string key, value;
+ Status status = reader_->ReadRecord(&key, &value);
+ if (!errors::IsOutOfRange(status)) {
+ TF_RETURN_IF_ERROR(status);
+
+ Tensor key_tensor(ctx->allocator({}), DT_STRING, {});
+ key_tensor.scalar<string>()() = key;
+ out_tensors->emplace_back(std::move(key_tensor));
+
+ Tensor value_tensor(ctx->allocator({}), DT_STRING, {});
+ value_tensor.scalar<string>()() = value;
+ out_tensors->emplace_back(std::move(value_tensor));
+
+ *end_of_sequence = false;
+ return Status::OK();
+ }
+ // We have reached the end of the current file, so maybe
+ // move on to next file.
+ ResetStreamsLocked();
+ ++current_file_index_;
+ }
+
+ // Iteration ends when there are no more files to process.
+ if (current_file_index_ == dataset()->filenames_.size()) {
+ *end_of_sequence = true;
+ return Status::OK();
+ }
+
+ TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
+ } while (true);
+ }
+
+ protected:
+ Status SaveInternal(IteratorStateWriter* writer) override {
+ return errors::Unimplemented("SaveInternal is currently not supported");
+ }
+
+ Status RestoreInternal(IteratorContext* ctx,
+ IteratorStateReader* reader) override {
+ return errors::Unimplemented(
+ "RestoreInternal is currently not supported");
+ }
+
+ private:
+ // Sets up SequenceFile streams to read from the topic at
+ // `current_file_index_`.
+ Status SetupStreamsLocked(Env* env) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
+ if (current_file_index_ >= dataset()->filenames_.size()) {
+ return errors::InvalidArgument(
+ "current_file_index_:", current_file_index_,
+ " >= filenames_.size():", dataset()->filenames_.size());
+ }
+
+ // Actually move on to next file.
+ const string& filename = dataset()->filenames_[current_file_index_];
+ TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename, &file_));
+ reader_.reset(new SequenceFileReader(file_.get()));
+ return reader_->ReadHeader();
+ }
+
+ // Resets all Hadoop SequenceFile streams.
+ void ResetStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
+ reader_.reset();
+ file_.reset();
+ }
+
+ mutex mu_;
+ size_t current_file_index_ GUARDED_BY(mu_) = 0;
+ std::unique_ptr<RandomAccessFile> file_ GUARDED_BY(mu_);
+ std::unique_ptr<SequenceFileReader> reader_ GUARDED_BY(mu_);
+ };
+
+ const std::vector<string> filenames_;
+ const DataTypeVector output_types_;
+ };
+ DataTypeVector output_types_;
+};
+} // namespace
+
+REGISTER_KERNEL_BUILDER(Name("SequenceFileDataset").Device(DEVICE_CPU),
+ SequenceFileDatasetOp);
+
+} // namespace tensorflow
diff --git a/tensorflow/contrib/lite/delegates/eager/constants.h b/tensorflow/contrib/hadoop/ops/dataset_ops.cc
index 7ed6ab7552..66ad549b47 100644
--- a/tensorflow/contrib/lite/delegates/eager/constants.h
+++ b/tensorflow/contrib/hadoop/ops/dataset_ops.cc
@@ -12,18 +12,18 @@ 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.
==============================================================================*/
-#ifndef TENSORFLOW_CONTRIB_LITE_DELEGATES_EAGER_CONSTANTS_H_
-#define TENSORFLOW_CONTRIB_LITE_DELEGATES_EAGER_CONSTANTS_H_
-namespace tflite {
-namespace eager {
+#include "tensorflow/core/framework/common_shape_fns.h"
+#include "tensorflow/core/framework/op.h"
+#include "tensorflow/core/framework/shape_inference.h"
-// The prefix of Eager op custom code.
-// This will be matched agains the `custom_code` field in `OperatorCode`
-// Flatbuffer Table.
-constexpr char kCustomCodePrefix[] = "Eager";
+namespace tensorflow {
-} // namespace eager
-} // namespace tflite
+REGISTER_OP("SequenceFileDataset")
+ .Input("filenames: string")
+ .Output("handle: variant")
+ .Attr("output_types: list(type) >= 1")
+ .SetIsStateful()
+ .SetShapeFn(shape_inference::ScalarShape);
-#endif // TENSORFLOW_CONTRIB_LITE_DELEGATES_EAGER_CONSTANTS_H_
+} // namespace tensorflow
diff --git a/tensorflow/contrib/hadoop/python/kernel_tests/hadoop_test.py b/tensorflow/contrib/hadoop/python/kernel_tests/hadoop_test.py
new file mode 100644
index 0000000000..d796e43d87
--- /dev/null
+++ b/tensorflow/contrib/hadoop/python/kernel_tests/hadoop_test.py
@@ -0,0 +1,66 @@
+# 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 SequenceFileDataset."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import os
+
+from tensorflow.contrib.hadoop.python.ops import hadoop_dataset_ops
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import errors
+from tensorflow.python.platform import resource_loader
+from tensorflow.python.platform import test
+
+
+class SequenceFileDatasetTest(test.TestCase):
+
+ def test_sequence_file_dataset(self):
+ """Test case for SequenceFileDataset.
+
+ The file is generated with `org.apache.hadoop.io.Text` for key/value.
+ There are 25 records in the file with the format of:
+ key = XXX
+ value = VALUEXXX
+ where XXX is replaced as the line number (starts with 001).
+ """
+ filename = os.path.join(resource_loader.get_data_files_path(),
+ "testdata", "string.seq")
+
+ filenames = constant_op.constant([filename], dtypes.string)
+ num_repeats = 2
+
+ dataset = hadoop_dataset_ops.SequenceFileDataset(filenames).repeat(
+ num_repeats)
+ iterator = dataset.make_initializable_iterator()
+ init_op = iterator.initializer
+ get_next = iterator.get_next()
+
+ with self.test_session() as sess:
+ sess.run(init_op)
+ for _ in range(num_repeats): # Dataset is repeated.
+ for i in range(25): # 25 records.
+ v0 = b"%03d" % (i + 1)
+ v1 = b"VALUE%03d" % (i + 1)
+ self.assertEqual((v0, v1), sess.run(get_next))
+ with self.assertRaises(errors.OutOfRangeError):
+ sess.run(get_next)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/contrib/hadoop/python/kernel_tests/testdata/string.seq b/tensorflow/contrib/hadoop/python/kernel_tests/testdata/string.seq
new file mode 100755
index 0000000000..b7175338af
--- /dev/null
+++ b/tensorflow/contrib/hadoop/python/kernel_tests/testdata/string.seq
Binary files differ
diff --git a/tensorflow/contrib/hadoop/python/ops/hadoop_dataset_ops.py b/tensorflow/contrib/hadoop/python/ops/hadoop_dataset_ops.py
new file mode 100644
index 0000000000..6e0e628655
--- /dev/null
+++ b/tensorflow/contrib/hadoop/python/ops/hadoop_dataset_ops.py
@@ -0,0 +1,75 @@
+# 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.
+# ==============================================================================
+"""SequenceFile Dataset."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.contrib.hadoop.python.ops import gen_dataset_ops
+from tensorflow.contrib.hadoop.python.ops import hadoop_op_loader # pylint: disable=unused-import
+from tensorflow.python.data.ops.dataset_ops import Dataset
+from tensorflow.python.data.util import nest
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import ops
+from tensorflow.python.framework import tensor_shape
+
+
+class SequenceFileDataset(Dataset):
+ """A Sequence File Dataset that reads the sequence file."""
+
+ def __init__(self, filenames):
+ """Create a `SequenceFileDataset`.
+
+ `SequenceFileDataset` allows a user to read data from a hadoop sequence
+ file. A sequence file consists of (key value) pairs sequentially. At
+ the moment, `org.apache.hadoop.io.Text` is the only serialization type
+ being supported, and there is no compression support.
+
+ For example:
+
+ ```python
+ dataset = tf.contrib.hadoop.SequenceFileDataset("/foo/bar.seq")
+ iterator = dataset.make_one_shot_iterator()
+ next_element = iterator.get_next()
+ # Prints the (key, value) pairs inside a hadoop sequence file.
+ while True:
+ try:
+ print(sess.run(next_element))
+ except tf.errors.OutOfRangeError:
+ break
+ ```
+
+ Args:
+ filenames: A `tf.string` tensor containing one or more filenames.
+ """
+ super(SequenceFileDataset, self).__init__()
+ self._filenames = ops.convert_to_tensor(
+ filenames, dtype=dtypes.string, name="filenames")
+
+ def _as_variant_tensor(self):
+ return gen_dataset_ops.sequence_file_dataset(
+ self._filenames, nest.flatten(self.output_types))
+
+ @property
+ def output_classes(self):
+ return ops.Tensor, ops.Tensor
+
+ @property
+ def output_shapes(self):
+ return (tensor_shape.TensorShape([]), tensor_shape.TensorShape([]))
+
+ @property
+ def output_types(self):
+ return dtypes.string, dtypes.string
diff --git a/tensorflow/contrib/hadoop/python/ops/hadoop_op_loader.py b/tensorflow/contrib/hadoop/python/ops/hadoop_op_loader.py
new file mode 100644
index 0000000000..6dbf1253f3
--- /dev/null
+++ b/tensorflow/contrib/hadoop/python/ops/hadoop_op_loader.py
@@ -0,0 +1,24 @@
+# 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.
+# ==============================================================================
+"""Python helper for loading hadoop ops and kernels."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.contrib.util import loader
+from tensorflow.python.platform import resource_loader
+
+_dataset_ops = loader.load_op_library(
+ resource_loader.get_path_to_datafile("../../_dataset_ops.so"))
diff --git a/tensorflow/contrib/image/kernels/image_ops.cc b/tensorflow/contrib/image/kernels/image_ops.cc
index 022e17d139..693724b457 100644
--- a/tensorflow/contrib/image/kernels/image_ops.cc
+++ b/tensorflow/contrib/image/kernels/image_ops.cc
@@ -71,6 +71,7 @@ class ImageProjectiveTransform : public OpKernel {
void Compute(OpKernelContext* ctx) override {
const Tensor& images_t = ctx->input(0);
const Tensor& transform_t = ctx->input(1);
+ const Tensor& shape_t = ctx->input(2);
OP_REQUIRES(ctx, images_t.shape().dims() == 4,
errors::InvalidArgument("Input images must have rank 4"));
OP_REQUIRES(ctx,
@@ -81,11 +82,28 @@ class ImageProjectiveTransform : public OpKernel {
ProjectiveGenerator<Device, T>::kNumParameters),
errors::InvalidArgument(
"Input transform should be num_images x 8 or 1 x 8"));
- auto images = images_t.tensor<T, 4>();
- auto transform = transform_t.matrix<float>();
+ OP_REQUIRES(ctx, shape_t.dims() == 1,
+ errors::InvalidArgument("output shape must be 1-dimensional",
+ shape_t.shape().DebugString()));
+ OP_REQUIRES(ctx, shape_t.NumElements() == 2,
+ errors::InvalidArgument("output shape must have two elements",
+ shape_t.shape().DebugString()));
+ auto shape_vec = shape_t.vec<int32>();
+ int32 out_height = shape_vec(0);
+ int32 out_width = shape_vec(1);
+ OP_REQUIRES(ctx, out_height > 0 && out_width > 0,
+ errors::InvalidArgument("output dimensions must be positive"));
+
Tensor* output_t;
- OP_REQUIRES_OK(ctx, ctx->allocate_output(0, images_t.shape(), &output_t));
+ OP_REQUIRES_OK(ctx, ctx->allocate_output(
+ 0,
+ TensorShape({images_t.dim_size(0), out_height,
+ out_width, images_t.dim_size(3)}),
+ &output_t));
auto output = output_t->tensor<T, 4>();
+ auto images = images_t.tensor<T, 4>();
+ auto transform = transform_t.matrix<float>();
+
(FillProjectiveTransform<Device, T>(interpolation_))(
ctx->eigen_device<Device>(), &output, images, transform);
}
@@ -129,10 +147,11 @@ TF_CALL_double(DECLARE_FUNCTOR);
} // end namespace functor
-#define REGISTER(TYPE) \
- REGISTER_KERNEL_BUILDER(Name("ImageProjectiveTransform") \
- .Device(DEVICE_GPU) \
- .TypeConstraint<TYPE>("dtype"), \
+#define REGISTER(TYPE) \
+ REGISTER_KERNEL_BUILDER(Name("ImageProjectiveTransform") \
+ .Device(DEVICE_GPU) \
+ .TypeConstraint<TYPE>("dtype") \
+ .HostMemory("output_shape"), \
ImageProjectiveTransform<GPUDevice, TYPE>)
TF_CALL_uint8(REGISTER);
diff --git a/tensorflow/contrib/image/kernels/image_ops.h b/tensorflow/contrib/image/kernels/image_ops.h
index 209aa24548..6b63eed130 100644
--- a/tensorflow/contrib/image/kernels/image_ops.h
+++ b/tensorflow/contrib/image/kernels/image_ops.h
@@ -167,7 +167,7 @@ struct FillProjectiveTransform {
void operator()(const Device& device, OutputType* output,
const InputType& images,
const TransformsType& transform) const {
- output->device(device) = images.generate(
+ output->device(device) = output->generate(
ProjectiveGenerator<Device, T>(images, transform, interpolation_));
}
};
diff --git a/tensorflow/contrib/image/ops/image_ops.cc b/tensorflow/contrib/image/ops/image_ops.cc
index e59f1bf844..4969ac58f9 100644
--- a/tensorflow/contrib/image/ops/image_ops.cc
+++ b/tensorflow/contrib/image/ops/image_ops.cc
@@ -19,23 +19,66 @@ limitations under the License.
namespace tensorflow {
+using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
+namespace {
+
+// Sets output[0] to shape [batch_dim,height,width,channel_dim], where
+// height and width come from the size_tensor.
+Status SetOutputToSizedImage(InferenceContext* c, DimensionHandle batch_dim,
+ int size_input_idx, DimensionHandle channel_dim) {
+ // Verify shape of size input.
+ ShapeHandle size;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(size_input_idx), 1, &size));
+ DimensionHandle unused;
+ TF_RETURN_IF_ERROR(c->WithValue(c->Dim(size, 0), 2, &unused));
+
+ // Get size values from the size tensor.
+ const Tensor* size_tensor = c->input_tensor(size_input_idx);
+ DimensionHandle width;
+ DimensionHandle height;
+ if (size_tensor == nullptr) {
+ width = c->UnknownDim();
+ height = c->UnknownDim();
+ } else {
+ // TODO(petewarden) - Remove once we have constant evaluation in C++ only.
+ if (size_tensor->dtype() != DT_INT32) {
+ return errors::InvalidArgument(
+ "Bad size input type for SetOutputToSizedImage: Expected DT_INT32 "
+ "but got ",
+ DataTypeString(size_tensor->dtype()), " for input #", size_input_idx,
+ " in ", c->DebugString());
+ }
+ auto vec = size_tensor->vec<int32>();
+ height = c->MakeDim(vec(0));
+ width = c->MakeDim(vec(1));
+ }
+ c->set_output(0, c->MakeShape({batch_dim, height, width, channel_dim}));
+ return Status::OK();
+}
+
+// TODO(qyu): Move this to core/framework/common_shape_fns.h
+Status ResizeShapeFn(InferenceContext* c) {
+ ShapeHandle input;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input));
+ return SetOutputToSizedImage(c, c->Dim(input, 0), 2 /* size_input_idx */,
+ c->Dim(input, 3));
+}
+
+} // namespace
+
// TODO(ringwalt): Add a "fill_mode" argument with "constant", "mirror", etc.
// TODO(ringwalt): Add a "fill_constant" argument for constant mode (default 0).
-// TODO(ringwalt): Add an "output_shape" argument. This is sufficient to
-// implement "same" and "valid" modes in the Python function.
REGISTER_OP("ImageProjectiveTransform")
.Input("images: dtype")
.Input("transforms: float32")
+ .Input("output_shape: int32")
.Attr("dtype: {uint8, int32, int64, float16, float32, float64}")
.Attr("interpolation: string")
.Output("transformed_images: dtype")
- .SetShapeFn([](InferenceContext* c) {
- c->set_output(0, c->input(0));
- return Status::OK();
- })
+ .SetShapeFn(ResizeShapeFn)
.Doc(R"doc(
Applies the given transform to each of the images.
@@ -49,7 +92,7 @@ If one row of `transforms` is `[a0, a1, a2, b0, b1, b2, c0, c1]`, then it maps
the *output* point `(x, y)` to a transformed *input* point
`(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where
`k = c0 x + c1 y + 1`. If the transformed point lays outside of the input
-image, the output pixel is set to 0. The output is the same size as the input,
+image, the output pixel is set to 0.
images: 4D `Tensor`, input image(s) in NHWC format.
transforms: 2D `Tensor`, projective transform(s) to apply to the image(s).
diff --git a/tensorflow/contrib/image/python/kernel_tests/image_ops_test.py b/tensorflow/contrib/image/python/kernel_tests/image_ops_test.py
index 62a22dcf34..f588eae923 100644
--- a/tensorflow/contrib/image/python/kernel_tests/image_ops_test.py
+++ b/tensorflow/contrib/image/python/kernel_tests/image_ops_test.py
@@ -27,6 +27,7 @@ from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import random_ops
from tensorflow.python.platform import googletest
_DTYPES = set(
@@ -194,6 +195,19 @@ class ImageOpsTest(test_util.TensorFlowTestCase):
[0.0, 149, 233, 149, 0.0],
[0.0, 0.0, 87., 0.0, 0.0]])
+ def test_rotate_static_shape(self):
+ image = array_ops.diag([1., 2., 3.])
+ result = image_ops.rotate(
+ image, random_ops.random_uniform((), -1, 1), interpolation="BILINEAR")
+ self.assertEqual(image.get_shape(), result.get_shape())
+
+ def test_transform_static_output_shape(self):
+ image = constant_op.constant([[1., 2.], [3., 4.]])
+ result = image_ops.transform(
+ image, random_ops.random_uniform([8], -1, 1),
+ output_shape=constant_op.constant([3, 5]))
+ self.assertAllEqual([3, 5], result.get_shape())
+
def _test_grad(self, shape_to_test):
with self.test_session():
test_image_shape = shape_to_test
@@ -213,10 +227,40 @@ class ImageOpsTest(test_util.TensorFlowTestCase):
x_init_value=test_image)
self.assertLess(left_err, 1e-10)
+ def _test_grad_different_shape(self, input_shape, output_shape):
+ with self.test_session():
+ test_image_shape = input_shape
+ test_image = np.random.randn(*test_image_shape)
+ test_image_tensor = constant_op.constant(
+ test_image, shape=test_image_shape)
+ test_transform = image_ops.angles_to_projective_transforms(
+ np.pi / 2, 4, 4)
+
+ if len(output_shape) == 2:
+ resize_shape = output_shape
+ elif len(output_shape) == 3:
+ resize_shape = output_shape[0:2]
+ elif len(output_shape) == 4:
+ resize_shape = output_shape[1:3]
+ output = image_ops.transform(
+ images=test_image_tensor,
+ transforms=test_transform,
+ output_shape=resize_shape)
+ left_err = gradient_checker.compute_gradient_error(
+ test_image_tensor,
+ test_image_shape,
+ output,
+ output_shape,
+ x_init_value=test_image)
+ self.assertLess(left_err, 1e-10)
+
def test_grad(self):
self._test_grad([16, 16])
self._test_grad([4, 12, 12])
self._test_grad([3, 4, 12, 12])
+ self._test_grad_different_shape([16, 16], [8, 8])
+ self._test_grad_different_shape([4, 12, 3], [8, 24, 3])
+ self._test_grad_different_shape([3, 4, 12, 3], [3, 8, 24, 3])
class BipartiteMatchTest(test_util.TensorFlowTestCase):
diff --git a/tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py b/tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py
index 1939caaa2d..3054128979 100644
--- a/tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py
+++ b/tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py
@@ -26,6 +26,7 @@ from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
+from tensorflow.python.ops import array_ops
from tensorflow.python.ops import clip_ops
from tensorflow.python.ops import gradients
from tensorflow.python.ops import math_ops
@@ -226,6 +227,81 @@ class InterpolateSplineTest(test_util.TensorFlowTestCase):
interp_val = sess.run(interpolator)
self.assertAllClose(interp_val[0, :, 0], target_interpolation)
+ def test_nd_linear_interpolation_unspecified_shape(self):
+ """Ensure that interpolation supports dynamic batch_size and num_points."""
+
+ tp = _QuadraticPlusSinProblemND()
+ (query_points, _, train_points,
+ train_values) = tp.get_problem(dtype='float64')
+
+ # Construct placeholders such that the batch size, number of train points,
+ # and number of query points are not known at graph construction time.
+ feature_dim = query_points.shape[-1]
+ value_dim = train_values.shape[-1]
+ train_points_ph = array_ops.placeholder(
+ dtype=train_points.dtype, shape=[None, None, feature_dim])
+ train_values_ph = array_ops.placeholder(
+ dtype=train_values.dtype, shape=[None, None, value_dim])
+ query_points_ph = array_ops.placeholder(
+ dtype=query_points.dtype, shape=[None, None, feature_dim])
+
+ order = 1
+ reg_weight = 0.01
+
+ interpolator = interpolate_spline.interpolate_spline(
+ train_points_ph, train_values_ph, query_points_ph, order, reg_weight)
+
+ target_interpolation = tp.HARDCODED_QUERY_VALUES[(order, reg_weight)]
+ target_interpolation = np.array(target_interpolation)
+ with self.test_session() as sess:
+
+ (train_points_value, train_values_value, query_points_value) = sess.run(
+ [train_points, train_values, query_points])
+
+ interp_val = sess.run(
+ interpolator,
+ feed_dict={
+ train_points_ph: train_points_value,
+ train_values_ph: train_values_value,
+ query_points_ph: query_points_value
+ })
+ self.assertAllClose(interp_val[0, :, 0], target_interpolation)
+
+ def test_fully_unspecified_shape(self):
+ """Ensure that erreor is thrown when input/output dim unspecified."""
+
+ tp = _QuadraticPlusSinProblemND()
+ (query_points, _, train_points,
+ train_values) = tp.get_problem(dtype='float64')
+
+ # Construct placeholders such that the batch size, number of train points,
+ # and number of query points are not known at graph construction time.
+ feature_dim = query_points.shape[-1]
+ value_dim = train_values.shape[-1]
+ train_points_ph = array_ops.placeholder(
+ dtype=train_points.dtype, shape=[None, None, feature_dim])
+ train_points_ph_invalid = array_ops.placeholder(
+ dtype=train_points.dtype, shape=[None, None, None])
+ train_values_ph = array_ops.placeholder(
+ dtype=train_values.dtype, shape=[None, None, value_dim])
+ train_values_ph_invalid = array_ops.placeholder(
+ dtype=train_values.dtype, shape=[None, None, None])
+ query_points_ph = array_ops.placeholder(
+ dtype=query_points.dtype, shape=[None, None, feature_dim])
+
+ order = 1
+ reg_weight = 0.01
+
+ with self.assertRaises(ValueError):
+ _ = interpolate_spline.interpolate_spline(
+ train_points_ph_invalid, train_values_ph, query_points_ph, order,
+ reg_weight)
+
+ with self.assertRaises(ValueError):
+ _ = interpolate_spline.interpolate_spline(
+ train_points_ph, train_values_ph_invalid, query_points_ph, order,
+ reg_weight)
+
def test_interpolation_gradient(self):
"""Make sure that backprop can run. Correctness of gradients is assumed.
diff --git a/tensorflow/contrib/image/python/ops/image_ops.py b/tensorflow/contrib/image/python/ops/image_ops.py
index 86b0ffe9a0..e7a09041ad 100644
--- a/tensorflow/contrib/image/python/ops/image_ops.py
+++ b/tensorflow/contrib/image/python/ops/image_ops.py
@@ -23,6 +23,7 @@ from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
+from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import linalg_ops
@@ -40,6 +41,9 @@ ops.RegisterShape("ImageConnectedComponents")(common_shapes.call_cpp_shape_fn)
ops.RegisterShape("ImageProjectiveTransform")(common_shapes.call_cpp_shape_fn)
+# TODO(ringwalt): Support a "reshape" (name used by SciPy) or "expand" (name
+# used by PIL, maybe more readable) mode, which determines the correct
+# output_shape and translation for the transform.
def rotate(images, angles, interpolation="NEAREST", name=None):
"""Rotate image(s) counterclockwise by the passed angle(s) in radians.
@@ -213,7 +217,11 @@ def translations_to_projective_transforms(translations, name=None):
axis=1)
-def transform(images, transforms, interpolation="NEAREST", name=None):
+def transform(images,
+ transforms,
+ interpolation="NEAREST",
+ output_shape=None,
+ name=None):
"""Applies the given transform(s) to the image(s).
Args:
@@ -230,6 +238,10 @@ def transform(images, transforms, interpolation="NEAREST", name=None):
the transform mapping input points to output points. Note that gradients
are not backpropagated into transformation parameters.
interpolation: Interpolation mode. Supported values: "NEAREST", "BILINEAR".
+ output_shape: Output dimesion after the transform, [height, width].
+ If None, output is the same size as input image.
+
+ name: The name of the op.
Returns:
Image(s) with the same type and shape as `images`, with the given
@@ -238,6 +250,7 @@ def transform(images, transforms, interpolation="NEAREST", name=None):
Raises:
TypeError: If `image` is an invalid type.
+ ValueError: If output shape is not 1-D int32 Tensor.
"""
with ops.name_scope(name, "transform"):
image_or_images = ops.convert_to_tensor(images, name="images")
@@ -256,6 +269,17 @@ def transform(images, transforms, interpolation="NEAREST", name=None):
else:
raise TypeError("Images should have rank between 2 and 4.")
+ if output_shape is None:
+ output_shape = tensor_util.constant_value(
+ array_ops.shape(images)[1:3]) or array_ops.shape(images)[1:3]
+
+ output_shape = ops.convert_to_tensor(
+ output_shape, dtypes.int32, name="output_shape")
+
+ if not output_shape.get_shape().is_compatible_with([2]):
+ raise ValueError("output_shape must be a 1-D Tensor of 2 elements: "
+ "new_height, new_width")
+
if len(transform_or_transforms.get_shape()) == 1:
transforms = transform_or_transforms[None]
elif transform_or_transforms.get_shape().ndims is None:
@@ -265,8 +289,12 @@ def transform(images, transforms, interpolation="NEAREST", name=None):
transforms = transform_or_transforms
else:
raise TypeError("Transforms should have rank 1 or 2.")
+
output = gen_image_ops.image_projective_transform(
- images, transforms, interpolation=interpolation.upper())
+ images,
+ output_shape=output_shape,
+ transforms=transforms,
+ interpolation=interpolation.upper())
if len(image_or_images.get_shape()) == 2:
return output[0, :, :, 0]
elif len(image_or_images.get_shape()) == 3:
@@ -376,14 +404,6 @@ def _image_projective_transform_grad(op, grad):
if image_or_images.dtype.base_dtype not in _IMAGE_DTYPES:
raise TypeError("Invalid dtype %s." % image_or_images.dtype)
- if len(image_or_images.get_shape()) == 2:
- images = image_or_images[None, :, :, None]
- elif len(image_or_images.get_shape()) == 3:
- images = image_or_images[None, :, :, :]
- elif len(image_or_images.get_shape()) == 4:
- images = image_or_images
- else:
- raise TypeError("Images should have rank between 2 and 4")
if len(transform_or_transforms.get_shape()) == 1:
transforms = transform_or_transforms[None]
elif len(transform_or_transforms.get_shape()) == 2:
@@ -396,13 +416,11 @@ def _image_projective_transform_grad(op, grad):
inverse = linalg_ops.matrix_inverse(transforms)
transforms = matrices_to_flat_transforms(inverse)
output = gen_image_ops.image_projective_transform(
- grad, transforms, interpolation=interpolation)
- if len(image_or_images.get_shape()) == 2:
- return [output[0, :, :, 0], None]
- elif len(image_or_images.get_shape()) == 3:
- return [output[0, :, :, :], None]
- else:
- return [output, None]
+ images=grad,
+ transforms=transforms,
+ output_shape=array_ops.shape(image_or_images)[1:3],
+ interpolation=interpolation)
+ return [output, None, None]
def bipartite_match(distance_mat,
diff --git a/tensorflow/contrib/image/python/ops/interpolate_spline.py b/tensorflow/contrib/image/python/ops/interpolate_spline.py
index daf8c56456..f0b408faa3 100644
--- a/tensorflow/contrib/image/python/ops/interpolate_spline.py
+++ b/tensorflow/contrib/image/python/ops/interpolate_spline.py
@@ -17,9 +17,6 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import numpy as np
-
-from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
@@ -95,10 +92,22 @@ def _solve_interpolation(train_points, train_values, order,
Returns:
w: `[b, n, k]` weights on each interpolation center
v: `[b, d, k]` weights on each input dimension
+ Raises:
+ ValueError: if d or k is not fully specified.
"""
- b, n, d = train_points.get_shape().as_list()
- _, _, k = train_values.get_shape().as_list()
+ # These dimensions are set dynamically at runtime.
+ b, n, _ = array_ops.unstack(array_ops.shape(train_points), num=3)
+
+ d = train_points.shape[-1]
+ if d.value is None:
+ raise ValueError('The dimensionality of the input points (d) must be '
+ 'statically-inferrable.')
+
+ k = train_values.shape[-1]
+ if k.value is None:
+ raise ValueError('The dimensionality of the output values (k) must be '
+ 'statically-inferrable.')
# First, rename variables so that the notation (c, f, w, v, A, B, etc.)
# follows https://en.wikipedia.org/wiki/Polyharmonic_spline.
@@ -113,14 +122,12 @@ def _solve_interpolation(train_points, train_values, order,
matrix_a = _phi(_pairwise_squared_distance_matrix(c), order) # [b, n, n]
if regularization_weight > 0:
- batch_identity_matrix = np.expand_dims(np.eye(n), 0)
- batch_identity_matrix = constant_op.constant(
- batch_identity_matrix, dtype=train_points.dtype)
-
+ batch_identity_matrix = array_ops.expand_dims(
+ linalg_ops.eye(n, dtype=c.dtype), 0)
matrix_a += regularization_weight * batch_identity_matrix
# Append ones to the feature values for the bias term in the linear model.
- ones = array_ops.ones([b, n, 1], train_points.dtype)
+ ones = array_ops.ones_like(c[..., :1], dtype=c.dtype)
matrix_b = array_ops.concat([c, ones], 2) # [b, n, d + 1]
# [b, n + d + 1, n]
@@ -164,9 +171,6 @@ def _apply_interpolation(query_points, train_points, w, v, order):
Polyharmonic interpolation evaluated at points defined in query_points.
"""
- batch_size = train_points.get_shape()[0].value
- num_query_points = query_points.get_shape()[1].value
-
# First, compute the contribution from the rbf term.
pairwise_dists = _cross_squared_distance_matrix(query_points, train_points)
phi_pairwise_dists = _phi(pairwise_dists, order)
@@ -177,7 +181,7 @@ def _apply_interpolation(query_points, train_points, w, v, order):
# Pad query_points with ones, for the bias term in the linear model.
query_points_pad = array_ops.concat([
query_points,
- array_ops.ones([batch_size, num_query_points, 1], train_points.dtype)
+ array_ops.ones_like(query_points[..., :1], train_points.dtype)
], 2)
linear_term = math_ops.matmul(query_points_pad, v)
@@ -251,6 +255,9 @@ def interpolate_spline(train_points,
Note the interpolation procedure is differentiable with respect to all inputs
besides the order parameter.
+ We support dynamically-shaped inputs, where batch_size, n, and m are None
+ at graph construction time. However, d and k must be known.
+
Args:
train_points: `[batch_size, n, d]` float `Tensor` of n d-dimensional
locations. These do not need to be regularly-spaced.
diff --git a/tensorflow/contrib/image/python/ops/sparse_image_warp.py b/tensorflow/contrib/image/python/ops/sparse_image_warp.py
index 54a215d6db..1ea8f705b7 100644
--- a/tensorflow/contrib/image/python/ops/sparse_image_warp.py
+++ b/tensorflow/contrib/image/python/ops/sparse_image_warp.py
@@ -112,10 +112,10 @@ def sparse_image_warp(image,
Apply a non-linear warp to the image, where the warp is specified by
the source and destination locations of a (potentially small) number of
control points. First, we use a polyharmonic spline
- (@{tf.contrib.image.interpolate_spline}) to interpolate the displacements
+ (`tf.contrib.image.interpolate_spline`) to interpolate the displacements
between the corresponding control points to a dense flow field.
Then, we warp the image using this dense flow field
- (@{tf.contrib.image.dense_image_warp}).
+ (`tf.contrib.image.dense_image_warp`).
Let t index our control points. For regularization_weight=0, we have:
warped_image[b, dest_control_point_locations[b, t, 0],
@@ -126,7 +126,7 @@ def sparse_image_warp(image,
For regularization_weight > 0, this condition is met approximately, since
regularized interpolation trades off smoothness of the interpolant vs.
reconstruction of the interpolant at the control points.
- See @{tf.contrib.image.interpolate_spline} for further documentation of the
+ See `tf.contrib.image.interpolate_spline` for further documentation of the
interpolation_order and regularization_weight arguments.
diff --git a/tensorflow/contrib/integrate/__init__.py b/tensorflow/contrib/integrate/__init__.py
index 694f0c14bd..3c37f152e5 100644
--- a/tensorflow/contrib/integrate/__init__.py
+++ b/tensorflow/contrib/integrate/__init__.py
@@ -15,7 +15,9 @@
"""Integration and ODE solvers.
-See the @{$python/contrib.integrate} guide.
+See the
+[Contrib Integrate](https://tensorflow.org/api_guides/python/contrib.integrate)
+guide.
@@odeint
@@odeint_fixed
diff --git a/tensorflow/contrib/integrate/python/ops/odes.py b/tensorflow/contrib/integrate/python/ops/odes.py
index 61f78febfc..7b7ac4f347 100644
--- a/tensorflow/contrib/integrate/python/ops/odes.py
+++ b/tensorflow/contrib/integrate/python/ops/odes.py
@@ -73,7 +73,7 @@ def _scaled_dot_product(scale, xs, ys, name=None):
# _possibly_nonzero lets us avoid wasted computation.
return math_ops.add_n(
[(scale * x) * y for x, y in zip(xs, ys)
- if _possibly_nonzero(x) or _possibly_nonzero(y)],
+ if _possibly_nonzero(x) and _possibly_nonzero(y)],
name=scope)
@@ -122,7 +122,7 @@ def _runge_kutta_step(func,
yi = y0 + _scaled_dot_product(dt_cast, beta_i, k)
k.append(func(yi, ti))
- if not (tableau.c_sol[-1] == 0 and tableau.c_sol == tableau.beta[-1]):
+ if not (tableau.c_sol[-1] == 0 and tableau.c_sol[:-1] == tableau.beta[-1]):
# This property (true for Dormand-Prince) lets us save a few FLOPs.
yi = y0 + _scaled_dot_product(dt_cast, tableau.c_sol, k)
diff --git a/tensorflow/contrib/kafka/kernels/kafka_dataset_ops.cc b/tensorflow/contrib/kafka/kernels/kafka_dataset_ops.cc
index 2638b25ec4..d0ea961473 100644
--- a/tensorflow/contrib/kafka/kernels/kafka_dataset_ops.cc
+++ b/tensorflow/contrib/kafka/kernels/kafka_dataset_ops.cc
@@ -15,7 +15,7 @@ limitations under the License.
#include "tensorflow/core/framework/dataset.h"
-#include "src-cpp/rdkafkacpp.h"
+#include "rdkafkacpp.h"
namespace tensorflow {
@@ -52,12 +52,12 @@ class KafkaDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::vector<string> topics,
const string& servers, const string& group, const bool eof,
const int64 timeout)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
topics_(std::move(topics)),
servers_(servers),
group_(group),
@@ -84,7 +84,8 @@ class KafkaDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "KafkaDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* topics = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(topics_, &topics));
diff --git a/tensorflow/contrib/keras/__init__.py b/tensorflow/contrib/keras/__init__.py
index a162f0cb58..cecf1ddcdb 100644
--- a/tensorflow/contrib/keras/__init__.py
+++ b/tensorflow/contrib/keras/__init__.py
@@ -15,7 +15,7 @@
# ==============================================================================
"""Implementation of the Keras API meant to be a high-level API for TensorFlow.
-This module an alias for @{tf.keras}, for backwards compatibility.
+This module an alias for `tf.keras`, for backwards compatibility.
Detailed documentation and user guides are also available at
[keras.io](https://keras.io).
diff --git a/tensorflow/contrib/kernel_methods/README.md b/tensorflow/contrib/kernel_methods/README.md
index 44ed9670a0..1bce3277ff 100644
--- a/tensorflow/contrib/kernel_methods/README.md
+++ b/tensorflow/contrib/kernel_methods/README.md
@@ -21,13 +21,15 @@ Currently, there is a [RandomFourierFeatureMapper](https://www.tensorflow.org/co
output. More mappers are on the way.
## Kernel-based Estimators
-These are estimators inheriting from the @{tf.contrib.learn.Estimator} class and
-use kernel mappers internally to discover non-linearities in the data. These
-canned estimators map their input features using kernel mapper Ops and then
-apply linear models to the mapped features. Combining kernel mappers with linear
-models and different loss functions leads to a variety of models: linear and
-non-linear SVMs, linear regression (with and without kernels) and (multinomial)
-logistic regression (with and without kernels).
+
+These estimators inherit from the
+[`tf.contrib.learn.Estimator`](https://www.tensorflow.org/code/tensorflow/contrib/learn/python/learn/estimators/estimator.py)
+class and use kernel mappers internally to discover non-linearities in the
+data. These canned estimators map their input features using kernel mapper
+Ops and then apply linear models to the mapped features. Combining kernel
+mappers with linear models and different loss functions leads to a variety of
+models: linear and non-linear SVMs, linear regression (with and without
+kernels) and (multinomial) logistic regression (with and without kernels).
Currently there is a [KernelLinearClassifier](https://www.tensorflow.org/code/tensorflow/contrib/kernel_methods/python/kernel_estimators.py) implemented but more pre-packaged estimators
are on the way.
diff --git a/tensorflow/contrib/kfac/examples/convnet.py b/tensorflow/contrib/kfac/examples/convnet.py
index d6b1a61b71..44e01e1aeb 100644
--- a/tensorflow/contrib/kfac/examples/convnet.py
+++ b/tensorflow/contrib/kfac/examples/convnet.py
@@ -202,7 +202,7 @@ def minimize_loss_single_machine(loss,
accuracy: 0-D Tensor. Accuracy of classifier on current minibatch.
layer_collection: LayerCollection instance describing model architecture.
Used by K-FAC to construct preconditioner.
- device: string, Either '/cpu:0' or '/gpu:0'. The covaraince and invserse
+ device: string, Either '/cpu:0' or '/gpu:0'. The covariance and inverse
update ops are run on this device.
session_config: None or tf.ConfigProto. Configuration for tf.Session().
@@ -470,7 +470,7 @@ def train_mnist_single_machine(data_dir,
data_dir: string. Directory to read MNIST examples from.
num_epochs: int. Number of passes to make over the training set.
use_fake_data: bool. If True, generate a synthetic dataset.
- device: string, Either '/cpu:0' or '/gpu:0'. The covaraince and inverse
+ device: string, Either '/cpu:0' or '/gpu:0'. The covariance and inverse
update ops are run on this device.
Returns:
@@ -509,7 +509,7 @@ def train_mnist_multitower(data_dir, num_epochs, num_towers,
num_epochs: int. Number of passes to make over the training set.
num_towers: int. Number of CPUs to split inference across.
use_fake_data: bool. If True, generate a synthetic dataset.
- devices: string, Either list of CPU or GPU. The covaraince and inverse
+ devices: string, Either list of CPU or GPU. The covariance and inverse
update ops are run on this device.
Returns:
@@ -621,7 +621,7 @@ def train_mnist_distributed_sync_replicas(task_id,
data_dir: string. Directory to read MNIST examples from.
num_epochs: int. Number of passes to make over the training set.
op_strategy: `string`, Strategy to run the covariance and inverse
- ops. If op_strategy == `chief_worker` then covaraiance and inverse
+ ops. If op_strategy == `chief_worker` then covariance and inverse
update ops are run on chief worker otherwise they are run on dedicated
workers.
diff --git a/tensorflow/contrib/kfac/python/ops/estimator.py b/tensorflow/contrib/kfac/python/ops/estimator.py
index 854f885c26..323234c403 100644
--- a/tensorflow/contrib/kfac/python/ops/estimator.py
+++ b/tensorflow/contrib/kfac/python/ops/estimator.py
@@ -97,8 +97,8 @@ class FisherEstimator(object):
and to regularize the update direction by making it closer to the
gradient. (Higher damping means the update looks more like a standard
gradient update - see Tikhonov regularization.)
- layer_collection: The layer collection object, which holds the fisher
- blocks, kronecker factors, and losses associated with the
+ layer_collection: The layer collection object, which holds the Fisher
+ blocks, Kronecker factors, and losses associated with the
graph.
exps: List of floats or ints. These represent the different matrix
powers of the approximate Fisher that the FisherEstimator will be able
@@ -464,7 +464,7 @@ class FisherEstimator(object):
def _get_grads_lists_empirical(self, tensors):
# Passing in a list of loss values is better than passing in the sum as
- # the latter creates unnessesary ops on the default device
+ # the latter creates unnecessary ops on the default device
grads_flat = gradients_impl.gradients(
self._layers.eval_losses(),
nest.flatten(tensors),
diff --git a/tensorflow/contrib/kfac/python/ops/fisher_blocks.py b/tensorflow/contrib/kfac/python/ops/fisher_blocks.py
index 3a5c8eb5f9..9fa6eb7dcd 100644
--- a/tensorflow/contrib/kfac/python/ops/fisher_blocks.py
+++ b/tensorflow/contrib/kfac/python/ops/fisher_blocks.py
@@ -870,7 +870,7 @@ class ConvKFCBasicFB(InputOutputMultiTower, KroneckerProductFB):
Estimates the Fisher Information matrix's blog for a convolutional
layer.
- Consider a convoluational layer in this model with (unshared) filter matrix
+ Consider a convolutional layer in this model with (unshared) filter matrix
'w'. For a minibatch that produces inputs 'a' and output preactivations 's',
this FisherBlock estimates,
diff --git a/tensorflow/contrib/kfac/python/ops/fisher_factors.py b/tensorflow/contrib/kfac/python/ops/fisher_factors.py
index b43232dfaf..afa2fd1ca7 100644
--- a/tensorflow/contrib/kfac/python/ops/fisher_factors.py
+++ b/tensorflow/contrib/kfac/python/ops/fisher_factors.py
@@ -71,15 +71,15 @@ _MAX_NUM_OUTER_PRODUCTS_PER_COV_ROW = 1
# factor. This parameter is used only if `_SUB_SAMPLE_INPUTS` is True.
_INPUTS_TO_EXTRACT_PATCHES_FACTOR = 0.5
-# If True, then subsamples the tensor passed to compute the covaraince matrix.
+# If True, then subsamples the tensor passed to compute the covariance matrix.
_SUB_SAMPLE_OUTER_PRODUCTS = False
-# If True, then subsamples the tensor passed to compute the covaraince matrix.
+# If True, then subsamples the tensor passed to compute the covariance matrix.
_SUB_SAMPLE_INPUTS = False
# TOWER_STRATEGY can be one of "concat" or "separate". If "concat", the data
# passed to the factors from the blocks will be concatenated across towers
-# (lazilly via PartitionedTensor objects). Otherwise a tuple of tensors over
+# (lazily via PartitionedTensor objects). Otherwise a tuple of tensors over
# towers will be passed in, and the factors will iterate over this and do the
# cov computations separately for each one, averaging the results together.
TOWER_STRATEGY = "concat"
@@ -309,7 +309,7 @@ def _subsample_for_cov_computation(array, name=None):
def _random_tensor_gather(array, max_size):
- """Generates a random set of indices and gathers the value at the indcices.
+ """Generates a random set of indices and gathers the value at the indices.
Args:
array: Tensor, of shape `[batch_size, dim_2]`.
@@ -1762,8 +1762,8 @@ class FullyConnectedMultiKF(FullyConnectedKroneckerFactor):
# Might need to enforce symmetry lost due to numerical issues.
invsqrtC0 = (invsqrtC0 + array_ops.transpose(invsqrtC0)) / 2.0
- # The following line imposses the symmetry assumed by "Option 1" on C1.
- # Stangely the code can work okay with this line commented out,
+ # The following line imposes the symmetry assumed by "Option 1" on C1.
+ # Strangely the code can work okay with this line commented out,
# depending on how psd_eig is defined. I'm not sure why.
C1 = (C1 + array_ops.transpose(C1)) / 2.0
diff --git a/tensorflow/contrib/kfac/python/ops/layer_collection.py b/tensorflow/contrib/kfac/python/ops/layer_collection.py
index cbbfe7212c..43aa713edc 100644
--- a/tensorflow/contrib/kfac/python/ops/layer_collection.py
+++ b/tensorflow/contrib/kfac/python/ops/layer_collection.py
@@ -609,7 +609,7 @@ class LayerCollection(object):
outputs,
approx=None,
reuse=VARIABLE_SCOPE):
- """Registers a fully connnected layer.
+ """Registers a fully connected layer.
Args:
params: Tensor or 2-tuple of Tensors corresponding to weight and bias of
@@ -975,7 +975,7 @@ class LayerCollection(object):
block for this layer (which must have already been registered). If
"VARIABLE_SCOPE", use tf.get_variable_scope().reuse. (Note that the
word `use` here has a completely different meaning to "use in the graph"
- as it perturns to the `inputs`, `outputs`, and `num_uses` arguments.)
+ as it pertains to the `inputs`, `outputs`, and `num_uses` arguments.)
(Default: "VARIABLE_SCOPE")
Raises:
@@ -1045,7 +1045,7 @@ class LayerCollection(object):
block for this layer (which must have already been registered). If
"VARIABLE_SCOPE", use tf.get_variable_scope().reuse. (Note that the
word `use` here has a completely different meaning to "use in the graph"
- as it perturns to the `inputs`, `outputs`, and `num_uses` arguments.)
+ as it pertains to the `inputs`, `outputs`, and `num_uses` arguments.)
(Default: "VARIABLE_SCOPE")
Raises:
@@ -1116,7 +1116,7 @@ class LayerCollection(object):
block for this layer (which must have already been registered). If
"VARIABLE_SCOPE", use tf.get_variable_scope().reuse. (Note that the
word `use` here has a completely different meaning to "use in the graph"
- as it perturns to the `inputs`, `outputs`, and `num_uses` arguments.)
+ as it pertains to the `inputs`, `outputs`, and `num_uses` arguments.)
(Default: "VARIABLE_SCOPE")
Raises:
diff --git a/tensorflow/contrib/kfac/python/ops/loss_functions.py b/tensorflow/contrib/kfac/python/ops/loss_functions.py
index 42d525c2c2..c8cebc42cb 100644
--- a/tensorflow/contrib/kfac/python/ops/loss_functions.py
+++ b/tensorflow/contrib/kfac/python/ops/loss_functions.py
@@ -214,7 +214,7 @@ class NegativeLogProbLoss(LossFunction):
Here the 'Fisher' is the Fisher information matrix (i.e. expected outer-
product of gradients) with respect to the parameters of the underlying
- probability distribtion (whose log-prob defines the loss). Typically this
+ probability distribution (whose log-prob defines the loss). Typically this
will be block-diagonal across different cases in the batch, since the
distribution is usually (but not always) conditionally iid across different
cases.
@@ -238,7 +238,7 @@ class NegativeLogProbLoss(LossFunction):
Here the 'Fisher' is the Fisher information matrix (i.e. expected outer-
product of gradients) with respect to the parameters of the underlying
- probability distribtion (whose log-prob defines the loss). Typically this
+ probability distribution (whose log-prob defines the loss). Typically this
will be block-diagonal across different cases in the batch, since the
distribution is usually (but not always) conditionally iid across different
cases.
@@ -262,7 +262,7 @@ class NegativeLogProbLoss(LossFunction):
Here the 'Fisher' is the Fisher information matrix (i.e. expected outer-
product of gradients) with respect to the parameters of the underlying
- probability distribtion (whose log-prob defines the loss). Typically this
+ probability distribution (whose log-prob defines the loss). Typically this
will be block-diagonal across different cases in the batch, since the
distribution is usually (but not always) conditionally iid across different
cases.
diff --git a/tensorflow/contrib/kfac/python/ops/optimizer.py b/tensorflow/contrib/kfac/python/ops/optimizer.py
index 03b9da7933..38605259b5 100644
--- a/tensorflow/contrib/kfac/python/ops/optimizer.py
+++ b/tensorflow/contrib/kfac/python/ops/optimizer.py
@@ -72,7 +72,7 @@ class KfacOptimizer(gradient_descent.GradientDescentOptimizer):
(Higher damping means the update looks more like a standard gradient
update - see Tikhonov regularization.)
layer_collection: The layer collection object, which holds the fisher
- blocks, kronecker factors, and losses associated with the
+ blocks, Kronecker factors, and losses associated with the
graph. The layer_collection cannot be modified after KfacOptimizer's
initialization.
var_list: Optional list or tuple of variables to train. Defaults to the
@@ -99,7 +99,7 @@ class KfacOptimizer(gradient_descent.GradientDescentOptimizer):
placement_strategy: string, Device placement strategy used when creating
covariance variables, covariance ops, and inverse ops.
(Default: `None`)
- **kwargs: Arguments to be passesd to specific placement
+ **kwargs: Arguments to be passed to specific placement
strategy mixin. Check `placement.RoundRobinPlacementMixin` for example.
Raises:
@@ -120,7 +120,7 @@ class KfacOptimizer(gradient_descent.GradientDescentOptimizer):
self._estimation_mode = estimation_mode
self._colocate_gradients_with_ops = colocate_gradients_with_ops
- # The below parameters are required only if damping needs to be adapated.
+ # The below parameters are required only if damping needs to be adapted.
# These parameters can be set by calling
# set_damping_adaptation_params() explicitly.
self._damping_adaptation_decay = 0.95
@@ -574,7 +574,7 @@ class KfacOptimizer(gradient_descent.GradientDescentOptimizer):
"""Wrapper function for `self._compute_qmodel_hyperparams`.
Constructs a list of preconditioned gradients and variables. Also creates a
- op to asssign the computed q model change to `self._q_model_change`.
+ op to assign the computed q model change to `self._q_model_change`.
Args:
grads_and_vars: List of (gradient, variable) pairs.
diff --git a/tensorflow/contrib/kinesis/kernels/kinesis_dataset_ops.cc b/tensorflow/contrib/kinesis/kernels/kinesis_dataset_ops.cc
index 3212279c4c..95c7001371 100644
--- a/tensorflow/contrib/kinesis/kernels/kinesis_dataset_ops.cc
+++ b/tensorflow/contrib/kinesis/kernels/kinesis_dataset_ops.cc
@@ -164,11 +164,11 @@ class KinesisDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const string& stream, const string& shard,
const bool read_indefinitely, const int64 interval)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
stream_(stream),
shard_(shard),
read_indefinitely_(read_indefinitely),
@@ -194,7 +194,8 @@ class KinesisDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "KinesisDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* stream = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(stream_, &stream));
diff --git a/tensorflow/contrib/layers/__init__.py b/tensorflow/contrib/layers/__init__.py
index a7b41b714f..af8e673f59 100644
--- a/tensorflow/contrib/layers/__init__.py
+++ b/tensorflow/contrib/layers/__init__.py
@@ -14,7 +14,9 @@
# ==============================================================================
"""Ops for building neural network layers, regularizers, summaries, etc.
-See the @{$python/contrib.layers} guide.
+See the
+[Contrib Layers](https://tensorflow.org/api_guides/python/contrib.layers)
+guide.
@@avg_pool2d
@@avg_pool3d
diff --git a/tensorflow/contrib/layers/python/layers/feature_column.py b/tensorflow/contrib/layers/python/layers/feature_column.py
index 3ae07cedab..28d19a0445 100644
--- a/tensorflow/contrib/layers/python/layers/feature_column.py
+++ b/tensorflow/contrib/layers/python/layers/feature_column.py
@@ -997,9 +997,14 @@ class _OneHotColumn(
# Remove (?, -1) index
weighted_column = sparse_ops.sparse_slice(
weighted_column,
- [0, 0],
+ array_ops.zeros_like(weighted_column.dense_shape),
weighted_column.dense_shape)
- return sparse_ops.sparse_tensor_to_dense(weighted_column)
+ dense_tensor = sparse_ops.sparse_tensor_to_dense(weighted_column)
+ batch_shape = array_ops.shape(dense_tensor)[:-1]
+ dense_tensor_shape = array_ops.concat(
+ [batch_shape, [self.length]], axis=0)
+ dense_tensor = array_ops.reshape(dense_tensor, dense_tensor_shape)
+ return dense_tensor
dense_id_tensor = sparse_ops.sparse_tensor_to_dense(sparse_id_column,
default_value=-1)
diff --git a/tensorflow/contrib/layers/python/layers/feature_column_test.py b/tensorflow/contrib/layers/python/layers/feature_column_test.py
index 1de9ab7056..eaaf9f8d5f 100644
--- a/tensorflow/contrib/layers/python/layers/feature_column_test.py
+++ b/tensorflow/contrib/layers/python/layers/feature_column_test.py
@@ -57,6 +57,29 @@ def _sparse_id_tensor(shape, vocab_size, seed=112123):
indices=indices, values=values, dense_shape=shape)
+def _sparse_id_tensor_with_weights(shape, vocab_size, seed=112123):
+ # Returns a arbitrary `SparseTensor` with given shape and vocab size.
+ assert vocab_size >= shape[-1]
+ np.random.seed(seed)
+ indices = np.array(list(itertools.product(*[range(s) for s in shape])))
+
+ # Values must be distinct from the vocab
+ values = np.ndarray.flatten(np.array([
+ np.random.choice(vocab_size, size=shape[-1], replace=False)
+ for _ in range(np.prod(shape[:-1]))]))
+ weights = np.sort(np.random.rand(*shape), axis=len(shape)-1)
+
+ # Remove entries if weight < 0.5 for sparsity.
+ keep = np.ndarray.flatten(weights < 0.5) # Remove half of them
+ indices = indices[keep]
+ values = values[keep]
+ weights = np.ndarray.flatten(weights)[keep]
+ return (sparse_tensor_lib.SparseTensor(
+ indices=indices, values=values, dense_shape=shape),
+ sparse_tensor_lib.SparseTensor(
+ indices=indices, values=weights, dense_shape=shape))
+
+
class FeatureColumnTest(test.TestCase):
def testImmutability(self):
@@ -329,6 +352,34 @@ class FeatureColumnTest(test.TestCase):
self.assertEqual(one_hot.sparse_id_column.name, "ids_weighted_by_weights")
self.assertEqual(one_hot.length, 3)
+ def testIntegerizedOneHotColumnForWeightedSparseColumn(self):
+ vocab_size = 5
+ ids = fc.sparse_column_with_integerized_feature("ids", vocab_size)
+ weighted_ids = fc.weighted_sparse_column(ids, "weights")
+ one_hot = fc.one_hot_column(weighted_ids)
+ self.assertEqual(one_hot.sparse_id_column.name, "ids_weighted_by_weights")
+ self.assertEqual(one_hot.length, vocab_size)
+
+ def testIntegerizedOneHotWeightedSparseColumnShape(self):
+ vocab_size = 5
+ for id_tensor_shape in [[4, 3], [2, 4], [3, 3, 3]]:
+ output_rank = len(id_tensor_shape)
+ a = fc.sparse_column_with_integerized_feature("a", vocab_size)
+ weighted = fc.weighted_sparse_column(a, "weights")
+ one_hot = fc.one_hot_column(weighted)
+ id_tensor, weight_tensor = _sparse_id_tensor_with_weights(
+ id_tensor_shape, vocab_size)
+
+ one_hot_output = one_hot._to_dnn_input_layer(
+ (id_tensor, weight_tensor),
+ output_rank=output_rank)
+ one_hot_output_shape = one_hot_output.get_shape().as_list()
+ expected_shape = id_tensor_shape[:-1] + [vocab_size]
+ self.assertEquals(expected_shape, one_hot_output_shape)
+ with self.test_session() as sess:
+ one_hot_value = sess.run(one_hot_output)
+ self.assertEquals(expected_shape, list(one_hot_value.shape))
+
def testOneHotColumnWithSparseColumnWithHashKeys(self):
input_values = ["marlo", "unknown", "omar"]
inputs = constant_op.constant(input_values)
diff --git a/tensorflow/contrib/layers/python/layers/initializers.py b/tensorflow/contrib/layers/python/layers/initializers.py
index 51610f21b2..655f038b18 100644
--- a/tensorflow/contrib/layers/python/layers/initializers.py
+++ b/tensorflow/contrib/layers/python/layers/initializers.py
@@ -47,7 +47,7 @@ def xavier_initializer(uniform=True, seed=None, dtype=dtypes.float32):
Args:
uniform: Whether to use uniform or normal distributed random initialization.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
dtype: The data type. Only floating point types are supported.
Returns:
@@ -98,7 +98,7 @@ def variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False,
mode: String. 'FAN_IN', 'FAN_OUT', 'FAN_AVG'.
uniform: Whether to use uniform or normal distributed random initialization.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
dtype: The data type. Only floating point types are supported.
Returns:
@@ -111,7 +111,7 @@ def variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False,
if not dtype.is_floating:
raise TypeError('Cannot create initializer for non-floating point type.')
if mode not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG']:
- raise TypeError('Unknow mode %s [FAN_IN, FAN_OUT, FAN_AVG]', mode)
+ raise TypeError('Unknown mode %s [FAN_IN, FAN_OUT, FAN_AVG]', mode)
# pylint: disable=unused-argument
def _initializer(shape, dtype=dtype, partition_info=None):
diff --git a/tensorflow/contrib/layers/python/layers/layers.py b/tensorflow/contrib/layers/python/layers/layers.py
index 6250f88529..04668f112d 100644
--- a/tensorflow/contrib/layers/python/layers/layers.py
+++ b/tensorflow/contrib/layers/python/layers/layers.py
@@ -1584,7 +1584,7 @@ def dropout(inputs,
outputs_collections: Collection to add the outputs.
scope: Optional scope for name_scope.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
Returns:
A tensor representing the output of the operation.
diff --git a/tensorflow/contrib/layers/python/layers/layers_test.py b/tensorflow/contrib/layers/python/layers/layers_test.py
index c5c7269b1f..51c7abb105 100644
--- a/tensorflow/contrib/layers/python/layers/layers_test.py
+++ b/tensorflow/contrib/layers/python/layers/layers_test.py
@@ -1189,7 +1189,7 @@ class ConvolutionInPlaneTest(test.TestCase):
result = sess.run(horz_gradients)
expected = np.zeros((1, 10, 9, 1))
- self.assertAllEqual(result, expected)
+ self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5)
def testHorzConvWithBlankImageAndPlaceholder(self):
image = array_ops.placeholder(dtypes.float32, shape=(None, None, None, 1))
@@ -1209,7 +1209,7 @@ class ConvolutionInPlaneTest(test.TestCase):
})
expected = np.zeros((1, 10, 9, 1))
- self.assertAllEqual(result, expected)
+ self.assertAllClose(result, expected, rtol=1e-5, atol=1e-5)
def testHorzConvWithRandomImageMultiBatch(self):
np.random.seed(1)
diff --git a/tensorflow/contrib/learn/BUILD b/tensorflow/contrib/learn/BUILD
index b56a88659b..418b0cf392 100644
--- a/tensorflow/contrib/learn/BUILD
+++ b/tensorflow/contrib/learn/BUILD
@@ -79,16 +79,7 @@ py_library(
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
"//tensorflow/python:weights_broadcast_ops",
- "//tensorflow/python/estimator",
"//tensorflow/python/estimator:estimator_py",
- "//tensorflow/python/estimator:export_export",
- "//tensorflow/python/estimator:export_output",
- "//tensorflow/python/estimator:inputs",
- "//tensorflow/python/estimator:inputs_queues",
- "//tensorflow/python/estimator:model_fn",
- "//tensorflow/python/estimator:numpy_io",
- "//tensorflow/python/estimator:pandas_io",
- "//tensorflow/python/estimator:run_config",
"//tensorflow/python/feature_column",
"//tensorflow/python/feature_column:feature_column_py",
"//tensorflow/python/ops/losses",
@@ -117,7 +108,6 @@ py_test(
size = "small",
srcs = ["python/learn/learn_io/data_feeder_test.py"],
srcs_version = "PY2AND3",
- tags = ["no_windows"], # TODO: needs investigation on Windows
deps = [
":learn",
"//tensorflow/python:client_testlib",
@@ -171,9 +161,8 @@ tf_py_test(
"//tensorflow/python:training",
"//tensorflow/python:util",
"//tensorflow/python:variables",
- "//tensorflow/python/estimator",
+ "//tensorflow/python/estimator:estimator_py",
],
- tags = ["no_windows"], # TODO: needs investigation on Windows
)
py_test(
@@ -220,7 +209,7 @@ py_test(
"//tensorflow/contrib/training:training_py",
"//tensorflow/python:client_testlib",
"//tensorflow/python:platform",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -245,7 +234,7 @@ py_test(
"//tensorflow/python:summary",
"//tensorflow/python:training",
"//tensorflow/python:variables",
- "//tensorflow/python/estimator",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -259,7 +248,7 @@ py_test(
"//tensorflow/core:protos_all_py",
"//tensorflow/python:client_testlib",
"//tensorflow/python:training",
- "//tensorflow/python/estimator:run_config",
+ "//tensorflow/python/estimator:estimator_py",
],
)
@@ -600,7 +589,6 @@ py_test(
size = "small",
srcs = ["python/learn/learn_io/io_test.py"],
srcs_version = "PY2AND3",
- tags = ["no_windows"], # TODO: needs investigation on Windows
deps = [
":learn",
"//tensorflow/contrib/learn/python/learn/datasets",
@@ -621,7 +609,7 @@ py_test(
"//tensorflow/python:control_flow_ops",
"//tensorflow/python:session",
"//tensorflow/python:training",
- "//tensorflow/python/estimator:export_output",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/saved_model:signature_constants",
"@six_archive//:six",
],
diff --git a/tensorflow/contrib/learn/__init__.py b/tensorflow/contrib/learn/__init__.py
index 79bd73faaf..28a6f5aed9 100644
--- a/tensorflow/contrib/learn/__init__.py
+++ b/tensorflow/contrib/learn/__init__.py
@@ -19,7 +19,8 @@ This module and all its submodules are deprecated. See
[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
for migration instructions.
-See the @{$python/contrib.learn} guide.
+See the [Contrib Learn](https://tensorflow.org/api_guides/python/contrib.learn)
+guide.
@@BaseEstimator
@@Estimator
diff --git a/tensorflow/contrib/learn/python/learn/estimators/kmeans.py b/tensorflow/contrib/learn/python/learn/estimators/kmeans.py
index 66ebcfd1d8..21f7dcc5e4 100644
--- a/tensorflow/contrib/learn/python/learn/estimators/kmeans.py
+++ b/tensorflow/contrib/learn/python/learn/estimators/kmeans.py
@@ -15,9 +15,9 @@
"""Implementation of k-means clustering on top of `Estimator` API (deprecated).
This module is deprecated. Please use
-@{tf.contrib.factorization.KMeansClustering} instead of
-@{tf.contrib.learn.KMeansClustering}. It has a similar interface, but uses the
-@{tf.estimator.Estimator} API instead of @{tf.contrib.learn.Estimator}.
+`tf.contrib.factorization.KMeansClustering` instead of
+`tf.contrib.learn.KMeansClustering`. It has a similar interface, but uses the
+`tf.estimator.Estimator` API instead of `tf.contrib.learn.Estimator`.
"""
from __future__ import absolute_import
diff --git a/tensorflow/contrib/learn/python/learn/estimators/run_config.py b/tensorflow/contrib/learn/python/learn/estimators/run_config.py
index c36879e048..08f23aa223 100644
--- a/tensorflow/contrib/learn/python/learn/estimators/run_config.py
+++ b/tensorflow/contrib/learn/python/learn/estimators/run_config.py
@@ -221,7 +221,7 @@ class ClusterConfig(object):
class RunConfig(ClusterConfig, core_run_config.RunConfig):
"""This class specifies the configurations for an `Estimator` run.
- This class is a deprecated implementation of @{tf.estimator.RunConfig}
+ This class is a deprecated implementation of `tf.estimator.RunConfig`
interface.
"""
_USE_DEFAULT = 0
diff --git a/tensorflow/contrib/learn/python/learn/experiment.py b/tensorflow/contrib/learn/python/learn/experiment.py
index 08e907a608..4e64efdd95 100644
--- a/tensorflow/contrib/learn/python/learn/experiment.py
+++ b/tensorflow/contrib/learn/python/learn/experiment.py
@@ -162,16 +162,16 @@ class Experiment(object):
Args:
estimator: Object implementing Estimator interface, which could be a
- combination of @{tf.contrib.learn.Trainable} and
- @{tf.contrib.learn.Evaluable} (deprecated), or
- @{tf.estimator.Estimator}.
+ combination of `tf.contrib.learn.Trainable` and
+ `tf.contrib.learn.Evaluable` (deprecated), or
+ `tf.estimator.Estimator`.
train_input_fn: function, returns features and labels for training.
eval_input_fn: function, returns features and labels for evaluation. If
`eval_steps` is `None`, this should be configured only to produce for a
finite number of batches (generally, 1 epoch over the evaluation data).
eval_metrics: `dict` of string, metric function. If `None`, default set
is used. This should be `None` if the `estimator` is
- @{tf.estimator.Estimator}. If metrics are provided they will be
+ `tf.estimator.Estimator`. If metrics are provided they will be
*appended* to the default set.
train_steps: Perform this many steps of training. `None`, the default,
means train forever.
diff --git a/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py b/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py
index 66af6833da..4f22054af3 100644
--- a/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py
+++ b/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py
@@ -415,7 +415,7 @@ def make_export_strategy(serving_input_fn,
`InputFnOps`.
default_output_alternative_key: the name of the head to serve when an
incoming serving request does not explicitly request a specific head.
- Must be `None` if the estimator inherits from @{tf.estimator.Estimator}
+ Must be `None` if the estimator inherits from `tf.estimator.Estimator`
or for single-headed models.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported SavedModel. Each key should give the destination
@@ -453,7 +453,7 @@ def make_export_strategy(serving_input_fn,
The string path to the exported directory.
Raises:
- ValueError: If `estimator` is a @{tf.estimator.Estimator} instance
+ ValueError: If `estimator` is a `tf.estimator.Estimator` instance
and `default_output_alternative_key` was specified.
"""
if isinstance(estimator, core_estimator.Estimator):
@@ -504,7 +504,7 @@ def make_parsing_export_strategy(feature_columns,
that must be provided at serving time (excluding labels!).
default_output_alternative_key: the name of the head to serve when an
incoming serving request does not explicitly request a specific head.
- Must be `None` if the estimator inherits from @{tf.estimator.Estimator}
+ Must be `None` if the estimator inherits from `tf.estimator.Estimator`
or for single-headed models.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported SavedModel. Each key should give the destination
@@ -767,7 +767,7 @@ def extend_export_strategy(base_export_strategy,
The string path to the SavedModel indicated by post_export_fn.
Raises:
- ValueError: If `estimator` is a @{tf.estimator.Estimator} instance
+ ValueError: If `estimator` is a `tf.estimator.Estimator` instance
and `default_output_alternative_key` was specified or if post_export_fn
does not return a valid directory.
RuntimeError: If unable to create temporary or final export directory.
diff --git a/tensorflow/contrib/linalg/__init__.py b/tensorflow/contrib/linalg/__init__.py
index a262a099cf..cbe4c03e4d 100644
--- a/tensorflow/contrib/linalg/__init__.py
+++ b/tensorflow/contrib/linalg/__init__.py
@@ -14,7 +14,8 @@
# ==============================================================================
"""Linear algebra libraries.
-See the @{$python/contrib.linalg} guide.
+See the[Contrib Linalg](https://tensorflow.org/api_guides/python/contrib.linalg)
+guide.
@@LinearOperator
@@LinearOperatorBlockDiag
diff --git a/tensorflow/contrib/linear_optimizer/python/sdca_optimizer.py b/tensorflow/contrib/linear_optimizer/python/sdca_optimizer.py
index 9872c6f97c..8ebe45d851 100644
--- a/tensorflow/contrib/linear_optimizer/python/sdca_optimizer.py
+++ b/tensorflow/contrib/linear_optimizer/python/sdca_optimizer.py
@@ -158,7 +158,7 @@ class SDCAOptimizer(object):
# exactly 2 (i.e., its shape should be [batch_size, column.dim]).
check_rank_op = control_flow_ops.Assert(
math_ops.less_equal(array_ops.rank(transformed_tensor), 2),
- ['transformed_tensor shouls have rank at most 2.'])
+ ['transformed_tensor should have rank at most 2.'])
# Reshape to [batch_size, dense_column_dimension].
with ops.control_dependencies([check_rank_op]):
transformed_tensor = array_ops.reshape(transformed_tensor, [
@@ -172,7 +172,7 @@ class SDCAOptimizer(object):
elif isinstance(column, layers.feature_column._BucketizedColumn): # pylint: disable=protected-access
# A bucketized column corresponds to a sparse feature in SDCA. The
# bucketized feature is "sparsified" for SDCA by converting it to a
- # SparseFeatureColumn respresenting the one-hot encoding of the
+ # SparseFeatureColumn representing the one-hot encoding of the
# bucketized feature.
#
# TODO(sibyl-vie3Poto): Explore whether it is more efficient to translate a
@@ -220,7 +220,7 @@ class SDCAOptimizer(object):
# occur multiple times for a single example.
projected_ids = projection_length * example_ids + flat_ids
- # Remove any redudant ids.
+ # Remove any redundant ids.
ids, idx = array_ops.unique(projected_ids)
# Keep only one example id per duplicated ids.
example_ids_filtered = math_ops.unsorted_segment_min(
diff --git a/tensorflow/contrib/lite/BUILD b/tensorflow/contrib/lite/BUILD
index 1e6f1e7da2..0091587bf7 100644
--- a/tensorflow/contrib/lite/BUILD
+++ b/tensorflow/contrib/lite/BUILD
@@ -154,6 +154,14 @@ cc_library(
"optional_debug_tools.h",
],
copts = tflite_copts(),
+ linkopts = [
+ ] + select({
+ "//tensorflow:android": [
+ "-llog",
+ ],
+ "//conditions:default": [
+ ],
+ }),
deps = [
":arena_planner",
":builtin_op_data",
diff --git a/tensorflow/contrib/lite/build_def.bzl b/tensorflow/contrib/lite/build_def.bzl
index 81844756bc..05d0b453ab 100644
--- a/tensorflow/contrib/lite/build_def.bzl
+++ b/tensorflow/contrib/lite/build_def.bzl
@@ -227,6 +227,8 @@ def generated_test_models():
"constant",
"control_dep",
"conv",
+ "conv_with_shared_weights",
+ "conv_to_depthwiseconv_with_shared_weights",
"depthwiseconv",
"div",
"equal",
diff --git a/tensorflow/contrib/lite/context.h b/tensorflow/contrib/lite/context.h
index 5bc20106d3..c7f4df3cdc 100644
--- a/tensorflow/contrib/lite/context.h
+++ b/tensorflow/contrib/lite/context.h
@@ -29,9 +29,6 @@ limitations under the License.
#ifndef TENSORFLOW_CONTRIB_LITE_CONTEXT_H_
#define TENSORFLOW_CONTRIB_LITE_CONTEXT_H_
-#if defined(_MSC_VER)
-#include <complex.h>
-#endif
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
@@ -49,7 +46,8 @@ typedef enum { kTfLiteOk = 0, kTfLiteError = 1 } TfLiteStatus;
typedef enum {
kTfLiteEigenContext = 0, // include eigen_support.h to use.
kTfLiteGemmLowpContext = 1, // include gemm_support.h to use.
- kTfLiteMaxExternalContexts = 2
+ kTfLiteEdgeTpuContext = 2, // Placeholder for Edge TPU support.
+ kTfLiteMaxExternalContexts = 3
} TfLiteExternalContextType;
// An external context is a collection of information unrelated to the TF Lite
@@ -152,6 +150,11 @@ void TfLiteIntArrayFree(TfLiteIntArray* v);
} \
} while (0)
+// Single-precision complex data type compatible with the C99 definition.
+typedef struct {
+ float re, im; // real and imaginary parts, respectively.
+} TfLiteComplex64;
+
// Types supported by tensor
typedef enum {
kTfLiteNoType = 0,
@@ -183,11 +186,7 @@ typedef union {
uint8_t* uint8;
bool* b;
int16_t* i16;
-#if defined(_MSC_VER)
- _Fcomplex* c64;
-#else
- _Complex float* c64;
-#endif
+ TfLiteComplex64* c64;
} TfLitePtrUnion;
// Memory allocation strategies. kTfLiteMmapRo is for read-only memory-mapped
@@ -452,13 +451,15 @@ typedef struct _TfLiteDelegate {
// Copy the data from delegate buffer handle to raw memory.
// This can be null if the delegate doesn't use its own buffer.
- TfLiteStatus (*CopyFromBufferHandle)(TfLiteDelegate* delegate,
+ TfLiteStatus (*CopyFromBufferHandle)(TfLiteContext* context,
+ TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle,
void* data, size_t size);
// Copy the data from raw memory to delegate buffer handle.
// This can be null if the delegate doesn't use its own buffer.
- TfLiteStatus (*CopyToBufferHandle)(TfLiteDelegate* delegate,
+ TfLiteStatus (*CopyToBufferHandle)(TfLiteContext* context,
+ TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle,
void* data, size_t size);
@@ -466,7 +467,7 @@ typedef struct _TfLiteDelegate {
// this doesn't release the underlying resource (e.g. textures). The
// resources are either owned by application layer or the delegate.
// This can be null if the delegate doesn't use its own buffer.
- void (*FreeBufferHandle)(TfLiteDelegate* delegate,
+ void (*FreeBufferHandle)(TfLiteContext* context, TfLiteDelegate* delegate,
TfLiteBufferHandle* handle);
} TfLiteDelegate;
diff --git a/tensorflow/contrib/lite/delegates/eager/BUILD b/tensorflow/contrib/lite/delegates/eager/BUILD
index f21540d524..8abc828578 100644
--- a/tensorflow/contrib/lite/delegates/eager/BUILD
+++ b/tensorflow/contrib/lite/delegates/eager/BUILD
@@ -7,6 +7,8 @@ package(default_visibility = [
licenses(["notice"]) # Apache 2.0
+load("//tensorflow:tensorflow.bzl", "tf_cc_test")
+
cc_library(
name = "buffer_map",
srcs = ["buffer_map.cc"],
@@ -14,21 +16,22 @@ cc_library(
deps = [
":util",
"//tensorflow/c:c_api_internal",
- "//tensorflow/contrib/lite:framework",
"//tensorflow/contrib/lite:kernel_api",
- "//tensorflow/core:framework",
- "//tensorflow/core:protos_all_cc",
- ],
+ ] + select({
+ "//tensorflow:android": [
+ "//tensorflow/core:android_tensorflow_lib_lite_no_runtime",
+ ],
+ "//conditions:default": [
+ "//tensorflow/core:framework",
+ "//tensorflow/core:protos_all_cc",
+ ],
+ }),
)
-cc_test(
+tf_cc_test(
name = "buffer_map_test",
size = "small",
srcs = ["buffer_map_test.cc"],
- tags = [
- "no_oss",
- "tflite_not_portable",
- ],
deps = [
":buffer_map",
"//tensorflow/contrib/lite:framework",
@@ -51,21 +54,22 @@ cc_library(
":delegate_data",
":kernel",
":util",
- "//tensorflow/contrib/lite:framework",
"//tensorflow/contrib/lite:kernel_api",
"//tensorflow/contrib/lite:util",
- "//tensorflow/core:lib",
- ],
+ ] + select({
+ "//tensorflow:android": [
+ "//tensorflow/core:android_tensorflow_lib_lite_no_runtime",
+ ],
+ "//conditions:default": [
+ "//tensorflow/core:lib",
+ ],
+ }),
)
-cc_test(
+tf_cc_test(
name = "delegate_test",
size = "small",
srcs = ["delegate_test.cc"],
- tags = [
- "no_oss",
- "tflite_not_portable",
- ],
deps = [
":delegate",
":test_util",
@@ -80,20 +84,22 @@ cc_library(
hdrs = ["delegate_data.h"],
deps = [
":buffer_map",
- "//tensorflow/core:core_cpu",
- "//tensorflow/core:lib",
"//tensorflow/core/common_runtime/eager:context",
- ],
+ ] + select({
+ "//tensorflow:android": [
+ "//tensorflow/core:android_tensorflow_lib_lite",
+ ],
+ "//conditions:default": [
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:lib",
+ ],
+ }),
)
-cc_test(
+tf_cc_test(
name = "delegate_data_test",
size = "small",
srcs = ["delegate_data_test.cc"],
- tags = [
- "no_oss",
- "tflite_not_portable",
- ],
deps = [
":delegate_data",
"//tensorflow/contrib/lite:framework",
@@ -110,25 +116,30 @@ cc_library(
deps = [
":delegate_data",
":util",
- "//tensorflow/contrib/lite:framework",
+ "@flatbuffers",
"//tensorflow/contrib/lite:kernel_api",
+ "//tensorflow/contrib/lite:string",
"//tensorflow/contrib/lite/kernels:kernel_util",
- "//tensorflow/core:protos_all_cc",
"//tensorflow/core/common_runtime/eager:context",
"//tensorflow/core/common_runtime/eager:execute",
"//tensorflow/core/common_runtime/eager:tensor_handle",
- "@flatbuffers",
- ],
+ ] + select({
+ # TODO(b/111881878): The android_tensorflow_lib target pulls in the full
+ # set of core TensorFlow kernels. We may want to revisit this dependency
+ # to allow selective registration via build targets.
+ "//tensorflow:android": [
+ "//tensorflow/core:android_tensorflow_lib",
+ ],
+ "//conditions:default": [
+ "//tensorflow/core:protos_all_cc",
+ ],
+ }),
)
-cc_test(
+tf_cc_test(
name = "kernel_test",
size = "small",
srcs = ["kernel_test.cc"],
- tags = [
- "no_oss",
- "tflite_not_portable",
- ],
deps = [
":delegate_data",
":kernel",
@@ -144,6 +155,7 @@ cc_library(
hdrs = ["test_util.h"],
deps = [
"//tensorflow/c:c_api_internal",
+ "//tensorflow/contrib/lite:string",
"//tensorflow/contrib/lite/kernels:test_util",
"@com_google_absl//absl/memory",
"@flatbuffers",
@@ -155,32 +167,27 @@ cc_library(
srcs = ["util.cc"],
hdrs = ["util.h"],
deps = [
- ":constants",
"//tensorflow/c:c_api_internal",
- "//tensorflow/contrib/lite:framework",
"//tensorflow/contrib/lite:kernel_api",
- "//tensorflow/core:framework",
- "//tensorflow/core:lib",
- ],
+ ] + select({
+ "//tensorflow:android": [
+ "//tensorflow/core:android_tensorflow_lib_lite_no_runtime",
+ ],
+ "//conditions:default": [
+ "//tensorflow/core:lib",
+ "//tensorflow/core:framework",
+ ],
+ }),
)
-cc_test(
+tf_cc_test(
name = "util_test",
size = "small",
srcs = ["util_test.cc"],
- tags = [
- "no_oss",
- "tflite_not_portable",
- ],
deps = [
":util",
+ "//tensorflow/contrib/lite:string",
"//tensorflow/contrib/lite/testing:util",
- "//tensorflow/core:lib",
"@com_google_googletest//:gtest",
],
)
-
-cc_library(
- name = "constants",
- hdrs = ["constants.h"],
-)
diff --git a/tensorflow/contrib/lite/delegates/eager/buffer_map_test.cc b/tensorflow/contrib/lite/delegates/eager/buffer_map_test.cc
index dcb3f6c941..a046943e56 100644
--- a/tensorflow/contrib/lite/delegates/eager/buffer_map_test.cc
+++ b/tensorflow/contrib/lite/delegates/eager/buffer_map_test.cc
@@ -56,8 +56,8 @@ tensorflow::Tensor MakeTensor(const std::vector<int>& shape,
return buffer_map.GetTensor(0);
}
-std::vector<int64> GetTensorShape(const tensorflow::Tensor& t) {
- std::vector<int64> shape(t.dims());
+std::vector<tensorflow::int64> GetTensorShape(const tensorflow::Tensor& t) {
+ std::vector<tensorflow::int64> shape(t.dims());
for (int i = 0; i < t.dims(); ++i) {
shape[i] = t.dim_size(i);
}
diff --git a/tensorflow/contrib/lite/delegates/eager/delegate.cc b/tensorflow/contrib/lite/delegates/eager/delegate.cc
index 7d22b45419..45fc158157 100644
--- a/tensorflow/contrib/lite/delegates/eager/delegate.cc
+++ b/tensorflow/contrib/lite/delegates/eager/delegate.cc
@@ -55,17 +55,15 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteDelegate* delegate) {
return kTfLiteOk;
}
-TfLiteStatus CopyFromBufferHandle(TfLiteDelegate* delegate,
+TfLiteStatus CopyFromBufferHandle(TfLiteContext* context,
+ TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle, void* data,
size_t size) {
- // TODO(nupurgarg): Make BufferMap unique to each interpreter in order to
- // support multiple interpreters using a single delegate.
BufferMap* buffer_map =
- reinterpret_cast<DelegateData*>(delegate->data_)->GetBufferMap();
+ reinterpret_cast<DelegateData*>(delegate->data_)->GetBufferMap(context);
- // TODO(nupurgarg): Use TfLiteContext's ReportError instead of fprinf.
if (!buffer_map->HasTensor(buffer_handle)) {
- fprintf(stderr, "Invalid tensor index %d.\n", buffer_handle);
+ context->ReportError(context, "Invalid tensor index %d.", buffer_handle);
return kTfLiteError;
}
@@ -73,7 +71,8 @@ TfLiteStatus CopyFromBufferHandle(TfLiteDelegate* delegate,
tensorflow::StringPiece t_data = t.tensor_data();
if (size != t_data.size()) {
- fprintf(stderr, "Not enough space to store TensorFlow's aligned buffer.\n");
+ context->ReportError(
+ context, "Not enough space to store TensorFlow's aligned buffer.");
return kTfLiteError;
}
@@ -84,27 +83,26 @@ TfLiteStatus CopyFromBufferHandle(TfLiteDelegate* delegate,
} // namespace delegate
} // namespace eager
-EagerDelegate::EagerDelegate() {}
-
-EagerDelegate::~EagerDelegate() {}
-
-TfLiteStatus EagerDelegate::Apply(Interpreter* interpreter) {
- if (!delegate_) {
- if (!eager::DelegateData::Create(&delegate_data_).ok()) {
- fprintf(stderr, "Unable to initialize TensorFlow context.\n");
- return kTfLiteError;
- }
-
- delegate_.reset(new TfLiteDelegate{
- /*data_=*/delegate_data_.get(),
- /*nullptr,*/ &eager::delegate::Prepare,
- /*CopyFromBufferHandle=*/&eager::delegate::CopyFromBufferHandle,
- /*CopyToBufferHandle=*/nullptr,
- /*FreeBufferHandle=*/nullptr});
+std::unique_ptr<EagerDelegate> EagerDelegate::Create() {
+ std::unique_ptr<eager::DelegateData> delegate_data;
+ if (!eager::DelegateData::Create(&delegate_data).ok()) {
+ fprintf(stderr, "Unable to initialize TensorFlow context.\n");
+ return nullptr;
}
- return interpreter->ModifyGraphWithDelegate(delegate_.get(),
- /*allow_dynamic_tensors=*/true);
+ return std::unique_ptr<EagerDelegate>(
+ new EagerDelegate(std::move(delegate_data)));
}
+EagerDelegate::EagerDelegate(std::unique_ptr<eager::DelegateData> delegate_data)
+ : TfLiteDelegate{
+ /*data_=*/delegate_data.get(),
+ /*nullptr,*/ &eager::delegate::Prepare,
+ /*CopyFromBufferHandle=*/&eager::delegate::CopyFromBufferHandle,
+ /*CopyToBufferHandle=*/nullptr,
+ /*FreeBufferHandle=*/nullptr},
+ delegate_data_(std::move(delegate_data)) {}
+
+EagerDelegate::~EagerDelegate() {}
+
} // namespace tflite
diff --git a/tensorflow/contrib/lite/delegates/eager/delegate.h b/tensorflow/contrib/lite/delegates/eager/delegate.h
index 0defca7c32..6d15ba47dc 100644
--- a/tensorflow/contrib/lite/delegates/eager/delegate.h
+++ b/tensorflow/contrib/lite/delegates/eager/delegate.h
@@ -17,7 +17,6 @@ limitations under the License.
#include "tensorflow/contrib/lite/context.h"
#include "tensorflow/contrib/lite/delegates/eager/delegate_data.h"
-#include "tensorflow/contrib/lite/interpreter.h"
namespace tflite {
@@ -26,28 +25,33 @@ namespace tflite {
// executed by TensorFlow's runtime via Eager.
//
// The interpreter must be constructed after the EagerDelegate and destructed
-// before the EagerDelegate. This delegate can only be used with one
-// interpreter.
+// before the EagerDelegate. This delegate may be used with multiple
+// interpreters, but it is *not* thread-safe.
//
// Usage:
-// EagerDelegate delegate;
+// auto delegate = EagerDelegate::Create();
// ... build interpreter ...
//
-// delegate.Apply(interpreter);
+// if (delegate) {
+// interpreter->ModifyGraphWithDelegate(
+// delegate.get(), /*allow_dynamic_tensors=*/true);
+// }
// ... run inference ...
// ... destroy interpreter ...
// ... destroy delegate ...
-class EagerDelegate {
+class EagerDelegate : public TfLiteDelegate {
public:
- EagerDelegate();
- ~EagerDelegate();
+ // Creates a delegate that supports TF ops.
+ //
+ // If the underyling TF Eager context creation fails, returns null.
+ static std::unique_ptr<EagerDelegate> Create();
- // Modifies the graph loaded in the interpreter.
- TfLiteStatus Apply(Interpreter* interpreter);
+ ~EagerDelegate();
private:
+ explicit EagerDelegate(std::unique_ptr<eager::DelegateData> delegate_data);
+
std::unique_ptr<eager::DelegateData> delegate_data_;
- std::unique_ptr<TfLiteDelegate> delegate_;
};
} // namespace tflite
diff --git a/tensorflow/contrib/lite/delegates/eager/delegate_data.h b/tensorflow/contrib/lite/delegates/eager/delegate_data.h
index 8a0e8ba8bf..772d26f44e 100644
--- a/tensorflow/contrib/lite/delegates/eager/delegate_data.h
+++ b/tensorflow/contrib/lite/delegates/eager/delegate_data.h
@@ -32,14 +32,18 @@ class DelegateData {
// The EagerContext that is required for execution of Eager Ops.
tensorflow::EagerContext* GetEagerContext() { return eager_context_.get(); }
- // Map from TF Lite tensor index to TensorFlow tensor.
- BufferMap* GetBufferMap() { return &buffer_map_; }
+ // Map from TF Lite tensor index to TensorFlow tensor for a given context.
+ BufferMap* GetBufferMap(const TfLiteContext* context) {
+ return &buffer_map_[context];
+ }
private:
explicit DelegateData(tensorflow::EagerContext* eager_context);
std::unique_ptr<tensorflow::EagerContext> eager_context_;
- BufferMap buffer_map_;
+ // TODO(b/112439500): Clean up stale BufferMap instances after adding the
+ // necessary cleanup hook from a TfLiteContext to a TfLiteDelegate.
+ std::unordered_map<const TfLiteContext*, BufferMap> buffer_map_;
};
} // namespace eager
diff --git a/tensorflow/contrib/lite/delegates/eager/delegate_data_test.cc b/tensorflow/contrib/lite/delegates/eager/delegate_data_test.cc
index 30251b8f82..b3a0ffcec1 100644
--- a/tensorflow/contrib/lite/delegates/eager/delegate_data_test.cc
+++ b/tensorflow/contrib/lite/delegates/eager/delegate_data_test.cc
@@ -16,6 +16,7 @@ limitations under the License.
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include "tensorflow/contrib/lite/context.h"
#include "tensorflow/contrib/lite/testing/util.h"
namespace tflite {
@@ -29,8 +30,12 @@ TEST(DelegateDataTest, Basic) {
// binary.
EXPECT_TRUE(DelegateData::Create(&data).ok());
+ TfLiteContext dummy_context1 = {};
+ TfLiteContext dummy_context2 = {};
EXPECT_NE(data->GetEagerContext(), nullptr);
- EXPECT_NE(data->GetBufferMap(), nullptr);
+ EXPECT_NE(data->GetBufferMap(&dummy_context1), nullptr);
+ EXPECT_NE(data->GetBufferMap(&dummy_context1),
+ data->GetBufferMap(&dummy_context2));
}
} // namespace
diff --git a/tensorflow/contrib/lite/delegates/eager/delegate_test.cc b/tensorflow/contrib/lite/delegates/eager/delegate_test.cc
index 88fb34044e..eb47f46c0b 100644
--- a/tensorflow/contrib/lite/delegates/eager/delegate_test.cc
+++ b/tensorflow/contrib/lite/delegates/eager/delegate_test.cc
@@ -25,26 +25,24 @@ namespace {
using ::testing::ContainsRegex;
using ::testing::ElementsAre;
-// TODO(nupurgarg): Add a test with multiple interpreters for one delegate.
-
class DelegateTest : public testing::EagerModelTest {
public:
DelegateTest() {
- // The delegate needs to be constructed before the interpreter because the
- // interpreter references data contained in the delegate.
- delegate_.reset(new EagerDelegate());
+ delegate_ = EagerDelegate::Create();
interpreter_.reset(new Interpreter(&error_reporter_));
}
~DelegateTest() override {
// The delegate needs to be destructed after the interpreter because the
// interpreter references data contained in the delegate.
- delete interpreter_.release();
- delete delegate_.release();
+ interpreter_.reset();
+ delegate_.reset();
}
void ConfigureDelegate() {
- CHECK(delegate_->Apply(interpreter_.get()) == kTfLiteOk);
+ ASSERT_EQ(interpreter_->ModifyGraphWithDelegate(
+ delegate_.get(), /*allow_dynamic_tensors=*/true),
+ kTfLiteOk);
}
private:
@@ -139,6 +137,56 @@ TEST_F(DelegateTest, OnlyTFLite) {
ASSERT_THAT(GetValues(2), ElementsAre(1.1f, 4.4f, 9.9f, 17.6f));
}
+TEST_F(DelegateTest, MultipleInterpretersSameDelegate) {
+ // Build a graph, configure the delegate and set inputs.
+ {
+ AddTensors(9, {0, 3}, {8}, kTfLiteFloat32, {3});
+ AddTfOp(testing::kUnpack, {0}, {1, 2});
+ AddTfOp(testing::kUnpack, {3}, {4, 5});
+ AddTfOp(testing::kAdd, {1, 4}, {6});
+ AddTfOp(testing::kAdd, {2, 5}, {7});
+ AddTfOp(testing::kMul, {6, 7}, {8});
+ ConfigureDelegate();
+ SetShape(0, {2, 2, 1});
+ SetValues(0, {1.1f, 2.2f, 3.3f, 4.4f});
+ SetShape(3, {2, 2, 1});
+ SetValues(3, {1.1f, 2.2f, 3.3f, 4.4f});
+ }
+
+ // Create a new interpreter, inject into the test framework and build
+ // a different graph using the *same* delegate.
+ std::unique_ptr<Interpreter> interpreter(new Interpreter(&error_reporter_));
+ interpreter_.swap(interpreter);
+ {
+ AddTensors(10, {0}, {9}, kTfLiteFloat32, {3});
+ AddTfOp(testing::kUnpack, {0}, {1, 2});
+ AddTfOp(testing::kAdd, {1, 2}, {3});
+ AddTfOp(testing::kUnpack, {3}, {4, 5});
+ AddTfLiteMulOp({4, 5}, {6});
+ AddTfOp(testing::kUnpack, {6}, {7, 8});
+ AddTfOp(testing::kAdd, {7, 8}, {9});
+ ConfigureDelegate();
+ SetShape(0, {2, 2, 2, 1});
+ SetValues(0, {3.0f, 1.0f, 0.5f, -1.0f, 0.0f, 1.0f, 1.5f, 3.0f});
+ }
+
+ // Swap back in the first interpreter and validate inference.
+ interpreter_.swap(interpreter);
+ {
+ ASSERT_TRUE(Invoke());
+ EXPECT_THAT(GetShape(8), ElementsAre(2, 1));
+ EXPECT_THAT(GetValues(8), ElementsAre(14.52f, 38.72f));
+ }
+
+ // Swap in the second interpreter and validate inference.
+ interpreter_.swap(interpreter);
+ {
+ ASSERT_TRUE(Invoke());
+ EXPECT_THAT(GetShape(9), ElementsAre(1));
+ EXPECT_THAT(GetValues(9), ElementsAre(10.0f));
+ }
+}
+
} // namespace
} // namespace eager
} // namespace tflite
diff --git a/tensorflow/contrib/lite/delegates/eager/kernel.cc b/tensorflow/contrib/lite/delegates/eager/kernel.cc
index 1727981807..1082b78725 100644
--- a/tensorflow/contrib/lite/delegates/eager/kernel.cc
+++ b/tensorflow/contrib/lite/delegates/eager/kernel.cc
@@ -14,13 +14,14 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/lite/delegates/eager/kernel.h"
-#include "third_party/flatbuffers/include/flatbuffers/flexbuffers.h"
+#include "flatbuffers/flexbuffers.h"
#include "tensorflow/contrib/lite/builtin_ops.h"
#include "tensorflow/contrib/lite/context.h"
#include "tensorflow/contrib/lite/context_util.h"
#include "tensorflow/contrib/lite/delegates/eager/delegate_data.h"
#include "tensorflow/contrib/lite/delegates/eager/util.h"
#include "tensorflow/contrib/lite/kernels/kernel_util.h"
+#include "tensorflow/contrib/lite/string.h"
#include "tensorflow/core/common_runtime/eager/context.h"
#include "tensorflow/core/common_runtime/eager/execute.h"
#include "tensorflow/core/common_runtime/eager/tensor_handle.h"
@@ -149,8 +150,8 @@ void* Init(TfLiteContext* context, const char* buffer, size_t length) {
op_data->eager_context =
reinterpret_cast<DelegateData*>(params->delegate->data_)
->GetEagerContext();
- op_data->buffer_map =
- reinterpret_cast<DelegateData*>(params->delegate->data_)->GetBufferMap();
+ op_data->buffer_map = reinterpret_cast<DelegateData*>(params->delegate->data_)
+ ->GetBufferMap(context);
CHECK(params->output_tensors);
for (auto tensor_index : TfLiteIntArrayView(params->output_tensors)) {
diff --git a/tensorflow/contrib/lite/delegates/eager/kernel_test.cc b/tensorflow/contrib/lite/delegates/eager/kernel_test.cc
index b7bfbb34e4..66f2226626 100644
--- a/tensorflow/contrib/lite/delegates/eager/kernel_test.cc
+++ b/tensorflow/contrib/lite/delegates/eager/kernel_test.cc
@@ -55,12 +55,14 @@ class KernelTest : public testing::EagerModelTest {
delegate_.data_ = delegate_data_.get();
delegate_.FreeBufferHandle = nullptr;
delegate_.Prepare = prepare_function;
- delegate_.CopyFromBufferHandle = [](TfLiteDelegate* delegate,
+ delegate_.CopyFromBufferHandle = [](TfLiteContext* context,
+ TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle,
void* data, size_t size) {
auto* delegate_data = reinterpret_cast<DelegateData*>(delegate->data_);
- tensorflow::StringPiece values =
- delegate_data->GetBufferMap()->GetTensor(buffer_handle).tensor_data();
+ tensorflow::StringPiece values = delegate_data->GetBufferMap(context)
+ ->GetTensor(buffer_handle)
+ .tensor_data();
memcpy(data, values.data(), values.size());
return kTfLiteOk;
};
diff --git a/tensorflow/contrib/lite/delegates/eager/test_util.cc b/tensorflow/contrib/lite/delegates/eager/test_util.cc
index 80acf5d995..26d96acc82 100644
--- a/tensorflow/contrib/lite/delegates/eager/test_util.cc
+++ b/tensorflow/contrib/lite/delegates/eager/test_util.cc
@@ -16,7 +16,8 @@ limitations under the License.
#include "tensorflow/contrib/lite/delegates/eager/test_util.h"
#include "absl/memory/memory.h"
-#include "third_party/flatbuffers/include/flatbuffers/flexbuffers.h"
+#include "flatbuffers/flexbuffers.h"
+#include "tensorflow/contrib/lite/string.h"
namespace tflite {
namespace eager {
diff --git a/tensorflow/contrib/lite/delegates/eager/util.cc b/tensorflow/contrib/lite/delegates/eager/util.cc
index c8aa0b7f69..4426c653e6 100644
--- a/tensorflow/contrib/lite/delegates/eager/util.cc
+++ b/tensorflow/contrib/lite/delegates/eager/util.cc
@@ -13,16 +13,10 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/lite/delegates/eager/util.h"
-#include "tensorflow/contrib/lite/delegates/eager/constants.h"
namespace tflite {
namespace eager {
-bool IsEagerOp(const char* custom_name) {
- return custom_name && strncmp(custom_name, kCustomCodePrefix,
- strlen(kCustomCodePrefix)) == 0;
-}
-
TfLiteStatus ConvertStatus(TfLiteContext* context,
const tensorflow::Status& status) {
if (!status.ok()) {
diff --git a/tensorflow/contrib/lite/delegates/eager/util.h b/tensorflow/contrib/lite/delegates/eager/util.h
index b7363361be..a9407be071 100644
--- a/tensorflow/contrib/lite/delegates/eager/util.h
+++ b/tensorflow/contrib/lite/delegates/eager/util.h
@@ -23,10 +23,6 @@ limitations under the License.
namespace tflite {
namespace eager {
-// Checks whether the prefix of the custom name indicates the operation is an
-// Eager operation.
-bool IsEagerOp(const char* custom_name);
-
// Converts a tensorflow:Status into a TfLiteStatus. If the original status
// represented an error, reports it using the given 'context'.
TfLiteStatus ConvertStatus(TfLiteContext* context,
diff --git a/tensorflow/contrib/lite/delegates/eager/util_test.cc b/tensorflow/contrib/lite/delegates/eager/util_test.cc
index 4e92da8d34..53378a1eaf 100644
--- a/tensorflow/contrib/lite/delegates/eager/util_test.cc
+++ b/tensorflow/contrib/lite/delegates/eager/util_test.cc
@@ -18,6 +18,7 @@ limitations under the License.
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include "tensorflow/contrib/lite/string.h"
#include "tensorflow/contrib/lite/testing/util.h"
namespace tflite {
@@ -102,16 +103,6 @@ TEST(UtilTest, TypeConversions) {
EXPECT_EQ(TF_BOOL, GetTensorFlowDataType(kTfLiteBool));
}
-TEST(UtilTest, IsEagerOp) {
- EXPECT_TRUE(IsEagerOp("Eager"));
- EXPECT_TRUE(IsEagerOp("EagerOp"));
- EXPECT_FALSE(IsEagerOp("eager"));
- EXPECT_FALSE(IsEagerOp("Eage"));
- EXPECT_FALSE(IsEagerOp("OpEager"));
- EXPECT_FALSE(IsEagerOp(nullptr));
- EXPECT_FALSE(IsEagerOp(""));
-}
-
} // namespace
} // namespace eager
} // namespace tflite
diff --git a/tensorflow/contrib/lite/delegates/nnapi/nnapi_delegate.cc b/tensorflow/contrib/lite/delegates/nnapi/nnapi_delegate.cc
index b1b8e9890c..e6cc3dd99c 100644
--- a/tensorflow/contrib/lite/delegates/nnapi/nnapi_delegate.cc
+++ b/tensorflow/contrib/lite/delegates/nnapi/nnapi_delegate.cc
@@ -27,7 +27,9 @@ limitations under the License.
#include "tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h"
#ifdef __ANDROID__
+#include <sys/mman.h>
#include <sys/system_properties.h>
+#include <unistd.h>
#endif
namespace tflite {
@@ -80,6 +82,44 @@ struct NNFreeCompilation {
}
};
+// Manage NNAPI shared memory handle
+class NNMemory {
+ public:
+ NNMemory(const char* name, size_t size) {
+#ifdef __ANDROID__
+ byte_size_ = size;
+ fd_ = ASharedMemory_create(name, size);
+ data_ptr_ = reinterpret_cast<uint8_t*>(
+ mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
+ ANeuralNetworksMemory_createFromFd(size, PROT_READ | PROT_WRITE, fd_, 0,
+ &nn_memory_handle_);
+#endif
+ }
+
+ ~NNMemory() {
+#ifdef __ANDROID__
+ if (data_ptr_) {
+ munmap(data_ptr_, byte_size_);
+ }
+ if (nn_memory_handle_) {
+ ANeuralNetworksMemory_free(nn_memory_handle_);
+ }
+ if (fd_ > 0) close(fd_);
+#endif
+ }
+
+ ANeuralNetworksMemory* get_handle() { return nn_memory_handle_; }
+ uint8_t* get_data_ptr() { return data_ptr_; }
+
+ private:
+#ifdef __ANDROID__
+ int fd_ = 0;
+ size_t byte_size_ = 0;
+#endif
+ uint8_t* data_ptr_ = nullptr;
+ ANeuralNetworksMemory* nn_memory_handle_ = nullptr;
+}; // namespace
+
// Track tensor indices to NN API tensor indices mapping.
class OperandMapping {
public:
@@ -326,15 +366,21 @@ class NNAPIOpBuilder {
std::vector<uint32_t> augmented_outputs_;
};
+struct NNAPIOpMappingArgs {
+ TfLiteContext* context;
+ NNAPIOpBuilder* builder;
+ TfLiteNode* node;
+ std::vector<int>* model_state_inputs;
+ std::vector<int>* model_state_tfl_outputs;
+};
+
// The kernel that represents the subgraph of TF Lite being run on NN API.
class NNAPIDelegateKernel {
public:
NNAPIDelegateKernel() = default;
typedef ANeuralNetworksOperationType (*MappingFn)(
- TfLiteContext*, NNAPIOpBuilder* builder, TfLiteNode* node,
- std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs);
+ const NNAPIOpMappingArgs& mapping_args);
// Return a function that knows how to translate a node into its operands
// when called. You can use this function to see if a node is supported
@@ -344,13 +390,11 @@ class NNAPIDelegateKernel {
switch (builtin_code) {
case kTfLiteBuiltinAdd:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteAddParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
+ auto builtin = reinterpret_cast<TfLiteAddParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_ADD;
};
} else {
@@ -359,13 +403,11 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinMul:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteMulParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
+ auto builtin = reinterpret_cast<TfLiteMulParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_MUL;
};
} else {
@@ -374,11 +416,10 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinAveragePool2d:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- builder->AddPoolingParams(node->builtin_data);
+ mapping_args.builder->AddPoolingParams(
+ mapping_args.node->builtin_data);
return ANEURALNETWORKS_AVERAGE_POOL_2D;
};
} else {
@@ -387,11 +428,10 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinMaxPool2d:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- builder->AddPoolingParams(node->builtin_data);
+ mapping_args.builder->AddPoolingParams(
+ mapping_args.node->builtin_data);
return ANEURALNETWORKS_MAX_POOL_2D;
};
} else {
@@ -400,11 +440,10 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinL2Pool2d:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- builder->AddPoolingParams(node->builtin_data);
+ mapping_args.builder->AddPoolingParams(
+ mapping_args.node->builtin_data);
return ANEURALNETWORKS_L2_POOL_2D;
};
} else {
@@ -420,16 +459,14 @@ class NNAPIDelegateKernel {
// NNAPI does not support dilated Conv2D.
return nullptr;
}
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteConvParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->padding);
- builder->AddScalarInt32Operand(builtin->stride_width);
- builder->AddScalarInt32Operand(builtin->stride_height);
- builder->AddScalarInt32Operand(builtin->activation);
+ auto builtin = reinterpret_cast<TfLiteConvParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->padding);
+ mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
+ mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_CONV_2D;
};
} else {
@@ -438,17 +475,16 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinDepthwiseConv2d:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
auto builtin = reinterpret_cast<TfLiteDepthwiseConvParams*>(
- node->builtin_data);
- builder->AddScalarInt32Operand(builtin->padding);
- builder->AddScalarInt32Operand(builtin->stride_width);
- builder->AddScalarInt32Operand(builtin->stride_height);
- builder->AddScalarInt32Operand(builtin->depth_multiplier);
- builder->AddScalarInt32Operand(builtin->activation);
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->padding);
+ mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
+ mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
+ mapping_args.builder->AddScalarInt32Operand(
+ builtin->depth_multiplier);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_DEPTHWISE_CONV_2D;
};
} else {
@@ -457,13 +493,11 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinFullyConnected:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
auto builtin = reinterpret_cast<TfLiteFullyConnectedParams*>(
- node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_FULLY_CONNECTED;
};
} else {
@@ -472,13 +506,11 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinSoftmax:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteSoftmaxParams*>(node->builtin_data);
- builder->AddScalarFloat32Operand(builtin->beta);
+ auto builtin = reinterpret_cast<TfLiteSoftmaxParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarFloat32Operand(builtin->beta);
return ANEURALNETWORKS_SOFTMAX;
};
} else {
@@ -487,9 +519,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinReshape:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_RESHAPE;
};
@@ -499,15 +529,13 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinSqueeze:
if (version == 1 && kAndroidSdkVersion >= kMinSdkVersionForNNAPI11) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteSqueezeParams*>(node->builtin_data);
+ auto builtin = reinterpret_cast<TfLiteSqueezeParams*>(
+ mapping_args.node->builtin_data);
// Note that we add the squeeze dimensions even if the dimensions
// were unspecified (empty), as NNAPI requires the operand.
- builder->AddVectorInt32Operand(
+ mapping_args.builder->AddVectorInt32Operand(
builtin->squeeze_dims,
static_cast<uint32_t>(builtin->num_squeeze_dims));
return ANEURALNETWORKS_SQUEEZE;
@@ -522,25 +550,21 @@ class NNAPIDelegateKernel {
// NNAPI does not support activations
return nullptr;
}
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_L2_NORMALIZATION;
};
}
case kTfLiteBuiltinLocalResponseNormalization:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
auto builtin = reinterpret_cast<TfLiteLocalResponseNormParams*>(
- node->builtin_data);
- builder->AddScalarInt32Operand(builtin->radius);
- builder->AddScalarFloat32Operand(builtin->bias);
- builder->AddScalarFloat32Operand(builtin->alpha);
- builder->AddScalarFloat32Operand(builtin->beta);
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->radius);
+ mapping_args.builder->AddScalarFloat32Operand(builtin->bias);
+ mapping_args.builder->AddScalarFloat32Operand(builtin->alpha);
+ mapping_args.builder->AddScalarFloat32Operand(builtin->beta);
return ANEURALNETWORKS_LOCAL_RESPONSE_NORMALIZATION;
};
} else {
@@ -556,13 +580,11 @@ class NNAPIDelegateKernel {
->type == kTfLiteLshProjectionSparse) {
return nullptr;
}
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
auto builtin = reinterpret_cast<TfLiteLSHProjectionParams*>(
- node->builtin_data);
- builder->AddScalarInt32Operand(builtin->type);
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->type);
return ANEURALNETWORKS_LSH_PROJECTION;
};
} else {
@@ -585,13 +607,11 @@ class NNAPIDelegateKernel {
}
}
}
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
auto builtin = reinterpret_cast<TfLiteConcatenationParams*>(
- node->builtin_data);
- builder->AddScalarInt32Operand(builtin->axis);
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->axis);
return ANEURALNETWORKS_CONCATENATION;
};
} else {
@@ -600,9 +620,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinDequantize:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_DEQUANTIZE;
};
@@ -612,9 +630,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinFloor:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_FLOOR;
};
@@ -624,9 +640,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinRelu:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_RELU;
};
@@ -636,9 +650,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinReluN1To1:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_RELU1;
};
@@ -648,9 +660,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinRelu6:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_RELU6;
};
@@ -660,9 +670,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinLogistic:
if (version == 1) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_LOGISTIC;
};
@@ -675,9 +683,7 @@ class NNAPIDelegateKernel {
if (version == 1 &&
context->tensors[node->inputs->data[0]].type == kTfLiteFloat32) {
// NNAPI only support float tanh.
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_TANH;
};
@@ -689,13 +695,11 @@ class NNAPIDelegateKernel {
if (version == 1 && kAndroidSdkVersion >= kMinSdkVersionForNNAPI11 &&
context->tensors[node->inputs->data[0]].type == kTfLiteFloat32) {
// NNAPI only support float sub.
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteSubParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
+ auto builtin = reinterpret_cast<TfLiteSubParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_SUB;
};
} else {
@@ -706,13 +710,11 @@ class NNAPIDelegateKernel {
if (version == 1 && kAndroidSdkVersion >= kMinSdkVersionForNNAPI11 &&
context->tensors[node->inputs->data[0]].type == kTfLiteFloat32) {
// NNAPI only support float div.
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteDivParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
+ auto builtin = reinterpret_cast<TfLiteDivParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_DIV;
};
} else {
@@ -726,9 +728,7 @@ class NNAPIDelegateKernel {
// NNAPI does not support specifying the padding value.
// NNAPI pads physical zero for quantized tensors, so only delegate
// float pad to NNAPI.
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_PAD;
};
@@ -738,9 +738,7 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinSpaceToBatchNd:
if (version == 1 && kAndroidSdkVersion >= kMinSdkVersionForNNAPI11) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_SPACE_TO_BATCH_ND;
};
@@ -750,15 +748,14 @@ class NNAPIDelegateKernel {
break;
case kTfLiteBuiltinStridedSlice:
if (version == 1 && kAndroidSdkVersion >= kMinSdkVersionForNNAPI11) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteStridedSliceParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->begin_mask);
- builder->AddScalarInt32Operand(builtin->end_mask);
- builder->AddScalarInt32Operand(builtin->shrink_axis_mask);
+ auto builtin = reinterpret_cast<TfLiteStridedSliceParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->begin_mask);
+ mapping_args.builder->AddScalarInt32Operand(builtin->end_mask);
+ mapping_args.builder->AddScalarInt32Operand(
+ builtin->shrink_axis_mask);
return ANEURALNETWORKS_STRIDED_SLICE;
};
} else {
@@ -774,9 +771,7 @@ class NNAPIDelegateKernel {
(node->inputs->size > 1) &&
(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo)) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_TRANSPOSE;
};
@@ -790,20 +785,19 @@ class NNAPIDelegateKernel {
if (version == 1 &&
context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type ==
kTfLiteFloat32) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
// NNAPI need both state_in and state_out.
int ann_index;
- builder->AddStateFloat32Tensor(
- node->outputs->data[/*kHiddenStateTensor*/ 0], &ann_index);
- model_state_inputs->push_back(ann_index);
- model_state_tfl_outputs->push_back(
- node->outputs->data[/*kHiddenStateTensor*/ 0]);
- auto builtin =
- reinterpret_cast<TfLiteRNNParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
+ mapping_args.builder->AddStateFloat32Tensor(
+ mapping_args.node->outputs->data[/*kHiddenStateTensor*/ 0],
+ &ann_index);
+ mapping_args.model_state_inputs->push_back(ann_index);
+ mapping_args.model_state_tfl_outputs->push_back(
+ mapping_args.node->outputs->data[/*kHiddenStateTensor*/ 0]);
+ auto builtin = reinterpret_cast<TfLiteRNNParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_RNN;
};
} else {
@@ -815,22 +809,21 @@ class NNAPIDelegateKernel {
if (version == 1 &&
context->tensors[node->inputs->data[/*kWeightsFeatureTensor*/ 1]]
.type == kTfLiteFloat32) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
// NNAPI need both state_in and state_out.
int ann_index;
- builder->AddStateFloat32Tensor(
- node->outputs->data[/*kStateTensor*/ 0], &ann_index);
- model_state_inputs->push_back(ann_index);
- model_state_tfl_outputs->push_back(
- node->outputs->data[/*kStateTensor*/ 0]);
-
- auto builtin =
- reinterpret_cast<TfLiteSVDFParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->rank);
- builder->AddScalarInt32Operand(builtin->activation);
+ mapping_args.builder->AddStateFloat32Tensor(
+ mapping_args.node->outputs->data[/*kStateTensor*/ 0],
+ &ann_index);
+ mapping_args.model_state_inputs->push_back(ann_index);
+ mapping_args.model_state_tfl_outputs->push_back(
+ mapping_args.node->outputs->data[/*kStateTensor*/ 0]);
+
+ auto builtin = reinterpret_cast<TfLiteSVDFParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->rank);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
return ANEURALNETWORKS_SVDF;
};
} else {
@@ -844,33 +837,33 @@ class NNAPIDelegateKernel {
context->tensors[node->inputs
->data[/*kInputToOutputWeightsTensor*/ 4]]
.type == kTfLiteFloat32) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
// NNAPI need both state_in and state_out for cell_state and
// output_state.
int ann_index;
- builder->AddStateFloat32Tensor(
- node->outputs->data[/*kOutputStateTensor*/ 0], &ann_index);
- model_state_inputs->push_back(ann_index);
- model_state_tfl_outputs->push_back(
- node->outputs->data[/*kOutputStateTensor*/ 0]);
- builder->AddStateFloat32Tensor(
- node->outputs->data[/*kCellStateTensor*/ 1], &ann_index);
- model_state_inputs->push_back(ann_index);
- model_state_tfl_outputs->push_back(
- node->outputs->data[/*kCellStateTensor*/ 1]);
-
- auto builtin =
- reinterpret_cast<TfLiteLSTMParams*>(node->builtin_data);
- builder->AddScalarInt32Operand(builtin->activation);
- builder->AddScalarFloat32Operand(builtin->cell_clip);
- builder->AddScalarFloat32Operand(builtin->proj_clip);
+ mapping_args.builder->AddStateFloat32Tensor(
+ mapping_args.node->outputs->data[/*kOutputStateTensor*/ 0],
+ &ann_index);
+ mapping_args.model_state_inputs->push_back(ann_index);
+ mapping_args.model_state_tfl_outputs->push_back(
+ mapping_args.node->outputs->data[/*kOutputStateTensor*/ 0]);
+ mapping_args.builder->AddStateFloat32Tensor(
+ mapping_args.node->outputs->data[/*kCellStateTensor*/ 1],
+ &ann_index);
+ mapping_args.model_state_inputs->push_back(ann_index);
+ mapping_args.model_state_tfl_outputs->push_back(
+ mapping_args.node->outputs->data[/*kCellStateTensor*/ 1]);
+
+ auto builtin = reinterpret_cast<TfLiteLSTMParams*>(
+ mapping_args.node->builtin_data);
+ mapping_args.builder->AddScalarInt32Operand(builtin->activation);
+ mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
+ mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
// Current NNAPI implementation requires the sratch_buffer as
// output.
- builder->AddAdditionalFloat32OutputTensor(2);
+ mapping_args.builder->AddAdditionalFloat32OutputTensor(2);
return ANEURALNETWORKS_LSTM;
};
} else {
@@ -882,15 +875,13 @@ class NNAPIDelegateKernel {
if (version == 1 && kAndroidSdkVersion >= kMinSdkVersionForNNAPI11 &&
context->tensors[node->inputs->data[0]].type == kTfLiteFloat32 &&
context->tensors[node->outputs->data[0]].dims->size > 0) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
- auto builtin =
- reinterpret_cast<TfLiteReducerParams*>(node->builtin_data);
+ auto builtin = reinterpret_cast<TfLiteReducerParams*>(
+ mapping_args.node->builtin_data);
int32_t keep_dims = 0;
if (builtin->keep_dims) keep_dims = 1;
- builder->AddScalarInt32Operand(keep_dims);
+ mapping_args.builder->AddScalarInt32Operand(keep_dims);
return ANEURALNETWORKS_MEAN;
};
} else {
@@ -900,9 +891,7 @@ class NNAPIDelegateKernel {
// NNAPI only support float32 values.
if (version == 1 &&
context->tensors[node->inputs->data[1]].type == kTfLiteFloat32) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_EMBEDDING_LOOKUP;
};
@@ -914,9 +903,7 @@ class NNAPIDelegateKernel {
// NNAPI only support float32 output.
if (version == 1 &&
context->tensors[node->outputs->data[0]].type == kTfLiteFloat32) {
- return [](TfLiteContext* context, NNAPIOpBuilder* builder,
- TfLiteNode* node, std::vector<int>* model_state_inputs,
- std::vector<int>* model_state_tfl_outputs)
+ return [](const NNAPIOpMappingArgs& mapping_args)
-> ANeuralNetworksOperationType {
return ANEURALNETWORKS_HASHTABLE_LOOKUP;
};
@@ -964,6 +951,8 @@ class NNAPIDelegateKernel {
// absolute indices but NN api indices inputs by relative indices.
int relative_input_index = 0;
int num_optional_tensors = 0;
+
+ size_t input_offset = 0;
for (auto absolute_input_index : TfLiteIntArrayView(node->inputs)) {
if (absolute_input_index == kOptionalTensor) {
num_optional_tensors++;
@@ -973,20 +962,28 @@ class NNAPIDelegateKernel {
// TODO(miaowang): make sure the delegation works with dequantized weights
// as intermediate tensors.
if (tensor->allocation_type != kTfLiteMmapRo) {
- CHECK_NN(context, ANeuralNetworksExecution_setInput(
+ // copy data to pre-allocated shared memory.
+ memcpy(nn_input_memory_->get_data_ptr() + input_offset,
+ tensor->data.raw, tensor->bytes);
+ CHECK_NN(context, ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, nullptr,
- tensor->data.raw, tensor->bytes));
+ nn_input_memory_->get_handle(), input_offset,
+ tensor->bytes));
+ input_offset += tensor->bytes;
relative_input_index++;
}
}
// Set the output tensor buffers.
int relative_output_index = 0;
+ size_t output_offset = 0;
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
TfLiteTensor* tensor = &context->tensors[output_index];
- CHECK_NN(context, ANeuralNetworksExecution_setOutput(
+ CHECK_NN(context, ANeuralNetworksExecution_setOutputFromMemory(
execution, relative_output_index, nullptr,
- tensor->data.raw, tensor->bytes));
+ nn_output_memory_->get_handle(), output_offset,
+ tensor->bytes));
+ output_offset += tensor->bytes;
relative_output_index++;
}
@@ -1010,6 +1007,15 @@ class NNAPIDelegateKernel {
ANeuralNetworksEvent_free(event);
ANeuralNetworksExecution_free(execution);
+ // copy results from shared memory to the destination.
+ output_offset = 0;
+ for (auto output_index : TfLiteIntArrayView(node->outputs)) {
+ TfLiteTensor* tensor = &context->tensors[output_index];
+ memcpy(tensor->data.raw,
+ nn_output_memory_->get_data_ptr() + output_offset, tensor->bytes);
+ output_offset += tensor->bytes;
+ }
+
return kTfLiteOk;
}
@@ -1027,6 +1033,9 @@ class NNAPIDelegateKernel {
std::vector<int> model_state_inputs_;
std::vector<int> model_state_tfl_outputs_;
+ std::unique_ptr<NNMemory> nn_input_memory_;
+ std::unique_ptr<NNMemory> nn_output_memory_;
+
TfLiteStatus AddOpsAndTensors(TfLiteContext* context) {
// The operand builder allows creating a single op. We create it at this
// reduced power position rather than in the for loop to avoid reallocating
@@ -1054,9 +1063,9 @@ class NNAPIDelegateKernel {
}
}
// Get op type and operands
- int nn_op_type = Map(context, reg->builtin_code, reg->version, node)(
- context, &builder, node, &model_state_inputs_,
- &model_state_tfl_outputs_);
+ int nn_op_type = Map(context, reg->builtin_code, reg->version,
+ node)({context, &builder, node, &model_state_inputs_,
+ &model_state_tfl_outputs_});
// Map outputs to NN API tensor indices.
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
TF_LITE_ENSURE_STATUS(builder.AddTensorOutput(output_index));
@@ -1077,21 +1086,27 @@ class NNAPIDelegateKernel {
inputs.reserve(input_tensors->size);
std::vector<uint32_t> outputs;
outputs.reserve(output_tensors->size);
+
+ size_t total_input_byte_size = 0;
// Make the TensorFlow lite inputs and outputs to ann_indices.
for (int i : TfLiteIntArrayView(input_tensors)) {
// Constant tensors are not NNAPI inputs.
if (i != kOptionalTensor &&
context->tensors[i].allocation_type != kTfLiteMmapRo) {
inputs.push_back(operand_mapping_.lite_index_to_ann(i));
+ total_input_byte_size += context->tensors[i].bytes;
}
}
+
// Add state input tensors as model inputs
for (int i : model_state_inputs_) {
inputs.push_back(i);
}
+ size_t total_output_byte_size = 0;
for (int i : TfLiteIntArrayView(output_tensors)) {
outputs.push_back(operand_mapping_.lite_index_to_ann(i));
+ total_output_byte_size += context->tensors[i].bytes;
}
// Tell ANN to declare inputs/outputs
@@ -1101,6 +1116,11 @@ class NNAPIDelegateKernel {
// Finalize the model
CHECK_NN(context, ANeuralNetworksModel_finish(nn_model_.get()));
+ // Create shared memory pool for inputs and outputs.
+ nn_input_memory_.reset(new NNMemory("input_pool", total_input_byte_size));
+ nn_output_memory_.reset(
+ new NNMemory("output_pool", total_output_byte_size));
+
return kTfLiteOk;
}
};
diff --git a/tensorflow/contrib/lite/error_reporter.cc b/tensorflow/contrib/lite/error_reporter.cc
index 03fcd5409c..646913c026 100644
--- a/tensorflow/contrib/lite/error_reporter.cc
+++ b/tensorflow/contrib/lite/error_reporter.cc
@@ -16,6 +16,10 @@ limitations under the License.
#include <cstdarg>
#include <cstdio>
+#ifdef __ANDROID__
+#include <android/log.h>
+#endif
+
namespace tflite {
ErrorReporter::~ErrorReporter() {}
@@ -39,6 +43,15 @@ int ErrorReporter::ReportError(void*, const char* format, ...) {
}
int StderrReporter::Report(const char* format, va_list args) {
+#ifdef __ANDROID__
+ // On Android stderr is not captured for applications, only for code run from
+ // the shell. Rather than assume all users will set up a custom error
+ // reporter, let's output to logcat here
+ va_list args_for_log;
+ va_copy(args_for_log, args);
+ __android_log_vprint(ANDROID_LOG_ERROR, "tflite", format, args_for_log);
+ va_end(args_for_log);
+#endif
const int result = vfprintf(stderr, format, args);
fputc('\n', stderr);
return result;
diff --git a/tensorflow/contrib/lite/examples/android/build.gradle b/tensorflow/contrib/lite/examples/android/build.gradle
index a47fa4bbf6..66a62a921a 100644
--- a/tensorflow/contrib/lite/examples/android/build.gradle
+++ b/tensorflow/contrib/lite/examples/android/build.gradle
@@ -14,6 +14,7 @@ buildscript {
allprojects {
repositories {
+ google()
jcenter()
}
}
diff --git a/tensorflow/contrib/lite/examples/ios/camera/CameraExampleViewController.mm b/tensorflow/contrib/lite/examples/ios/camera/CameraExampleViewController.mm
index d74e275f04..734b15e0a1 100644
--- a/tensorflow/contrib/lite/examples/ios/camera/CameraExampleViewController.mm
+++ b/tensorflow/contrib/lite/examples/ios/camera/CameraExampleViewController.mm
@@ -26,7 +26,7 @@
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/string_util.h"
-#include "tensorflow/contrib/lite/tools/mutable_op_resolver.h"
+#include "tensorflow/contrib/lite/op_resolver.h"
#define LOG(x) std::cerr
@@ -315,7 +315,7 @@ static void GetTopN(const uint8_t* prediction, const int prediction_size, const
labelLayers = [[NSMutableArray alloc] init];
oldPredictionValues = [[NSMutableDictionary alloc] init];
- NSString* graph_path = FilePathForResourceName(model_file_name, @"tflite");
+ NSString* graph_path = FilePathForResourceName(model_file_name, model_file_type);
model = tflite::FlatBufferModel::BuildFromFile([graph_path UTF8String]);
if (!model) {
LOG(FATAL) << "Failed to mmap model " << graph_path;
diff --git a/tensorflow/contrib/lite/examples/ios/camera/Podfile b/tensorflow/contrib/lite/examples/ios/camera/Podfile
index cd8c39043f..8084307ac7 100644
--- a/tensorflow/contrib/lite/examples/ios/camera/Podfile
+++ b/tensorflow/contrib/lite/examples/ios/camera/Podfile
@@ -2,4 +2,4 @@ platform :ios, '8.0'
inhibit_all_warnings!
target 'tflite_camera_example'
- pod 'TensorFlowLite', '0.1.7'
+ pod 'TensorFlowLite', '1.10.0'
diff --git a/tensorflow/contrib/lite/examples/ios/simple/Podfile b/tensorflow/contrib/lite/examples/ios/simple/Podfile
index c885398f44..eea7ecb759 100644
--- a/tensorflow/contrib/lite/examples/ios/simple/Podfile
+++ b/tensorflow/contrib/lite/examples/ios/simple/Podfile
@@ -2,4 +2,4 @@ platform :ios, '8.0'
inhibit_all_warnings!
target 'tflite_simple_example'
- pod 'TensorFlowLite', '0.1.7'
+ pod 'TensorFlowLite', '1.10.0'
diff --git a/tensorflow/contrib/lite/examples/ios/simple/RunModelViewController.mm b/tensorflow/contrib/lite/examples/ios/simple/RunModelViewController.mm
index 0ab7aa25d0..650c73f732 100644
--- a/tensorflow/contrib/lite/examples/ios/simple/RunModelViewController.mm
+++ b/tensorflow/contrib/lite/examples/ios/simple/RunModelViewController.mm
@@ -25,7 +25,7 @@
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/string_util.h"
-#include "tensorflow/contrib/lite/tools/mutable_op_resolver.h"
+#include "tensorflow/contrib/lite/op_resolver.h"
#include "ios_image_load.h"
diff --git a/tensorflow/contrib/lite/examples/ios/simple/ios_image_load.h b/tensorflow/contrib/lite/examples/ios/simple/ios_image_load.h
index 98934ce41d..96d2810937 100644
--- a/tensorflow/contrib/lite/examples/ios/simple/ios_image_load.h
+++ b/tensorflow/contrib/lite/examples/ios/simple/ios_image_load.h
@@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#ifndef TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
-#define TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
+#ifndef TENSORFLOW_CONTRIB_LITE_EXAMPLES_IOS_SIMPLE_IOS_IMAGE_LOAD_H_
+#define TENSORFLOW_CONTRIB_LITE_EXAMPLES_IOS_SIMPLE_IOS_IMAGE_LOAD_H_
#include <vector>
std::vector<uint8_t> LoadImageFromFile(const char* file_name, int* out_width,
int* out_height, int* out_channels);
-#endif // TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
+#endif // TENSORFLOW_CONTRIB_LITE_EXAMPLES_IOS_SIMPLE_IOS_IMAGE_LOAD_H_
diff --git a/tensorflow/contrib/lite/examples/python/BUILD b/tensorflow/contrib/lite/examples/python/BUILD
new file mode 100644
index 0000000000..d337c3ddc4
--- /dev/null
+++ b/tensorflow/contrib/lite/examples/python/BUILD
@@ -0,0 +1,13 @@
+licenses(["notice"]) # Apache 2.0
+
+package(default_visibility = ["//tensorflow:internal"])
+
+py_binary(
+ name = "label_image",
+ srcs = ["label_image.py"],
+ main = "label_image.py",
+ srcs_version = "PY2AND3",
+ deps = [
+ "//tensorflow/contrib/lite/python:lite",
+ ],
+)
diff --git a/tensorflow/contrib/lite/examples/python/label_image.md b/tensorflow/contrib/lite/examples/python/label_image.md
new file mode 100644
index 0000000000..e81192a96c
--- /dev/null
+++ b/tensorflow/contrib/lite/examples/python/label_image.md
@@ -0,0 +1,50 @@
+
+With model, input image (grace_hopper.bmp), and labels file (labels.txt)
+in /tmp.
+
+The example input image and labels file are from TensorFlow repo and
+MobileNet V1 model files.
+
+```
+curl https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/contrib/lite/examples/label_image/testdata/grace_hopper.bmp > /tmp/grace_hopper.bmp
+
+curl https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_1.0_224_frozen.tgz | tar xzv -C /tmp mobilenet_v1_1.0_224/labels.txt
+mv /tmp/mobilenet_v1_1.0_224/labels.txt /tmp/
+
+```
+
+Run
+
+```
+curl http://download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_1.0_224_quant.tgz | tar xzv -C /tmp
+bazel run --config opt //tensorflow/contrib/lite/examples/python:label_image
+```
+
+We can get results like
+
+```
+0.470588: military uniform
+0.337255: Windsor tie
+0.047059: bow tie
+0.031373: mortarboard
+0.019608: suit
+```
+
+Run
+
+```
+curl http://download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_1.0_224.tgz | tar xzv -C /tmp
+bazel run --config opt //tensorflow/contrib/lite/examples/python:label_image \
+-- --model_file /tmp/mobilenet_v1_1.0_224.tflite
+```
+
+We can get results like
+```
+0.728693: military uniform
+0.116163: Windsor tie
+0.035517: bow tie
+0.014874: mortarboard
+0.011758: bolo tie
+```
+
+Check [models](../../g3doc/models.md) for models hosted by Google.
diff --git a/tensorflow/contrib/lite/examples/python/label_image.py b/tensorflow/contrib/lite/examples/python/label_image.py
new file mode 100644
index 0000000000..282118a1d2
--- /dev/null
+++ b/tensorflow/contrib/lite/examples/python/label_image.py
@@ -0,0 +1,86 @@
+# 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.
+# ==============================================================================
+"""label_image for tflite"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import argparse
+import numpy as np
+
+from PIL import Image
+
+from tensorflow.contrib.lite.python import interpreter as interpreter_wrapper
+
+def load_labels(filename):
+ my_labels = []
+ input_file = open(filename, 'r')
+ for l in input_file:
+ my_labels.append(l.strip())
+ return my_labels
+
+if __name__ == "__main__":
+ floating_model = False
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-i", "--image", default="/tmp/grace_hopper.bmp", \
+ help="image to be classified")
+ parser.add_argument("-m", "--model_file", \
+ default="/tmp/mobilenet_v1_1.0_224_quant.tflite", \
+ help=".tflite model to be executed")
+ parser.add_argument("-l", "--label_file", default="/tmp/labels.txt", \
+ help="name of file containing labels")
+ parser.add_argument("--input_mean", default=127.5, help="input_mean")
+ parser.add_argument("--input_std", default=127.5, \
+ help="input standard deviation")
+ args = parser.parse_args()
+
+ interpreter = interpreter_wrapper.Interpreter(model_path=args.model_file)
+ interpreter.allocate_tensors()
+
+ input_details = interpreter.get_input_details()
+ output_details = interpreter.get_output_details()
+
+ # check the type of the input tensor
+ if input_details[0]['dtype'] == np.float32:
+ floating_model = True
+
+ # NxHxWxC, H:1, W:2
+ height = input_details[0]['shape'][1]
+ width = input_details[0]['shape'][2]
+ img = Image.open(args.image)
+ img = img.resize((width, height))
+
+ # add N dim
+ input_data = np.expand_dims(img, axis=0)
+
+ if floating_model:
+ input_data = (np.float32(input_data) - args.input_mean) / args.input_std
+
+ interpreter.set_tensor(input_details[0]['index'], input_data)
+
+ interpreter.invoke()
+
+ output_data = interpreter.get_tensor(output_details[0]['index'])
+ results = np.squeeze(output_data)
+
+ top_k = results.argsort()[-5:][::-1]
+ labels = load_labels(args.label_file)
+ for i in top_k:
+ if floating_model:
+ print('{0:08.6f}'.format(float(results[i]))+":", labels[i])
+ else:
+ print('{0:08.6f}'.format(float(results[i]/255.0))+":", labels[i])
diff --git a/tensorflow/contrib/lite/experimental/c/BUILD b/tensorflow/contrib/lite/experimental/c/BUILD
index 50f8da66d0..8fc07e8eb7 100644
--- a/tensorflow/contrib/lite/experimental/c/BUILD
+++ b/tensorflow/contrib/lite/experimental/c/BUILD
@@ -26,17 +26,33 @@ tflite_cc_shared_object(
}),
deps = [
":c_api",
+ ":c_api_experimental",
":exported_symbols.lds",
":version_script.lds",
],
)
cc_library(
+ name = "c_api_internal",
+ srcs = ["c_api.h"],
+ hdrs = ["c_api_internal.h"],
+ copts = tflite_copts(),
+ visibility = [
+ "//tensorflow/contrib/lite/experimental/c:__subpackages__",
+ ],
+ deps = [
+ "//tensorflow/contrib/lite:context",
+ "//tensorflow/contrib/lite:framework",
+ ],
+)
+
+cc_library(
name = "c_api",
srcs = ["c_api.cc"],
hdrs = ["c_api.h"],
copts = tflite_copts(),
deps = [
+ ":c_api_internal",
"//tensorflow/contrib/lite:context",
"//tensorflow/contrib/lite:framework",
"//tensorflow/contrib/lite:schema_fbs_version",
@@ -44,6 +60,17 @@ cc_library(
],
)
+cc_library(
+ name = "c_api_experimental",
+ srcs = ["c_api_experimental.cc"],
+ hdrs = ["c_api_experimental.h"],
+ copts = tflite_copts(),
+ deps = [
+ ":c_api",
+ ":c_api_internal",
+ ],
+)
+
cc_test(
name = "c_api_test",
size = "small",
@@ -51,9 +78,21 @@ cc_test(
data = ["//tensorflow/contrib/lite:testdata/add.bin"],
deps = [
":c_api",
- "//tensorflow/contrib/lite:framework",
"//tensorflow/contrib/lite:kernel_api",
"//tensorflow/contrib/lite/testing:util",
"@com_google_googletest//:gtest",
],
)
+
+cc_test(
+ name = "c_api_experimental_test",
+ size = "small",
+ srcs = ["c_api_experimental_test.cc"],
+ data = ["//tensorflow/contrib/lite:testdata/add.bin"],
+ deps = [
+ ":c_api",
+ ":c_api_experimental",
+ "//tensorflow/contrib/lite/testing:util",
+ "@com_google_googletest//:gtest",
+ ],
+)
diff --git a/tensorflow/contrib/lite/experimental/c/c_api.cc b/tensorflow/contrib/lite/experimental/c/c_api.cc
index 9d29e8b3e0..a4ab0e8c30 100644
--- a/tensorflow/contrib/lite/experimental/c/c_api.cc
+++ b/tensorflow/contrib/lite/experimental/c/c_api.cc
@@ -15,6 +15,7 @@ limitations under the License.
#include "tensorflow/contrib/lite/experimental/c/c_api.h"
#include "tensorflow/contrib/lite/context.h"
+#include "tensorflow/contrib/lite/experimental/c/c_api_internal.h"
#include "tensorflow/contrib/lite/interpreter.h"
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
@@ -23,28 +24,55 @@ limitations under the License.
extern "C" {
#endif // __cplusplus
-struct _TFL_Interpreter {
- std::unique_ptr<tflite::Interpreter> impl;
-};
-
// LINT.IfChange
-TFL_Interpreter* TFL_NewInterpreter(const void* model_data,
- int32_t model_size) {
+TFL_Model* TFL_NewModel(const void* model_data, size_t model_size) {
auto model = tflite::FlatBufferModel::BuildFromBuffer(
- static_cast<const char*>(model_data), static_cast<size_t>(model_size));
- if (!model) {
+ static_cast<const char*>(model_data), model_size);
+ return model ? new TFL_Model{std::move(model)} : nullptr;
+}
+
+TFL_Model* TFL_NewModelFromFile(const char* model_path) {
+ auto model = tflite::FlatBufferModel::BuildFromFile(model_path);
+ return model ? new TFL_Model{std::move(model)} : nullptr;
+}
+
+void TFL_DeleteModel(TFL_Model* model) { delete model; }
+
+TFL_InterpreterOptions* TFL_NewInterpreterOptions() {
+ return new TFL_InterpreterOptions{};
+}
+
+void TFL_DeleteInterpreterOptions(TFL_InterpreterOptions* options) {
+ delete options;
+}
+
+void TFL_InterpreterOptionsSetNumThreads(TFL_InterpreterOptions* options,
+ int32_t num_threads) {
+ options->num_threads = num_threads;
+}
+
+TFL_Interpreter* TFL_NewInterpreter(
+ const TFL_Model* model, const TFL_InterpreterOptions* optional_options) {
+ if (!model || !model->impl) {
return nullptr;
}
tflite::ops::builtin::BuiltinOpResolver resolver;
- tflite::InterpreterBuilder builder(*model, resolver);
- std::unique_ptr<tflite::Interpreter> interpreter_impl;
- if (builder(&interpreter_impl) != kTfLiteOk) {
+ tflite::InterpreterBuilder builder(*model->impl, resolver);
+ std::unique_ptr<tflite::Interpreter> interpreter;
+ if (builder(&interpreter) != kTfLiteOk) {
return nullptr;
}
- return new TFL_Interpreter{std::move(interpreter_impl)};
+ if (optional_options) {
+ if (optional_options->num_threads !=
+ TFL_InterpreterOptions::kDefaultNumThreads) {
+ interpreter->SetNumThreads(optional_options->num_threads);
+ }
+ }
+
+ return new TFL_Interpreter{std::move(interpreter)};
}
void TFL_DeleteInterpreter(TFL_Interpreter* interpreter) { delete interpreter; }
@@ -97,9 +125,13 @@ int32_t TFL_TensorDim(const TFL_Tensor* tensor, int32_t dim_index) {
size_t TFL_TensorByteSize(const TFL_Tensor* tensor) { return tensor->bytes; }
+void* TFL_TensorData(const TFL_Tensor* tensor) {
+ return static_cast<void*>(tensor->data.raw);
+}
+
TFL_Status TFL_TensorCopyFromBuffer(TFL_Tensor* tensor, const void* input_data,
- int32_t input_data_size) {
- if (tensor->bytes != static_cast<size_t>(input_data_size)) {
+ size_t input_data_size) {
+ if (tensor->bytes != input_data_size) {
return kTfLiteError;
}
memcpy(tensor->data.raw, input_data, input_data_size);
@@ -107,8 +139,8 @@ TFL_Status TFL_TensorCopyFromBuffer(TFL_Tensor* tensor, const void* input_data,
}
TFL_Status TFL_TensorCopyToBuffer(const TFL_Tensor* tensor, void* output_data,
- int32_t output_data_size) {
- if (tensor->bytes != static_cast<size_t>(output_data_size)) {
+ size_t output_data_size) {
+ if (tensor->bytes != output_data_size) {
return kTfLiteError;
}
memcpy(output_data, tensor->data.raw, output_data_size);
diff --git a/tensorflow/contrib/lite/experimental/c/c_api.h b/tensorflow/contrib/lite/experimental/c/c_api.h
index 070f1add13..3757349b55 100644
--- a/tensorflow/contrib/lite/experimental/c/c_api.h
+++ b/tensorflow/contrib/lite/experimental/c/c_api.h
@@ -30,6 +30,9 @@ limitations under the License.
//
// Conventions:
// * We use the prefix TFL_ for everything in the API.
+// * size_t is used to represent byte sizes of objects that are
+// materialized in the address space of the calling process.
+// * int is used as an index into arrays.
#ifdef SWIG
#define TFL_CAPI_EXPORT
@@ -54,15 +57,50 @@ typedef TfLiteStatus TFL_Status;
typedef TfLiteType TFL_Type;
// --------------------------------------------------------------------------
+// TFL_Model wraps a loaded TensorFlow Lite model.
+typedef struct TFL_Model TFL_Model;
+
+// Returns a model from the provided buffer, or null on failure.
+TFL_CAPI_EXPORT extern TFL_Model* TFL_NewModel(const void* model_data,
+ size_t model_size);
+
+// Returns a model from the provided file, or null on failure.
+TFL_CAPI_EXPORT extern TFL_Model* TFL_NewModelFromFile(const char* model_path);
+
+// Destroys the model instance.
+TFL_CAPI_EXPORT extern void TFL_DeleteModel(TFL_Model* model);
+
+// --------------------------------------------------------------------------
+// TFL_InterpreterOptions allows customized interpreter configuration.
+typedef struct TFL_InterpreterOptions TFL_InterpreterOptions;
+
+// Returns a new interpreter options instances.
+TFL_CAPI_EXPORT extern TFL_InterpreterOptions* TFL_NewInterpreterOptions();
+
+// Destroys the interpreter options instance.
+TFL_CAPI_EXPORT extern void TFL_DeleteInterpreterOptions(
+ TFL_InterpreterOptions* options);
+
+// Sets the number of CPU threads to use for the interpreter.
+TFL_CAPI_EXPORT extern void TFL_InterpreterOptionsSetNumThreads(
+ TFL_InterpreterOptions* options, int32_t num_threads);
+
+// --------------------------------------------------------------------------
// TFL_Interpreter provides inference from a provided model.
-typedef struct _TFL_Interpreter TFL_Interpreter;
+typedef struct TFL_Interpreter TFL_Interpreter;
-// Returns an interpreter for the provided model, or null on failure.
+// Returns a new interpreter using the provided model and options, or null on
+// failure.
+//
+// * `model` must be a valid model instance. The caller retains ownership of the
+// object, and can destroy it immediately after creating the interpreter.
+// * `optional_options` may be null. The caller retains ownership of the object,
+// and can safely destroy it immediately after creating the interpreter.
//
// NOTE: The client *must* explicitly allocate tensors before attempting to
// access input tensor data or invoke the interpreter.
TFL_CAPI_EXPORT extern TFL_Interpreter* TFL_NewInterpreter(
- const void* model_data, int32_t model_size);
+ const TFL_Model* model, const TFL_InterpreterOptions* optional_options);
// Destroys the interpreter.
TFL_CAPI_EXPORT extern void TFL_DeleteInterpreter(TFL_Interpreter* interpreter);
@@ -76,7 +114,8 @@ TFL_CAPI_EXPORT extern int TFL_InterpreterGetInputTensorCount(
TFL_CAPI_EXPORT extern TFL_Tensor* TFL_InterpreterGetInputTensor(
const TFL_Interpreter* interpreter, int32_t input_index);
-// Attempts to resize the specified input tensor.
+// Resizes the specified input tensor.
+//
// NOTE: After a resize, the client *must* explicitly allocate tensors before
// attempting to access the resized tensor data or invoke the interpreter.
// REQUIRES: 0 <= input_index < TFL_InterpreterGetInputTensorCount(tensor)
@@ -131,16 +170,24 @@ TFL_CAPI_EXPORT extern int32_t TFL_TensorDim(const TFL_Tensor* tensor,
// Returns the size of the underlying data in bytes.
TFL_CAPI_EXPORT extern size_t TFL_TensorByteSize(const TFL_Tensor* tensor);
+// Returns a pointer to the underlying data buffer.
+//
+// Note: The result may be null if tensors have not yet been allocated, e.g.,
+// if the Tensor has just been created or resized and `TFL_AllocateTensors()`
+// has yet to be called, or if the output tensor is dynamically sized and the
+// interpreter hasn't been invoked.
+TFL_CAPI_EXPORT extern void* TFL_TensorData(const TFL_Tensor* tensor);
+
// Copies from the provided input buffer into the tensor's buffer.
// REQUIRES: input_data_size == TFL_TensorByteSize(tensor)
TFL_CAPI_EXPORT extern TFL_Status TFL_TensorCopyFromBuffer(
- TFL_Tensor* tensor, const void* input_data, int32_t input_data_size);
+ TFL_Tensor* tensor, const void* input_data, size_t input_data_size);
// Copies to the provided output buffer from the tensor's buffer.
// REQUIRES: output_data_size == TFL_TensorByteSize(tensor)
TFL_CAPI_EXPORT extern TFL_Status TFL_TensorCopyToBuffer(
const TFL_Tensor* output_tensor, void* output_data,
- int32_t output_data_size);
+ size_t output_data_size);
#ifdef __cplusplus
} // extern "C"
diff --git a/tensorflow/contrib/lite/experimental/c/c_api_experimental.cc b/tensorflow/contrib/lite/experimental/c/c_api_experimental.cc
new file mode 100644
index 0000000000..c4dbc55cbf
--- /dev/null
+++ b/tensorflow/contrib/lite/experimental/c/c_api_experimental.cc
@@ -0,0 +1,31 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/contrib/lite/experimental/c/c_api_experimental.h"
+
+#include "tensorflow/contrib/lite/experimental/c/c_api_internal.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+TFL_Status TFL_InterpreterResetVariableTensorsToZero(
+ TFL_Interpreter* interpreter) {
+ return interpreter->impl->ResetVariableTensorsToZero();
+}
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git a/tensorflow/contrib/lite/experimental/c/c_api_experimental.h b/tensorflow/contrib/lite/experimental/c/c_api_experimental.h
new file mode 100644
index 0000000000..b0ac258dcf
--- /dev/null
+++ b/tensorflow/contrib/lite/experimental/c/c_api_experimental.h
@@ -0,0 +1,32 @@
+/* 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.
+==============================================================================*/
+#ifndef TENSORFLOW_CONTRIB_LITE_EXPERIMENTAL_C_C_API_EXPERIMENTAL_H_
+#define TENSORFLOW_CONTRIB_LITE_EXPERIMENTAL_C_C_API_EXPERIMENTAL_H_
+
+#include "tensorflow/contrib/lite/experimental/c/c_api.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+// Resets all variable tensors to zero.
+TFL_CAPI_EXPORT extern TFL_Status TFL_InterpreterResetVariableTensorsToZero(
+ TFL_Interpreter* interpreter);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+
+#endif // TENSORFLOW_CONTRIB_LITE_EXPERIMENTAL_C_C_API_EXPERIMENTAL_H_
diff --git a/tensorflow/contrib/lite/experimental/c/c_api_experimental_test.cc b/tensorflow/contrib/lite/experimental/c/c_api_experimental_test.cc
new file mode 100644
index 0000000000..db6e5251de
--- /dev/null
+++ b/tensorflow/contrib/lite/experimental/c/c_api_experimental_test.cc
@@ -0,0 +1,46 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/contrib/lite/experimental/c/c_api_experimental.h"
+
+#include <gtest/gtest.h>
+#include "tensorflow/contrib/lite/experimental/c/c_api.h"
+#include "tensorflow/contrib/lite/testing/util.h"
+
+namespace {
+
+TEST(CApiExperimentalSimple, Smoke) {
+ TFL_Model* model = TFL_NewModelFromFile(
+ "tensorflow/contrib/lite/testdata/add.bin");
+ ASSERT_NE(model, nullptr);
+
+ TFL_Interpreter* interpreter =
+ TFL_NewInterpreter(model, /*optional_options=*/nullptr);
+ ASSERT_NE(interpreter, nullptr);
+ ASSERT_EQ(TFL_InterpreterAllocateTensors(interpreter), kTfLiteOk);
+
+ EXPECT_EQ(TFL_InterpreterResetVariableTensorsToZero(interpreter), kTfLiteOk);
+
+ TFL_DeleteModel(model);
+ TFL_DeleteInterpreter(interpreter);
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ ::tflite::LogToStderr();
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/tensorflow/contrib/lite/experimental/c/c_api_internal.h b/tensorflow/contrib/lite/experimental/c/c_api_internal.h
new file mode 100644
index 0000000000..c5c612a4c6
--- /dev/null
+++ b/tensorflow/contrib/lite/experimental/c/c_api_internal.h
@@ -0,0 +1,41 @@
+/* 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.
+==============================================================================*/
+#ifndef TENSORFLOW_CONTRIB_LITE_EXPERIMENTAL_C_C_API_INTERNAL_H_
+#define TENSORFLOW_CONTRIB_LITE_EXPERIMENTAL_C_C_API_INTERNAL_H_
+
+#include "tensorflow/contrib/lite/experimental/c/c_api.h"
+
+#include "tensorflow/contrib/lite/interpreter.h"
+#include "tensorflow/contrib/lite/model.h"
+
+// Internal structures used by the C API. These are likely to change and should
+// not be depended on.
+
+struct TFL_Model {
+ std::unique_ptr<tflite::FlatBufferModel> impl;
+};
+
+struct TFL_InterpreterOptions {
+ enum {
+ kDefaultNumThreads = -1,
+ };
+ int num_threads = kDefaultNumThreads;
+};
+
+struct TFL_Interpreter {
+ std::unique_ptr<tflite::Interpreter> impl;
+};
+
+#endif // TENSORFLOW_CONTRIB_LITE_EXPERIMENTAL_C_C_API_INTERNAL_H_
diff --git a/tensorflow/contrib/lite/experimental/c/c_api_test.cc b/tensorflow/contrib/lite/experimental/c/c_api_test.cc
index bc925e00a6..a631dae890 100644
--- a/tensorflow/contrib/lite/experimental/c/c_api_test.cc
+++ b/tensorflow/contrib/lite/experimental/c/c_api_test.cc
@@ -18,22 +18,28 @@ limitations under the License.
#include "tensorflow/contrib/lite/experimental/c/c_api.h"
#include <gtest/gtest.h>
-#include "tensorflow/contrib/lite/allocation.h"
#include "tensorflow/contrib/lite/context.h"
#include "tensorflow/contrib/lite/testing/util.h"
namespace {
TEST(CApiSimple, Smoke) {
- tflite::FileCopyAllocation model_file(
- "tensorflow/contrib/lite/testdata/add.bin",
- tflite::DefaultErrorReporter());
+ TFL_Model* model = TFL_NewModelFromFile(
+ "tensorflow/contrib/lite/testdata/add.bin");
+ ASSERT_NE(model, nullptr);
- TFL_Interpreter* interpreter =
- TFL_NewInterpreter(model_file.base(), model_file.bytes());
+ TFL_InterpreterOptions* options = TFL_NewInterpreterOptions();
+ ASSERT_NE(options, nullptr);
+ TFL_InterpreterOptionsSetNumThreads(options, 2);
+
+ TFL_Interpreter* interpreter = TFL_NewInterpreter(model, options);
ASSERT_NE(interpreter, nullptr);
- ASSERT_EQ(TFL_InterpreterAllocateTensors(interpreter), kTfLiteOk);
+ // The options/model can be deleted immediately after interpreter creation.
+ TFL_DeleteInterpreterOptions(options);
+ TFL_DeleteModel(model);
+
+ ASSERT_EQ(TFL_InterpreterAllocateTensors(interpreter), kTfLiteOk);
ASSERT_EQ(TFL_InterpreterGetInputTensorCount(interpreter), 1);
ASSERT_EQ(TFL_InterpreterGetOutputTensorCount(interpreter), 1);
diff --git a/tensorflow/contrib/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/SDK/Scripts/Interpreter.cs b/tensorflow/contrib/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/SDK/Scripts/Interpreter.cs
index ab966bae2e..b6905b5fbf 100644
--- a/tensorflow/contrib/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/SDK/Scripts/Interpreter.cs
+++ b/tensorflow/contrib/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/SDK/Scripts/Interpreter.cs
@@ -16,6 +16,8 @@ using System;
using System.Runtime.InteropServices;
using TFL_Interpreter = System.IntPtr;
+using TFL_InterpreterOptions = System.IntPtr;
+using TFL_Model = System.IntPtr;
using TFL_Tensor = System.IntPtr;
namespace TensorFlowLite
@@ -32,7 +34,9 @@ namespace TensorFlowLite
public Interpreter(byte[] modelData) {
GCHandle modelDataHandle = GCHandle.Alloc(modelData, GCHandleType.Pinned);
IntPtr modelDataPtr = modelDataHandle.AddrOfPinnedObject();
- handle = TFL_NewInterpreter(modelDataPtr, modelData.Length);
+ TFL_Model model = TFL_NewModel(modelDataPtr, modelData.Length);
+ handle = TFL_NewInterpreter(model, /*options=*/IntPtr.Zero);
+ TFL_DeleteModel(model);
if (handle == IntPtr.Zero) throw new Exception("Failed to create TensorFlowLite Interpreter");
}
@@ -89,9 +93,15 @@ namespace TensorFlowLite
#region Externs
[DllImport (TensorFlowLibrary)]
+ private static extern unsafe TFL_Interpreter TFL_NewModel(IntPtr model_data, int model_size);
+
+ [DllImport (TensorFlowLibrary)]
+ private static extern unsafe TFL_Interpreter TFL_DeleteModel(TFL_Model model);
+
+ [DllImport (TensorFlowLibrary)]
private static extern unsafe TFL_Interpreter TFL_NewInterpreter(
- IntPtr model_data,
- int model_size);
+ TFL_Model model,
+ TFL_InterpreterOptions optional_options);
[DllImport (TensorFlowLibrary)]
private static extern unsafe void TFL_DeleteInterpreter(TFL_Interpreter interpreter);
diff --git a/tensorflow/contrib/lite/g3doc/_book.yaml b/tensorflow/contrib/lite/g3doc/_book.yaml
index 98abd5743b..1dffe30790 100644
--- a/tensorflow/contrib/lite/g3doc/_book.yaml
+++ b/tensorflow/contrib/lite/g3doc/_book.yaml
@@ -1,6 +1,7 @@
upper_tabs:
# Tabs left of dropdown menu
- include: /_upper_tabs_left.yaml
+- include: /versions/_upper_tabs_versions.yaml
# Dropdown menu
- name: Ecosystem
path: /ecosystem
diff --git a/tensorflow/contrib/lite/g3doc/rpi.md b/tensorflow/contrib/lite/g3doc/rpi.md
index cdc9172d87..9fcf79ba00 100644
--- a/tensorflow/contrib/lite/g3doc/rpi.md
+++ b/tensorflow/contrib/lite/g3doc/rpi.md
@@ -20,7 +20,7 @@ Clone this Tensorflow repository, Run this script at the root of the repository
```bash
./tensorflow/contrib/lite/download_dependencies.sh
```
-Note than you only need to to this once.
+Note that you only need to do this once.
You should then be able to compile:
```bash
@@ -42,7 +42,7 @@ First, clone this TensorFlow repository. Run this at the root of the repository:
```bash
./tensorflow/contrib/lite/download_dependencies.sh
```
-Note than you only need to to this once.
+Note that you only need to do this once.
You should then be able to compile:
```bash
diff --git a/tensorflow/contrib/lite/interpreter.cc b/tensorflow/contrib/lite/interpreter.cc
index 7a680f5c64..362e588725 100644
--- a/tensorflow/contrib/lite/interpreter.cc
+++ b/tensorflow/contrib/lite/interpreter.cc
@@ -157,7 +157,7 @@ Interpreter::~Interpreter() {
TfLiteTensor* tensor = &context_.tensors[i];
if (tensor->buffer_handle != kTfLiteNullBufferHandle &&
tensor->delegate->FreeBufferHandle != nullptr) {
- tensor->delegate->FreeBufferHandle(tensor->delegate,
+ tensor->delegate->FreeBufferHandle(&context_, tensor->delegate,
&tensor->buffer_handle);
}
TfLiteTensorFree(tensor);
@@ -988,7 +988,7 @@ TfLiteStatus Interpreter::SetBufferHandle(int tensor_index,
tensor->delegate = delegate;
if (tensor->buffer_handle != kTfLiteNullBufferHandle) {
TF_LITE_ENSURE(&context_, tensor->delegate->FreeBufferHandle != nullptr);
- tensor->delegate->FreeBufferHandle(tensor->delegate,
+ tensor->delegate->FreeBufferHandle(&context_, tensor->delegate,
&tensor->buffer_handle);
}
tensor->buffer_handle = buffer_handle;
diff --git a/tensorflow/contrib/lite/interpreter.h b/tensorflow/contrib/lite/interpreter.h
index e8301ff507..7d69aa2ad3 100644
--- a/tensorflow/contrib/lite/interpreter.h
+++ b/tensorflow/contrib/lite/interpreter.h
@@ -165,7 +165,7 @@ class Interpreter {
return SetTensorParametersReadOnly(tensor_index, type, name, dims.size(),
dims.data(), quantization, buffer, bytes,
allocation);
- };
+ }
TfLiteStatus SetTensorParametersReadOnly(
int tensor_index, TfLiteType type, const char* name, const size_t rank,
@@ -350,7 +350,7 @@ class Interpreter {
// This can be null if the delegate doesn't use its own buffer.
TF_LITE_ENSURE(&context_,
tensor->delegate->CopyFromBufferHandle != nullptr);
- tensor->delegate->CopyFromBufferHandle(tensor->delegate,
+ tensor->delegate->CopyFromBufferHandle(&context_, tensor->delegate,
tensor->buffer_handle,
tensor->data.raw, tensor->bytes);
tensor->data_is_stale = false;
@@ -413,7 +413,12 @@ class Interpreter {
return op_reg.profiling_string(&context_, node);
}
+ // Set the value of an external context.
+ void SetExternalContext(TfLiteExternalContextType type,
+ TfLiteExternalContext* ctx);
+
private:
+ friend class InterpreterBuilder;
friend class InterpreterTest;
// Prevent 'context_' from accessing functions that are only available to
@@ -543,12 +548,30 @@ class Interpreter {
struct TfLiteContext* context, TfLiteExternalContextType type);
// Set the value of an external context.
- void SetExternalContext(TfLiteExternalContextType type,
- TfLiteExternalContext* ctx);
static void SetExternalContext(struct TfLiteContext* context,
TfLiteExternalContextType type,
TfLiteExternalContext* ctx);
+ using TfLiteDelegatePtr =
+ std::unique_ptr<TfLiteDelegate, void (*)(TfLiteDelegate*)>;
+
+ // Variant of the public ModifyGraphWithDelegate method that additionally
+ // Assumes ownership of the provided delegate.
+ // WARNING: This is an experimental API and subject to change.
+ template <typename Delegate>
+ TfLiteStatus ModifyGraphWithDelegate(std::unique_ptr<Delegate> typed_delegate,
+ bool allow_dynamic_tensors = false) {
+ TfLiteDelegatePtr delegate(typed_delegate.release(),
+ [](TfLiteDelegate* delegate) {
+ delete static_cast<Delegate*>(delegate);
+ });
+ // Note that we retain ownership of the delegate even if graph modification
+ // fails, as delegate use will be in an indeterminate state at that point.
+ owned_delegates_.push_back(std::move(delegate));
+ return ModifyGraphWithDelegate(owned_delegates_.back().get(),
+ allow_dynamic_tensors);
+ }
+
// Ensures that `tensors_` has at least `kTensorsCapacityHeadroom` extra
// capacity. Calling this function may invalidate existing pointers to
// tensors. After calling this function, adding `kTensorsCapacityHeadroom`
@@ -628,6 +651,11 @@ class Interpreter {
// Whether to delegate to NN API
std::unique_ptr<NNAPIDelegate> nnapi_delegate_;
+ // List of delegates that have been installed and are owned by this
+ // interpreter instance. Useful if client delegate ownership is burdensome.
+ // WARNING: This is an experimental API and subject to change.
+ std::vector<TfLiteDelegatePtr> owned_delegates_;
+
std::unique_ptr<MemoryPlanner> memory_planner_;
bool allow_buffer_handle_output_ = false;
diff --git a/tensorflow/contrib/lite/interpreter_test.cc b/tensorflow/contrib/lite/interpreter_test.cc
index 2bf598bad7..5bcf0927d8 100644
--- a/tensorflow/contrib/lite/interpreter_test.cc
+++ b/tensorflow/contrib/lite/interpreter_test.cc
@@ -26,6 +26,13 @@ namespace tflite {
// InterpreterTest is a friend of Interpreter, so it can access context_.
class InterpreterTest : public ::testing::Test {
+ public:
+ template <typename Delegate>
+ static TfLiteStatus ModifyGraphWithDelegate(
+ Interpreter* interpreter, std::unique_ptr<Delegate> delegate) {
+ return interpreter->ModifyGraphWithDelegate(std::move(delegate));
+ }
+
protected:
TfLiteContext* GetInterpreterContext() { return &interpreter_.context_; }
@@ -1080,21 +1087,22 @@ class TestDelegate : public ::testing::Test {
return kTfLiteOk;
};
delegate_.CopyToBufferHandle =
- [](TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle,
- void* data, size_t size) -> TfLiteStatus {
+ [](TfLiteContext* context, TfLiteDelegate* delegate,
+ TfLiteBufferHandle buffer_handle, void* data,
+ size_t size) -> TfLiteStatus {
// TODO(ycling): Implement tests to test buffer copying logic.
return kTfLiteOk;
};
delegate_.CopyFromBufferHandle =
- [](TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle,
- void* data, size_t size) -> TfLiteStatus {
+ [](TfLiteContext* context, TfLiteDelegate* delegate,
+ TfLiteBufferHandle buffer_handle, void* data,
+ size_t size) -> TfLiteStatus {
// TODO(ycling): Implement tests to test buffer copying logic.
return kTfLiteOk;
};
- delegate_.FreeBufferHandle = [](TfLiteDelegate* delegate,
- TfLiteBufferHandle* handle) {
- *handle = kTfLiteNullBufferHandle;
- };
+ delegate_.FreeBufferHandle =
+ [](TfLiteContext* context, TfLiteDelegate* delegate,
+ TfLiteBufferHandle* handle) { *handle = kTfLiteNullBufferHandle; };
// Store type-punned data SimpleDelegate structure.
delegate_.data_ = reinterpret_cast<void*>(this);
}
@@ -1301,6 +1309,57 @@ TEST_F(TestDelegateWithDynamicTensors, AllowDynamicTensors) {
ASSERT_EQ(interpreter_->execution_plan()[0], 1);
}
+TEST(TestDelegateOwnership, ProperlyDisposed) {
+ struct TfLiteInterpreterOwnedDelegate : public TfLiteDelegate {
+ TfLiteInterpreterOwnedDelegate(bool* destroyed, bool* prepared)
+ : destroyed(destroyed), prepared(prepared) {
+ Prepare = [](TfLiteContext*, TfLiteDelegate* delegate) -> TfLiteStatus {
+ *static_cast<TfLiteInterpreterOwnedDelegate*>(delegate)->prepared =
+ true;
+ return kTfLiteOk;
+ };
+ }
+ ~TfLiteInterpreterOwnedDelegate() { *destroyed = true; }
+
+ bool* destroyed;
+ bool* prepared;
+ };
+
+ // Construct a delegate with flags for indicating preparation/destruction.
+ bool destroyed = false;
+ bool prepared = false;
+ std::unique_ptr<TfLiteInterpreterOwnedDelegate> delegate(
+ new TfLiteInterpreterOwnedDelegate(&destroyed, &prepared));
+ {
+ // Create an interpreter and assemble a simple graph.
+ Interpreter interpreter;
+ TfLiteRegistration registration = {nullptr, nullptr, nullptr, nullptr};
+ ASSERT_EQ(interpreter.AddTensors(2), kTfLiteOk);
+ ASSERT_EQ(interpreter.SetInputs({0}), kTfLiteOk);
+ ASSERT_EQ(interpreter.SetOutputs({1}), kTfLiteOk);
+ ASSERT_EQ(interpreter.AddNodeWithParameters({0}, {1}, nullptr, 0, nullptr,
+ &registration),
+ kTfLiteOk);
+
+ // Pass delegate ownership to that interpreter.
+ ASSERT_EQ(InterpreterTest::ModifyGraphWithDelegate(&interpreter,
+ std::move(delegate)),
+ kTfLiteOk);
+
+ // The delegate should be prepared as normal, and should be preserved.
+ EXPECT_TRUE(prepared);
+ EXPECT_FALSE(destroyed);
+
+ // Interpreter interaction should not impact the delegate's validity.
+ interpreter.AllocateTensors();
+ interpreter.Invoke();
+ EXPECT_FALSE(destroyed);
+ }
+
+ // Only after the interpreter is destroyed should the delegate be destroyed.
+ EXPECT_TRUE(destroyed);
+}
+
} // namespace
} // namespace tflite
diff --git a/tensorflow/contrib/lite/java/demo/.gitignore b/tensorflow/contrib/lite/java/demo/.gitignore
index 39fb081a42..d245ab6109 100644
--- a/tensorflow/contrib/lite/java/demo/.gitignore
+++ b/tensorflow/contrib/lite/java/demo/.gitignore
@@ -1,9 +1,29 @@
+# This file is based on https://github.com/github/gitignore/blob/master/Android.gitignore
*.iml
+.idea/compiler.xml
+.idea/copyright
+.idea/dictionaries
+.idea/gradle.xml
+.idea/libraries
+.idea/inspectionProfiles
+.idea/misc.xml
+.idea/modules.xml
+.idea/runConfigurations.xml
+.idea/tasks.xml
+.idea/workspace.xml
.gradle
-/local.properties
-/.idea/workspace.xml
-/.idea/libraries
+local.properties
.DS_Store
-/build
+build/
+gradleBuild/
+*.apk
+*.ap_
+*.dex
+*.class
+bin/
+gen/
+out/
+*.log
+.navigation/
/captures
.externalNativeBuild
diff --git a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/DataType.java b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/DataType.java
index 94a1ec65d6..41093e8ffe 100644
--- a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/DataType.java
+++ b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/DataType.java
@@ -15,8 +15,8 @@ limitations under the License.
package org.tensorflow.lite;
-/** Type of elements in a {@link TfLiteTensor}. */
-enum DataType {
+/** Represents the type of elements in a TensorFlow Lite {@link Tensor} as an enum. */
+public enum DataType {
/** 32-bit single precision floating point. */
FLOAT32(1),
@@ -35,13 +35,29 @@ enum DataType {
this.value = value;
}
- /** Corresponding value of the kTfLite* enum in the TensorFlow Lite CC API. */
- int getNumber() {
+ /** Returns the size of an element of this type, in bytes, or -1 if element size is variable. */
+ public int byteSize() {
+ switch (this) {
+ case FLOAT32:
+ return 4;
+ case INT32:
+ return 4;
+ case UINT8:
+ return 1;
+ case INT64:
+ return 8;
+ }
+ throw new IllegalArgumentException(
+ "DataType error: DataType " + this + " is not supported yet");
+ }
+
+ /** Corresponding value of the TfLiteType enum in the TensorFlow Lite C API. */
+ int c() {
return value;
}
- /** Converts an integer to the corresponding type. */
- static DataType fromNumber(int c) {
+ /** Converts a C TfLiteType enum value to the corresponding type. */
+ static DataType fromC(int c) {
for (DataType t : values) {
if (t.value == c) {
return t;
@@ -55,22 +71,6 @@ enum DataType {
+ ")");
}
- /** Returns byte size of the type. */
- int elemByteSize() {
- switch (this) {
- case FLOAT32:
- return 4;
- case INT32:
- return 4;
- case UINT8:
- return 1;
- case INT64:
- return 8;
- }
- throw new IllegalArgumentException(
- "DataType error: DataType " + this + " is not supported yet");
- }
-
/** Gets string names of the data type. */
String toStringName() {
switch (this) {
diff --git a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Interpreter.java b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Interpreter.java
index 7002f82677..b84720ae8e 100644
--- a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Interpreter.java
+++ b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Interpreter.java
@@ -162,9 +162,7 @@ public final class Interpreter implements AutoCloseable {
*/
public void runForMultipleInputsOutputs(
@NonNull Object[] inputs, @NonNull Map<Integer, Object> outputs) {
- if (wrapper == null) {
- throw new IllegalStateException("Internal error: The Interpreter has already been closed.");
- }
+ checkNotClosed();
wrapper.run(inputs, outputs);
}
@@ -174,12 +172,16 @@ public final class Interpreter implements AutoCloseable {
* <p>IllegalArgumentException will be thrown if it fails to resize.
*/
public void resizeInput(int idx, @NonNull int[] dims) {
- if (wrapper == null) {
- throw new IllegalStateException("Internal error: The Interpreter has already been closed.");
- }
+ checkNotClosed();
wrapper.resizeInput(idx, dims);
}
+ /** Gets the number of input tensors. */
+ public int getInputTensorCount() {
+ checkNotClosed();
+ return wrapper.getInputTensorCount();
+ }
+
/**
* Gets index of an input given the op name of the input.
*
@@ -187,51 +189,65 @@ public final class Interpreter implements AutoCloseable {
* to initialize the {@link Interpreter}.
*/
public int getInputIndex(String opName) {
- if (wrapper == null) {
- throw new IllegalStateException("Internal error: The Interpreter has already been closed.");
- }
+ checkNotClosed();
return wrapper.getInputIndex(opName);
}
/**
+ * Gets the Tensor associated with the provdied input index.
+ *
+ * <p>IllegalArgumentException will be thrown if the provided index is invalid.
+ */
+ public Tensor getInputTensor(int inputIndex) {
+ checkNotClosed();
+ return wrapper.getInputTensor(inputIndex);
+ }
+
+ /** Gets the number of output Tensors. */
+ public int getOutputTensorCount() {
+ checkNotClosed();
+ return wrapper.getOutputTensorCount();
+ }
+
+ /**
* Gets index of an output given the op name of the output.
*
* <p>IllegalArgumentException will be thrown if the op name does not exist in the model file used
* to initialize the {@link Interpreter}.
*/
public int getOutputIndex(String opName) {
- if (wrapper == null) {
- throw new IllegalStateException("Internal error: The Interpreter has already been closed.");
- }
+ checkNotClosed();
return wrapper.getOutputIndex(opName);
}
/**
+ * Gets the Tensor associated with the provdied output index.
+ *
+ * <p>IllegalArgumentException will be thrown if the provided index is invalid.
+ */
+ public Tensor getOutputTensor(int outputIndex) {
+ checkNotClosed();
+ return wrapper.getOutputTensor(outputIndex);
+ }
+
+ /**
* Returns native inference timing.
* <p>IllegalArgumentException will be thrown if the model is not initialized by the
* {@link Interpreter}.
*/
public Long getLastNativeInferenceDurationNanoseconds() {
- if (wrapper == null) {
- throw new IllegalStateException("Internal error: The interpreter has already been closed.");
- }
+ checkNotClosed();
return wrapper.getLastNativeInferenceDurationNanoseconds();
}
/** Turns on/off Android NNAPI for hardware acceleration when it is available. */
public void setUseNNAPI(boolean useNNAPI) {
- if (wrapper != null) {
- wrapper.setUseNNAPI(useNNAPI);
- } else {
- throw new IllegalStateException(
- "Internal error: NativeInterpreterWrapper has already been closed.");
- }
+ checkNotClosed();
+ wrapper.setUseNNAPI(useNNAPI);
}
public void setNumThreads(int numThreads) {
- if (wrapper == null) {
- throw new IllegalStateException("The interpreter has already been closed.");
- }
+ checkNotClosed();
wrapper.setNumThreads(numThreads);
}
@@ -253,5 +269,11 @@ public final class Interpreter implements AutoCloseable {
}
}
+ private void checkNotClosed() {
+ if (wrapper == null) {
+ throw new IllegalStateException("Internal error: The Interpreter has already been closed.");
+ }
+ }
+
NativeInterpreterWrapper wrapper;
}
diff --git a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/NativeInterpreterWrapper.java b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/NativeInterpreterWrapper.java
index 767a220f8c..fa25082304 100644
--- a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/NativeInterpreterWrapper.java
+++ b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/NativeInterpreterWrapper.java
@@ -114,12 +114,10 @@ final class NativeInterpreterWrapper implements AutoCloseable {
}
}
- if (!isMemoryAllocated) {
+ boolean needsAllocation = !isMemoryAllocated;
+ if (needsAllocation) {
allocateTensors(interpreterHandle, errorHandle);
isMemoryAllocated = true;
- // Allocation can trigger dynamic resizing of output tensors, so clear the
- // output tensor cache.
- Arrays.fill(outputTensors, null);
}
for (int i = 0; i < inputs.length; ++i) {
@@ -130,6 +128,14 @@ final class NativeInterpreterWrapper implements AutoCloseable {
run(interpreterHandle, errorHandle);
long inferenceDurationNanoseconds = System.nanoTime() - inferenceStartNanos;
+ // Allocation can trigger dynamic resizing of output tensors, so refresh all output shapes.
+ if (needsAllocation) {
+ for (int i = 0; i < outputTensors.length; ++i) {
+ if (outputTensors[i] != null) {
+ outputTensors[i].refreshShape();
+ }
+ }
+ }
for (Map.Entry<Integer, Object> output : outputs.entrySet()) {
getOutputTensor(output.getKey()).copyTo(output.getValue());
}
@@ -144,8 +150,9 @@ final class NativeInterpreterWrapper implements AutoCloseable {
void resizeInput(int idx, int[] dims) {
if (resizeInput(interpreterHandle, errorHandle, idx, dims)) {
isMemoryAllocated = false;
- // Resizing will invalidate the Tensor's shape, so invalidate the Tensor handle.
- inputTensors[idx] = null;
+ if (inputTensors[idx] != null) {
+ inputTensors[idx].refreshShape();
+ }
}
}
@@ -230,6 +237,11 @@ final class NativeInterpreterWrapper implements AutoCloseable {
return getOutputQuantizationScale(interpreterHandle, index);
}
+ /** Gets the number of input tensors. */
+ int getInputTensorCount() {
+ return inputTensors.length;
+ }
+
/**
* Gets the input {@link Tensor} for the provided input index.
*
@@ -247,6 +259,11 @@ final class NativeInterpreterWrapper implements AutoCloseable {
return inputTensor;
}
+ /** Gets the number of output tensors. */
+ int getOutputTensorCount() {
+ return inputTensors.length;
+ }
+
/**
* Gets the output {@link Tensor} for the provided output index.
*
diff --git a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Tensor.java b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Tensor.java
index 2403570c52..f174178d98 100644
--- a/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Tensor.java
+++ b/tensorflow/contrib/lite/java/src/main/java/org/tensorflow/lite/Tensor.java
@@ -26,7 +26,7 @@ import java.util.Arrays;
* <p>The native handle of a {@code Tensor} belongs to {@code NativeInterpreterWrapper}, thus not
* needed to be closed here.
*/
-final class Tensor {
+public final class Tensor {
static Tensor fromHandle(long nativeHandle) {
return new Tensor(nativeHandle);
@@ -37,11 +37,26 @@ final class Tensor {
return dtype;
}
+ /**
+ * Returns the number of dimensions (sometimes referred to as <a
+ * href="https://www.tensorflow.org/resources/dims_types.html#rank">rank</a>) of the Tensor.
+ *
+ * <p>Will be 0 for a scalar, 1 for a vector, 2 for a matrix, 3 for a 3-dimensional tensor etc.
+ */
+ public int numDimensions() {
+ return shapeCopy.length;
+ }
+
/** Returns the size, in bytes, of the tensor data. */
public int numBytes() {
return numBytes(nativeHandle);
}
+ /** Returns the number of elements in a flattened (1-D) view of the tensor. */
+ public int numElements() {
+ return computeNumElements(shapeCopy);
+ }
+
/**
* Returns the <a href="https://www.tensorflow.org/resources/dims_types.html#shape">shape</a> of
* the Tensor, i.e., the sizes of each dimension.
@@ -103,13 +118,22 @@ final class Tensor {
if (isByteBuffer(input)) {
return null;
}
- int[] inputShape = shapeOf(input);
+ int[] inputShape = computeShapeOf(input);
if (Arrays.equals(shapeCopy, inputShape)) {
return null;
}
return inputShape;
}
+ /**
+ * Forces a refresh of the tensor's cached shape.
+ *
+ * <p>This is useful if the tensor is resized or has a dynamic shape.
+ */
+ void refreshShape() {
+ this.shapeCopy = shape(nativeHandle);
+ }
+
/** Returns the type of the data. */
static DataType dataTypeOf(Object o) {
if (o != null) {
@@ -132,22 +156,31 @@ final class Tensor {
}
/** Returns the shape of an object as an int array. */
- static int[] shapeOf(Object o) {
- int size = numDimensions(o);
+ static int[] computeShapeOf(Object o) {
+ int size = computeNumDimensions(o);
int[] dimensions = new int[size];
fillShape(o, 0, dimensions);
return dimensions;
}
+ /** Returns the number of elements in a flattened (1-D) view of the tensor's shape. */
+ static int computeNumElements(int[] shape) {
+ int n = 1;
+ for (int i = 0; i < shape.length; ++i) {
+ n *= shape[i];
+ }
+ return n;
+ }
+
/** Returns the number of dimensions of a multi-dimensional array, otherwise 0. */
- static int numDimensions(Object o) {
+ static int computeNumDimensions(Object o) {
if (o == null || !o.getClass().isArray()) {
return 0;
}
if (Array.getLength(o) == 0) {
throw new IllegalArgumentException("Array lengths cannot be 0.");
}
- return 1 + numDimensions(Array.get(o, 0));
+ return 1 + computeNumDimensions(Array.get(o, 0));
}
/** Recursively populates the shape dimensions for a given (multi-dimensional) array. */
@@ -188,7 +221,7 @@ final class Tensor {
dtype, o.getClass().getName(), oType));
}
- int[] oShape = shapeOf(o);
+ int[] oShape = computeShapeOf(o);
if (!Arrays.equals(oShape, shapeCopy)) {
throw new IllegalArgumentException(
String.format(
@@ -204,11 +237,11 @@ final class Tensor {
private final long nativeHandle;
private final DataType dtype;
- private final int[] shapeCopy;
+ private int[] shapeCopy;
private Tensor(long nativeHandle) {
this.nativeHandle = nativeHandle;
- this.dtype = DataType.fromNumber(dtype(nativeHandle));
+ this.dtype = DataType.fromC(dtype(nativeHandle));
this.shapeCopy = shape(nativeHandle);
}
diff --git a/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/DataTypeTest.java b/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/DataTypeTest.java
index cebc944200..6d6417f895 100644
--- a/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/DataTypeTest.java
+++ b/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/DataTypeTest.java
@@ -26,9 +26,16 @@ public final class DataTypeTest {
@Test
public void testElemByteSize() {
- assertThat(DataType.FLOAT32.elemByteSize()).isEqualTo(4);
- assertThat(DataType.INT32.elemByteSize()).isEqualTo(4);
- assertThat(DataType.UINT8.elemByteSize()).isEqualTo(1);
- assertThat(DataType.INT64.elemByteSize()).isEqualTo(8);
+ assertThat(DataType.FLOAT32.byteSize()).isEqualTo(4);
+ assertThat(DataType.INT32.byteSize()).isEqualTo(4);
+ assertThat(DataType.UINT8.byteSize()).isEqualTo(1);
+ assertThat(DataType.INT64.byteSize()).isEqualTo(8);
+ }
+
+ @Test
+ public void testConversion() {
+ for (DataType dataType : DataType.values()) {
+ assertThat(DataType.fromC(dataType.c())).isEqualTo(dataType);
+ }
}
}
diff --git a/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/InterpreterTest.java b/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/InterpreterTest.java
index d66a73db94..9070b788b6 100644
--- a/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/InterpreterTest.java
+++ b/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/InterpreterTest.java
@@ -47,6 +47,10 @@ public final class InterpreterTest {
public void testInterpreter() throws Exception {
Interpreter interpreter = new Interpreter(MODEL_FILE);
assertThat(interpreter).isNotNull();
+ assertThat(interpreter.getInputTensorCount()).isEqualTo(1);
+ assertThat(interpreter.getInputTensor(0).dataType()).isEqualTo(DataType.FLOAT32);
+ assertThat(interpreter.getOutputTensorCount()).isEqualTo(1);
+ assertThat(interpreter.getOutputTensor(0).dataType()).isEqualTo(DataType.FLOAT32);
interpreter.close();
}
@@ -183,6 +187,19 @@ public final class InterpreterTest {
}
@Test
+ public void testResizeInput() {
+ try (Interpreter interpreter = new Interpreter(MODEL_FILE)) {
+ int[] inputDims = {1};
+ interpreter.resizeInput(0, inputDims);
+ assertThat(interpreter.getInputTensor(0).shape()).isEqualTo(inputDims);
+ ByteBuffer input = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder());
+ ByteBuffer output = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder());
+ interpreter.run(input, output);
+ assertThat(interpreter.getOutputTensor(0).shape()).isEqualTo(inputDims);
+ }
+ }
+
+ @Test
public void testMobilenetRun() {
// Create a gray image.
float[][][][] img = new float[1][224][224][3];
@@ -199,6 +216,8 @@ public final class InterpreterTest {
Interpreter interpreter = new Interpreter(MOBILENET_MODEL_FILE);
interpreter.run(img, labels);
+ assertThat(interpreter.getInputTensor(0).shape()).isEqualTo(new int[] {1, 224, 224, 3});
+ assertThat(interpreter.getOutputTensor(0).shape()).isEqualTo(new int[] {1, 1001});
interpreter.close();
assertThat(labels[0])
diff --git a/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/TensorTest.java b/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/TensorTest.java
index 71ef044943..85ad393d89 100644
--- a/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/TensorTest.java
+++ b/tensorflow/contrib/lite/java/src/test/java/org/tensorflow/lite/TensorTest.java
@@ -64,6 +64,8 @@ public final class TensorTest {
assertThat(tensor.shape()).isEqualTo(expectedShape);
assertThat(tensor.dataType()).isEqualTo(DataType.FLOAT32);
assertThat(tensor.numBytes()).isEqualTo(2 * 8 * 8 * 3 * 4);
+ assertThat(tensor.numElements()).isEqualTo(2 * 8 * 8 * 3);
+ assertThat(tensor.numDimensions()).isEqualTo(4);
}
@Test
@@ -201,12 +203,12 @@ public final class TensorTest {
@Test
public void testNumDimensions() {
int scalar = 1;
- assertThat(Tensor.numDimensions(scalar)).isEqualTo(0);
+ assertThat(Tensor.computeNumDimensions(scalar)).isEqualTo(0);
int[][] array = {{2, 4}, {1, 9}};
- assertThat(Tensor.numDimensions(array)).isEqualTo(2);
+ assertThat(Tensor.computeNumDimensions(array)).isEqualTo(2);
try {
int[] emptyArray = {};
- Tensor.numDimensions(emptyArray);
+ Tensor.computeNumDimensions(emptyArray);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessageThat().contains("Array lengths cannot be 0.");
@@ -214,9 +216,21 @@ public final class TensorTest {
}
@Test
+ public void testNumElements() {
+ int[] scalarShape = {};
+ assertThat(Tensor.computeNumElements(scalarShape)).isEqualTo(1);
+ int[] vectorShape = {3};
+ assertThat(Tensor.computeNumElements(vectorShape)).isEqualTo(3);
+ int[] matrixShape = {3, 4};
+ assertThat(Tensor.computeNumElements(matrixShape)).isEqualTo(12);
+ int[] degenerateShape = {3, 4, 0};
+ assertThat(Tensor.computeNumElements(degenerateShape)).isEqualTo(0);
+ }
+
+ @Test
public void testFillShape() {
int[][][] array = {{{23}, {14}, {87}}, {{12}, {42}, {31}}};
- int num = Tensor.numDimensions(array);
+ int num = Tensor.computeNumDimensions(array);
int[] shape = new int[num];
Tensor.fillShape(array, 0, shape);
assertThat(num).isEqualTo(3);
diff --git a/tensorflow/contrib/lite/java/src/testhelper/java/org/tensorflow/lite/TestHelper.java b/tensorflow/contrib/lite/java/src/testhelper/java/org/tensorflow/lite/TestHelper.java
index c23521c077..38b740021b 100644
--- a/tensorflow/contrib/lite/java/src/testhelper/java/org/tensorflow/lite/TestHelper.java
+++ b/tensorflow/contrib/lite/java/src/testhelper/java/org/tensorflow/lite/TestHelper.java
@@ -66,6 +66,25 @@ public class TestHelper {
}
/**
+ * Gets the string name of the data type of an input.
+ *
+ * @param interpreter an instance of {@code Interpreter}. If it is not initialized, an {@code
+ * IllegalArgumentException} will be thrown.
+ * @param index an integer index of the input. If it is invalid, an {@code
+ * IllegalArgumentException} will be thrown.
+ * @return string name of the data type. Possible values include "float", "int", "byte", and
+ * "long".
+ */
+ public static String getInputDataType(Interpreter interpreter, int index) {
+ if (interpreter != null && interpreter.wrapper != null) {
+ return interpreter.wrapper.getInputTensor(index).dataType().toStringName();
+ } else {
+ throw new IllegalArgumentException(
+ "Interpreter has not initialized;" + " Failed to get input data type.");
+ }
+ }
+
+ /**
* Gets the string name of the data type of an output.
*
* @param interpreter an instance of {@code Interpreter}. If it is not initialized, an {@code
diff --git a/tensorflow/contrib/lite/kernels/BUILD b/tensorflow/contrib/lite/kernels/BUILD
index c5586475ec..1f528fdab9 100644
--- a/tensorflow/contrib/lite/kernels/BUILD
+++ b/tensorflow/contrib/lite/kernels/BUILD
@@ -225,6 +225,7 @@ cc_library(
"//tensorflow/contrib/lite:builtin_op_data",
"//tensorflow/contrib/lite:framework",
"//tensorflow/contrib/lite:string_util",
+ "//tensorflow/contrib/lite:util",
"//tensorflow/contrib/lite/kernels:gemm_support",
"//tensorflow/contrib/lite/kernels/internal:audio_utils",
"//tensorflow/contrib/lite/kernels/internal:kernel_utils",
diff --git a/tensorflow/contrib/lite/kernels/activations.cc b/tensorflow/contrib/lite/kernels/activations.cc
index 817266a471..d6d62580e2 100644
--- a/tensorflow/contrib/lite/kernels/activations.cc
+++ b/tensorflow/contrib/lite/kernels/activations.cc
@@ -40,6 +40,11 @@ struct OpData {
int diff_min = 0;
};
+struct LogSoftmaxOpData : public OpData {
+ int32_t reverse_scaling_divisor = 0;
+ int32_t reverse_scaling_right_shift = 0;
+};
+
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
// This is a builtin op, so we don't use the contents in 'buffer', if any.
// Instead, we allocate a new object to carry information from Prepare() to
@@ -47,10 +52,19 @@ void* Init(TfLiteContext* context, const char* buffer, size_t length) {
return new OpData;
}
+void* LogSoftmaxInit(TfLiteContext* context, const char* buffer,
+ size_t length) {
+ return new LogSoftmaxOpData;
+}
+
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
+void LogSoftmaxFree(TfLiteContext* context, void* buffer) {
+ delete reinterpret_cast<LogSoftmaxOpData*>(buffer);
+}
+
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
@@ -205,6 +219,34 @@ TfLiteStatus SoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) {
TfLiteIntArrayCopy(input->dims));
}
+TfLiteStatus LogSoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) {
+ LogSoftmaxOpData* data = reinterpret_cast<LogSoftmaxOpData*>(node->user_data);
+
+ TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
+ TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
+ const TfLiteTensor* input = GetInput(context, node, 0);
+ TfLiteTensor* output = GetOutput(context, node, 0);
+ TF_LITE_ENSURE_EQ(context, input->type, output->type);
+
+ if (input->type == kTfLiteUInt8) {
+ TF_LITE_ENSURE_EQ(context, output->params.zero_point, 255);
+ TF_LITE_ENSURE_EQ(context, output->params.scale, 16.0 / 256);
+
+ static const double kBeta = 1.0;
+ static const int kScaledDiffIntegerBits = 5;
+ tflite::PreprocessLogSoftmaxScalingExp(
+ kBeta, input->params.scale, kScaledDiffIntegerBits,
+ &data->input_multiplier, &data->input_left_shift,
+ &data->reverse_scaling_divisor, &data->reverse_scaling_right_shift);
+ data->reverse_scaling_right_shift *= -1;
+ data->diff_min = -1.0 * tflite::CalculateInputRadius(
+ kScaledDiffIntegerBits, data->input_left_shift);
+ }
+
+ return context->ResizeTensor(context, output,
+ TfLiteIntArrayCopy(input->dims));
+}
+
TfLiteStatus PreluPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
@@ -509,6 +551,8 @@ TfLiteStatus SoftmaxEval(TfLiteContext* context, TfLiteNode* node) {
}
TfLiteStatus LogSoftmaxEval(TfLiteContext* context, TfLiteNode* node) {
+ const LogSoftmaxOpData* data =
+ reinterpret_cast<LogSoftmaxOpData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
switch (input->type) {
@@ -517,6 +561,14 @@ TfLiteStatus LogSoftmaxEval(TfLiteContext* context, TfLiteNode* node) {
GetTensorData<float>(input), GetTensorShape(input),
GetTensorData<float>(output), GetTensorShape(output));
return kTfLiteOk;
+ case kTfLiteUInt8:
+ optimized_ops::LogSoftmax(
+ GetTensorData<uint8_t>(input), GetTensorShape(input),
+ data->input_multiplier, data->input_left_shift,
+ data->reverse_scaling_divisor, data->reverse_scaling_right_shift,
+ data->diff_min, GetTensorData<uint8_t>(output),
+ GetTensorShape(output));
+ return kTfLiteOk;
default:
context->ReportError(context, "Only float32 supported currently., got %d",
input->type);
@@ -590,9 +642,9 @@ TfLiteRegistration* Register_SOFTMAX() {
}
TfLiteRegistration* Register_LOG_SOFTMAX() {
- static TfLiteRegistration r = {activations::Init, activations::Free,
- activations::GenericPrepare,
- activations::LogSoftmaxEval};
+ static TfLiteRegistration r = {
+ activations::LogSoftmaxInit, activations::LogSoftmaxFree,
+ activations::LogSoftmaxPrepare, activations::LogSoftmaxEval};
return &r;
}
diff --git a/tensorflow/contrib/lite/kernels/activations_test.cc b/tensorflow/contrib/lite/kernels/activations_test.cc
index 083cdf78d7..e577e3a762 100644
--- a/tensorflow/contrib/lite/kernels/activations_test.cc
+++ b/tensorflow/contrib/lite/kernels/activations_test.cc
@@ -471,6 +471,28 @@ TEST(FloatActivationsOpTest, LogSoftmax) {
})));
}
+TEST(QuantizedActivationsOpTest, LogSoftmax) {
+ const float kLogSoftmaxQuantizedTolerance = 16 / 256.0;
+ QuantizedActivationsOpModel m(
+ BuiltinOperator_LOG_SOFTMAX,
+ /*input=*/{TensorType_UINT8, {2, 4}, -10, 10},
+ /*output=*/{TensorType_UINT8, {}, 0, 0, 16. / 256, 255});
+ m.SetInput<uint8_t>({
+ 0, -6, 2, 4, //
+ 3, -2, 10, 1, //
+ });
+ m.Invoke();
+ EXPECT_THAT(m.GetDequantizedOutput<uint8_t>(),
+ ElementsAreArray(ArrayFloatNear(
+ {
+ -4.14297, -10.14297, -2.14297, -.142971, //
+ -7.00104, -12.00104, -.00104087, -9.00104, //
+ },
+ kLogSoftmaxQuantizedTolerance)));
+ EXPECT_THAT(m.GetOutput<uint8_t>(),
+ ElementsAreArray({189, 93, 221, 253, 142, 63, 255, 111}));
+}
+
class PReluOpModel : public SingleOpModel {
public:
PReluOpModel(const TensorData& input, const TensorData& alpha) {
diff --git a/tensorflow/contrib/lite/kernels/conv.cc b/tensorflow/contrib/lite/kernels/conv.cc
index 04c0263b78..50fe5c2e04 100644
--- a/tensorflow/contrib/lite/kernels/conv.cc
+++ b/tensorflow/contrib/lite/kernels/conv.cc
@@ -334,18 +334,31 @@ void EvalQuantized(TfLiteContext* context, TfLiteNode* node,
auto filter_offset = -filter->params.zero_point;
auto output_offset = output->params.zero_point;
- switch (kernel_type) {
+ KernelType effective_kernel_type;
+ if ((kernel_type == kMultithreadOptimized ||
+ kernel_type == kCblasOptimized) &&
+ (params->dilation_width_factor != 1 ||
+ params->dilation_height_factor != 1)) {
+ // kMultithreadOptimized and kCblasOptimized do not support dilation.
+ // Therefore, fallback to optimized.
+ effective_kernel_type = kGenericOptimized;
+ } else {
+ effective_kernel_type = kernel_type;
+ }
+
+ switch (effective_kernel_type) {
case kReference:
reference_ops::Conv(
GetTensorData<uint8_t>(input), GetTensorDims(input), input_offset,
GetTensorData<uint8_t>(filter), GetTensorDims(filter), filter_offset,
GetTensorData<int32_t>(bias), GetTensorDims(bias),
- params->stride_width, params->stride_height, data->padding.width,
- data->padding.height, output_offset, data->output_multiplier,
- data->output_shift, data->output_activation_min,
- data->output_activation_max, GetTensorData<uint8_t>(output),
- GetTensorDims(output), GetTensorData<uint8_t>(im2col),
- GetTensorDims(im2col), gemm_context);
+ params->stride_width, params->stride_height,
+ params->dilation_width_factor, params->dilation_height_factor,
+ data->padding.width, data->padding.height, output_offset,
+ data->output_multiplier, data->output_shift,
+ data->output_activation_min, data->output_activation_max,
+ GetTensorData<uint8_t>(output), GetTensorDims(output),
+ GetTensorData<uint8_t>(im2col), GetTensorDims(im2col), gemm_context);
break;
case kGenericOptimized:
case kMultithreadOptimized:
@@ -355,12 +368,13 @@ void EvalQuantized(TfLiteContext* context, TfLiteNode* node,
GetTensorData<uint8_t>(input), GetTensorDims(input), input_offset,
GetTensorData<uint8_t>(filter), GetTensorDims(filter), filter_offset,
GetTensorData<int32_t>(bias), GetTensorDims(bias),
- params->stride_width, params->stride_height, data->padding.width,
- data->padding.height, output_offset, data->output_multiplier,
- data->output_shift, data->output_activation_min,
- data->output_activation_max, GetTensorData<uint8_t>(output),
- GetTensorDims(output), GetTensorData<uint8_t>(im2col),
- GetTensorDims(im2col), gemm_context);
+ params->stride_width, params->stride_height,
+ params->dilation_width_factor, params->dilation_height_factor,
+ data->padding.width, data->padding.height, output_offset,
+ data->output_multiplier, data->output_shift,
+ data->output_activation_min, data->output_activation_max,
+ GetTensorData<uint8_t>(output), GetTensorDims(output),
+ GetTensorData<uint8_t>(im2col), GetTensorDims(im2col), gemm_context);
break;
}
}
@@ -374,10 +388,10 @@ void EvalFloat(TfLiteContext* context, TfLiteNode* node,
CalculateActivationRange(params->activation, &output_activation_min,
&output_activation_max);
KernelType effective_kernel_type;
- if (((kernel_type == kMultithreadOptimized) ||
- (kernel_type == kCblasOptimized)) &&
- ((params->dilation_width_factor != 1) ||
- (params->dilation_height_factor != 1))) {
+ if ((kernel_type == kMultithreadOptimized ||
+ kernel_type == kCblasOptimized) &&
+ (params->dilation_width_factor != 1 ||
+ params->dilation_height_factor != 1)) {
// kMultithreadOptimized and kCblasOptimized do not support dilation.
// Therefore, fallback to optimized.
effective_kernel_type = kGenericOptimized;
diff --git a/tensorflow/contrib/lite/kernels/conv_test.cc b/tensorflow/contrib/lite/kernels/conv_test.cc
index 24633c2fd7..98152043c9 100644
--- a/tensorflow/contrib/lite/kernels/conv_test.cc
+++ b/tensorflow/contrib/lite/kernels/conv_test.cc
@@ -370,6 +370,65 @@ TEST_P(ConvolutionOpTest, HandCalculatedValidFloat32) {
EXPECT_THAT(m.GetOutput(), ElementsAreArray({312, 357}));
}
+TEST_P(ConvolutionOpTest, SimpleTestFloatWithDilation) {
+ const int depth = 1;
+ const int image_width = 9;
+ const int image_height = 9;
+ const int image_batch_count = 1;
+ const int filter_size = 3;
+ const int filter_count = 1;
+ const int stride_width = 1;
+ const int stride_height = 1;
+ const int dilation_width_factor = 3;
+ const int dilation_height_factor = 3;
+ const Padding padding = Padding_VALID;
+ ConvolutionOpModel m(
+ GetRegistration(),
+ {TensorType_FLOAT32,
+ {image_batch_count, image_height, image_width, depth}},
+ {TensorType_FLOAT32, {depth, filter_size, filter_size, filter_count}},
+ {TensorType_FLOAT32, {}}, stride_width, stride_height, padding,
+ ActivationFunctionType_NONE, dilation_width_factor,
+ dilation_height_factor);
+
+ // The image matrix is:
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // clang-format off
+ m.SetInput({0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0});
+ // clang-format on
+ // The filter matrix is:
+ // | 1 | 2 | 3 |
+ // | 4 | 5 | 6 |
+ // | 7 | 8 | 9 |
+ m.SetFilter({1, 2, 3, 4, 5, 6, 7, 8, 9});
+ // No bias for this test.
+ m.SetBias({0});
+ m.Invoke();
+
+ // Since the dilation rate is 3 this will reduce the size of the output from
+ // 10x10 to 3x3 of all 5s. Specifically:
+ // | 5 | 5 | 5 |
+ // | 5 | 5 | 5 |
+ // | 5 | 5 | 5 |
+ EXPECT_THAT(m.GetOutput(), ElementsAreArray({5, 5, 5, 5, 5, 5, 5, 5, 5}));
+}
+
class QuantizedConvolutionOpModel : public BaseConvolutionOpModel {
public:
using BaseConvolutionOpModel::BaseConvolutionOpModel;
@@ -500,6 +559,71 @@ TEST_P(ConvolutionOpTest, SimpleTestQuantizedWithAnisotropicStrides) {
}));
}
+TEST_P(ConvolutionOpTest, SimpleTestQuantizedWithDilation) {
+ const int depth = 1;
+ const int image_width = 9;
+ const int image_height = 9;
+ const int image_batch_count = 1;
+ const int filter_size = 3;
+ const int filter_count = 1;
+ const int stride_width = 1;
+ const int stride_height = 1;
+ const int dilation_width_factor = 3;
+ const int dilation_height_factor = 3;
+ const Padding padding = Padding_VALID;
+ QuantizedConvolutionOpModel m(
+ GetRegistration(),
+ {TensorType_UINT8,
+ {image_batch_count, image_height, image_width, depth},
+ 0,
+ 255},
+ {TensorType_UINT8,
+ {depth, filter_size, filter_size, filter_count},
+ 0,
+ 255},
+ {TensorType_UINT8, {}, 0, 255}, stride_width, stride_height, padding,
+ ActivationFunctionType_NONE, dilation_width_factor,
+ dilation_height_factor);
+
+ // The image matrix is:
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+ // clang-format off
+ m.SetInput({0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0});
+ // clang-format on
+ // The filter matrix is:
+ // | 1 | 2 | 3 |
+ // | 4 | 5 | 6 |
+ // | 7 | 8 | 9 |
+ m.SetFilter({1, 2, 3, 4, 5, 6, 7, 8, 9});
+ // No bias for this test.
+ m.SetBias({0});
+ m.Invoke();
+
+ // Since the dilation rate is 3 this will reduce the size of the output from
+ // 10x10 to 3x3 of all 5s. Specifically:
+ // | 5 | 5 | 5 |
+ // | 5 | 5 | 5 |
+ // | 5 | 5 | 5 |
+ EXPECT_THAT(m.GetDequantizedOutput(),
+ ElementsAreArray({5, 5, 5, 5, 5, 5, 5, 5, 5}));
+}
+
INSTANTIATE_TEST_CASE_P(
ConvolutionOpTest, ConvolutionOpTest,
::testing::ValuesIn(SingleOpTest::GetKernelTags(*kKernelMap)));
diff --git a/tensorflow/contrib/lite/kernels/dequantize.cc b/tensorflow/contrib/lite/kernels/dequantize.cc
index 672b2170e4..2b0f04489a 100644
--- a/tensorflow/contrib/lite/kernels/dequantize.cc
+++ b/tensorflow/contrib/lite/kernels/dequantize.cc
@@ -36,6 +36,21 @@ struct OpContext {
TfLiteTensor* output;
};
+struct OpData {
+ // This boolean value is only used when the input tensor is constant.
+ bool float_dequantized_weights_initialized;
+};
+
+void* Init(TfLiteContext* context, const char* buffer, size_t length) {
+ auto* op_data = new OpData();
+ op_data->float_dequantized_weights_initialized = false;
+ return op_data;
+}
+
+void Free(TfLiteContext* context, void* buffer) {
+ delete reinterpret_cast<OpData*>(buffer);
+}
+
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
@@ -45,12 +60,22 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE(context, op_context.input->type == kTfLiteUInt8);
op_context.output->type = kTfLiteFloat32;
+ // If the input tensor is constant, we can persist the dequantized value in
+ // the output tensor. Otherwise we run dequantize upon each eval.
+ if (IsConstantTensor(op_context.input)) {
+ op_context.output->allocation_type = kTfLiteArenaRwPersistent;
+ }
return context->ResizeTensor(context, op_context.output,
TfLiteIntArrayCopy(op_context.input->dims));
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
+ OpData* op_data = reinterpret_cast<OpData*>(node->user_data);
OpContext op_context(context, node);
+ if (IsConstantTensor(op_context.input) &&
+ op_data->float_dequantized_weights_initialized) {
+ return kTfLiteOk;
+ }
auto zero_point = op_context.input->params.zero_point;
auto scale = op_context.input->params.scale;
@@ -59,14 +84,19 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
GetTensorDims(op_context.input), zero_point, scale,
GetTensorData<float>(op_context.output),
GetTensorDims(op_context.output));
+
+ if (IsConstantTensor(op_context.input)) {
+ op_data->float_dequantized_weights_initialized = true;
+ }
+
return kTfLiteOk;
}
} // namespace dequantize
TfLiteRegistration* Register_DEQUANTIZE_OPT() {
- static TfLiteRegistration r = {nullptr, nullptr, dequantize::Prepare,
- dequantize::Eval};
+ static TfLiteRegistration r = {dequantize::Init, dequantize::Free,
+ dequantize::Prepare, dequantize::Eval};
return &r;
}
diff --git a/tensorflow/contrib/lite/kernels/fully_connected.cc b/tensorflow/contrib/lite/kernels/fully_connected.cc
index bc370608c0..eaf5a67d67 100644
--- a/tensorflow/contrib/lite/kernels/fully_connected.cc
+++ b/tensorflow/contrib/lite/kernels/fully_connected.cc
@@ -121,10 +121,9 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
double real_multiplier = 0.0;
TF_LITE_ENSURE_STATUS(GetQuantizedConvolutionMultipler(
context, input, filter, bias, output, &real_multiplier));
- TF_LITE_ENSURE(context, real_multiplier < 1.0);
- QuantizeMultiplierSmallerThanOneExp(
- real_multiplier, &data->output_multiplier, &data->output_shift);
- data->output_shift *= -1;
+ int exponent;
+ QuantizeMultiplier(real_multiplier, &data->output_multiplier, &exponent);
+ data->output_shift = -exponent;
TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
context, params->activation, output, &data->output_activation_min,
&data->output_activation_max));
diff --git a/tensorflow/contrib/lite/kernels/fully_connected_test.cc b/tensorflow/contrib/lite/kernels/fully_connected_test.cc
index ec94905697..08b4320946 100644
--- a/tensorflow/contrib/lite/kernels/fully_connected_test.cc
+++ b/tensorflow/contrib/lite/kernels/fully_connected_test.cc
@@ -423,6 +423,37 @@ TEST_P(QuantizedFullyConnectedOpTest, SimpleTestQuantized) {
ElementsAre(151, 152, 153, 185, 186, 187));
}
+TEST_P(QuantizedFullyConnectedOpTest,
+ SimpleTestQuantizedOutputMultiplierGreaterThan1) {
+ // real_multiplier = 2.
+ QuantizedFullyConnectedOpModel m(
+ GetRegistration(), /*units=*/3, /*batches*/ 2,
+ /*input=*/{TensorType_UINT8, {2, 10}, -127, 128},
+ /*output=*/{TensorType_UINT8, {}, -63.5, 64});
+
+ m.SetWeights({
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // u = 0
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // u = 1
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // u = 2
+ });
+ m.SetBias({1, 2, 3});
+
+ m.SetInput({
+ 1, 2, 3, 4, 5, 6, 7, 8, -9, -10, // b = 0
+ 1, 2, 3, 4, 5, 6, 7, -8, 9, -10, // b = 1
+ });
+
+ m.Invoke();
+
+ EXPECT_THAT(m.GetDequantizedOutput<uint8_t>(),
+ ElementsAreArray(ArrayFloatNear({
+ 24, 25, 26, // first batch
+ 58, 59, 60, // second batch
+ })));
+ EXPECT_THAT(m.GetOutput<uint8_t>(),
+ ElementsAre(175, 177, 179, 243, 245, 247));
+}
+
void SimpleTestQuantizedInt16OutputCase(
TfLiteRegistration* registration, int input_depth, int output_depth,
int batches, FullyConnectedOptionsWeightsFormat weights_format) {
@@ -631,6 +662,37 @@ TEST_P(QuantizedFullyConnectedOpTest, SimpleTest4dInputQuantized) {
ElementsAre(151, 152, 153, 185, 186, 187));
}
+TEST_P(QuantizedFullyConnectedOpTest,
+ SimpleTest4dInputQuantizedOutputMultiplierGreaterThan1) {
+ // real_multiplier = 2.
+ QuantizedFullyConnectedOpModel m(
+ GetRegistration(), /*units=*/3, /*batches=*/2,
+ /*input=*/{TensorType_UINT8, {4, 1, 5, 1}, -127, 128},
+ /*output=*/{TensorType_UINT8, {}, -63.5, 64});
+
+ m.SetWeights({
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // u = 0
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // u = 1
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // u = 1
+ });
+ m.SetBias({1, 2, 3});
+
+ m.SetInput({
+ 1, 2, 3, 4, 5, 6, 7, 8, -9, -10, // b = 0
+ 1, 2, 3, 4, 5, 6, 7, -8, 9, -10, // b = 1
+ });
+
+ m.Invoke();
+
+ EXPECT_THAT(m.GetDequantizedOutput<uint8_t>(),
+ ElementsAreArray(ArrayFloatNear({
+ 24, 25, 26, // first batch
+ 58, 59, 60, // second batch
+ })));
+ EXPECT_THAT(m.GetOutput<uint8_t>(),
+ ElementsAre(175, 177, 179, 243, 245, 247));
+}
+
INSTANTIATE_TEST_CASE_P(
FloatFullyConnectedOpTest, FloatFullyConnectedOpTest,
::testing::ValuesIn(SingleOpTest::GetKernelTags(*kKernelMap)));
diff --git a/tensorflow/contrib/lite/kernels/internal/BUILD b/tensorflow/contrib/lite/kernels/internal/BUILD
index 0d424071da..a97db6c6b2 100644
--- a/tensorflow/contrib/lite/kernels/internal/BUILD
+++ b/tensorflow/contrib/lite/kernels/internal/BUILD
@@ -496,6 +496,7 @@ cc_library(
hdrs = ["test_util.h"],
deps = [
":types",
+ "//tensorflow/contrib/lite:string",
],
)
@@ -538,7 +539,10 @@ cc_test(
cc_test(
name = "depthwiseconv_quantized_test",
srcs = ["depthwiseconv_quantized_test.cc"],
- tags = ["no_oss"],
+ tags = [
+ "no_oss",
+ "tflite_not_portable_ios",
+ ],
deps = [
":optimized_base",
":reference_base",
@@ -576,6 +580,7 @@ cc_test(
":quantization_util",
":reference_base",
":test_util",
+ "//tensorflow/contrib/lite:string",
"@com_google_googletest//:gtest_main",
],
)
@@ -595,6 +600,7 @@ cc_test(
":quantization_util",
":reference_base",
":test_util",
+ "//tensorflow/contrib/lite:string",
"@com_google_googletest//:gtest_main",
],
)
@@ -606,6 +612,7 @@ cc_test(
deps = [
":optimized_base",
":reference_base",
+ "//tensorflow/contrib/lite:string",
"@com_google_googletest//:gtest_main",
],
)
diff --git a/tensorflow/contrib/lite/kernels/internal/log_quantized_test.cc b/tensorflow/contrib/lite/kernels/internal/log_quantized_test.cc
index 7e9ff5242a..8963abb9af 100644
--- a/tensorflow/contrib/lite/kernels/internal/log_quantized_test.cc
+++ b/tensorflow/contrib/lite/kernels/internal/log_quantized_test.cc
@@ -29,8 +29,9 @@ limitations under the License.
#include <gtest/gtest.h>
#include "tensorflow/contrib/lite/kernels/internal/optimized/optimized_ops.h"
#include "tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h"
+#include "tensorflow/contrib/lite/string.h"
-namespace {
+namespace tflite {
class NumberGenerator {
public:
@@ -330,4 +331,4 @@ TEST_F(LogQuantizedTest, SelectedIntegerBits) {
&generator_);
}
-} // namespace
+} // namespace tflite
diff --git a/tensorflow/contrib/lite/kernels/internal/logsoftmax_quantized_test.cc b/tensorflow/contrib/lite/kernels/internal/logsoftmax_quantized_test.cc
index d2f1103e14..3624c20ae3 100644
--- a/tensorflow/contrib/lite/kernels/internal/logsoftmax_quantized_test.cc
+++ b/tensorflow/contrib/lite/kernels/internal/logsoftmax_quantized_test.cc
@@ -27,6 +27,7 @@ limitations under the License.
#include "tensorflow/contrib/lite/kernels/internal/quantization_util.h"
#include "tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/contrib/lite/kernels/internal/test_util.h"
+#include "tensorflow/contrib/lite/string.h"
namespace tflite {
namespace {
diff --git a/tensorflow/contrib/lite/kernels/internal/optimized/legacy_optimized_ops.h b/tensorflow/contrib/lite/kernels/internal/optimized/legacy_optimized_ops.h
index d5503073a7..df4d871466 100644
--- a/tensorflow/contrib/lite/kernels/internal/optimized/legacy_optimized_ops.h
+++ b/tensorflow/contrib/lite/kernels/internal/optimized/legacy_optimized_ops.h
@@ -30,11 +30,6 @@ namespace optimized_ops {
using reference_ops::Relu1;
using reference_ops::Relu6;
-inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {
- return RuntimeShape(
- {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});
-}
-
template <FusedActivationFunctionType Ac>
void L2Normalization(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
@@ -51,8 +46,8 @@ inline void L2Normalization(const uint8* input_data, const Dims<4>& input_dims,
inline void Relu(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Relu(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Relu(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
// legacy, for compatibility with old checked-in code
@@ -294,6 +289,37 @@ void Sub(const T* input1_data, const Dims<4>& input1_dims, const T* input2_data,
output_data);
}
+inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
+ int32 input1_offset, const uint8* input2_data,
+ const Dims<4>& input2_dims, int32 input2_offset,
+ int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims) {
+ BroadcastMul4DSlow(
+ input1_data, input1_dims, input1_offset, input2_data, input2_dims,
+ input2_offset, output_offset, output_multiplier,
+ // This legacy version switches the sign of the output shift.
+ kReverseShift * output_shift,
+ // (Break to highlight preceding line.)
+ output_activation_min, output_activation_max, output_data, output_dims);
+}
+
+// legacy, for compatibility with old checked-in code
+template <FusedActivationFunctionType Ac>
+inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
+ int32 input1_offset, const uint8* input2_data,
+ const Dims<4>& input2_dims, int32 input2_offset,
+ int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims) {
+ BroadcastMul(input1_data, input1_dims, input1_offset, input2_data,
+ input2_dims, input2_offset, output_offset, output_multiplier,
+ output_shift, output_activation_min, output_activation_max,
+ output_data, output_dims);
+}
+
inline void AveragePool(const float* input_data, const Dims<4>& input_dims,
int stride_width, int stride_height, int pad_width,
int pad_height, int kwidth, int kheight,
@@ -554,8 +580,8 @@ inline void LogSoftmax(const uint8* input_data, const Dims<4>& input_dims,
inline void Logistic(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Logistic(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Logistic(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Logistic(const uint8* input_data, const Dims<4>& input_dims,
@@ -575,8 +601,8 @@ inline void Logistic(const int16* input_data, const Dims<4>& input_dims,
inline void Tanh(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Tanh(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Tanh(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Tanh(const uint8* input_data, const Dims<4>& input_dims,
diff --git a/tensorflow/contrib/lite/kernels/internal/optimized/optimized_ops.h b/tensorflow/contrib/lite/kernels/internal/optimized/optimized_ops.h
index 6adb879c71..f19df5e17e 100644
--- a/tensorflow/contrib/lite/kernels/internal/optimized/optimized_ops.h
+++ b/tensorflow/contrib/lite/kernels/internal/optimized/optimized_ops.h
@@ -47,6 +47,7 @@ using reference_ops::BroadcastGreater;
using reference_ops::BroadcastGreaterEqual;
using reference_ops::BroadcastLess;
using reference_ops::BroadcastLessEqual;
+using reference_ops::BroadcastMul4DSlow;
using reference_ops::BroadcastSub4DSlow;
using reference_ops::Concatenation;
using reference_ops::DepthConcatenation;
@@ -75,6 +76,11 @@ using reference_ops::Transpose;
// Used mainly to convert from old-style shifts (right) to new-style (left).
static constexpr int kReverseShift = -1;
+inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {
+ return RuntimeShape(
+ {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});
+}
+
// Make a local VectorMap typedef allowing to map a float array
// as a Eigen vector expression. The std::conditional here is to
// construct the suitable Eigen type for the constness of the
@@ -893,6 +899,7 @@ inline void FullyConnectedAsGEMV(
const int input_size = FlatSizeSkipDim(input_dims, 3);
const int output_size = MatchingArraySize(filter_dims, 1, output_dims, 0);
static constexpr int kPeel = 4;
+ const bool shift_left = (output_shift <= 0);
for (int k = 0; k < input_size; k += 64) {
optimized_ops_preload_l1_stream(input_data + k);
}
@@ -1004,11 +1011,17 @@ inline void FullyConnectedAsGEMV(
int32x4_t bias_vec = vld1q_s32(bias_ptr);
bias_ptr += 4;
reduced = vaddq_s32(reduced, bias_vec);
- // Multiply by the fixed-point multiplier.
- reduced = vqrdmulhq_n_s32(reduced, output_multiplier);
- // Rounding-shift-right.
- using gemmlowp::RoundingDivideByPOT;
- reduced = RoundingDivideByPOT(reduced, output_shift);
+ if (shift_left) {
+ const int32 multiplier_power_of_two = 1 << -output_shift;
+ reduced = vmulq_n_s32(reduced, multiplier_power_of_two);
+ reduced = vqrdmulhq_n_s32(reduced, output_multiplier);
+ } else {
+ // Multiply by the fixed-point multiplier.
+ reduced = vqrdmulhq_n_s32(reduced, output_multiplier);
+ // Rounding-shift-right.
+ using gemmlowp::RoundingDivideByPOT;
+ reduced = RoundingDivideByPOT(reduced, output_shift);
+ }
// Add the output offset.
const int32x4_t output_offset_vec = vdupq_n_s32(output_offset);
reduced = vaddq_s32(reduced, output_offset_vec);
@@ -1971,12 +1984,12 @@ inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
int32 input_offset, const uint8* filter_data,
const Dims<4>& filter_dims, int32 filter_offset,
const int32* bias_data, const Dims<4>& bias_dims,
- int stride_width, int stride_height, int pad_width,
- int pad_height, int32 output_offset, int32 output_multiplier,
- int output_shift, int32 output_activation_min,
- int32 output_activation_max, uint8* output_data,
- const Dims<4>& output_dims, uint8* im2col_data,
- const Dims<4>& im2col_dims,
+ int stride_width, int stride_height, int dilation_width_factor,
+ int dilation_height_factor, int pad_width, int pad_height,
+ int32 output_offset, int32 output_multiplier, int output_shift,
+ int32 output_activation_min, int32 output_activation_max,
+ uint8* output_data, const Dims<4>& output_dims,
+ uint8* im2col_data, const Dims<4>& im2col_dims,
gemmlowp::GemmContext* gemm_context) {
gemmlowp::ScopedProfilingLabel label("Conv/8bit");
@@ -1988,9 +2001,22 @@ inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
const Dims<4>* gemm_input_dims = nullptr;
const int filter_width = ArraySize(filter_dims, 1);
const int filter_height = ArraySize(filter_dims, 2);
+ const bool need_dilated_im2col =
+ dilation_width_factor != 1 || dilation_height_factor != 1;
const bool need_im2col = stride_width != 1 || stride_height != 1 ||
filter_width != 1 || filter_height != 1;
- if (need_im2col) {
+ if (need_dilated_im2col) {
+ TFLITE_DCHECK(im2col_data);
+ const int input_zero_point = -input_offset;
+ TFLITE_DCHECK_GE(input_zero_point, 0);
+ TFLITE_DCHECK_LE(input_zero_point, 255);
+ DilatedIm2col(input_data, input_dims, filter_dims, stride_width,
+ stride_height, dilation_width_factor, dilation_height_factor,
+ pad_width, pad_height, output_dims, input_zero_point,
+ im2col_data);
+ gemm_input_data = im2col_data;
+ gemm_input_dims = &im2col_dims;
+ } else if (need_im2col) {
TFLITE_DCHECK(im2col_data);
const int input_zero_point = -input_offset;
TFLITE_DCHECK_GE(input_zero_point, 0);
@@ -2046,6 +2072,24 @@ inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
input_offset, output_pipeline);
}
+inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
+ int32 input_offset, const uint8* filter_data,
+ const Dims<4>& filter_dims, int32 filter_offset,
+ const int32* bias_data, const Dims<4>& bias_dims,
+ int stride_width, int stride_height, int pad_width,
+ int pad_height, int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims, uint8* im2col_data,
+ const Dims<4>& im2col_dims,
+ gemmlowp::GemmContext* gemm_context) {
+ Conv(input_data, input_dims, input_offset, filter_data, filter_dims,
+ filter_offset, bias_data, bias_dims, stride_width, stride_height, 1, 1,
+ pad_width, pad_height, output_offset, output_multiplier, output_shift,
+ output_activation_min, output_activation_max, output_data, output_dims,
+ im2col_data, im2col_dims, gemm_context);
+}
+
// legacy, for compatibility with old checked-in code
template <FusedActivationFunctionType Ac>
inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
@@ -2283,8 +2327,8 @@ void GlobalBatchNormalization(const float* input_data,
}
}
-inline void Relu(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Relu(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
gemmlowp::ScopedProfilingLabel label("Relu (not fused)");
const auto input = MapAsVector(input_data, input_shape);
@@ -2897,68 +2941,225 @@ void BroadcastMul(const T* input1_data, const Dims<4>& input1_dims,
output_dims);
}
-inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
- int32 input1_offset, const uint8* input2_data,
- const Dims<4>& input2_dims, int32 input2_offset,
- int32 output_offset, int32 output_multiplier,
- int output_shift, int32 output_activation_min,
- int32 output_activation_max, uint8* output_data,
- const Dims<4>& output_dims) {
- gemmlowp::ScopedProfilingLabel label("BroadcastMul/8bit");
+// Element-wise mul that can often be used for inner loop of broadcast Mul as
+// well as the non-broadcast Mul.
+inline void MulElementwise(int size, const ArithmeticParams& params,
+ const uint8* input1_data, const uint8* input2_data,
+ uint8* output_data) {
+ int i = 0;
+ TFLITE_DCHECK_GT(params.input1_offset, -256);
+ TFLITE_DCHECK_LT(params.input1_offset, 256);
+ TFLITE_DCHECK_GT(params.input2_offset, -256);
+ TFLITE_DCHECK_LT(params.input2_offset, 256);
+ TFLITE_DCHECK_GT(params.output_offset, -256);
+ TFLITE_DCHECK_LT(params.output_offset, 256);
+#ifdef USE_NEON
+ const auto input1_offset_vector = vdupq_n_s16(params.input1_offset);
+ const auto input2_offset_vector = vdupq_n_s16(params.input2_offset);
+ const auto output_offset_vector = vdupq_n_s16(params.output_offset);
+ const auto output_activation_min_vector =
+ vdup_n_u8(params.quantized_activation_min);
+ const auto output_activation_max_vector =
+ vdup_n_u8(params.quantized_activation_max);
+ for (; i <= size - 8; i += 8) {
+ // We load / store 8 at a time, multiplying as two sets of 4 int32s.
+ const auto input1_val_original = vld1_u8(input1_data + i);
+ const auto input2_val_original = vld1_u8(input2_data + i);
+ const auto input1_val_s16 =
+ vreinterpretq_s16_u16(vmovl_u8(input1_val_original));
+ const auto input2_val_s16 =
+ vreinterpretq_s16_u16(vmovl_u8(input2_val_original));
+ const auto input1_val = vaddq_s16(input1_val_s16, input1_offset_vector);
+ const auto input2_val = vaddq_s16(input2_val_s16, input2_offset_vector);
- NdArrayDesc<4> desc1;
- NdArrayDesc<4> desc2;
- NdArrayDescsForElementwiseBroadcast(input1_dims, input2_dims, &desc1, &desc2);
+ const auto input1_val_low = vget_low_s16(input1_val);
+ const auto input1_val_high = vget_high_s16(input1_val);
+ const auto input2_val_low = vget_low_s16(input2_val);
+ const auto input2_val_high = vget_high_s16(input2_val);
- // In Tensorflow, the dimensions are canonically named (batch_number, row,
- // col, channel), with extents (batches, height, width, depth), with the
- // trailing dimension changing most rapidly (channels has the smallest stride,
- // typically 1 element).
- //
- // In generated C code, we store arrays with the dimensions reversed. The
- // first dimension has smallest stride.
- //
- // We name our variables by their Tensorflow convention, but generate C code
- // nesting loops such that the innermost loop has the smallest stride for the
- // best cache behavior.
- for (int b = 0; b < ArraySize(output_dims, 3); ++b) {
- for (int y = 0; y < ArraySize(output_dims, 2); ++y) {
- for (int x = 0; x < ArraySize(output_dims, 1); ++x) {
- for (int c = 0; c < ArraySize(output_dims, 0); ++c) {
- const int32 input1_val =
- input1_offset + input1_data[SubscriptToIndex(desc1, c, x, y, b)];
- const int32 input2_val =
- input2_offset + input2_data[SubscriptToIndex(desc2, c, x, y, b)];
- const int32 unclamped_result =
- output_offset + MultiplyByQuantizedMultiplierSmallerThanOneExp(
- input1_val * input2_val, output_multiplier,
- kReverseShift * output_shift);
- const int32 clamped_output =
- std::min(output_activation_max,
- std::max(output_activation_min, unclamped_result));
- output_data[Offset(output_dims, c, x, y, b)] =
- static_cast<uint8>(clamped_output);
+ auto p1 = vmull_s16(input2_val_low, input1_val_low);
+ auto p2 = vmull_s16(input2_val_high, input1_val_high);
+
+ p1 = vqrdmulhq_n_s32(p1, params.output_multiplier);
+ p2 = vqrdmulhq_n_s32(p2, params.output_multiplier);
+ using gemmlowp::RoundingDivideByPOT;
+ p1 = RoundingDivideByPOT(p1, -params.output_shift);
+ p2 = RoundingDivideByPOT(p2, -params.output_shift);
+
+ const auto p1_narrowed = vmovn_s32(p1);
+ const auto p2_narrowed = vmovn_s32(p2);
+ const auto p =
+ vaddq_s16(vcombine_s16(p1_narrowed, p2_narrowed), output_offset_vector);
+ const auto clamped =
+ vmax_u8(output_activation_min_vector,
+ vmin_u8(output_activation_max_vector, vqmovun_s16(p)));
+ vst1_u8(output_data + i, clamped);
+ }
+#endif // NEON
+
+ for (; i < size; ++i) {
+ const int32 input1_val = params.input1_offset + input1_data[i];
+ const int32 input2_val = params.input2_offset + input2_data[i];
+ const int32 unclamped_result =
+ params.output_offset +
+ MultiplyByQuantizedMultiplierSmallerThanOneExp(input1_val * input2_val,
+ params.output_multiplier,
+ params.output_shift);
+ const int32 clamped_output =
+ std::min(params.quantized_activation_max,
+ std::max(params.quantized_activation_min, unclamped_result));
+ output_data[i] = static_cast<uint8>(clamped_output);
+ }
+}
+
+// Broadcast mul that can often be used for inner loop of broadcast Mul.
+inline void MulSimpleBroadcast(int size, const ArithmeticParams& params,
+ const uint8 broadcast_value,
+ const uint8* input2_data, uint8* output_data) {
+ const int16 input1_val = params.input1_offset + broadcast_value;
+
+ int i = 0;
+ TFLITE_DCHECK_GT(params.input1_offset, -256);
+ TFLITE_DCHECK_LT(params.input1_offset, 256);
+ TFLITE_DCHECK_GT(params.input2_offset, -256);
+ TFLITE_DCHECK_LT(params.input2_offset, 256);
+ TFLITE_DCHECK_GT(params.output_offset, -256);
+ TFLITE_DCHECK_LT(params.output_offset, 256);
+#ifdef USE_NEON
+ const auto input2_offset_vector = vdupq_n_s16(params.input2_offset);
+ const auto output_offset_vector = vdupq_n_s16(params.output_offset);
+ const auto output_activation_min_vector =
+ vdup_n_u8(params.quantized_activation_min);
+ const auto output_activation_max_vector =
+ vdup_n_u8(params.quantized_activation_max);
+ for (; i <= size - 8; i += 8) {
+ // We load / store 8 at a time, multiplying as two sets of 4 int32s.
+ const auto input2_val_original = vld1_u8(input2_data + i);
+ const auto input2_val_s16 =
+ vreinterpretq_s16_u16(vmovl_u8(input2_val_original));
+ const auto input2_val = vaddq_s16(input2_val_s16, input2_offset_vector);
+
+ const auto input2_val_low = vget_low_s16(input2_val);
+ const auto input2_val_high = vget_high_s16(input2_val);
+
+ auto p1 = vmull_n_s16(input2_val_low, input1_val);
+ auto p2 = vmull_n_s16(input2_val_high, input1_val);
+
+ p1 = vqrdmulhq_n_s32(p1, params.output_multiplier);
+ p2 = vqrdmulhq_n_s32(p2, params.output_multiplier);
+ using gemmlowp::RoundingDivideByPOT;
+ p1 = RoundingDivideByPOT(p1, -params.output_shift);
+ p2 = RoundingDivideByPOT(p2, -params.output_shift);
+
+ const auto p1_narrowed = vmovn_s32(p1);
+ const auto p2_narrowed = vmovn_s32(p2);
+ const auto p =
+ vaddq_s16(vcombine_s16(p1_narrowed, p2_narrowed), output_offset_vector);
+ const auto clamped =
+ vmax_u8(output_activation_min_vector,
+ vmin_u8(output_activation_max_vector, vqmovun_s16(p)));
+ vst1_u8(output_data + i, clamped);
+ }
+#endif // NEON
+
+ for (; i < size; ++i) {
+ const int32 input2_val = params.input2_offset + input2_data[i];
+ const int32 unclamped_result =
+ params.output_offset +
+ MultiplyByQuantizedMultiplierSmallerThanOneExp(input1_val * input2_val,
+ params.output_multiplier,
+ params.output_shift);
+ const int32 clamped_output =
+ std::min(params.quantized_activation_max,
+ std::max(params.quantized_activation_min, unclamped_result));
+ output_data[i] = static_cast<uint8>(clamped_output);
+ }
+}
+
+inline void Mul(const ArithmeticParams& params,
+ const RuntimeShape& input1_shape, const uint8* input1_data,
+ const RuntimeShape& input2_shape, const uint8* input2_data,
+ const RuntimeShape& output_shape, uint8* output_data) {
+ TFLITE_DCHECK_LE(params.quantized_activation_min,
+ params.quantized_activation_max);
+ gemmlowp::ScopedProfilingLabel label("Mul/8bit");
+ const int flat_size =
+ MatchingFlatSize(input1_shape, input2_shape, output_shape);
+
+ MulElementwise(flat_size, params, input1_data, input2_data, output_data);
+}
+
+inline void BroadcastMulFivefold(const ArithmeticParams& unswitched_params,
+ const RuntimeShape& unswitched_input1_shape,
+ const uint8* unswitched_input1_data,
+ const RuntimeShape& unswitched_input2_shape,
+ const uint8* unswitched_input2_data,
+ const RuntimeShape& output_shape,
+ uint8* output_data) {
+ gemmlowp::ScopedProfilingLabel label("BroadcastMulFivefold/8bit");
+
+ ArithmeticParams switched_params = unswitched_params;
+ switched_params.input1_offset = unswitched_params.input2_offset;
+ switched_params.input2_offset = unswitched_params.input1_offset;
+
+ const bool use_unswitched =
+ unswitched_params.broadcast_category ==
+ tflite::BroadcastableOpCategory::kFirstInputBroadcastsFast;
+
+ const ArithmeticParams& params =
+ use_unswitched ? unswitched_params : switched_params;
+ const uint8* input1_data =
+ use_unswitched ? unswitched_input1_data : unswitched_input2_data;
+ const uint8* input2_data =
+ use_unswitched ? unswitched_input2_data : unswitched_input1_data;
+
+ // Fivefold nested loops. The second input resets its position for each
+ // iteration of the second loop. The first input resets its position at the
+ // beginning of the fourth loop. The innermost loop is an elementwise Mul of
+ // sections of the arrays.
+ uint8* output_data_ptr = output_data;
+ const uint8* input1_data_ptr = input1_data;
+ const uint8* input2_data_reset = input2_data;
+ int y0 = params.broadcast_shape[0];
+ int y1 = params.broadcast_shape[1];
+ int y2 = params.broadcast_shape[2];
+ int y3 = params.broadcast_shape[3];
+ int y4 = params.broadcast_shape[4];
+ if (y4 > 1) {
+ for (int i0 = 0; i0 < y0; ++i0) {
+ const uint8* input2_data_ptr;
+ for (int i1 = 0; i1 < y1; ++i1) {
+ input2_data_ptr = input2_data_reset;
+ for (int i2 = 0; i2 < y2; ++i2) {
+ for (int i3 = 0; i3 < y3; ++i3) {
+ MulElementwise(y4, params, input1_data_ptr, input2_data_ptr,
+ output_data_ptr);
+ input2_data_ptr += y4;
+ output_data_ptr += y4;
+ }
+ input1_data_ptr += y4;
+ }
+ }
+ input2_data_reset = input2_data_ptr;
+ }
+ } else {
+ for (int i0 = 0; i0 < y0; ++i0) {
+ const uint8* input2_data_ptr;
+ for (int i1 = 0; i1 < y1; ++i1) {
+ input2_data_ptr = input2_data_reset;
+ for (int i2 = 0; i2 < y2; ++i2) {
+ MulSimpleBroadcast(y3, params, *input1_data_ptr, input2_data_ptr,
+ output_data_ptr);
+ input2_data_ptr += y3;
+ output_data_ptr += y3;
+ ++input1_data_ptr;
}
}
+ input2_data_reset = input2_data_ptr;
}
}
}
-// legacy, for compatibility with old checked-in code
-template <FusedActivationFunctionType Ac>
-inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
- int32 input1_offset, const uint8* input2_data,
- const Dims<4>& input2_dims, int32 input2_offset,
- int32 output_offset, int32 output_multiplier,
- int output_shift, int32 output_activation_min,
- int32 output_activation_max, uint8* output_data,
- const Dims<4>& output_dims) {
- BroadcastMul(input1_data, input1_dims, input1_offset, input2_data,
- input2_dims, input2_offset, output_offset, output_multiplier,
- output_shift, output_activation_min, output_activation_max,
- output_data, output_dims);
-}
-
// TODO(jiawen): We can implement BroadcastDiv on buffers of arbitrary
// dimensionality if the runtime code does a single loop over one dimension
// that handles broadcasting as the base case. The code generator would then
@@ -4343,8 +4544,8 @@ inline void LogSoftmax(const uint8* input_data, const RuntimeShape& input_shape,
}
}
-inline void Logistic(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Logistic(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
gemmlowp::ScopedProfilingLabel label("Logistic");
auto input_map = MapAsVector(input_data, input_shape);
auto output_map = MapAsVector(output_data, output_shape);
@@ -4489,8 +4690,8 @@ inline void Logistic(const uint8* input_data, const RuntimeShape& input_shape,
}
}
-inline void Logistic(const int16* input_data, const RuntimeShape& input_shape,
- int16* output_data, const RuntimeShape& output_shape) {
+inline void Logistic(const RuntimeShape& input_shape, const int16* input_data,
+ const RuntimeShape& output_shape, int16* output_data) {
gemmlowp::ScopedProfilingLabel label("Logistic/Int16");
const int flat_size = MatchingFlatSize(input_shape, output_shape);
@@ -4549,8 +4750,14 @@ inline void Logistic(const int16* input_data, const RuntimeShape& input_shape,
}
}
-inline void Tanh(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+// Legacy version.
+inline void Logistic(const int16* input_data, const RuntimeShape& input_shape,
+ int16* output_data, const RuntimeShape& output_shape) {
+ Logistic(input_shape, input_data, output_shape, output_data);
+}
+
+inline void Tanh(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
gemmlowp::ScopedProfilingLabel label("Tanh");
auto input_map = MapAsVector(input_data, input_shape);
auto output_map = MapAsVector(output_data, output_shape);
@@ -4813,14 +5020,21 @@ inline void Cast(const SrcT* input_data, const Dims<4>& input_dims,
output_map.array() = input_map.array().template cast<DstT>();
}
-inline void Floor(const float* input_data, const Dims<4>& input_dims,
- float* output_data, const Dims<4>& output_dims) {
+inline void Floor(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
gemmlowp::ScopedProfilingLabel label("Floor");
- auto input_map = MapAsVector(input_data, input_dims);
- auto output_map = MapAsVector(output_data, output_dims);
+ auto input_map = MapAsVector(input_data, input_shape);
+ auto output_map = MapAsVector(output_data, output_shape);
output_map.array() = Eigen::floor(input_map.array());
}
+// Legacy Dims<4> version.
+inline void Floor(const float* input_data, const Dims<4>& input_dims,
+ float* output_data, const Dims<4>& output_dims) {
+ Floor(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
+}
+
#ifdef USE_NEON
inline void ResizeBilinearKernel(const float* input_ptr, int32 depth,
float scale, float* output_ptr) {
@@ -5376,31 +5590,53 @@ void TypedMemset(void* ptr, T value, size_t num) {
}
}
-template <typename T>
-inline void PadV2(const T* input_data, const Dims<4>& input_dims,
- const std::vector<int>& left_paddings,
- const std::vector<int>& right_paddings, T* output_data,
- const Dims<4>& output_dims, const T pad_value) {
+// There are two versions of pad: Pad and PadV2. In PadV2 there is a second
+// scalar input that provides the padding value. Therefore pad_value_ptr can be
+// equivalent to a simple input1_data. For Pad, it should point to a zero
+// value.
+//
+// Note that two typenames are required, so that T=P=int32 is considered a
+// specialization distinct from P=int32.
+template <typename T, typename P>
+inline void PadImpl(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const P* pad_value_ptr, const RuntimeShape& output_shape,
+ T* output_data) {
gemmlowp::ScopedProfilingLabel label("Pad");
- TFLITE_DCHECK_EQ(left_paddings.size(), 4);
- TFLITE_DCHECK_EQ(right_paddings.size(), 4);
+ RuntimeShape ext_input_shape = RuntimeShape::ExtendedShape(4, input_shape);
+ RuntimeShape ext_output_shape = RuntimeShape::ExtendedShape(4, output_shape);
+ TFLITE_DCHECK_LE(op_params.left_padding_count, 4);
+ TFLITE_DCHECK_LE(op_params.right_padding_count, 4);
+
+ // Runtime calls are currently fixed at 4 dimensions. Copy inputs so
+ // we can pad them to 4 dims (yes, we are "padding the padding").
+ std::vector<int> left_padding_copy(4, 0);
+ for (int i = 0; i < op_params.left_padding_count; ++i) {
+ left_padding_copy[i] = op_params.left_padding[i];
+ }
+ std::vector<int> right_padding_copy(4, 0);
+ for (int i = 0; i < op_params.right_padding_count; ++i) {
+ right_padding_copy[i] = op_params.right_padding[i];
+ }
- const int output_batch = ArraySize(output_dims, 3);
- const int output_height = ArraySize(output_dims, 2);
- const int output_width = ArraySize(output_dims, 1);
- const int output_depth = ArraySize(output_dims, 0);
+ const int output_batch = ext_output_shape.Dims(0);
+ const int output_height = ext_output_shape.Dims(1);
+ const int output_width = ext_output_shape.Dims(2);
+ const int output_depth = ext_output_shape.Dims(3);
- const int left_b_padding = left_paddings[3];
- const int left_h_padding = left_paddings[2];
- const int left_w_padding = left_paddings[1];
- const int left_d_padding = left_paddings[0];
+ const int left_b_padding = left_padding_copy[0];
+ const int left_h_padding = left_padding_copy[1];
+ const int left_w_padding = left_padding_copy[2];
+ const int left_d_padding = left_padding_copy[3];
- const int right_b_padding = right_paddings[3];
- const int right_h_padding = right_paddings[2];
- const int right_w_padding = right_paddings[1];
- const int right_d_padding = right_paddings[0];
+ const int right_b_padding = right_padding_copy[0];
+ const int right_h_padding = right_padding_copy[1];
+ const int right_w_padding = right_padding_copy[2];
+ const int right_d_padding = right_padding_copy[3];
- const int input_depth = ArraySize(input_dims, 0);
+ const int input_depth = ext_input_shape.Dims(3);
+ // const T pad_value = ExtractFloatOrInt<T>(op_params.pad_value);
+ const T pad_value = *pad_value_ptr;
if (left_b_padding != 0) {
TypedMemset<T>(
@@ -5410,61 +5646,113 @@ inline void PadV2(const T* input_data, const Dims<4>& input_dims,
for (int out_b = left_b_padding; out_b < output_batch - right_b_padding;
++out_b) {
if (left_h_padding != 0) {
- TypedMemset<T>(output_data + Offset(output_dims, 0, 0, 0, out_b),
+ TypedMemset<T>(output_data + Offset(ext_output_shape, out_b, 0, 0, 0),
pad_value, left_h_padding * output_width * output_depth);
}
for (int out_h = left_h_padding; out_h < output_height - right_h_padding;
++out_h) {
if (left_w_padding != 0) {
- TypedMemset<T>(output_data + Offset(output_dims, 0, 0, out_h, out_b),
- pad_value, left_w_padding * output_depth);
+ TypedMemset<T>(
+ output_data + Offset(ext_output_shape, out_b, out_h, 0, 0),
+ pad_value, left_w_padding * output_depth);
}
for (int out_w = left_w_padding; out_w < output_width - right_w_padding;
++out_w) {
if (left_d_padding != 0) {
TypedMemset<T>(
- output_data + Offset(output_dims, 0, out_w, out_h, out_b),
+ output_data + Offset(ext_output_shape, out_b, out_h, out_w, 0),
pad_value, left_d_padding);
}
T* out = output_data +
- Offset(output_dims, left_d_padding, out_w, out_h, out_b);
- const T* in =
- input_data + Offset(input_dims, 0, out_w - left_w_padding,
- out_h - left_h_padding, out_b - left_b_padding);
+ Offset(ext_output_shape, out_b, out_h, out_w, left_d_padding);
+ const T* in = input_data +
+ Offset(ext_input_shape, out_b - left_b_padding,
+ out_h - left_h_padding, out_w - left_w_padding, 0);
memcpy(out, in, input_depth * sizeof(T));
if (right_d_padding != 0) {
TypedMemset<T>(
- output_data + Offset(output_dims, output_depth - right_d_padding,
- out_w, out_h, out_b),
+ output_data + Offset(ext_output_shape, out_b, out_h, out_w,
+ output_depth - right_d_padding),
pad_value, right_d_padding);
}
}
if (right_w_padding != 0) {
- TypedMemset<T>(
- output_data + Offset(output_dims, 0, output_width - right_w_padding,
- out_h, out_b),
- pad_value, right_w_padding * output_depth);
+ TypedMemset<T>(output_data + Offset(ext_output_shape, out_b, out_h,
+ output_width - right_w_padding, 0),
+ pad_value, right_w_padding * output_depth);
}
}
if (right_h_padding != 0) {
TypedMemset<T>(
- output_data +
- Offset(output_dims, 0, 0, output_height - right_h_padding, out_b),
+ output_data + Offset(ext_output_shape, out_b,
+ output_height - right_h_padding, 0, 0),
pad_value, right_h_padding * output_width * output_depth);
}
}
if (right_b_padding != 0) {
TypedMemset<T>(
output_data +
- Offset(output_dims, 0, 0, 0, output_batch - right_b_padding),
+ Offset(ext_output_shape, output_batch - right_b_padding, 0, 0, 0),
pad_value,
right_b_padding * output_height * output_width * output_depth);
}
}
-// Legacy Pad() method that casts an int32_t to T before padding.
+template <typename T, typename P>
+inline void Pad(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const P* pad_value_ptr, const RuntimeShape& output_shape,
+ T* output_data) {
+ PadImpl(op_params, input_shape, input_data, pad_value_ptr, output_shape,
+ output_data);
+}
+
+// The second (pad-value) input can be int32 when, say, the first is uint8.
+template <typename T>
+inline void Pad(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const int32* pad_value_ptr, const RuntimeShape& output_shape,
+ T* output_data) {
+ const T converted_pad_value = static_cast<T>(*pad_value_ptr);
+ PadImpl(op_params, input_shape, input_data, &converted_pad_value,
+ output_shape, output_data);
+}
+
+// This version avoids conflicting template matching.
+template <>
+inline void Pad(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const int32* input_data,
+ const int32* pad_value_ptr, const RuntimeShape& output_shape,
+ int32* output_data) {
+ PadImpl(op_params, input_shape, input_data, pad_value_ptr, output_shape,
+ output_data);
+}
+
+// Legacy signature, function covered both Pad and PadV2.
+template <typename T>
+inline void PadV2(const T* input_data, const Dims<4>& input_dims,
+ const std::vector<int>& left_paddings,
+ const std::vector<int>& right_paddings, T* output_data,
+ const Dims<4>& output_dims, const T pad_value) {
+ TFLITE_DCHECK_EQ(left_paddings.size(), 4);
+ TFLITE_DCHECK_EQ(right_paddings.size(), 4);
+ tflite::PadParams op_params;
+ op_params.left_padding_count = 4;
+ op_params.right_padding_count = 4;
+ for (int i = 0; i < 4; ++i) {
+ op_params.left_padding[i] = left_paddings[3 - i];
+ op_params.right_padding[i] = right_paddings[3 - i];
+ }
+ // SetFloatOrInt(pad_value, &op_params.pad_value);
+ const T pad_value_copy = pad_value;
+
+ Pad(op_params, DimsToShape(input_dims), input_data, &pad_value_copy,
+ DimsToShape(output_dims), output_data);
+}
+
+// Old Pad that calls legacy PadV2.
template <typename T>
inline void Pad(const T* input_data, const Dims<4>& input_dims,
const std::vector<int>& left_paddings,
@@ -5475,34 +5763,45 @@ inline void Pad(const T* input_data, const Dims<4>& input_dims,
output_dims, converted_pad_value);
}
+// Old Pad that only padded with 0.
template <typename T>
inline void Pad(const T* input_data, const Dims<4>& input_dims,
const std::vector<int>& left_paddings,
const std::vector<int>& right_paddings, T* output_data,
const Dims<4>& output_dims) {
- Pad(input_data, input_dims, left_paddings, right_paddings, output_data,
- output_dims, 0);
+ const T pad_value = static_cast<T>(0);
+ PadV2<T>(input_data, input_dims, left_paddings, right_paddings, output_data,
+ output_dims, pad_value);
}
template <typename T>
-inline void Slice(const T* input_data, const Dims<4>& input_dims,
- const std::vector<int>& begin, const std::vector<int>& size,
- T* output_data, const Dims<4>& output_dims) {
- // TODO(dkalenichenko): This op only supports 4D tensors.
- TFLITE_DCHECK_EQ(begin.size(), 4);
- TFLITE_DCHECK_EQ(size.size(), 4);
- const int start_b = begin[3];
- const int stop_b =
- size[3] == -1 ? input_dims.sizes[3] - start_b : start_b + size[3];
- const int start_h = begin[2];
- const int stop_h =
- size[2] == -1 ? input_dims.sizes[2] - start_h : start_h + size[2];
- const int start_w = begin[1];
- const int stop_w =
- size[1] == -1 ? input_dims.sizes[1] - start_w : start_w + size[1];
- const int start_d = begin[0];
- const int stop_d =
- size[0] == -1 ? input_dims.sizes[0] - start_d : start_d + size[0];
+inline void Slice(const tflite::SliceParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const RuntimeShape& output_shape, T* output_data) {
+ gemmlowp::ScopedProfilingLabel label("Slice");
+ RuntimeShape ext_shape = RuntimeShape::ExtendedShape(4, input_shape);
+ // TODO(dkalenichenko): This op only supports 4D tensors or smaller.
+ TFLITE_DCHECK_LE(op_params.begin_count, 4);
+ TFLITE_DCHECK_LE(op_params.size_count, 4);
+ const int begin_count = op_params.begin_count;
+ const int size_count = op_params.size_count;
+ // We front-pad the begin and size vectors.
+ const int start_b = 4 - begin_count > 0 ? 0 : op_params.begin[0];
+ const int stop_b = (4 - size_count > 0 || op_params.size[0] == -1)
+ ? ext_shape.Dims(0) - start_b
+ : start_b + op_params.size[0];
+ const int start_h = begin_count < 3 ? 0 : op_params.begin[begin_count - 3];
+ const int stop_h = (size_count < 3 || op_params.size[size_count - 3] == -1)
+ ? ext_shape.Dims(1) - start_h
+ : start_h + op_params.size[size_count - 3];
+ const int start_w = begin_count < 2 ? 0 : op_params.begin[begin_count - 2];
+ const int stop_w = (size_count < 2 || op_params.size[size_count - 2] == -1)
+ ? ext_shape.Dims(2) - start_w
+ : start_w + op_params.size[size_count - 2];
+ const int start_d = begin_count < 1 ? 0 : op_params.begin[begin_count - 1];
+ const int stop_d = (size_count < 1 || op_params.size[size_count - 1] == -1)
+ ? ext_shape.Dims(3) - start_d
+ : start_d + op_params.size[size_count - 1];
T* out_ptr = output_data;
for (int in_b = start_b; in_b < stop_b; ++in_b) {
@@ -5510,7 +5809,7 @@ inline void Slice(const T* input_data, const Dims<4>& input_dims,
for (int in_w = start_w; in_w < stop_w; ++in_w) {
const int len = stop_d - start_d;
memcpy(out_ptr,
- input_data + Offset(input_dims, start_d, in_w, in_h, in_b),
+ input_data + Offset(ext_shape, in_b, in_h, in_w, start_d),
len * sizeof(T));
out_ptr += len;
}
@@ -5519,28 +5818,60 @@ inline void Slice(const T* input_data, const Dims<4>& input_dims,
}
template <typename T>
-void TensorFlowMinimum(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, T* output_data,
- const Dims<4>& output_dims) {
+inline void Slice(const T* input_data, const Dims<4>& input_dims,
+ const std::vector<int>& begin, const std::vector<int>& size,
+ T* output_data, const Dims<4>& output_dims) {
+ tflite::SliceParams op_params;
+ op_params.begin_count = 4;
+ op_params.size_count = 4;
+ for (int i = 0; i < 4; ++i) {
+ op_params.begin[i] = begin[3 - i];
+ op_params.size[i] = size[3 - i];
+ }
+
+ Slice(op_params, DimsToShape(input_dims), input_data,
+ DimsToShape(output_dims), output_data);
+}
+
+template <typename T>
+void Minimum(const RuntimeShape& input1_shape, const T* input1_data,
+ const T* input2_data, const RuntimeShape& output_shape,
+ T* output_data) {
gemmlowp::ScopedProfilingLabel label("TensorFlowMinimum");
- auto input1_map = MapAsVector(input1_data, input1_dims);
- auto output_map = MapAsVector(output_data, output_dims);
+ auto input1_map = MapAsVector(input1_data, input1_shape);
+ auto output_map = MapAsVector(output_data, output_shape);
auto min_value = input2_data[0];
output_map.array() = input1_map.array().min(min_value);
}
template <typename T>
-void TensorFlowMaximum(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, T* output_data,
- const Dims<4>& output_dims) {
+void Maximum(const RuntimeShape& input1_shape, const T* input1_data,
+ const T* input2_data, const RuntimeShape& output_shape,
+ T* output_data) {
gemmlowp::ScopedProfilingLabel label("TensorFlowMaximum");
- auto input1_map = MapAsVector(input1_data, input1_dims);
- auto output_map = MapAsVector(output_data, output_dims);
+ auto input1_map = MapAsVector(input1_data, input1_shape);
+ auto output_map = MapAsVector(output_data, output_shape);
auto max_value = input2_data[0];
output_map.array() = input1_map.array().max(max_value);
}
template <typename T>
+void TensorFlowMinimum(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, T* output_data,
+ const Dims<4>& output_dims) {
+ Minimum(DimsToShape(input1_dims), input1_data, input2_data,
+ DimsToShape(output_dims), output_data);
+}
+
+template <typename T>
+void TensorFlowMaximum(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, T* output_data,
+ const Dims<4>& output_dims) {
+ Maximum(DimsToShape(input1_dims), input1_data, input2_data,
+ DimsToShape(output_dims), output_data);
+}
+
+template <typename T>
void TransposeIm2col(const T* input_data, const Dims<4>& input_dims,
const Dims<4>& filter_dims, int stride_width,
int stride_height, int pad_width, int pad_height,
diff --git a/tensorflow/contrib/lite/kernels/internal/quantization_util_test.cc b/tensorflow/contrib/lite/kernels/internal/quantization_util_test.cc
index 94773b47d3..00fc3e91dc 100644
--- a/tensorflow/contrib/lite/kernels/internal/quantization_util_test.cc
+++ b/tensorflow/contrib/lite/kernels/internal/quantization_util_test.cc
@@ -130,22 +130,22 @@ void RunSafeCastTests() {
}
TEST(QuantizationUtilTest, SafeCast) {
- RunSafeCastTests<float, int8>();
- RunSafeCastTests<double, int8>();
- RunSafeCastTests<float, int16>();
- RunSafeCastTests<double, int16>();
- RunSafeCastTests<float, int32>();
- RunSafeCastTests<double, int32>();
- RunSafeCastTests<float, int64>();
- RunSafeCastTests<double, int64>();
- RunSafeCastTests<float, uint8>();
- RunSafeCastTests<double, uint8>();
- RunSafeCastTests<float, uint16>();
- RunSafeCastTests<double, uint16>();
- RunSafeCastTests<float, uint32>();
- RunSafeCastTests<double, uint32>();
- RunSafeCastTests<float, uint64>();
- RunSafeCastTests<double, uint64>();
+ RunSafeCastTests<float, int8_t>();
+ RunSafeCastTests<double, int8_t>();
+ RunSafeCastTests<float, int16_t>();
+ RunSafeCastTests<double, int16_t>();
+ RunSafeCastTests<float, int32_t>();
+ RunSafeCastTests<double, int32_t>();
+ RunSafeCastTests<float, int64_t>();
+ RunSafeCastTests<double, int64_t>();
+ RunSafeCastTests<float, uint8_t>();
+ RunSafeCastTests<double, uint8_t>();
+ RunSafeCastTests<float, uint16_t>();
+ RunSafeCastTests<double, uint16_t>();
+ RunSafeCastTests<float, uint32_t>();
+ RunSafeCastTests<double, uint32_t>();
+ RunSafeCastTests<float, uint64_t>();
+ RunSafeCastTests<double, uint64_t>();
}
// Example taken from http://www.tensorflow.org/performance/quantization
diff --git a/tensorflow/contrib/lite/kernels/internal/reference/legacy_reference_ops.h b/tensorflow/contrib/lite/kernels/internal/reference/legacy_reference_ops.h
index bcf5e4e4f6..71ae74f34c 100644
--- a/tensorflow/contrib/lite/kernels/internal/reference/legacy_reference_ops.h
+++ b/tensorflow/contrib/lite/kernels/internal/reference/legacy_reference_ops.h
@@ -26,11 +26,6 @@ namespace tflite {
namespace reference_ops {
-inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {
- return RuntimeShape(
- {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});
-}
-
template <FusedActivationFunctionType Ac>
void L2Normalization(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
@@ -47,20 +42,20 @@ inline void L2Normalization(const uint8* input_data, const Dims<4>& input_dims,
inline void Relu(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Relu(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Relu(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Relu1(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Relu1(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Relu1(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Relu6(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Relu6(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Relu6(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
template <FusedActivationFunctionType Ac>
@@ -316,6 +311,37 @@ inline void AveragePool(const float* input_data, const Dims<4>& input_dims,
DimsToShape(output_dims), output_data);
}
+inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
+ int32 input1_offset, const uint8* input2_data,
+ const Dims<4>& input2_dims, int32 input2_offset,
+ int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims) {
+ BroadcastMul4DSlow(
+ input1_data, input1_dims, input1_offset, input2_data, input2_dims,
+ input2_offset, output_offset, output_multiplier,
+ //
+ kReverseShift * output_shift,
+ //
+ output_activation_min, output_activation_max, output_data, output_dims);
+}
+
+// legacy, for compatibility with old checked-in code
+template <FusedActivationFunctionType Ac>
+inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
+ int32 input1_offset, const uint8* input2_data,
+ const Dims<4>& input2_dims, int32 input2_offset,
+ int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims) {
+ BroadcastMul(input1_data, input1_dims, input1_offset, input2_data,
+ input2_dims, input2_offset, output_offset, output_multiplier,
+ output_shift, output_activation_min, output_activation_max,
+ output_data, output_dims);
+}
+
// legacy, for compatibility with old checked-in code
template <FusedActivationFunctionType Ac>
void AveragePool(const float* input_data, const Dims<4>& input_dims,
@@ -557,8 +583,8 @@ inline void LogSoftmax(const uint8* input_data, const Dims<4>& input_dims,
inline void Logistic(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Logistic(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Logistic(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Logistic(const uint8* input_data, const Dims<4>& input_dims,
@@ -572,14 +598,14 @@ inline void Logistic(const uint8* input_data, const Dims<4>& input_dims,
inline void Logistic(const int16* input_data, const Dims<4>& input_dims,
int16* output_data, const Dims<4>& output_dims) {
- Logistic(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Logistic(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Tanh(const float* input_data, const Dims<4>& input_dims,
float* output_data, const Dims<4>& output_dims) {
- Tanh(input_data, DimsToShape(input_dims), output_data,
- DimsToShape(output_dims));
+ Tanh(DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data);
}
inline void Tanh(const uint8* input_data, const Dims<4>& input_dims,
diff --git a/tensorflow/contrib/lite/kernels/internal/reference/portable_tensor_utils.cc b/tensorflow/contrib/lite/kernels/internal/reference/portable_tensor_utils.cc
index a5f4addd5e..aa93e857d7 100644
--- a/tensorflow/contrib/lite/kernels/internal/reference/portable_tensor_utils.cc
+++ b/tensorflow/contrib/lite/kernels/internal/reference/portable_tensor_utils.cc
@@ -73,10 +73,12 @@ void PortableMatrixBatchVectorMultiplyAccumulate(const float* matrix,
for (int b = 0; b < n_batch; b++) {
const float* matrix_ptr = matrix;
for (int r = 0; r < m_rows; r++) {
+ float dot_prod = 0.0f;
const float* vector_in_batch = vector + b * m_cols;
for (int c = 0; c < m_cols; c++) {
- *result_in_batch += *matrix_ptr++ * *vector_in_batch++;
+ dot_prod += *matrix_ptr++ * *vector_in_batch++;
}
+ *result_in_batch += dot_prod;
result_in_batch += result_stride;
}
}
diff --git a/tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h b/tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h
index ace3af2da0..556049d8a6 100644
--- a/tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h
+++ b/tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h
@@ -105,6 +105,11 @@ namespace reference_ops {
// Used mainly to convert from old-style shifts (right) to new-style (left).
static constexpr int kReverseShift = -1;
+inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {
+ return RuntimeShape(
+ {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});
+}
+
template <typename T>
int CountLeadingZeros(T integer_input) {
static_assert(std::is_unsigned<T>::value,
@@ -271,12 +276,12 @@ inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
int32 input_offset, const uint8* filter_data,
const Dims<4>& filter_dims, int32 filter_offset,
const int32* bias_data, const Dims<4>& bias_dims,
- int stride_width, int stride_height, int pad_width,
- int pad_height, int32 output_offset, int32 output_multiplier,
- int output_shift, int32 output_activation_min,
- int32 output_activation_max, uint8* output_data,
- const Dims<4>& output_dims, uint8* im2col_data,
- const Dims<4>& im2col_dims,
+ int stride_width, int stride_height, int dilation_width_factor,
+ int dilation_height_factor, int pad_width, int pad_height,
+ int32 output_offset, int32 output_multiplier, int output_shift,
+ int32 output_activation_min, int32 output_activation_max,
+ uint8* output_data, const Dims<4>& output_dims,
+ uint8* im2col_data, const Dims<4>& im2col_dims,
gemmlowp::GemmContext* gemm_context) {
(void)im2col_data; // only used in optimized code.
(void)im2col_dims; // only used in optimized code.
@@ -302,8 +307,9 @@ inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
for (int filter_y = 0; filter_y < filter_height; ++filter_y) {
for (int filter_x = 0; filter_x < filter_width; ++filter_x) {
for (int in_channel = 0; in_channel < input_depth; ++in_channel) {
- const int in_x = in_x_origin + filter_x;
- const int in_y = in_y_origin + filter_y;
+ const int in_x = in_x_origin + dilation_width_factor * filter_x;
+ const int in_y =
+ in_y_origin + dilation_height_factor * filter_y;
// If the location is outside the bounds of the input image,
// use zero as a default value.
if ((in_x >= 0) && (in_x < input_width) && (in_y >= 0) &&
@@ -335,6 +341,24 @@ inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
}
}
+inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
+ int32 input_offset, const uint8* filter_data,
+ const Dims<4>& filter_dims, int32 filter_offset,
+ const int32* bias_data, const Dims<4>& bias_dims,
+ int stride_width, int stride_height, int pad_width,
+ int pad_height, int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims, uint8* im2col_data,
+ const Dims<4>& im2col_dims,
+ gemmlowp::GemmContext* gemm_context) {
+ Conv(input_data, input_dims, input_offset, filter_data, filter_dims,
+ filter_offset, bias_data, bias_dims, stride_width, stride_height, 1, 1,
+ pad_width, pad_height, output_offset, output_multiplier, output_shift,
+ output_activation_min, output_activation_max, output_data, output_dims,
+ im2col_data, im2col_dims, gemm_context);
+}
+
// legacy, for compatibility with old checked-in code
template <FusedActivationFunctionType Ac>
inline void Conv(const uint8* input_data, const Dims<4>& input_dims,
@@ -546,8 +570,8 @@ inline void FullyConnected(const uint8* input_data, const Dims<4>& input_dims,
if (bias_data) {
acc += bias_data[Offset(bias_dims, out_c, 0, 0, 0)];
}
- acc = MultiplyByQuantizedMultiplierSmallerThanOneExp(
- acc, output_multiplier, kReverseShift * output_shift);
+ acc = MultiplyByQuantizedMultiplier(acc, output_multiplier,
+ kReverseShift * output_shift);
acc += output_offset;
acc = std::max(acc, output_activation_min);
acc = std::min(acc, output_activation_max);
@@ -822,8 +846,8 @@ void GlobalBatchNormalization(const float* input_data,
}
}
-inline void Relu(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Relu(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
const int flat_size = MatchingFlatSize(input_shape, output_shape);
for (int i = 0; i < flat_size; ++i) {
const float val = input_data[i];
@@ -833,8 +857,8 @@ inline void Relu(const float* input_data, const RuntimeShape& input_shape,
}
}
-inline void Relu1(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Relu1(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
gemmlowp::ScopedProfilingLabel label("Relu1 (not fused)");
const int flat_size = MatchingFlatSize(input_shape, output_shape);
for (int i = 0; i < flat_size; ++i) {
@@ -846,8 +870,8 @@ inline void Relu1(const float* input_data, const RuntimeShape& input_shape,
}
}
-inline void Relu6(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Relu6(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
gemmlowp::ScopedProfilingLabel label("Relu6 (not fused)");
const int flat_size = MatchingFlatSize(input_shape, output_shape);
for (int i = 0; i < flat_size; ++i) {
@@ -1374,13 +1398,144 @@ void BroadcastMul(const T* input1_data, const Dims<4>& input1_dims,
output_dims);
}
-inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
- int32 input1_offset, const uint8* input2_data,
- const Dims<4>& input2_dims, int32 input2_offset,
- int32 output_offset, int32 output_multiplier,
- int output_shift, int32 output_activation_min,
- int32 output_activation_max, uint8* output_data,
- const Dims<4>& output_dims) {
+// Element-wise mul that can often be used for inner loop of broadcast Mul as
+// well as the non-broadcast Mul.
+inline void MulElementwise(int size, const ArithmeticParams& params,
+ const uint8* input1_data, const uint8* input2_data,
+ uint8* output_data) {
+ for (int i = 0; i < size; ++i) {
+ const int32 input1_val = params.input1_offset + input1_data[i];
+ const int32 input2_val = params.input2_offset + input2_data[i];
+ const int32 unclamped_result =
+ params.output_offset +
+ MultiplyByQuantizedMultiplierSmallerThanOneExp(input1_val * input2_val,
+ params.output_multiplier,
+ params.output_shift);
+ const int32 clamped_output =
+ std::min(params.quantized_activation_max,
+ std::max(params.quantized_activation_min, unclamped_result));
+ output_data[i] = static_cast<uint8>(clamped_output);
+ }
+}
+
+inline void Mul(const ArithmeticParams& params,
+ const RuntimeShape& input1_shape, const uint8* input1_data,
+ const RuntimeShape& input2_shape, const uint8* input2_data,
+ const RuntimeShape& output_shape, uint8* output_data) {
+ TFLITE_DCHECK_LE(params.quantized_activation_min,
+ params.quantized_activation_max);
+ gemmlowp::ScopedProfilingLabel label("Mul/8bit");
+ const int flat_size =
+ MatchingFlatSize(input1_shape, input2_shape, output_shape);
+
+ MulElementwise(flat_size, params, input1_data, input2_data, output_data);
+}
+
+inline void BroadcastMulFivefold(const ArithmeticParams& unswitched_params,
+ const RuntimeShape& unswitched_input1_shape,
+ const uint8* unswitched_input1_data,
+ const RuntimeShape& unswitched_input2_shape,
+ const uint8* unswitched_input2_data,
+ const RuntimeShape& output_shape,
+ uint8* output_data) {
+ ArithmeticParams switched_params = unswitched_params;
+ switched_params.input1_offset = unswitched_params.input2_offset;
+ switched_params.input2_offset = unswitched_params.input1_offset;
+
+ const bool use_unswitched =
+ unswitched_params.broadcast_category ==
+ tflite::BroadcastableOpCategory::kFirstInputBroadcastsFast;
+
+ const ArithmeticParams& params =
+ use_unswitched ? unswitched_params : switched_params;
+ const uint8* input1_data =
+ use_unswitched ? unswitched_input1_data : unswitched_input2_data;
+ const uint8* input2_data =
+ use_unswitched ? unswitched_input2_data : unswitched_input1_data;
+
+ // Fivefold nested loops. The second input resets its position for each
+ // iteration of the second loop. The first input resets its position at the
+ // beginning of the fourth loop. The innermost loop is an elementwise Mul of
+ // sections of the arrays.
+ uint8* output_data_ptr = output_data;
+ const uint8* input1_data_ptr = input1_data;
+ const uint8* input2_data_reset = input2_data;
+ int y0 = params.broadcast_shape[0];
+ int y1 = params.broadcast_shape[1];
+ int y2 = params.broadcast_shape[2];
+ int y3 = params.broadcast_shape[3];
+ int y4 = params.broadcast_shape[4];
+ for (int i0 = 0; i0 < y0; ++i0) {
+ const uint8* input2_data_ptr;
+ for (int i1 = 0; i1 < y1; ++i1) {
+ input2_data_ptr = input2_data_reset;
+ for (int i2 = 0; i2 < y2; ++i2) {
+ for (int i3 = 0; i3 < y3; ++i3) {
+ MulElementwise(y4, params, input1_data_ptr, input2_data_ptr,
+ output_data_ptr);
+ input2_data_ptr += y4;
+ output_data_ptr += y4;
+ }
+ input1_data_ptr += y4;
+ }
+ }
+ input2_data_reset = input2_data_ptr;
+ }
+}
+
+inline void BroadcastMul4DSlow(const ArithmeticParams& params,
+ const RuntimeShape& input1_shape,
+ const uint8* input1_data,
+ const RuntimeShape& input2_shape,
+ const uint8* input2_data,
+ const RuntimeShape& output_shape,
+ uint8* output_data) {
+ gemmlowp::ScopedProfilingLabel label("BroadcastMul4DSlow/8bit");
+
+ NdArrayDesc<4> desc1;
+ NdArrayDesc<4> desc2;
+ // The input shapes are extended as part of NdArrayDesc initialization.
+ NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
+ &desc2);
+ RuntimeShape extended_output_shape =
+ RuntimeShape::ExtendedShape(4, output_shape);
+
+ for (int b = 0; b < extended_output_shape.Dims(0); ++b) {
+ for (int y = 0; y < extended_output_shape.Dims(1); ++y) {
+ for (int x = 0; x < extended_output_shape.Dims(2); ++x) {
+ for (int c = 0; c < extended_output_shape.Dims(3); ++c) {
+ const int32 input1_val =
+ params.input1_offset +
+ input1_data[SubscriptToIndex(desc1, b, y, x, c)];
+ const int32 input2_val =
+ params.input2_offset +
+ input2_data[SubscriptToIndex(desc2, b, y, x, c)];
+ const int32 unclamped_result =
+ params.output_offset +
+ MultiplyByQuantizedMultiplierSmallerThanOneExp(
+ input1_val * input2_val, params.output_multiplier,
+ params.output_shift);
+ const int32 clamped_output = std::min(
+ params.quantized_activation_max,
+ std::max(params.quantized_activation_min, unclamped_result));
+ output_data[Offset(extended_output_shape, b, y, x, c)] =
+ static_cast<uint8>(clamped_output);
+ }
+ }
+ }
+ }
+}
+
+// Transitional version that will be moved shortly to legacy_reference_ops, as
+// part of RuntimeShape revisions.
+inline void BroadcastMul4DSlow(const uint8* input1_data,
+ const Dims<4>& input1_dims, int32 input1_offset,
+ const uint8* input2_data,
+ const Dims<4>& input2_dims, int32 input2_offset,
+ int32 output_offset, int32 output_multiplier,
+ int output_shift, int32 output_activation_min,
+ int32 output_activation_max, uint8* output_data,
+ const Dims<4>& output_dims) {
gemmlowp::ScopedProfilingLabel label("BroadcastMul/8bit");
NdArrayDesc<4> desc1;
@@ -1407,9 +1562,9 @@ inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
const int32 input2_val =
input2_offset + input2_data[SubscriptToIndex(desc2, c, x, y, b)];
const int32 unclamped_result =
- output_offset + MultiplyByQuantizedMultiplierSmallerThanOneExp(
- input1_val * input2_val, output_multiplier,
- kReverseShift * output_shift);
+ output_offset +
+ MultiplyByQuantizedMultiplierSmallerThanOneExp(
+ input1_val * input2_val, output_multiplier, output_shift);
const int32 clamped_output =
std::min(output_activation_max,
std::max(output_activation_min, unclamped_result));
@@ -1464,21 +1619,6 @@ inline void Mul(const int16* input1_data, const Dims<4>& input1_dims,
}
}
-// legacy, for compatibility with old checked-in code
-template <FusedActivationFunctionType Ac>
-inline void BroadcastMul(const uint8* input1_data, const Dims<4>& input1_dims,
- int32 input1_offset, const uint8* input2_data,
- const Dims<4>& input2_dims, int32 input2_offset,
- int32 output_offset, int32 output_multiplier,
- int output_shift, int32 output_activation_min,
- int32 output_activation_max, uint8* output_data,
- const Dims<4>& output_dims) {
- BroadcastMul(input1_data, input1_dims, input1_offset, input2_data,
- input2_dims, input2_offset, output_offset, output_multiplier,
- output_shift, output_activation_min, output_activation_max,
- output_data, output_dims);
-}
-
// TODO(jiawen): We can implement BroadcastDiv on buffers of arbitrary
// dimensionality if the runtime code does a single loop over one dimension
// that handles broadcasting as the base case. The code generator would then
@@ -1936,6 +2076,44 @@ inline void Concatenation(int concat_dim, const uint8* const* input_data,
}
}
+template <typename Scalar>
+void Pack(int dim, const Scalar* const* input_data,
+ const Dims<4>* const* input_dims, const int32* input_zeropoint,
+ const float* input_scale, int inputs_count, Scalar* output_data,
+ const Dims<4>& output_dims, const int32 output_zeropoint,
+ const float output_scale) {
+ TFLITE_DCHECK(IsPackedWithoutStrides(output_dims));
+ int outer_size = 1;
+ for (int i = dim + 1; i < 4; i++) {
+ outer_size *= output_dims.sizes[i];
+ }
+ Scalar* output_ptr = output_data;
+ const int copy_size = FlatSize(**input_dims) / outer_size;
+ const float inverse_output_scale = 1.f / output_scale;
+ for (int k = 0; k < outer_size; k++) {
+ for (int i = 0; i < inputs_count; ++i) {
+ if (input_zeropoint[i] == output_zeropoint &&
+ input_scale[i] == output_scale) {
+ memcpy(output_ptr, input_data[i] + k * copy_size,
+ copy_size * sizeof(Scalar));
+ } else {
+ assert(false);
+ const float scale = input_scale[i] * inverse_output_scale;
+ const float bias = -input_zeropoint[i] * scale;
+ auto input_ptr = input_data[i];
+ for (int j = 0; j < copy_size; ++j) {
+ const int32_t value =
+ static_cast<int32_t>(round(input_ptr[j] * scale + bias)) +
+ output_zeropoint;
+ output_ptr[j] =
+ static_cast<uint8_t>(std::max(std::min(255, value), 0));
+ }
+ }
+ output_ptr += copy_size;
+ }
+ }
+}
+
template <FusedActivationFunctionType Ac, typename Scalar>
void DepthConcatenation(const Scalar* const* input_data,
const Dims<4>* const* input_dims, int inputs_count,
@@ -2978,8 +3156,8 @@ inline void LogSoftmax(const uint8* input_data, const RuntimeShape& input_shape,
}
}
-inline void Logistic(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Logistic(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
const int flat_size = MatchingFlatSize(input_shape, output_shape);
for (int i = 0; i < flat_size; i++) {
@@ -3027,8 +3205,8 @@ inline void Logistic(const uint8* input_data, const RuntimeShape& input_shape,
}
}
-inline void Logistic(const int16* input_data, const RuntimeShape& input_shape,
- int16* output_data, const RuntimeShape& output_shape) {
+inline void Logistic(const RuntimeShape& input_shape, const int16* input_data,
+ const RuntimeShape& output_shape, int16* output_data) {
const int flat_size = MatchingFlatSize(input_shape, output_shape);
for (int i = 0; i < flat_size; i++) {
@@ -3045,8 +3223,8 @@ inline void Logistic(const int16* input_data, const RuntimeShape& input_shape,
}
}
-inline void Tanh(const float* input_data, const RuntimeShape& input_shape,
- float* output_data, const RuntimeShape& output_shape) {
+inline void Tanh(const RuntimeShape& input_shape, const float* input_data,
+ const RuntimeShape& output_shape, float* output_data) {
const int flat_size = MatchingFlatSize(input_shape, output_shape);
for (int i = 0; i < flat_size; i++) {
@@ -3370,28 +3548,50 @@ inline void BatchToSpaceND(const T* input_data, const Dims<4>& input_dims,
}
}
-template <typename T>
-inline void PadV2(const T* input_data, const Dims<4>& input_dims,
- const std::vector<int>& left_paddings,
- const std::vector<int>& right_paddings, T* output_data,
- const Dims<4>& output_dims, const T pad_value) {
- TFLITE_DCHECK_EQ(left_paddings.size(), 4);
- TFLITE_DCHECK_EQ(right_paddings.size(), 4);
-
- const int output_batch = ArraySize(output_dims, 3);
- const int output_height = ArraySize(output_dims, 2);
- const int output_width = ArraySize(output_dims, 1);
- const int output_depth = ArraySize(output_dims, 0);
-
- const int left_b_padding = left_paddings[3];
- const int left_h_padding = left_paddings[2];
- const int left_w_padding = left_paddings[1];
- const int left_d_padding = left_paddings[0];
-
- const int right_b_padding = right_paddings[3];
- const int right_h_padding = right_paddings[2];
- const int right_w_padding = right_paddings[1];
- const int right_d_padding = right_paddings[0];
+// There are two versions of pad: Pad and PadV2. In PadV2 there is a second
+// scalar input that provides the padding value. Therefore pad_value_ptr can be
+// equivalent to a simple input1_data. For Pad, it should point to a zero
+// value.
+//
+// Note that two typenames are required, so that T=P=int32 is considered a
+// specialization distinct from P=int32.
+template <typename T, typename P>
+inline void PadImpl(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const P* pad_value_ptr, const RuntimeShape& output_shape,
+ T* output_data) {
+ RuntimeShape ext_input_shape = RuntimeShape::ExtendedShape(4, input_shape);
+ RuntimeShape ext_output_shape = RuntimeShape::ExtendedShape(4, output_shape);
+ TFLITE_DCHECK_LE(op_params.left_padding_count, 4);
+ TFLITE_DCHECK_LE(op_params.right_padding_count, 4);
+
+ // Runtime calls are currently fixed at 4 dimensions. Copy inputs so
+ // we can pad them to 4 dims (yes, we are "padding the padding").
+ std::vector<int> left_padding_copy(4, 0);
+ for (int i = 0; i < op_params.left_padding_count; ++i) {
+ left_padding_copy[i] = op_params.left_padding[i];
+ }
+ std::vector<int> right_padding_copy(4, 0);
+ for (int i = 0; i < op_params.right_padding_count; ++i) {
+ right_padding_copy[i] = op_params.right_padding[i];
+ }
+
+ const int output_batch = ext_output_shape.Dims(0);
+ const int output_height = ext_output_shape.Dims(1);
+ const int output_width = ext_output_shape.Dims(2);
+ const int output_depth = ext_output_shape.Dims(3);
+
+ const int left_b_padding = left_padding_copy[0];
+ const int left_h_padding = left_padding_copy[1];
+ const int left_w_padding = left_padding_copy[2];
+ const int left_d_padding = left_padding_copy[3];
+
+ const int right_b_padding = right_padding_copy[0];
+ const int right_h_padding = right_padding_copy[1];
+ const int right_w_padding = right_padding_copy[2];
+ const int right_d_padding = right_padding_copy[3];
+
+ const T pad_value = *pad_value_ptr;
const T* in_ptr = input_data;
T* out_ptr = output_data;
@@ -3417,7 +3617,59 @@ inline void PadV2(const T* input_data, const Dims<4>& input_dims,
}
}
-// Legacy Pad() method that casts an int32_t to T before padding.
+template <typename T, typename P>
+inline void Pad(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const P* pad_value_ptr, const RuntimeShape& output_shape,
+ T* output_data) {
+ PadImpl(op_params, input_shape, input_data, pad_value_ptr, output_shape,
+ output_data);
+}
+
+// The second (pad-value) input can be int32 when, say, the first is uint8.
+template <typename T>
+inline void Pad(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const int32* pad_value_ptr, const RuntimeShape& output_shape,
+ T* output_data) {
+ const T converted_pad_value = static_cast<T>(*pad_value_ptr);
+ PadImpl(op_params, input_shape, input_data, &converted_pad_value,
+ output_shape, output_data);
+}
+
+// This version avoids conflicting template matching.
+template <>
+inline void Pad(const tflite::PadParams& op_params,
+ const RuntimeShape& input_shape, const int32* input_data,
+ const int32* pad_value_ptr, const RuntimeShape& output_shape,
+ int32* output_data) {
+ PadImpl(op_params, input_shape, input_data, pad_value_ptr, output_shape,
+ output_data);
+}
+
+// Legacy signature, function covered both Pad and PadV2.
+template <typename T>
+inline void PadV2(const T* input_data, const Dims<4>& input_dims,
+ const std::vector<int>& left_paddings,
+ const std::vector<int>& right_paddings, T* output_data,
+ const Dims<4>& output_dims, const T pad_value) {
+ TFLITE_DCHECK_EQ(left_paddings.size(), 4);
+ TFLITE_DCHECK_EQ(right_paddings.size(), 4);
+ tflite::PadParams op_params;
+ op_params.left_padding_count = 4;
+ op_params.right_padding_count = 4;
+ for (int i = 0; i < 4; ++i) {
+ op_params.left_padding[i] = left_paddings[3 - i];
+ op_params.right_padding[i] = right_paddings[3 - i];
+ }
+ // SetFloatOrInt(pad_value, &op_params.pad_value);
+ const T pad_value_copy = pad_value;
+
+ Pad(op_params, DimsToShape(input_dims), input_data, &pad_value_copy,
+ DimsToShape(output_dims), output_data);
+}
+
+// Old Pad that calls legacy PadV2.
template <typename T>
inline void Pad(const T* input_data, const Dims<4>& input_dims,
const std::vector<int>& left_paddings,
@@ -3428,13 +3680,15 @@ inline void Pad(const T* input_data, const Dims<4>& input_dims,
output_dims, converted_pad_value);
}
+// Old Pad that only padded with 0.
template <typename T>
inline void Pad(const T* input_data, const Dims<4>& input_dims,
const std::vector<int>& left_paddings,
const std::vector<int>& right_paddings, T* output_data,
const Dims<4>& output_dims) {
- Pad(input_data, input_dims, left_paddings, right_paddings, output_data,
- output_dims, 0);
+ const T pad_value = static_cast<T>(0);
+ PadV2<T>(input_data, input_dims, left_paddings, right_paddings, output_data,
+ output_dims, pad_value);
}
template <typename T>
@@ -3491,31 +3745,39 @@ inline void StridedSlice(const T* input_data, const Dims<4>& input_dims,
}
template <typename T>
-inline void Slice(const T* input_data, const Dims<4>& input_dims,
- const std::vector<int>& begin, const std::vector<int>& size,
- T* output_data, const Dims<4>& output_dims) {
- // TODO(dkalenichenko): This op only supports 4D tensors.
- TFLITE_DCHECK_EQ(begin.size(), 4);
- TFLITE_DCHECK_EQ(size.size(), 4);
- const int start_b = begin[3];
- const int stop_b =
- size[3] == -1 ? input_dims.sizes[3] - start_b : start_b + size[3];
- const int start_h = begin[2];
- const int stop_h =
- size[2] == -1 ? input_dims.sizes[2] - start_h : start_h + size[2];
- const int start_w = begin[1];
- const int stop_w =
- size[1] == -1 ? input_dims.sizes[1] - start_w : start_w + size[1];
- const int start_d = begin[0];
- const int stop_d =
- size[0] == -1 ? input_dims.sizes[0] - start_d : start_d + size[0];
+inline void Slice(const tflite::SliceParams& op_params,
+ const RuntimeShape& input_shape, const T* input_data,
+ const RuntimeShape& output_shape, T* output_data) {
+ RuntimeShape ext_shape = RuntimeShape::ExtendedShape(4, input_shape);
+ // TODO(dkalenichenko): This op only supports 4D tensors or smaller.
+ TFLITE_DCHECK_LE(op_params.begin_count, 4);
+ TFLITE_DCHECK_LE(op_params.size_count, 4);
+ const int begin_count = op_params.begin_count;
+ const int size_count = op_params.size_count;
+ // We front-pad the begin and size vectors.
+ const int start_b = 4 - begin_count > 0 ? 0 : op_params.begin[0];
+ const int stop_b = (4 - size_count > 0 || op_params.size[0] == -1)
+ ? ext_shape.Dims(0) - start_b
+ : start_b + op_params.size[0];
+ const int start_h = begin_count < 3 ? 0 : op_params.begin[begin_count - 3];
+ const int stop_h = (size_count < 3 || op_params.size[size_count - 3] == -1)
+ ? ext_shape.Dims(1) - start_h
+ : start_h + op_params.size[size_count - 3];
+ const int start_w = begin_count < 2 ? 0 : op_params.begin[begin_count - 2];
+ const int stop_w = (size_count < 2 || op_params.size[size_count - 2] == -1)
+ ? ext_shape.Dims(2) - start_w
+ : start_w + op_params.size[size_count - 2];
+ const int start_d = begin_count < 1 ? 0 : op_params.begin[begin_count - 1];
+ const int stop_d = (size_count < 1 || op_params.size[size_count - 1] == -1)
+ ? ext_shape.Dims(3) - start_d
+ : start_d + op_params.size[size_count - 1];
T* out_ptr = output_data;
for (int in_b = start_b; in_b < stop_b; ++in_b) {
for (int in_h = start_h; in_h < stop_h; ++in_h) {
for (int in_w = start_w; in_w < stop_w; ++in_w) {
for (int in_d = start_d; in_d < stop_d; ++in_d) {
- *out_ptr++ = input_data[Offset(input_dims, in_d, in_w, in_h, in_b)];
+ *out_ptr++ = input_data[Offset(ext_shape, in_b, in_h, in_w, in_d)];
}
}
}
@@ -3523,6 +3785,22 @@ inline void Slice(const T* input_data, const Dims<4>& input_dims,
}
template <typename T>
+inline void Slice(const T* input_data, const Dims<4>& input_dims,
+ const std::vector<int>& begin, const std::vector<int>& size,
+ T* output_data, const Dims<4>& output_dims) {
+ tflite::SliceParams op_params;
+ op_params.begin_count = 4;
+ op_params.size_count = 4;
+ for (int i = 0; i < 4; ++i) {
+ op_params.begin[i] = begin[3 - i];
+ op_params.size[i] = size[3 - i];
+ }
+
+ Slice(op_params, DimsToShape(input_dims), input_data,
+ DimsToShape(output_dims), output_data);
+}
+
+template <typename T>
inline void Exp(const T* input_data, const size_t num_elements,
T* output_data) {
for (size_t idx = 0; idx < num_elements; ++idx) {
@@ -3790,10 +4068,10 @@ inline void Mean(const T* input_data, const Dims<4>& input_dims,
}
template <typename T>
-void TensorFlowMinimum(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, T* output_data,
- const Dims<4>& output_dims) {
- const int flat_size = MatchingFlatSize(output_dims, input1_dims);
+void Minimum(const RuntimeShape& input1_shape, const T* input1_data,
+ const T* input2_data, const RuntimeShape& output_shape,
+ T* output_data) {
+ const int flat_size = MatchingFlatSize(input1_shape, output_shape);
auto min_value = input2_data[0];
for (int i = 0; i < flat_size; i++) {
@@ -3802,10 +4080,10 @@ void TensorFlowMinimum(const T* input1_data, const Dims<4>& input1_dims,
}
template <typename T>
-void TensorFlowMaximum(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, T* output_data,
- const Dims<4>& output_dims) {
- const int flat_size = MatchingFlatSize(output_dims, input1_dims);
+void Maximum(const RuntimeShape& input1_shape, const T* input1_data,
+ const T* input2_data, const RuntimeShape& output_shape,
+ T* output_data) {
+ const int flat_size = MatchingFlatSize(input1_shape, output_shape);
auto max_value = input2_data[0];
for (int i = 0; i < flat_size; i++) {
@@ -3813,22 +4091,41 @@ void TensorFlowMaximum(const T* input1_data, const Dims<4>& input1_dims,
}
}
+template <typename T>
+void TensorFlowMinimum(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, T* output_data,
+ const Dims<4>& output_dims) {
+ Minimum(DimsToShape(input1_dims), input1_data, input2_data,
+ DimsToShape(output_dims), output_data);
+}
+
+template <typename T>
+void TensorFlowMaximum(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, T* output_data,
+ const Dims<4>& output_dims) {
+ Maximum(DimsToShape(input1_dims), input1_data, input2_data,
+ DimsToShape(output_dims), output_data);
+}
+
template <typename T, typename Op>
-void TensorFlowMaximumMinimum(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, const Dims<4>& input2_dims,
- T* output_data, const Dims<4>& output_dims,
- Op op) {
+void MaximumMinimumBroadcast4DSlow(const RuntimeShape& input1_shape,
+ const T* input1_data,
+ const RuntimeShape& input2_shape,
+ const T* input2_data,
+ const RuntimeShape& output_shape,
+ T* output_data, Op op) {
NdArrayDesc<4> desc1;
NdArrayDesc<4> desc2;
- NdArrayDescsForElementwiseBroadcast(input1_dims, input2_dims, &desc1, &desc2);
+ NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
+ &desc2);
- for (int b = 0; b < ArraySize(output_dims, 3); ++b) {
- for (int y = 0; y < ArraySize(output_dims, 2); ++y) {
- for (int x = 0; x < ArraySize(output_dims, 1); ++x) {
- for (int c = 0; c < ArraySize(output_dims, 0); ++c) {
- auto out_idx = Offset(output_dims, c, x, y, b);
- auto in1_idx = SubscriptToIndex(desc1, c, x, y, b);
- auto in2_idx = SubscriptToIndex(desc2, c, x, y, b);
+ for (int b = 0; b < output_shape.Dims(0); ++b) {
+ for (int y = 0; y < output_shape.Dims(1); ++y) {
+ for (int x = 0; x < output_shape.Dims(2); ++x) {
+ for (int c = 0; c < output_shape.Dims(3); ++c) {
+ auto out_idx = Offset(output_shape, b, y, x, c);
+ auto in1_idx = SubscriptToIndex(desc1, b, y, x, c);
+ auto in2_idx = SubscriptToIndex(desc2, b, y, x, c);
auto in1_val = input1_data[in1_idx];
auto in2_val = input2_data[in2_idx];
output_data[out_idx] = op(in1_val, in2_val);
@@ -3838,9 +4135,20 @@ void TensorFlowMaximumMinimum(const T* input1_data, const Dims<4>& input1_dims,
}
}
+template <typename T, typename Op>
+void TensorFlowMaximumMinimum(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, const Dims<4>& input2_dims,
+ T* output_data, const Dims<4>& output_dims,
+ Op op) {
+ MaximumMinimumBroadcast4DSlow(DimsToShape(input1_dims), input1_data,
+ DimsToShape(input2_dims), input2_data,
+ DimsToShape(output_dims), output_data, op);
+}
+
template <typename T1, typename T2, typename T3, typename Cmp>
-void ArgMinMax(const T3* axis, const T1* input_data, const Dims<4>& input_dims,
- T2* output_data, const Dims<4>& output_dims, const Cmp& cmp) {
+void ArgMinMax(const T3* axis, const RuntimeShape& input_shape,
+ const T1* input_data, const RuntimeShape& output_shape,
+ T2* output_data, const Cmp& cmp) {
// The current ArgMax implemention can only determine the index of the maximum
// value in the last dimension. So the axis argument is ignored.
@@ -3848,9 +4156,11 @@ void ArgMinMax(const T3* axis, const T1* input_data, const Dims<4>& input_dims,
// 1). For the sake of simplicity, the output dimensions are equal to the
// input dimensions here. We enforce the constraint that the last dimension
// must always be 1.
- TFLITE_DCHECK_EQ(ArraySize(output_dims, 0), 1);
- const int outer_size = MatchingFlatSizeSkipDim(input_dims, 0, output_dims);
- const int depth = ArraySize(input_dims, 0);
+ TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
+ TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
+ TFLITE_DCHECK_EQ(output_shape.Dims(3), 1);
+ const int outer_size = MatchingFlatSizeSkipDim(input_shape, 3, output_shape);
+ const int depth = input_shape.Dims(3);
for (int i = 0; i < outer_size; ++i) {
auto min_max_value = input_data[i * depth];
@@ -3866,6 +4176,15 @@ void ArgMinMax(const T3* axis, const T1* input_data, const Dims<4>& input_dims,
}
}
+// Legacy Dims<4> version.
+template <typename T1, typename T2, typename T3, typename Cmp>
+void ArgMinMax(const T3* axis, const T1* input_data, const Dims<4>& input_dims,
+ T2* output_data, const Dims<4>& output_dims, const Cmp& cmp) {
+ ArgMinMax(axis, DimsToShape(input_dims), input_data, DimsToShape(output_dims),
+ output_data, cmp);
+}
+
+// Legacy.
// TODO(renjieliu): Remove this one.
template <typename T1, typename T2, typename T3>
void ArgMax(const T3* axis, const T1* input_data,
@@ -3998,16 +4317,26 @@ template <typename T>
using ComparisonFn = bool (*)(T, T);
template <typename T, ComparisonFn<T> F>
-inline void Comparison(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, const Dims<4>& input2_dims,
- bool* output_data, const Dims<4>& output_dims) {
+inline void Comparison(const RuntimeShape& input1_shape, const T* input1_data,
+ const RuntimeShape& input2_shape, const T* input2_data,
+ const RuntimeShape& output_shape, bool* output_data) {
const int64_t flatsize =
- MatchingFlatSize(input1_dims, input2_dims, output_dims);
+ MatchingFlatSize(input1_shape, input2_shape, output_shape);
for (int64_t i = 0; i < flatsize; ++i) {
output_data[i] = F(input1_data[i], input2_data[i]);
}
}
+// Legacy Dims<4> version.
+template <typename T, ComparisonFn<T> F>
+inline void Comparison(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, const Dims<4>& input2_dims,
+ bool* output_data, const Dims<4>& output_dims) {
+ Comparison<T, F>(DimsToShape(input1_dims), input1_data,
+ DimsToShape(input2_dims), input2_data,
+ DimsToShape(output_dims), output_data);
+}
+
template <typename T, ComparisonFn<int32> F>
inline void Comparison(int left_shift, const T* input1_data,
const Dims<4>& input1_dims, int32 input1_offset,
@@ -4218,69 +4547,156 @@ inline void SparseToDense(const std::vector<std::vector<TI>>& indices,
}
template <typename T>
-inline void Pow(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, const Dims<4>& input2_dims,
- T* output_data, const Dims<4>& output_dims) {
- const int flat_size = MatchingFlatSize(input1_dims, input2_dims, output_dims);
+inline void Pow(const RuntimeShape& input1_shape, const T* input1_data,
+ const RuntimeShape& input2_shape, const T* input2_data,
+ const RuntimeShape& output_shape, T* output_data) {
+ const int flat_size =
+ MatchingFlatSize(input1_shape, input2_shape, output_shape);
for (int i = 0; i < flat_size; ++i) {
output_data[i] = std::pow(input1_data[i], input2_data[i]);
}
}
+// Legacy Dims<4> version.
template <typename T>
-inline void BroadcastPow(const T* input1_data, const Dims<4>& input1_dims,
- const T* input2_data, const Dims<4>& input2_dims,
- T* output_data, const Dims<4>& output_dims) {
+inline void Pow(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, const Dims<4>& input2_dims,
+ T* output_data, const Dims<4>& output_dims) {
+ Pow(DimsToShape(input1_dims), input1_data, DimsToShape(input2_dims),
+ input2_data, DimsToShape(output_dims), output_data);
+}
+
+template <typename T>
+inline void BroadcastPow4DSlow(const RuntimeShape& input1_shape,
+ const T* input1_data,
+ const RuntimeShape& input2_shape,
+ const T* input2_data,
+ const RuntimeShape& output_shape,
+ T* output_data) {
NdArrayDesc<4> desc1;
NdArrayDesc<4> desc2;
- NdArrayDescsForElementwiseBroadcast(input1_dims, input2_dims, &desc1, &desc2);
- for (int b = 0; b < ArraySize(output_dims, 3); ++b) {
- for (int y = 0; y < ArraySize(output_dims, 2); ++y) {
- for (int x = 0; x < ArraySize(output_dims, 1); ++x) {
- for (int c = 0; c < ArraySize(output_dims, 0); ++c) {
- output_data[Offset(output_dims, c, x, y, b)] =
- std::pow(input1_data[SubscriptToIndex(desc1, c, x, y, b)],
- input2_data[SubscriptToIndex(desc2, c, x, y, b)]);
+ NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
+ &desc2);
+
+ for (int b = 0; b < output_shape.Dims(0); ++b) {
+ for (int y = 0; y < output_shape.Dims(1); ++y) {
+ for (int x = 0; x < output_shape.Dims(2); ++x) {
+ for (int c = 0; c < output_shape.Dims(3); ++c) {
+ auto out_idx = Offset(output_shape, b, y, x, c);
+ auto in1_idx = SubscriptToIndex(desc1, b, y, x, c);
+ auto in2_idx = SubscriptToIndex(desc2, b, y, x, c);
+ auto in1_val = input1_data[in1_idx];
+ auto in2_val = input2_data[in2_idx];
+ output_data[out_idx] = std::pow(in1_val, in2_val);
}
}
}
}
}
+// Legacy Dims<4> version.
+template <typename T>
+inline void BroadcastPow(const T* input1_data, const Dims<4>& input1_dims,
+ const T* input2_data, const Dims<4>& input2_dims,
+ T* output_data, const Dims<4>& output_dims) {
+ BroadcastPow4DSlow(DimsToShape(input1_dims), input1_data,
+ DimsToShape(input2_dims), input2_data,
+ DimsToShape(output_dims), output_data);
+}
+
+inline void Logical(const RuntimeShape& input1_shape, const bool* input1_data,
+ const RuntimeShape& input2_shape, const bool* input2_data,
+ const RuntimeShape& output_shape, bool* output_data,
+ const std::function<bool(bool, bool)>& func) {
+ const int flat_size =
+ MatchingFlatSize(input1_shape, input2_shape, output_shape);
+ for (int i = 0; i < flat_size; ++i) {
+ output_data[i] = func(input1_data[i], input2_data[i]);
+ }
+}
+
+// Legacy Dims<4> version.
inline void Logical(const bool* input1_data, const Dims<4>& input1_dims,
const bool* input2_data, const Dims<4>& input2_dims,
bool* output_data, const Dims<4>& output_dims,
const std::function<bool(bool, bool)>& func) {
- const int flat_size = MatchingFlatSize(input1_dims, input2_dims, output_dims);
- for (int i = 0; i < flat_size; ++i) {
- output_data[i] = func(input1_data[i], input2_data[i]);
+ Logical(DimsToShape(input1_dims), input1_data, DimsToShape(input2_dims),
+ input2_data, DimsToShape(output_dims), output_data, func);
+}
+
+inline void BroadcastLogical4DSlow(
+ const RuntimeShape& input1_shape, const bool* input1_data,
+ const RuntimeShape& input2_shape, const bool* input2_data,
+ const RuntimeShape& output_shape, bool* output_data,
+ const std::function<bool(bool, bool)>& func) {
+ NdArrayDesc<4> desc1;
+ NdArrayDesc<4> desc2;
+ NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
+ &desc2);
+
+ for (int b = 0; b < output_shape.Dims(0); ++b) {
+ for (int y = 0; y < output_shape.Dims(1); ++y) {
+ for (int x = 0; x < output_shape.Dims(2); ++x) {
+ for (int c = 0; c < output_shape.Dims(3); ++c) {
+ auto out_idx = Offset(output_shape, b, y, x, c);
+ auto in1_idx = SubscriptToIndex(desc1, b, y, x, c);
+ auto in2_idx = SubscriptToIndex(desc2, b, y, x, c);
+ auto in1_val = input1_data[in1_idx];
+ auto in2_val = input2_data[in2_idx];
+ output_data[out_idx] = func(in1_val, in2_val);
+ }
+ }
+ }
}
}
+// Legacy Dims<4> version.
inline void BroadcastLogical(const bool* input1_data,
const Dims<4>& input1_dims,
const bool* input2_data,
const Dims<4>& input2_dims, bool* output_data,
const Dims<4>& output_dims,
const std::function<bool(bool, bool)>& func) {
+ BroadcastLogical4DSlow(DimsToShape(input1_dims), input1_data,
+ DimsToShape(input2_dims), input2_data,
+ DimsToShape(output_dims), output_data, func);
+}
+
+// TODO(ycling): Refactoring. Remove BroadcastLogical and use the more
+// generalized and efficient BroadcastBinaryFunction.
+//
+// Also appears to duplicte MinimumMaximum.
+//
+// R: Result type. T1: Input 1 type. T2: Input 2 type.
+template <typename R, typename T1, typename T2>
+inline void BroadcastBinaryFunction4DSlow(const RuntimeShape& input1_shape,
+ const T1* input1_data,
+ const RuntimeShape& input2_shape,
+ const T2* input2_data,
+ const RuntimeShape& output_shape,
+ R* output_data, R (*func)(T1, T2)) {
NdArrayDesc<4> desc1;
NdArrayDesc<4> desc2;
- NdArrayDescsForElementwiseBroadcast(input1_dims, input2_dims, &desc1, &desc2);
- for (int b = 0; b < ArraySize(output_dims, 3); ++b) {
- for (int y = 0; y < ArraySize(output_dims, 2); ++y) {
- for (int x = 0; x < ArraySize(output_dims, 1); ++x) {
- for (int c = 0; c < ArraySize(output_dims, 0); ++c) {
- output_data[Offset(output_dims, c, x, y, b)] =
- func(input1_data[SubscriptToIndex(desc1, c, x, y, b)],
- input2_data[SubscriptToIndex(desc2, c, x, y, b)]);
+ NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
+ &desc2);
+
+ for (int b = 0; b < output_shape.Dims(0); ++b) {
+ for (int y = 0; y < output_shape.Dims(1); ++y) {
+ for (int x = 0; x < output_shape.Dims(2); ++x) {
+ for (int c = 0; c < output_shape.Dims(3); ++c) {
+ auto out_idx = Offset(output_shape, b, y, x, c);
+ auto in1_idx = SubscriptToIndex(desc1, b, y, x, c);
+ auto in2_idx = SubscriptToIndex(desc2, b, y, x, c);
+ auto in1_val = input1_data[in1_idx];
+ auto in2_val = input2_data[in2_idx];
+ output_data[out_idx] = func(in1_val, in2_val);
}
}
}
}
}
-// TODO(ycling): Refactoring. Remove BroadcastLogical and use the more
-// generalized and efficient BroadcastBinaryFunction.
+// Legacy Dims<4> version.
//
// R: Result type. T1: Input 1 type. T2: Input 2 type.
template <typename R, typename T1, typename T2>
@@ -4290,20 +4706,9 @@ inline void BroadcastBinaryFunction(const T1* input1_data,
const Dims<4>& input2_dims, R* output_data,
const Dims<4>& output_dims,
R (*func)(T1, T2)) {
- NdArrayDesc<4> desc1;
- NdArrayDesc<4> desc2;
- NdArrayDescsForElementwiseBroadcast(input1_dims, input2_dims, &desc1, &desc2);
- for (int b = 0; b < ArraySize(output_dims, 3); ++b) {
- for (int y = 0; y < ArraySize(output_dims, 2); ++y) {
- for (int x = 0; x < ArraySize(output_dims, 1); ++x) {
- for (int c = 0; c < ArraySize(output_dims, 0); ++c) {
- output_data[Offset(output_dims, c, x, y, b)] =
- func(input1_data[SubscriptToIndex(desc1, c, x, y, b)],
- input2_data[SubscriptToIndex(desc2, c, x, y, b)]);
- }
- }
- }
- }
+ BroadcastBinaryFunction4DSlow(DimsToShape(input1_dims), input1_data,
+ DimsToShape(input2_dims), input2_data,
+ DimsToShape(output_dims), output_data, func);
}
} // namespace reference_ops
diff --git a/tensorflow/contrib/lite/kernels/internal/softmax_quantized_test.cc b/tensorflow/contrib/lite/kernels/internal/softmax_quantized_test.cc
index a7dad3c14e..ca94e7740e 100644
--- a/tensorflow/contrib/lite/kernels/internal/softmax_quantized_test.cc
+++ b/tensorflow/contrib/lite/kernels/internal/softmax_quantized_test.cc
@@ -27,6 +27,7 @@ limitations under the License.
#include "tensorflow/contrib/lite/kernels/internal/quantization_util.h"
#include "tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/contrib/lite/kernels/internal/test_util.h"
+#include "tensorflow/contrib/lite/string.h"
namespace tflite {
namespace {
diff --git a/tensorflow/contrib/lite/kernels/internal/tensor_utils_test.cc b/tensorflow/contrib/lite/kernels/internal/tensor_utils_test.cc
index 372a6efec5..e8343f1223 100644
--- a/tensorflow/contrib/lite/kernels/internal/tensor_utils_test.cc
+++ b/tensorflow/contrib/lite/kernels/internal/tensor_utils_test.cc
@@ -72,7 +72,7 @@ TEST(uKernels, SymmetricQuantizeFloatsTest) {
static float input[kVectorSize] = {-640, -635.0, -630, 10.0, 2.0,
-5.0, -10.0, 0.0, 1000.0};
- int8 output[kVectorSize];
+ int8_t output[kVectorSize];
float min, max, scaling_factor;
SymmetricQuantizeFloats(input, kVectorSize, output, &min, &max,
&scaling_factor);
@@ -89,7 +89,7 @@ TEST(uKernels, SymmetricQuantizeFloatsAllZerosTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- int8 output[kVectorSize];
+ int8_t output[kVectorSize];
float min, max, scaling_factor;
SymmetricQuantizeFloats(input, kVectorSize, output, &min, &max,
&scaling_factor);
@@ -105,7 +105,7 @@ TEST(uKernels, SymmetricQuantizeFloatsAllAlmostZeroTest) {
static float input[kVectorSize] = {-1e-5, 3e-5, -7e-6, -9e-5, 1e-6,
4e-5, 9e-6, 2e-4, 0};
- int8 output[kVectorSize];
+ int8_t output[kVectorSize];
float min, max, scaling_factor;
SymmetricQuantizeFloats(input, kVectorSize, output, &min, &max,
&scaling_factor);
@@ -143,6 +143,7 @@ TEST(uKernels, MatrixBatchVectorMultiplyAccumulateTest) {
-1., 3., 7., 3., 23., 3.})));
}
+#ifdef __ANDROID__
TEST(uKernels, MatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
// Note we use 29 columns as this exercises all the neon kernel: the
// 16-block SIMD code, the 8-block postamble, and the leftover postamble.
@@ -166,13 +167,13 @@ TEST(uKernels, MatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
-13.13, 14.14, -15.15, 16.16, -17.17, 18.18, -19.19, 20.2, -21.21, 22.22,
-23.23, 24.24, -25.25, 26.26, -27.27, 28.28, 0};
- int8* a_int8_data = reinterpret_cast<int8*>(
+ int8_t* a_int8_data = reinterpret_cast<int8_t*>(
aligned_malloc(a_rows * a_cols, kWeightsPerUint32));
float a_min, a_max;
float scaling_factor_a;
SymmetricQuantizeFloats(a_float_data, a_rows * a_cols, a_int8_data, &a_min,
&a_max, &scaling_factor_a);
- const int8 expected_a_int8_data[] = {
+ const int8_t expected_a_int8_data[] = {
/* 1st row */
5,
10,
@@ -363,7 +364,7 @@ TEST(uKernels, MatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
};
// Quantized values of B:
- int8 b_int8_data[b_rows * b_cols * batches];
+ int8_t b_int8_data[b_rows * b_cols * batches];
float b_min, b_max;
float scaling_factor_b[batches];
SymmetricQuantizeFloats(b_float_data, b_rows * b_cols, b_int8_data, &b_min,
@@ -372,7 +373,7 @@ TEST(uKernels, MatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
&b_int8_data[b_rows * b_cols], &b_min, &b_max,
&scaling_factor_b[1]);
- const int8 expected_b_int8_data[] = {
+ const int8_t expected_b_int8_data[] = {
/* batch 1 */
127,
-127,
@@ -465,6 +466,7 @@ TEST(uKernels, MatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
aligned_free(a_int8_data);
}
+#endif // __ANDROID__
TEST(uKernels, VectorVectorCwiseProductTest) {
constexpr int kVectorSize = 10;
diff --git a/tensorflow/contrib/lite/kernels/internal/types.h b/tensorflow/contrib/lite/kernels/internal/types.h
index c44698b677..204df9ab19 100644
--- a/tensorflow/contrib/lite/kernels/internal/types.h
+++ b/tensorflow/contrib/lite/kernels/internal/types.h
@@ -129,6 +129,13 @@ class RuntimeShape {
}
}
+ RuntimeShape(int shape_size, int32 value) : size_(0) {
+ Resize(shape_size);
+ for (int i = 0; i < shape_size; ++i) {
+ SetDim(i, value);
+ }
+ }
+
RuntimeShape(int dimensions_count, const int32* dims_data) : size_(0) {
ReplaceWith(dimensions_count, dims_data);
}
@@ -237,7 +244,7 @@ class RuntimeShape {
bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); }
private:
- // For use only by ExtendFrom(), written to guarantee (return-value) copy
+ // For use only by ExtendedShape(), written to guarantee (return-value) copy
// elision in C++17.
// This creates a shape padded to the desired size with the specified value.
RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value)
@@ -645,22 +652,6 @@ void ComputeStrides(Dims<N>* dims) {
}
}
-struct PoolParams {
- FusedActivationFunctionType activation;
- PaddingType padding_type;
- PaddingValues padding_values;
- int stride_height;
- int stride_width;
- int filter_height;
- int filter_width;
- // uint8, etc, activation params.
- int32 quantized_activation_min;
- int32 quantized_activation_max;
- // float activation params.
- float float_activation_min;
- float float_activation_max;
-};
-
enum class BroadcastableOpCategory : uint8 {
kNone,
kNonBroadcast, // Matching input shapes.
@@ -669,6 +660,19 @@ enum class BroadcastableOpCategory : uint8 {
kGenericBroadcast, // Fall-back.
};
+struct MinMax {
+ float min;
+ float max;
+};
+static_assert(sizeof(MinMax) == 8, "");
+
+struct ActivationParams {
+ FusedActivationFunctionType activation_type;
+ // Quantized inference params.
+ int32 activation_min;
+ int32 activation_max;
+};
+
// For Add, Sub, Mul ops.
struct ArithmeticParams {
// Shape dependent / common to data / op types.
@@ -704,6 +708,206 @@ struct ArithmeticParams {
int broadcast_shape[5];
};
+struct ConcatenationParams {
+ int8 axis;
+};
+
+struct ComparisonParams {
+ // uint8 inference params.
+ int left_shift;
+ int32 input0_offset;
+ int32 input0_multiplier;
+ int input0_shift;
+ int32 input1_offset;
+ int32 input1_multiplier;
+ int input1_shift;
+ // Shape dependent / common to inference types.
+ bool is_broadcast;
+};
+
+struct ConvParams {
+ PaddingType padding_type;
+ PaddingValues padding_values;
+ // TODO(starka): This was just "stride", so check that width+height is OK.
+ int8 stride_width;
+ int8 stride_height;
+ int8 dilation_width_factor;
+ int8 dilation_height_factor;
+ // uint8 inference params.
+ // TODO(b/65838351): Use smaller types if appropriate.
+ int32 input_offset;
+ int32 weights_offset;
+ int32 output_offset;
+ int32 output_multiplier;
+ int output_shift;
+ int32 output_activation_min;
+ int32 output_activation_max;
+};
+
+struct DepthToSpaceParams {
+ int16 block_size;
+};
+
+struct DepthwiseParams {
+ PaddingType padding_type;
+ PaddingValues padding_values;
+ int8 stride;
+ int8 depth_multiplier;
+ // uint8 inference params.
+ // TODO(b/65838351): Use smaller types if appropriate.
+ int32 input_offset;
+ int32 weights_offset;
+ int32 output_offset;
+ int32 output_multiplier;
+ int output_shift;
+ int32 output_activation_min;
+ int32 output_activation_max;
+};
+
+struct FakeQuantParams {
+ MinMax minmax;
+ int32 num_bits;
+};
+
+struct FullyConnectedParams {
+ // uint8 inference params.
+ // TODO(b/65838351): Use smaller types if appropriate.
+ int32 input_offset;
+ int32 weights_offset;
+ int32 output_offset;
+ int32 output_multiplier;
+ int output_shift;
+ int32 output_activation_min;
+ int32 output_activation_max;
+ FullyConnectedWeightsFormat weights_format;
+};
+
+struct GatherParams {
+ int8 input_rank;
+ int16 axis;
+};
+
+struct L2NormalizationParams {
+ // uint8 inference params.
+ int32 input_zero_point;
+};
+
+struct LocalResponseNormalizationParams {
+ int32 range;
+ double bias;
+ double alpha;
+ double beta;
+};
+
+struct LogisticParams {
+ // uint8 inference params.
+ int32 input_zero_point;
+ int32 input_range_radius;
+ int32 input_multiplier;
+ int input_left_shift;
+};
+
+struct LstmCellParams {
+ int32 weights_zero_point;
+ int32 accum_multiplier;
+ int accum_shift;
+ int state_integer_bits;
+};
+
+struct MeanParams {
+ int8 axis_count;
+ int16 axis[4];
+};
+
+struct PadParams {
+ int8 left_padding_count;
+ int32 left_padding[4];
+ int8 right_padding_count;
+ int32 right_padding[4];
+};
+
+struct PoolParams {
+ FusedActivationFunctionType activation;
+ PaddingType padding_type;
+ PaddingValues padding_values;
+ int stride_height;
+ int stride_width;
+ int filter_height;
+ int filter_width;
+ // uint8, etc, activation params.
+ int32 quantized_activation_min;
+ int32 quantized_activation_max;
+ // float activation params.
+ float float_activation_min;
+ float float_activation_max;
+};
+
+struct ReshapeParams {
+ int8 shape_count;
+ int32 shape[4];
+};
+
+struct ResizeBilinearParams {
+ bool align_corners;
+};
+
+struct SliceParams {
+ int8 begin_count;
+ int32 begin[4];
+ int8 size_count;
+ int32 size[4];
+};
+
+struct SoftmaxParams {
+ // beta is not really used (not a Tensorflow parameter) and not implemented
+ // for LogSoftmax.
+ double beta;
+ // uint8 inference params. Used even when beta defaults to 1.0.
+ int32 input_beta_multiplier;
+ int32 input_beta_left_shift;
+ // Reverse scaling is only used by LogSoftmax.
+ int32 reverse_scaling_divisor;
+ int32 reverse_scaling_right_shift;
+ int diff_min;
+};
+
+struct SpaceToDepthParams {
+ int16 block_size;
+};
+
+struct SplitParams {
+ // Graphs that split into, say, 2000 nodes are encountered. The indices in
+ // OperatorEdges are of type uint16.
+ uint16 num_split;
+};
+
+struct SqueezeParams {
+ int8 squeeze_dims_count;
+ int32 squeeze_dims[4];
+};
+
+struct StridedSliceParams {
+ int8 start_indices_count;
+ int16 start_indices[4];
+ int8 stop_indices_count;
+ int16 stop_indices[4];
+ int8 strides_count;
+ int16 strides[4];
+
+ int16 begin_mask;
+ int16 ellipsis_mask;
+ int16 end_mask;
+ int16 new_axis_mask;
+ int16 shrink_axis_mask;
+};
+
+struct TanhParams {
+ int32 input_zero_point;
+ int32 input_range_radius;
+ int32 input_multiplier;
+ int input_left_shift;
+};
+
template <typename T>
inline void SetActivationParams(T min, T max, ArithmeticParams* params);
diff --git a/tensorflow/contrib/lite/kernels/mul.cc b/tensorflow/contrib/lite/kernels/mul.cc
index 349f3e6726..561e39cfc6 100644
--- a/tensorflow/contrib/lite/kernels/mul.cc
+++ b/tensorflow/contrib/lite/kernels/mul.cc
@@ -93,7 +93,6 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
input1->params.scale * input2->params.scale / output->params.scale;
QuantizeMultiplierSmallerThanOneExp(
real_multiplier, &data->output_multiplier, &data->output_shift);
- data->output_shift *= -1;
}
return context->ResizeTensor(context, output, output_size);
@@ -161,9 +160,9 @@ TfLiteStatus EvalQuantized(TfLiteContext* context, TfLiteNode* node,
// The quantized version of Mul doesn't support activations, so we
// always use BroadcastMul.
if (kernel_type == kReference) {
- TF_LITE_MUL(reference_ops, BroadcastMul);
+ TF_LITE_MUL(reference_ops, BroadcastMul4DSlow);
} else {
- TF_LITE_MUL(optimized_ops, BroadcastMul);
+ TF_LITE_MUL(optimized_ops, BroadcastMul4DSlow);
}
#undef TF_LITE_MUL
} else if (input1->type == kTfLiteInt16 && input2->type == kTfLiteInt16 &&
diff --git a/tensorflow/contrib/lite/kernels/pack.cc b/tensorflow/contrib/lite/kernels/pack.cc
index bb3416f6a6..cc326a7d51 100644
--- a/tensorflow/contrib/lite/kernels/pack.cc
+++ b/tensorflow/contrib/lite/kernels/pack.cc
@@ -27,24 +27,9 @@ namespace {
constexpr int kOutputTensor = 0;
-// Op data for pack op.
-struct OpData {
- int values_count;
- int axis;
-};
-
-void* Init(TfLiteContext* context, const char* buffer, size_t length) {
- auto* data = new OpData;
- data->axis = 0;
- return data;
-}
-
-void Free(TfLiteContext* context, void* buffer) {
- delete reinterpret_cast<OpData*>(buffer);
-}
-
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
- const OpData* data = reinterpret_cast<OpData*>(node->builtin_data);
+ const TfLitePackParams* data =
+ reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), data->values_count);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
@@ -54,9 +39,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE(context, NumDimensions(input0) >= data->axis);
// TODO(renjieliu): Support negative axis.
TF_LITE_ENSURE(context, data->axis >= 0);
- if (input0->type != kTfLiteInt32 && input0->type != kTfLiteFloat32) {
+ if (input0->type != kTfLiteInt32 && input0->type != kTfLiteFloat32 &&
+ input0->type != kTfLiteUInt8 && input0->type != kTfLiteInt16) {
context->ReportError(context,
- "Currently pack only supports int32 and float32.");
+ "Currently pack only supports "
+ "float32/uint8/int16/int32.");
return kTfLiteError;
}
// Make sure all inputs have the same shape and type.
@@ -82,6 +69,15 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, output->type, input0->type);
+ // Guarantee input/output quantization params match as we do not support
+ // packing quantized tensors.
+ for (int i = 0; i < data->values_count; i++) {
+ const TfLiteTensor* input = GetInput(context, node, i);
+ TF_LITE_ENSURE_EQ(context, input->params.zero_point,
+ output->params.zero_point);
+ TF_LITE_ENSURE_EQ(context, input->params.scale, output->params.scale);
+ }
+
return context->ResizeTensor(context, output, output_shape);
}
@@ -95,7 +91,8 @@ void PackImpl(TfLiteContext* context, TfLiteNode* node, TfLiteTensor* output,
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
- const OpData* data = reinterpret_cast<OpData*>(node->builtin_data);
+ const TfLitePackParams* data =
+ reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
@@ -103,13 +100,18 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
PackImpl<float>(context, node, output, data->values_count, data->axis);
break;
}
+ case kTfLiteUInt8: {
+ PackImpl<uint8_t>(context, node, output, data->values_count, data->axis);
+ break;
+ }
case kTfLiteInt32: {
PackImpl<int32_t>(context, node, output, data->values_count, data->axis);
break;
}
default: {
context->ReportError(context,
- "Currently pack only supports int32 and float32.");
+ "Currently pack only supports "
+ "float32/uint8/int32.");
return kTfLiteError;
}
}
@@ -121,8 +123,7 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
} // namespace pack
TfLiteRegistration* Register_PACK() {
- static TfLiteRegistration r = {pack::Init, pack::Free, pack::Prepare,
- pack::Eval};
+ static TfLiteRegistration r = {nullptr, nullptr, pack::Prepare, pack::Eval};
return &r;
}
diff --git a/tensorflow/contrib/lite/kernels/pack_test.cc b/tensorflow/contrib/lite/kernels/pack_test.cc
index 485a50ad3a..c70dbd2764 100644
--- a/tensorflow/contrib/lite/kernels/pack_test.cc
+++ b/tensorflow/contrib/lite/kernels/pack_test.cc
@@ -51,6 +51,7 @@ class PackOpModel : public SingleOpModel {
int output_;
};
+// float32 tests.
TEST(PackOpTest, FloatThreeInputs) {
PackOpModel<float> model({TensorType_FLOAT32, {2}}, 0, 3);
model.SetInput(0, {1, 4});
@@ -81,7 +82,8 @@ TEST(PackOpTest, FloatMultilDimensions) {
ElementsAreArray({1, 2, 3, 7, 8, 9, 4, 5, 6, 10, 11, 12}));
}
-TEST(PackOpTest, IntThreeInputs) {
+// int32 tests.
+TEST(PackOpTest, Int32ThreeInputs) {
PackOpModel<int32_t> model({TensorType_INT32, {2}}, 0, 3);
model.SetInput(0, {1, 4});
model.SetInput(1, {2, 5});
@@ -91,7 +93,7 @@ TEST(PackOpTest, IntThreeInputs) {
EXPECT_THAT(model.GetOutput(), ElementsAreArray({1, 4, 2, 5, 3, 6}));
}
-TEST(PackOpTest, IntThreeInputsDifferentAxis) {
+TEST(PackOpTest, Int32ThreeInputsDifferentAxis) {
PackOpModel<int32_t> model({TensorType_INT32, {2}}, 1, 3);
model.SetInput(0, {1, 4});
model.SetInput(1, {2, 5});
@@ -101,7 +103,7 @@ TEST(PackOpTest, IntThreeInputsDifferentAxis) {
EXPECT_THAT(model.GetOutput(), ElementsAreArray({1, 2, 3, 4, 5, 6}));
}
-TEST(PackOpTest, IntMultilDimensions) {
+TEST(PackOpTest, Int32MultilDimensions) {
PackOpModel<int32_t> model({TensorType_INT32, {2, 3}}, 1, 2);
model.SetInput(0, {1, 2, 3, 4, 5, 6});
model.SetInput(1, {7, 8, 9, 10, 11, 12});
@@ -110,6 +112,38 @@ TEST(PackOpTest, IntMultilDimensions) {
EXPECT_THAT(model.GetOutput(),
ElementsAreArray({1, 2, 3, 7, 8, 9, 4, 5, 6, 10, 11, 12}));
}
+
+// uint8
+TEST(PackOpTest, Uint8ThreeInputs) {
+ PackOpModel<uint8_t> model({TensorType_UINT8, {2}}, 0, 3);
+ model.SetInput(0, {1, 4});
+ model.SetInput(1, {2, 5});
+ model.SetInput(2, {3, 6});
+ model.Invoke();
+ EXPECT_THAT(model.GetOutputShape(), ElementsAre(3, 2));
+ EXPECT_THAT(model.GetOutput(), ElementsAreArray({1, 4, 2, 5, 3, 6}));
+}
+
+TEST(PackOpTest, Uint8ThreeInputsDifferentAxis) {
+ PackOpModel<uint8_t> model({TensorType_UINT8, {2}}, 1, 3);
+ model.SetInput(0, {1, 4});
+ model.SetInput(1, {2, 5});
+ model.SetInput(2, {3, 6});
+ model.Invoke();
+ EXPECT_THAT(model.GetOutputShape(), ElementsAre(2, 3));
+ EXPECT_THAT(model.GetOutput(), ElementsAreArray({1, 2, 3, 4, 5, 6}));
+}
+
+TEST(PackOpTest, Uint8MultilDimensions) {
+ PackOpModel<uint8_t> model({TensorType_UINT8, {2, 3}}, 1, 2);
+ model.SetInput(0, {1, 2, 3, 4, 5, 6});
+ model.SetInput(1, {7, 8, 9, 10, 11, 12});
+ model.Invoke();
+ EXPECT_THAT(model.GetOutputShape(), ElementsAre(2, 2, 3));
+ EXPECT_THAT(model.GetOutput(),
+ ElementsAreArray({1, 2, 3, 7, 8, 9, 4, 5, 6, 10, 11, 12}));
+}
+
} // namespace
} // namespace tflite
diff --git a/tensorflow/contrib/lite/kernels/register.cc b/tensorflow/contrib/lite/kernels/register.cc
index 8d2c108116..9681b900b7 100644
--- a/tensorflow/contrib/lite/kernels/register.cc
+++ b/tensorflow/contrib/lite/kernels/register.cc
@@ -14,6 +14,7 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/lite/kernels/register.h"
+#include "tensorflow/contrib/lite/util.h"
namespace tflite {
namespace ops {
@@ -127,9 +128,9 @@ const TfLiteRegistration* BuiltinOpResolver::FindOp(tflite::BuiltinOperator op,
const TfLiteRegistration* BuiltinOpResolver::FindOp(const char* op,
int version) const {
- // Return the NULL Op for all ops whose name start with "Eager:", allowing
+ // Return the NULL Op for all ops whose name start with "Eager", allowing
// the interpreter to delegate their execution.
- if (string(op).find("Eager:") == 0) {
+ if (IsEagerOp(op)) {
static TfLiteRegistration null_op{
nullptr, nullptr, &UnsupportedTensorFlowOp,
nullptr, nullptr, BuiltinOperator_CUSTOM,
diff --git a/tensorflow/contrib/lite/model.cc b/tensorflow/contrib/lite/model.cc
index 9edf5ba38f..7b9413cd17 100644
--- a/tensorflow/contrib/lite/model.cc
+++ b/tensorflow/contrib/lite/model.cc
@@ -26,6 +26,9 @@ limitations under the License.
#ifndef TFLITE_MCU
#include "tensorflow/contrib/lite/nnapi_delegate.h"
#endif
+#if defined(TFLITE_EXTENDED)
+#include "tensorflow/contrib/lite/delegates/eager/delegate.h"
+#endif
#include "tensorflow/contrib/lite/version.h"
namespace tflite {
@@ -1040,6 +1043,14 @@ TfLiteStatus InterpreterBuilder::operator()(
}
(**interpreter).SetVariables(std::move(variables));
+#if defined(TFLITE_EXTENDED)
+ if (auto delegate = EagerDelegate::Create()) {
+ (**interpreter)
+ .ModifyGraphWithDelegate(std::move(delegate),
+ /*allow_dynamic_tensors=*/true);
+ }
+#endif
+
return kTfLiteOk;
}
diff --git a/tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h b/tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h
index becd1f615f..42b8163445 100644
--- a/tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h
+++ b/tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h
@@ -44,6 +44,19 @@ inline void* loadLibrary(const char* name) {
return handle;
}
+typedef int (*ASharedMemory_create_fn)(const char* name, size_t size);
+
+// ASharedMemory_create was added in Android 8.0, so safe to use with NNAPI
+// which was added in 8.1.
+inline int ASharedMemory_create(const char* name, size_t size) {
+ static void* handle = loadLibrary("libandroid.so");
+ static ASharedMemory_create_fn fn =
+ handle != nullptr ? reinterpret_cast<ASharedMemory_create_fn>(
+ dlsym(handle, "ASharedMemory_create"))
+ : nullptr;
+ return fn(name, size);
+}
+
inline void* getLibraryHandle() {
static void* handle = loadLibrary("libneuralnetworks.so");
return handle;
diff --git a/tensorflow/contrib/lite/nnapi_delegate.cc b/tensorflow/contrib/lite/nnapi_delegate.cc
index 13325a8c7c..45c92a8671 100644
--- a/tensorflow/contrib/lite/nnapi_delegate.cc
+++ b/tensorflow/contrib/lite/nnapi_delegate.cc
@@ -24,20 +24,27 @@ limitations under the License.
#include "tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h"
#ifdef __ANDROID__
+#include <android/log.h>
#include <sys/system_properties.h>
#endif
namespace tflite {
void logError(const char* format, ...) {
- // TODO(mikie): use android logging, stderr is not captured for Java
- // applications
- va_list args;
- va_start(args, format);
- vfprintf(stderr, format, args);
- va_end(args);
+ // stderr is convenient for native tests, but is not captured for apps
+ va_list args_for_stderr;
+ va_start(args_for_stderr, format);
+ vfprintf(stderr, format, args_for_stderr);
+ va_end(args_for_stderr);
fprintf(stderr, "\n");
fflush(stderr);
+#ifdef __ANDROID__
+ // produce logcat output for general consumption
+ va_list args_for_log;
+ va_start(args_for_log, format);
+ __android_log_vprint(ANDROID_LOG_ERROR, "tflite", format, args_for_log);
+ va_end(args_for_log);
+#endif
}
#define FATAL(...) \
@@ -564,8 +571,14 @@ TfLiteStatus AddOpsAndParams(
nn_op_type = ANEURALNETWORKS_L2_NORMALIZATION;
if (reinterpret_cast<TfLiteL2NormParams*>(node.builtin_data)
->activation != kTfLiteActNone) {
- FATAL(
+ logError(
"NNAPI does not support L2Normalization with fused activations");
+ return kTfLiteError;
+ }
+ if ((node.inputs->size > 0) &&
+ (interpreter->tensor(node.inputs->data[0])->dims->size != 4)) {
+ logError("NNAPI only supports input rank 4 for L2Normalization");
+ return kTfLiteError;
}
break;
case tflite::BuiltinOperator_HASHTABLE_LOOKUP:
diff --git a/tensorflow/contrib/lite/python/BUILD b/tensorflow/contrib/lite/python/BUILD
index 860aff9e7e..47f0c8e9a2 100644
--- a/tensorflow/contrib/lite/python/BUILD
+++ b/tensorflow/contrib/lite/python/BUILD
@@ -112,8 +112,11 @@ py_library(
visibility = ["//visibility:public"],
deps = [
"//tensorflow/contrib/framework:framework_py",
+ "//tensorflow/contrib/graph_editor:graph_editor_py",
"//tensorflow/core:protos_all_py",
+ "//tensorflow/python:framework",
"//tensorflow/python:platform",
+ "//tensorflow/python:util",
],
)
diff --git a/tensorflow/contrib/lite/python/convert.py b/tensorflow/contrib/lite/python/convert.py
index ec49738fb5..12cc66dc55 100644
--- a/tensorflow/contrib/lite/python/convert.py
+++ b/tensorflow/contrib/lite/python/convert.py
@@ -19,6 +19,7 @@ from __future__ import division
from __future__ import print_function
import os as _os
+import platform as _platform
import subprocess as _subprocess
import tempfile as _tempfile
@@ -26,6 +27,7 @@ from tensorflow.contrib.lite.python import lite_constants
from tensorflow.contrib.lite.toco import model_flags_pb2 as _model_flags_pb2
from tensorflow.contrib.lite.toco import toco_flags_pb2 as _toco_flags_pb2
from tensorflow.python.platform import resource_loader as _resource_loader
+from tensorflow.python.util import deprecation
from tensorflow.python.util.lazy_loader import LazyLoader
@@ -54,7 +56,7 @@ def toco_convert_protos(model_flags_str, toco_flags_str, input_data_str):
"""Convert `input_data_str` according to model and toco parameters.
Unless you know what you are doing consider using
- the more friendly @{tf.contrib.lite.toco_convert}}.
+ the more friendly `tf.contrib.lite.toco_convert`.
Args:
model_flags_str: Serialized proto describing model properties, see
@@ -90,12 +92,13 @@ def toco_convert_protos(model_flags_str, toco_flags_str, input_data_str):
fp_output.name
]
cmdline = " ".join(cmd)
+ is_windows = _platform.system() == "Windows"
proc = _subprocess.Popen(
cmdline,
shell=True,
stdout=_subprocess.PIPE,
stderr=_subprocess.STDOUT,
- close_fds=True)
+ close_fds=not is_windows)
stdout, stderr = proc.communicate()
exitcode = proc.returncode
if exitcode == 0:
@@ -223,7 +226,8 @@ def build_toco_convert_protos(input_tensors,
return model, toco
-def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
+def toco_convert_impl(input_data, input_tensors, output_tensors, *args,
+ **kwargs):
""""Convert a model using TOCO.
Typically this function is used to convert from TensorFlow GraphDef to TFLite.
@@ -252,3 +256,30 @@ def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
toco_flags.SerializeToString(),
input_data.SerializeToString())
return data
+
+
+@deprecation.deprecated(None, "Use `lite.TocoConverter` instead.")
+def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
+ """"Convert a model using TOCO.
+
+ Typically this function is used to convert from TensorFlow GraphDef to TFLite.
+ Conversion can be customized by providing arguments that are forwarded to
+ `build_toco_convert_protos` (see documentation for details).
+
+ Args:
+ input_data: Input data (i.e. often `sess.graph_def`),
+ input_tensors: List of input tensors. Type and shape are computed using
+ `foo.get_shape()` and `foo.dtype`.
+ output_tensors: List of output tensors (only .name is used from this).
+ *args: See `build_toco_convert_protos`,
+ **kwargs: See `build_toco_convert_protos`.
+
+ Returns:
+ The converted data. For example if TFLite was the destination, then
+ this will be a tflite flatbuffer in a bytes array.
+
+ Raises:
+ Defined in `build_toco_convert_protos`.
+ """
+ return toco_convert_impl(input_data, input_tensors, output_tensors, *args,
+ **kwargs)
diff --git a/tensorflow/contrib/lite/python/convert_test.py b/tensorflow/contrib/lite/python/convert_test.py
index dc21a9b669..bc05514cec 100644
--- a/tensorflow/contrib/lite/python/convert_test.py
+++ b/tensorflow/contrib/lite/python/convert_test.py
@@ -113,12 +113,13 @@ class ConvertTestOpHint(test_util.TensorFlowTestCase):
# and 1 final output).
self.assertEqual(self._countIdentities(sess.graph_def.node), 4)
- stubbed_graphdef = op_hint.convert_op_hints_to_stubs(sess)
+ stubbed_graphdef = op_hint.convert_op_hints_to_stubs(
+ graph_def=sess.graph_def)
self.assertCountEqual(
self._getGraphOpTypes(
stubbed_graphdef,
- output_nodes=[op_hint._tensor_name_base(output)]),
+ output_nodes=[op_hint._tensor_name_base(output.name)]),
["cool_activation", "Const", "Identity"])
def testScaleAndBiasAndIdentity(self):
@@ -139,12 +140,13 @@ class ConvertTestOpHint(test_util.TensorFlowTestCase):
# +1 for the final output
self.assertEqual(self._countIdentities(sess.graph_def.node), 6)
- stubbed_graphdef = op_hint.convert_op_hints_to_stubs(sess)
+ stubbed_graphdef = op_hint.convert_op_hints_to_stubs(
+ graph_def=sess.graph_def)
self.assertCountEqual(
self._getGraphOpTypes(
stubbed_graphdef,
- output_nodes=[op_hint._tensor_name_base(output)]),
+ output_nodes=[op_hint._tensor_name_base(output.name)]),
["scale_and_bias_and_identity", "Const", "Identity", "Pack"])
def testTwoFunctions(self):
@@ -153,7 +155,7 @@ class ConvertTestOpHint(test_util.TensorFlowTestCase):
b = array_ops.constant([1.])
def _double_values(x):
custom = op_hint.OpHint("add_test")
- x = custom.add_inputs(x)
+ x, = custom.add_inputs(x)
output = math_ops.multiply(x, x)
output, = custom.add_outputs(output)
return output
@@ -164,13 +166,90 @@ class ConvertTestOpHint(test_util.TensorFlowTestCase):
# make sure one identity for each input (2) and output (2) => 2 + 2
# +1 for the final output
self.assertEqual(self._countIdentities(sess.graph_def.node), 5)
- stubbed_graphdef = op_hint.convert_op_hints_to_stubs(sess)
+ stubbed_graphdef = op_hint.convert_op_hints_to_stubs(
+ graph_def=sess.graph_def)
self.assertCountEqual(
self._getGraphOpTypes(
stubbed_graphdef,
- output_nodes=[op_hint._tensor_name_base(output)]),
+ output_nodes=[op_hint._tensor_name_base(output.name)]),
["add_test", "Const", "Identity", "Add"])
+ def _get_input_index(self, x):
+ return x.op.node_def.attr[op_hint.OpHint.FUNCTION_INPUT_INDEX_ATTR].i
+
+ def _get_output_index(self, x):
+ return x.op.node_def.attr[op_hint.OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i
+
+ def _get_sort_index(self, x):
+ return x.op.node_def.attr[op_hint.OpHint.FUNCTION_SORT_INDEX_ATTR].i
+
+ def testTags(self):
+ """Test if multiple args with the same tag are grouped."""
+ a = array_ops.constant([1.])
+ b = array_ops.constant([2.])
+ c = array_ops.constant([3.])
+ d = array_ops.constant([4.])
+ custom = op_hint.OpHint("test_tag")
+ a = custom.add_input(a, tag="mytag",
+ aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ b, = custom.add_inputs(b)
+ c = custom.add_input(c, tag="mytag",
+ aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ d = custom.add_input(d, tag="mytag2",
+ aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ res = math_ops.add(math_ops.mul(a, b), math_ops.mul(c, b))
+ custom.add_outputs([res])
+ with self.test_session():
+ self.assertEqual(self._get_input_index(a), 0)
+ self.assertEqual(self._get_sort_index(a), 0)
+ self.assertEqual(self._get_input_index(b), 1)
+ self.assertEqual(self._get_input_index(c), 0)
+ self.assertEqual(self._get_sort_index(c), 1)
+
+ def testOverrideIndex(self):
+ a = array_ops.constant([1.])
+ b = array_ops.constant([2.])
+ c = array_ops.constant([3.])
+ custom = op_hint.OpHint("test_override")
+ b = custom.add_input(b) # should auto assign 0
+ a = custom.add_input(a, index_override=1)
+ c = custom.add_input(c) # should auto assign 2
+ with self.test_session():
+ self.assertEqual(self._get_input_index(a), 1)
+ self.assertEqual(self._get_input_index(b), 0)
+ self.assertEqual(self._get_input_index(c), 2)
+
+ def testAggregate(self):
+ a = array_ops.constant([3., 4.])
+ b = array_ops.constant([5., 6.])
+ hint = op_hint.OpHint("agg")
+ a0, a1 = array_ops.unstack(a)
+ b0, b1 = array_ops.unstack(b)
+
+ a0 = hint.add_input(a0, tag="c", aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ b0 = hint.add_input(b0, tag="n", aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ a1 = hint.add_input(a1, tag="c", aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ b1 = hint.add_input(b1, tag="n", aggregate=op_hint.OpHint.AGGREGATE_STACK)
+
+ c0 = math_ops.add(a0, b0, name="addleft")
+ c1 = math_ops.add(a1, b1, name="addright")
+ c0 = hint.add_output(
+ c0, tag="out", aggregate=op_hint.OpHint.AGGREGATE_STACK)
+ c1 = hint.add_output(
+ c1, tag="out", aggregate=op_hint.OpHint.AGGREGATE_STACK)
+
+ curr = array_ops.stack([c0, c1])
+ output = array_ops.identity(curr, name="FINAL_OUTPUT")
+ with self.test_session() as sess:
+ stubbed_graphdef = op_hint.convert_op_hints_to_stubs(
+ graph_def=sess.graph_def)
+ print(stubbed_graphdef)
+ self.assertCountEqual(
+ self._getGraphOpTypes(
+ stubbed_graphdef,
+ output_nodes=[op_hint._tensor_name_base(output.name)]),
+ ["agg", "Const", "Identity"])
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/lite/python/interpreter.py b/tensorflow/contrib/lite/python/interpreter.py
index 3243bddac8..1be61fe053 100644
--- a/tensorflow/contrib/lite/python/interpreter.py
+++ b/tensorflow/contrib/lite/python/interpreter.py
@@ -54,6 +54,10 @@ class Interpreter(object):
if not self._interpreter:
raise ValueError('Failed to open {}'.format(model_path))
elif model_content and not model_path:
+ # Take a reference, so the pointer remains valid.
+ # Since python strings are immutable then PyString_XX functions
+ # will always return the same pointer.
+ self._model_content = model_content
self._interpreter = (
_interpreter_wrapper.InterpreterWrapper_CreateWrapperCPPFromBuffer(
model_content))
diff --git a/tensorflow/contrib/lite/python/interpreter_wrapper/interpreter_wrapper.h b/tensorflow/contrib/lite/python/interpreter_wrapper/interpreter_wrapper.h
index 3e03751da4..641dd93db5 100644
--- a/tensorflow/contrib/lite/python/interpreter_wrapper/interpreter_wrapper.h
+++ b/tensorflow/contrib/lite/python/interpreter_wrapper/interpreter_wrapper.h
@@ -15,12 +15,15 @@ limitations under the License.
#ifndef TENSORFLOW_CONTRIB_LITE_PYTHON_INTERPRETER_WRAPPER_INTERPRETER_WRAPPER_H_
#define TENSORFLOW_CONTRIB_LITE_PYTHON_INTERPRETER_WRAPPER_INTERPRETER_WRAPPER_H_
-// Place `<locale>` before <Python.h> to avoid build failures in macOS.
-#include <locale>
#include <memory>
#include <string>
#include <vector>
+// Place `<locale>` before <Python.h> to avoid build failures in macOS.
+#include <locale>
+
+// The empty line above is on purpose as otherwise clang-format will
+// automatically move <Python.h> before <locale>.
#include <Python.h>
// We forward declare TFLite classes here to avoid exposing them to SWIG.
diff --git a/tensorflow/contrib/lite/python/lite.py b/tensorflow/contrib/lite/python/lite.py
index 2f9b9d469a..2313bfa3b6 100644
--- a/tensorflow/contrib/lite/python/lite.py
+++ b/tensorflow/contrib/lite/python/lite.py
@@ -41,7 +41,8 @@ from google.protobuf.message import DecodeError
from tensorflow.contrib.lite.python import lite_constants as constants
from tensorflow.contrib.lite.python.convert import build_toco_convert_protos # pylint: disable=unused-import
from tensorflow.contrib.lite.python.convert import tensor_name as _tensor_name
-from tensorflow.contrib.lite.python.convert import toco_convert
+from tensorflow.contrib.lite.python.convert import toco_convert # pylint: disable=unused-import
+from tensorflow.contrib.lite.python.convert import toco_convert_impl as _toco_convert_impl
from tensorflow.contrib.lite.python.convert import toco_convert_protos # pylint: disable=unused-import
from tensorflow.contrib.lite.python.convert_saved_model import freeze_saved_model as _freeze_saved_model
from tensorflow.contrib.lite.python.convert_saved_model import get_tensors_from_tensor_names as _get_tensors_from_tensor_names
@@ -53,8 +54,8 @@ from tensorflow.core.framework import graph_pb2 as _graph_pb2
from tensorflow.python import keras as _keras
from tensorflow.python.client import session as _session
from tensorflow.python.framework import graph_util as _tf_graph_util
+from tensorflow.python.framework import ops as _ops
from tensorflow.python.framework.importer import import_graph_def as _import_graph_def
-from tensorflow.python.ops.variables import global_variables_initializer as _global_variables_initializer
from tensorflow.python.saved_model import signature_constants as _signature_constants
from tensorflow.python.saved_model import tag_constants as _tag_constants
@@ -110,6 +111,7 @@ class TocoConverter(object):
Example usage:
+ ```python
# Converting a GraphDef from session.
converter = lite.TocoConverter.from_session(sess, in_tensors, out_tensors)
tflite_model = converter.convert()
@@ -124,6 +126,11 @@ class TocoConverter(object):
# Converting a SavedModel.
converter = lite.TocoConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()
+
+ # Converting a tf.keras model.
+ converter = lite.TocoConverter.from_keras_model_file(keras_model)
+ tflite_model = converter.convert()
+ ```
"""
def __init__(self, graph_def, input_tensors, output_tensors):
@@ -194,42 +201,41 @@ class TocoConverter(object):
The graph is not frozen.
input_arrays or output_arrays contains an invalid tensor name.
"""
- with _session.Session() as sess:
- sess.run(_global_variables_initializer())
-
- # Read GraphDef from file.
- graph_def = _graph_pb2.GraphDef()
- with open(graph_def_file, "rb") as f:
- file_content = f.read()
- try:
- graph_def.ParseFromString(file_content)
- except (_text_format.ParseError, DecodeError):
+ with _ops.Graph().as_default():
+ with _session.Session() as sess:
+ # Read GraphDef from file.
+ graph_def = _graph_pb2.GraphDef()
+ with open(graph_def_file, "rb") as f:
+ file_content = f.read()
try:
- print("Ignore 'tcmalloc: large alloc' warnings.")
-
- if not isinstance(file_content, str):
- if PY3:
- file_content = file_content.decode('utf-8')
- else:
- file_content = file_content.encode('utf-8')
- _text_format.Merge(file_content, graph_def)
+ graph_def.ParseFromString(file_content)
except (_text_format.ParseError, DecodeError):
- raise ValueError(
- "Unable to parse input file '{}'.".format(graph_def_file))
- sess.graph.as_default()
- _import_graph_def(graph_def, name="")
-
- # Get input and output tensors.
- input_tensors = _get_tensors_from_tensor_names(sess.graph, input_arrays)
- output_tensors = _get_tensors_from_tensor_names(sess.graph, output_arrays)
- _set_tensor_shapes(input_tensors, input_shapes)
-
- # Check if graph is frozen.
- if not _is_frozen_graph(sess):
- raise ValueError("Please freeze the graph using freeze_graph.py.")
-
- # Create TocoConverter class.
- return cls(sess.graph_def, input_tensors, output_tensors)
+ try:
+ print("Ignore 'tcmalloc: large alloc' warnings.")
+
+ if not isinstance(file_content, str):
+ if PY3:
+ file_content = file_content.decode("utf-8")
+ else:
+ file_content = file_content.encode("utf-8")
+ _text_format.Merge(file_content, graph_def)
+ except (_text_format.ParseError, DecodeError):
+ raise ValueError(
+ "Unable to parse input file '{}'.".format(graph_def_file))
+ _import_graph_def(graph_def, name="")
+
+ # Get input and output tensors.
+ input_tensors = _get_tensors_from_tensor_names(sess.graph, input_arrays)
+ output_tensors = _get_tensors_from_tensor_names(sess.graph,
+ output_arrays)
+ _set_tensor_shapes(input_tensors, input_shapes)
+
+ # Check if graph is frozen.
+ if not _is_frozen_graph(sess):
+ raise ValueError("Please freeze the graph using freeze_graph.py.")
+
+ # Create TocoConverter class.
+ return cls(sess.graph_def, input_tensors, output_tensors)
@classmethod
def from_saved_model(cls,
@@ -355,7 +361,7 @@ class TocoConverter(object):
quantized_stats = None
# Converts model.
- result = toco_convert(
+ result = _toco_convert_impl(
input_data=self._graph_def,
input_tensors=self._input_tensors,
output_tensors=self._output_tensors,
@@ -427,7 +433,6 @@ def _freeze_graph(sess, output_tensors):
Frozen GraphDef.
"""
if not _is_frozen_graph(sess):
- sess.run(_global_variables_initializer())
output_arrays = [_tensor_name(tensor) for tensor in output_tensors]
return _tf_graph_util.convert_variables_to_constants(
sess, sess.graph_def, output_arrays)
diff --git a/tensorflow/contrib/lite/python/lite_test.py b/tensorflow/contrib/lite/python/lite_test.py
index ca2af5aaed..2f13684228 100644
--- a/tensorflow/contrib/lite/python/lite_test.py
+++ b/tensorflow/contrib/lite/python/lite_test.py
@@ -33,6 +33,7 @@ from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
+from tensorflow.python.ops.variables import global_variables_initializer as _global_variables_initializer
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.saved_model import saved_model
@@ -198,6 +199,7 @@ class FromSessionTest(test_util.TensorFlowTestCase):
'weights', shape=[1, 16, 16, 3], dtype=dtypes.float32)
out_tensor = in_tensor + var
sess = session.Session()
+ sess.run(_global_variables_initializer())
# Convert model and ensure model is not None.
converter = lite.TocoConverter.from_session(sess, [in_tensor], [out_tensor])
@@ -655,9 +657,7 @@ class FromKerasFile(test_util.TensorFlowTestCase):
tflite_model = converter.convert()
self.assertTrue(tflite_model)
- os.remove(keras_file)
-
- # Check values from converted model.
+ # Check tensor details of converted model.
interpreter = Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
@@ -675,6 +675,18 @@ class FromKerasFile(test_util.TensorFlowTestCase):
self.assertTrue(([1, 3, 3] == output_details[0]['shape']).all())
self.assertEqual((0., 0.), output_details[0]['quantization'])
+ # Check inference of converted model.
+ input_data = np.array([[1, 2, 3]], dtype=np.float32)
+ interpreter.set_tensor(input_details[0]['index'], input_data)
+ interpreter.invoke()
+ tflite_result = interpreter.get_tensor(output_details[0]['index'])
+
+ keras_model = keras.models.load_model(keras_file)
+ keras_result = keras_model.predict(input_data)
+
+ np.testing.assert_almost_equal(tflite_result, keras_result, 5)
+ os.remove(keras_file)
+
def testSequentialModelInputArray(self):
"""Test a Sequential tf.keras model testing input arrays argument."""
keras_file = self._getSequentialModel()
@@ -755,17 +767,17 @@ class FromKerasFile(test_util.TensorFlowTestCase):
model.predict(x)
fd, keras_file = tempfile.mkstemp('.h5')
- keras.models.save_model(model, keras_file)
+ try:
+ keras.models.save_model(model, keras_file)
+ finally:
+ os.close(fd)
# Convert to TFLite model.
converter = lite.TocoConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
self.assertTrue(tflite_model)
- os.close(fd)
- os.remove(keras_file)
-
- # Check values from converted model.
+ # Check tensor details of converted model.
interpreter = Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
@@ -783,6 +795,18 @@ class FromKerasFile(test_util.TensorFlowTestCase):
self.assertTrue(([1, 3] == output_details[0]['shape']).all())
self.assertEqual((0., 0.), output_details[0]['quantization'])
+ # Check inference of converted model.
+ input_data = np.array([[1, 2, 3]], dtype=np.float32)
+ interpreter.set_tensor(input_details[0]['index'], input_data)
+ interpreter.invoke()
+ tflite_result = interpreter.get_tensor(output_details[0]['index'])
+
+ keras_model = keras.models.load_model(keras_file)
+ keras_result = keras_model.predict(input_data)
+
+ np.testing.assert_almost_equal(tflite_result, keras_result, 5)
+ os.remove(keras_file)
+
def testFunctionalModelMultipleInputs(self):
"""Test a Functional tf.keras model with multiple inputs and outputs."""
a = keras.layers.Input(shape=(3,), name='input_a')
@@ -865,17 +889,17 @@ class FromKerasFile(test_util.TensorFlowTestCase):
model.predict(x)
fd, keras_file = tempfile.mkstemp('.h5')
- keras.models.save_model(model, keras_file)
+ try:
+ keras.models.save_model(model, keras_file)
+ finally:
+ os.close(fd)
# Convert to TFLite model.
converter = lite.TocoConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
self.assertTrue(tflite_model)
- os.close(fd)
- os.remove(keras_file)
-
- # Check values from converted model.
+ # Check tensor details of converted model.
interpreter = Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
@@ -893,6 +917,18 @@ class FromKerasFile(test_util.TensorFlowTestCase):
self.assertTrue(([1, 3, 3] == output_details[0]['shape']).all())
self.assertEqual((0., 0.), output_details[0]['quantization'])
+ # Check inference of converted model.
+ input_data = np.array([[1, 2, 3]], dtype=np.float32)
+ interpreter.set_tensor(input_details[0]['index'], input_data)
+ interpreter.invoke()
+ tflite_result = interpreter.get_tensor(output_details[0]['index'])
+
+ keras_model = keras.models.load_model(keras_file)
+ keras_result = keras_model.predict(input_data)
+
+ np.testing.assert_almost_equal(tflite_result, keras_result, 5)
+ os.remove(keras_file)
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/contrib/lite/python/op_hint.py b/tensorflow/contrib/lite/python/op_hint.py
index 7908689ce4..8c920132e5 100644
--- a/tensorflow/contrib/lite/python/op_hint.py
+++ b/tensorflow/contrib/lite/python/op_hint.py
@@ -25,9 +25,9 @@ Example:
def tflite_cool_activation(input):
# A cool activation function.
custom = tf.contrib.lite.OpHint("cool_activation")
- input = custom.add_inputs(input)
+ input, = custom.add_inputs(input)
output = tf.sigmoid(input) * input
- custom.add_outputs(output)
+ output, = custom.add_outputs(output)
return output
image = tf.placeholder(tf.float32, (1, 16, 16, 1))
@@ -64,18 +64,27 @@ ops don't actually exist in the normal TensorFlow runtime, but will be
understood by toco later.
"""
+# TODO(aselle): Make this use generic graph transformations.
+# TODO(aselle): _tensor_name_base should be called _tensor_name_to_op_name.
+
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections as _collections
-import itertools as _itertools
+import copy as _copy
import uuid as _uuid
+import six as _six
-from tensorflow.contrib import framework as _framework
from tensorflow.core.framework import attr_value_pb2 as _attr_value_pb2
+from tensorflow.core.framework import graph_pb2 as _graph_pb2
+from tensorflow.core.framework import node_def_pb2 as _node_def_pb2
from tensorflow.python.framework import ops as _ops
+# TODO(aselle): publicize these apis if we continue to use these.
+from tensorflow.python.framework.graph_util_impl import _bfs_for_reachable_nodes
+from tensorflow.python.framework.graph_util_impl import _extract_graph_summary
from tensorflow.python.ops import array_ops as _array_ops
+from tensorflow.python.util import compat as _compat
from tensorflow.python.util.all_util import remove_undocumented
@@ -97,11 +106,174 @@ class OpHint(object):
constructs, this mechanism can be retired and changed to use python defun's.
"""
- # Attr constants that are used for representation in the GraphDef
+ # Attr constants that are used for representation in the GraphDef. These
+ # will be used on every Identity op that is involved in a total OpHint.
+
+ # Name of the OpHint function (cosmetic).
FUNCTION_NAME_ATTR = "_tflite_function_name"
+ # UUID of the function (each OpHint gets a new uuid).
FUNCTION_UUID_ATTR = "_tflite_function_uuid"
+ # The index index of the input (or nothing if it is an output).
FUNCTION_INPUT_INDEX_ATTR = "_tflite_function_input_index"
+ # The output index of the output (or nothing if it is an input).
FUNCTION_OUTPUT_INDEX_ATTR = "_tflite_function_output_index"
+ # An index that orders aggregate arguments. Aggregate arguments are ones
+ # that are separate but will be fused horizontally. For example a static LSTM
+ # has a lstm cell for each time step. Each one has a separate opHint, but a
+ # fused SequentialLSTM will treat this as a single tensor.
+ FUNCTION_SORT_INDEX_ATTR = "_tflite_function_sort_index"
+ # The way in which multiple parts of the aggregate argument will be joined
+ # into a fused operand. Valid options are OpHint.AGGREGATE_FIRST,
+ # OpHint.AGGREGATE_LAST, OpHint.AGGREGATE_STACK.
+ FUNCTION_AGGREGATE_ATTR = "_tflite_function_aggregate"
+ # On fused OpHint stub, the order of inputs that the final LSTM call will
+ # have. What this means is that the TensorFlow order might be
+ # "foo", "bar", "stuff" and you might want the TF lite op order to be
+ # "stuff", "foo", "bar", -1 (where -1 is unused). So you would set this
+ # attribute to [2, 0, 1, -1].
+ TFLITE_INPUT_INDICES = "_tflite_input_indices"
+
+ # Types of aggregations
+ # stack: stacks all ophints with matching tags. i.e. for a static rnn.
+ # specifically, this is good for an input or output to a static rnn cell.
+ AGGREGATE_STACK = _compat.as_bytes("stack")
+ # first: only takes the first output (one with lowest sort index)
+ # of matching tags. This is good for the input state to an RNN.
+ AGGREGATE_FIRST = _compat.as_bytes("first")
+ # aggregation last takes only the last tag (one with highest sort index).
+ # This is good for an output value on the last stack item of a
+ # static rnn.
+ AGGREGATE_LAST = _compat.as_bytes("last")
+
+ class OpHintArgumentTracker(object):
+ """Conceptually tracks indices of arguments of "OpHint functions".
+
+ The inputs and arguments of these functions both use an instance
+ of the class so they can have independent numbering."""
+
+ def __init__(self, function_name, unique_function_id, node_name_prefix,
+ attr_name):
+ """Initialize ophint argument.
+
+ Args:
+ function_name: Name of the function that this tracks arguments for.
+ unique_function_id: UUID of function that this tracks arguments for.
+ node_name_prefix: How identities that are created are named.
+ attr_name: Name of attribute to use to store the index for this hint.
+ i.e. FUNCTION_INPUT_INDEX or FUNCTION_OUTPUT_INDEX
+ """
+
+ # The global index is the argument index of the op. This is in contrast
+ # to the sort index which is the sequence number of a particular instance
+ # of a given global index. For example, you may have called add hint
+ # twice with the tag "foo". Then the global index will be 0 for both
+ # and the sort index will be 0 for the first added and 1 for the second.
+ self._function_name = function_name
+ self._unique_function_id = unique_function_id
+ self._next_global_index = 0 # The absolute global index
+ self._used_global_indices = set()
+ self._tag_to_global_index = {} # The argument index a given tag maps to
+ self._tag_to_next_sort_index = {} # The current index for each tag
+ self._node_name_prefix = node_name_prefix
+ self._attr_name = attr_name
+
+ def _get_new_global_index(self, index_override):
+ """Return the next unused argument index in order or use an override.
+
+ Args:
+ index_override: An index to use instead of the next available or None
+ to use the next available.
+
+ Returns:
+ A valid global_index to use for the next hint argument.
+
+ Raises:
+ ValueError: If the index_override is already used by another hint.
+ """
+ if index_override is None:
+ global_index = self._next_global_index
+ else:
+ if index_override in self._used_global_indices:
+ raise ValueError("Index %d was already used by another call to add")
+ global_index = index_override
+ # Make next_global_index valid
+ self._used_global_indices.add(global_index)
+ while self._next_global_index in self._used_global_indices:
+ self._next_global_index += 1
+ return global_index
+
+ def add(self, arg, tag=None, name=None, aggregate=None,
+ index_override=None):
+ """Return a wrapped tensor of an input tensor as an argument.
+
+ Args:
+ arg: A TensorFlow tensor that should be considered an argument.
+ tag: String tag to identify arguments that should be packed.
+ name: Name of argument. This is included in the Identity hint op names.
+ aggregate: Strategy to aggregate.
+ Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
+ and OpHint.AGGREGATE_STACK.
+ Note, aggregate is only valid if tag is specified.
+ index_override: Specify what input/output index should this be in the
+ final stub. i.e. add(arg0, index=1); add(arg1, index=0) wil make the
+ final stub be as stub_func(inputs[arg1, arg0], outputs=[]) rather than
+ the default call order based ordering.
+
+ Returns:
+ A tensor representing the wrapped argument.
+
+ Raises:
+ ValueError: When indices are not consistent.
+ """
+
+ # Find the appropriate index
+ if tag is None:
+ if aggregate is not None:
+ raise ValueError("You must specify `tag` if using aggregate.")
+ global_index = self._get_new_global_index(index_override)
+ sort_index = None
+ else:
+ if aggregate is None:
+ raise ValueError("You must specify `aggregate` if using tag.")
+ if tag not in self._tag_to_global_index:
+ self._tag_to_global_index[tag] = (
+ self._get_new_global_index(index_override))
+ self._tag_to_next_sort_index[tag] = 0
+ elif (index_override and
+ index_override != self._tag_to_global_index[tag]):
+ raise ValueError(
+ "Tag %r was called with two indices %r and %r" %
+ (tag, index_override, self._tag_to_global_index[tag]))
+ global_index = self._tag_to_global_index[tag]
+ sort_index = self._tag_to_next_sort_index[tag]
+ self._tag_to_next_sort_index[tag] += 1
+
+ uuid = self._unique_function_id
+ name = "%s-%s-%s-%r-%r-%s" % (self._node_name_prefix, self._function_name,
+ uuid, global_index, sort_index, name)
+ identity_op = _array_ops.identity(arg, name=name)
+
+ # pylint: disable=protected-access
+ identity_op.op._set_attr(
+ OpHint.FUNCTION_NAME_ATTR,
+ _attr_value_pb2.AttrValue(
+ s=_compat.as_bytes(self._function_name)))
+ identity_op.op._set_attr(
+ OpHint.FUNCTION_UUID_ATTR,
+ _attr_value_pb2.AttrValue(
+ s=_compat.as_bytes(self._unique_function_id)))
+ identity_op.op._set_attr(
+ self._attr_name, _attr_value_pb2.AttrValue(i=global_index))
+ if sort_index is not None:
+ identity_op.op._set_attr(
+ OpHint.FUNCTION_SORT_INDEX_ATTR,
+ _attr_value_pb2.AttrValue(i=sort_index))
+ if aggregate is not None:
+ identity_op.op._set_attr(
+ OpHint.FUNCTION_AGGREGATE_ATTR,
+ _attr_value_pb2.AttrValue(s=_compat.as_bytes((aggregate))))
+ # pylint: enable=protected-access
+ return identity_op
def __init__(self, function_name, **kwargs):
"""Create a OpHint.
@@ -112,10 +284,14 @@ class OpHint(object):
"""
self._function_name = function_name
self._unique_function_id = _uuid.uuid1().hex # TODO(aselle): Unique enough?
- self._curr_input_index = 0
- self._curr_output_index = 0
self._attrs_to_store_later = kwargs
self._stored_attrs = False
+ self._inputs = OpHint.OpHintArgumentTracker(
+ self._function_name, self._unique_function_id, "InputHint",
+ OpHint.FUNCTION_INPUT_INDEX_ATTR)
+ self._outputs = OpHint.OpHintArgumentTracker(
+ self._function_name, self._unique_function_id, "OutputHint",
+ OpHint.FUNCTION_OUTPUT_INDEX_ATTR)
def _setattr(self, dest_op, name, value):
tensor_value = _ops.convert_to_tensor(value)
@@ -124,68 +300,278 @@ class OpHint(object):
tensor=tensor_value.op.node_def.attr["value"].tensor))
# pylint: enable=protected-access
- def add_inputs(self, *args):
+ def add_input(self, *args, **kwargs):
+ """Add a wrapped input argument to the hint.
+
+ Args:
+ *args: The input tensor.
+ **kwargs:
+ "name" label
+ "tag" a tag to group multiple arguments that will be aggregated. I.e.
+ a string like 'cool_input'. Basically multiple inputs can be added
+ to the same hint for parallel operations that will eventually be
+ combined. An example would be static_rnn which creates multiple copies
+ of state or inputs.
+ "aggregate" aggregation strategy that is valid only for tag non None.
+ Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
+ and OpHint.AGGREGATE_STACK.
+ "index_override" The global index to use. This corresponds to the
+ argument order in the final stub that will be generated.
+ Returns:
+ The wrapped input tensor.
+ """
+ return self._inputs.add(*args, **kwargs)
+
+ def add_output(self, *args, **kwargs):
+ """Add a wrapped output argument to the hint.
+
+ Args:
+ *args: The output tensor.
+ **kwargs:
+ "name" label
+ "tag" a tag to group multiple arguments that will be aggregated. I.e.
+ a string like 'cool_input'. Basically multiple inputs can be added
+ to the same hint for parallel operations that will eventually be
+ combined. An example would be static_rnn which creates multiple copies
+ of state or inputs.
+ "aggregate" aggregation strategy that is valid only for tag non None.
+ Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
+ and OpHint.AGGREGATE_STACK.
+ "index_override" The global index to use. This corresponds to the
+ argument order in the final stub that will be generated.
+ Returns:
+ The wrapped output tensor.
+ """
+ return self._outputs.add(*args, **kwargs)
+
+ def add_inputs(self, *args, **kwargs):
"""Add a sequence of inputs to the function invocation.
Args:
*args: List of inputs to be converted (should be Tf.Tensor).
+ **kwargs: This allows 'names' which should be a list of names.
Returns:
Wrapped inputs (identity standins that have additional metadata). These
are also are also tf.Tensor's.
"""
-
- def augmented_identity(arg):
- identity_op = _array_ops.identity(arg)
- # pylint: disable=protected-access
- identity_op.op._set_attr(
- OpHint.FUNCTION_NAME_ATTR,
- _attr_value_pb2.AttrValue(s=self._function_name))
- identity_op.op._set_attr(
- OpHint.FUNCTION_UUID_ATTR,
- _attr_value_pb2.AttrValue(s=self._unique_function_id))
- identity_op.op._set_attr(
- OpHint.FUNCTION_INPUT_INDEX_ATTR,
- _attr_value_pb2.AttrValue(i=self._curr_input_index))
- # pylint: enable=protected-access
- self._curr_input_index += 1
- return identity_op
-
- return [augmented_identity(arg) for arg in args]
-
- def add_outputs(self, *args):
+ if "names" in kwargs:
+ return [
+ self._inputs.add(arg, name=name)
+ for arg, name in zip(args, kwargs["names"])
+ ]
+ else:
+ return [self._inputs.add(arg) for arg in args]
+
+ def add_outputs(self, *args, **kwargs):
"""Add a sequence of outputs to the function invocation.
Args:
*args: List of outputs to be converted (should be tf.Tensor).
+ **kwargs: See
Returns:
Wrapped outputs (identity standins that have additional metadata). These
are also tf.Tensor's.
"""
+ if "names" in kwargs:
+ return [
+ self._outputs.add(arg, name=name)
+ for arg, name in zip(args, kwargs["names"])
+ ]
+ else:
+ return [self._outputs.add(arg) for arg in args]
+
+
+class _LiteOperand(object):
+ """Abstract operand for a tflite hint function.
+
+ This is a base class that handles representing arguments to an OpHint.
+ It also is able to serialize operands to the stubbed graph_def.
+ Child classes are responsible for being able to
+ store information about the hint identity operators. They are also responsible
+ for knowing how to serialize to output graphdefs.
+
+ Typically this will be implemented by holding one or more identity nodes
+ that were previously discovered as hints.
+ """
+
+ def aggregate_and_return_name_for_input(self, out_graphdef):
+ """This adds the node(s) to out_graphdef and returns the input node name.
+
+ Args:
+ out_graphdef: A graphdef that is ready to have this input added.
+
+ Returns:
+ The the output that the stub should use as an input for this operand.
+
+ Raises:
+ RuntimeError: if the method is not implemented.
+ """
+ del out_graphdef
+ raise RuntimeError("Unimplemented abstract method.")
+
+ def aggregate_and_return_name_for_output(self, fused_op_name, output_index,
+ out_graphdef):
+ """Add node(s) to graph representing output operands and returns type.
+
+ Args:
+ fused_op_name: name of the fused op stub name.
+ output_index: Output index that we are currently processing from stub.
+ out_graphdef: The destination graphdef we are currently building up.
+
+ Returns:
+ The datatype of this identity.
+
+ Raises:
+ RuntimeError: if the method is not implemented.
+ """
+ del fused_op_name, output_index, out_graphdef
+ raise RuntimeError("Unimplemented abstract method.")
- def augmented_identity(arg):
- identity_op = _array_ops.identity(arg)
- # pylint: disable=protected-access
- identity_op.op._set_attr(
- OpHint.FUNCTION_NAME_ATTR,
- _attr_value_pb2.AttrValue(s=self._function_name))
- identity_op.op._set_attr(
- OpHint.FUNCTION_UUID_ATTR,
- _attr_value_pb2.AttrValue(s=self._unique_function_id))
- identity_op.op._set_attr(
- OpHint.FUNCTION_OUTPUT_INDEX_ATTR,
- _attr_value_pb2.AttrValue(i=self._curr_output_index))
- # pylint: enable=protected-access
- self._curr_output_index += 1
- return identity_op
- wrapped_outputs = [augmented_identity(arg) for arg in args]
+class _LiteSingleOperand(_LiteOperand):
+ """A simple operand that is non-aggregated (i.e. most hints)."""
- if not self._stored_attrs:
- for key, value in self._attrs_to_store_later.iteritems():
- self._setattr(wrapped_outputs[0], "_tflite_attr_" + key, value)
- self._stored_attrs = True
+ def __init__(self, node):
+ _LiteOperand.__init__(self)
+ self.node = node
+ self.name = _tensor_name_base(node.name)
- return wrapped_outputs
+ def flatten(self):
+ return [self.name]
+
+ def aggregate_and_return_name_for_input(self, out_graphdef):
+ return self.name
+
+ def aggregate_and_return_name_for_output(self, fused_op_name, index,
+ out_graphdef):
+ output_node = _copy.deepcopy(self.node)
+ del output_node.input[:]
+ output_node.input.append(_tensorflow_output_name(fused_op_name, index))
+ out_graphdef.node.extend([output_node])
+ return self.node.attr["type"].i
+
+ def __str__(self):
+ return str(self.name)
+
+
+class _LiteAggregateOperand(_LiteOperand):
+ """An operand for a tflite hint function that is aggregated from many.
+
+ For example, an LSTM is a grid of operators that are all related. Inputs
+ going into them may need to be fused, so they should all be tracked as
+ related arguments.
+ """
+
+ def __init__(self, aggregation):
+ _LiteOperand.__init__(self)
+ self.aggregation = aggregation
+ self.names = {}
+ self.nodes = {}
+ self.flattened = None
+
+ def add(self, sort, node):
+ self.names[sort] = _tensor_name_base(node.name)
+ self.nodes[sort] = node
+
+ def flatten_nodes(self):
+ """Return a list of all the node protos in aggregation sorted order."""
+ if not self.flattened:
+ self.flattened = [None] * len(self.nodes)
+ for idx, node in _six.iteritems(self.nodes):
+ self.flattened[idx] = node
+ for n in self.nodes:
+ if n is None:
+ raise RuntimeError("Aggregate was missing argument.")
+ if self.aggregation == OpHint.AGGREGATE_FIRST:
+ self.flattened = self.flattened[:1]
+ elif self.aggregation == OpHint.AGGREGATE_LAST:
+ self.flattened = self.flattened[-1:]
+ elif self.aggregation == OpHint.AGGREGATE_STACK:
+ pass
+ else:
+ raise ValueError(
+ "Invalid aggregation type %r specified" % self.aggregation)
+ return self.flattened
+
+ def flatten(self):
+ """Return a list of all node names in aggregation sorted sorter."""
+ return [_tensor_name_base(x.name) for x in self.flatten_nodes()]
+
+ def aggregate_and_return_name_for_input(self, out_graphdef):
+ """This adds the nodes to out_graphdef and returns an aggregated output.
+
+ In particular, if you have 4 inputs to a hint stub, this will be the
+ node that you can use as an output. I.e. you have 4 timesteps from a
+ static rnn, then a fused UnidriecitonalLSTM will expect 1 input with
+ all 4 time steps. So here we make a pack and return the output name of
+ that pack.
+
+ Args:
+ out_graphdef: A graphdef that is ready to have this input added.
+
+ Returns:
+ The name of a pack that aggregates this node.
+ """
+ flattened = self.flatten_nodes()
+ if len(flattened) == 1:
+ return _tensor_name_base(flattened[0].name)
+ else:
+ new_node = _node_def_pb2.NodeDef()
+ new_node.op = "Pack"
+ new_node.name = "OpHintStack-%s" % flattened[0].name
+ new_node.attr["N"].i = len(flattened)
+ new_node.attr["T"].type = flattened[0].attr["T"].type
+ for discrete in flattened:
+ new_node.input.append(_tensor_name_base(discrete.name))
+ out_graphdef.node.extend([new_node])
+ return new_node.name
+
+ def aggregate_and_return_name_for_output(self, fused_op_name, output_index,
+ out_graphdef):
+ """This adds to `out_graphdef` all the unaggregated outputs.
+
+ I.e. we are outputting from a fused stub, but we need to make it compatible
+ with the unfused original graph so we insert an unpack. Ideally in a later
+ stage the unpack -> pack sequences will be removed.
+
+ Args:
+ fused_op_name: The name of the stub we are in the process of fusing.
+ output_index: The output output_index this object represents.
+ out_graphdef: The graphdef we are in the process of buildings
+
+ Returns:
+ The type of the aggregated output (so we can finish building the stub
+ op).
+ """
+ flattened = self.flatten_nodes()
+ if len(flattened) == 1:
+ temp_op = _LiteSingleOperand(flattened[0])
+ return temp_op.aggregate_and_return_name_for_output(
+ fused_op_name, output_index, out_graphdef)
+ else:
+ stack_node = _node_def_pb2.NodeDef()
+ stack_node.op = "Unpack"
+ stack_node.name = "OpHintUnstack-%s" % flattened[0].name
+ stack_node.attr["num"].i = len(flattened)
+ output_type = flattened[0].attr["T"].type
+ stack_node.attr["T"].type = output_type
+ stack_node.input.append(_tensorflow_output_name(
+ fused_op_name, output_index))
+ out_graphdef.node.extend([stack_node])
+
+ for idx, discrete in enumerate(flattened):
+ output_node = _copy.deepcopy(discrete)
+ del output_node.input[:]
+ output_node.input.append(_tensorflow_output_name(stack_node.name, idx))
+ out_graphdef.node.extend([output_node])
+
+ return output_type
+
+ def __str__(self):
+ s = "\t\t\tAGGREGATE %s\n" % self.aggregation
+ for sort, val in self.names.iteritems():
+ s += "\t\t\t%d: %s\n" % (sort, val)
+ return s
class _LiteFuncCall(object):
@@ -212,46 +598,87 @@ class _LiteFuncCall(object):
self.uuid = None
self.params = {}
+ def flattened_inputs_and_outputs(self):
+ """Return a list of inputs and outputs in a flattened format.
+
+ Returns:
+ Tuple of (inputs, outputs). where input and output i a list of names.
+ """
+ def _flatten(input_or_output_dict):
+ flattened_items = []
+ for item in input_or_output_dict.values():
+ flattened_items.extend(item.flatten())
+ return flattened_items
+
+ return _flatten(self.inputs), _flatten(self.outputs)
+
def __str__(self):
- return "tflite function %s call %s\n\tinputs: %r\n\toutputs: %r" % (
- self.function_name, self.uuid, self.inputs, self.outputs)
+ def format_args(items):
+ s = ""
+ for idx, item in items.iteritems():
+ s += ("\t\t%d:\n" % idx) + str(item)
+ return s
+
+ inputs_str = "\tInputs\n" + format_args(self.inputs)
+ outputs_str = "\tOutputs\n" + format_args(self.outputs)
+ return ("tflite function %s call %s\n\tinputs:\n\t\t%s\n\toutputs:\n\t\t%s"
+ % (self.function_name, self.uuid, inputs_str, outputs_str))
-def _find_all_hints_in_graph_def(session):
+
+def _find_all_hints_in_graph_def(graphdef):
"""Look at the current default graph and return a list of LiteFuncCall objs.
Args:
- session: A TensorFlow session that contains the graph to convert.
+ graphdef: A TensorFlow graph_def to look for LiteFuncCalls.
Returns:
a list of `LifeFuncCall` objects in the form
"""
func_calls = _collections.defaultdict(_LiteFuncCall)
- seen_ops = set()
-
- for op in session.graph.get_operations():
- for operand in _itertools.chain(op.inputs, op.outputs):
- if operand in seen_ops:
- continue
- seen_ops.add(operand)
- attr = operand.op.node_def.attr
- uuid = attr[OpHint.FUNCTION_UUID_ATTR].s
- if OpHint.FUNCTION_UUID_ATTR not in attr:
- continue
- call_def = func_calls[uuid]
- call_def.uuid = uuid
- if OpHint.FUNCTION_UUID_ATTR in attr:
- call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s
- if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr:
- call_def.inputs[attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i] = operand
- if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr:
- call_def.outputs[attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i] = operand
-
- for a in attr:
- if a.startswith("_tflite_attr_"):
- # TODO(aselle): Remember the attribute tensors so we can put them
- # in collapse.
- call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor
+
+ for node in graphdef.node:
+ attr = node.attr
+ # This is an op hint if it has a FUNCTION_UUID_ATTR, otherwise skip
+ uuid = attr[OpHint.FUNCTION_UUID_ATTR].s
+ if (OpHint.FUNCTION_UUID_ATTR not in attr
+ or not attr[OpHint.FUNCTION_UUID_ATTR].s):
+ continue
+
+ # Start building function
+ call_def = func_calls[uuid]
+ call_def.uuid = uuid
+ call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s
+ # Get sorting and aggregation information
+
+ sort = (attr[OpHint.FUNCTION_SORT_INDEX_ATTR].i
+ if OpHint.FUNCTION_SORT_INDEX_ATTR in attr else None)
+ if sort == -1: sort = None
+ aggregation = None
+ if OpHint.FUNCTION_AGGREGATE_ATTR in attr:
+ aggregation = attr[OpHint.FUNCTION_AGGREGATE_ATTR].s
+
+ # Add the input or output
+ def put_operand(stuff, index, sort, operand, aggregation):
+ """Add a given index into the function structure."""
+ if sort is None:
+ stuff[index] = _LiteSingleOperand(operand)
+ else:
+ if index not in stuff:
+ stuff[index] = _LiteAggregateOperand(aggregation)
+ stuff[index].add(sort, operand)
+
+ if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr:
+ put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i,
+ sort, node, aggregation)
+ if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr:
+ put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i,
+ sort, node, aggregation)
+
+ # Remember attributes
+ for a in attr:
+ if a.startswith("_tflite_attr_"):
+ call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor
return func_calls
@@ -267,42 +694,305 @@ def _tensor_name_base(full_tensor_name):
Returns:
A name without any device assignment.
"""
- return full_tensor_name.name.split(":")[0]
+ if full_tensor_name.startswith("^"):
+ return full_tensor_name[1:]
+ return full_tensor_name.split(":")[0]
+
+
+def _tensorflow_output_name(tensor_name, output_index):
+ return tensor_name if output_index == 0 else "%s:%d" % (tensor_name,
+ output_index)
+
+
+# TODO(aselle): This should be converted to grappler in the future.
+def _check_subgraph_closed(n, reachable_by_input, input_nodes_set,
+ name_to_input_name):
+ """Checks to make sure node only connects to predecessor graph through inputs.
+
+ Args:
+ n: Node to check
+ reachable_by_input: Nodes that are reachable by all inputs of subgraph
+ input_nodes_set: The set of nodes that are "inputs".
+ name_to_input_name: Maps from name to the list of inputs.
+
+ Raises:
+ TypeError: If the given node uses items past inputs directly.
+ """
+ next_to_visit = [n]
+ visited = set()
+ while next_to_visit:
+ current_node = next_to_visit.pop()
+ visited.add(current_node)
+ if (current_node in reachable_by_input
+ and current_node not in input_nodes_set):
+ raise TypeError(
+ "Node %s uses input %s not in input_nodes." % (n, current_node))
+ if current_node not in input_nodes_set:
+ next_to_visit += [
+ input_node for input_node in name_to_input_name[current_node]
+ if input_node not in visited
+ ]
+
+
+# TODO(aselle): This should be converted to grappler in the future.
+def _convert_single_op_hint_to_stub(call, graph_def):
+ """Given a graph_def, converts `call` into a stub and returns a new graph_def.
+ Args:
+ call: A single function call to be converted.
+ graph_def: A graph_def to use as input (that hass call obviously).
+ Returns:
+ A new transformed graph-def that has call as a stub (single op).
-def convert_op_hints_to_stubs(session):
+ Note: after this process, the graph_def can no longer be loaded into
+ the tensorflow runtime, so all future manipulations are done in graph_def
+ level.
+ """
+ name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(
+ graph_def)
+ input_names, output_names = call.flattened_inputs_and_outputs()
+
+ reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name)
+ reachable_by_output = _bfs_for_reachable_nodes(output_names,
+ name_to_input_name)
+ input_nodes_set = set(input_names)
+ output_nodes_set = set(output_names)
+ nodes_after_fuse = []
+ nodes_deleted_by_fuse = set()
+ # Classify each node. We want to keep everything reachable by input, but
+ # we don't know if things that are not reachable by output or input (things
+ # after fusing).
+ for node in graph_def.node:
+ n = _tensor_name_base(node.name)
+ if n in reachable_by_output:
+ if n not in reachable_by_input and n not in output_nodes_set:
+ # n is an internal node. Check to make sure it is really internal.
+ # TODO(aselle): this could be done more efficiently by flooding
+ # the graph first.
+ _check_subgraph_closed(n, reachable_by_input, input_nodes_set,
+ name_to_input_name)
+ nodes_deleted_by_fuse.add(n)
+ elif n not in reachable_by_input:
+ # n is a node that after all the fusings, so keep it.
+ nodes_after_fuse.append(n)
+ else:
+ # n is a node that is randomly in the graph but not connected to
+ # the chain of dependencies.
+ pass
+
+ # Make a new graphdef with all the pre-input and input nodes
+ out = _graph_pb2.GraphDef()
+ reachable_by_input_sorted = sorted(
+ list(reachable_by_input), key=lambda n: name_to_seq_num[n])
+ for node in reachable_by_input_sorted:
+ out.node.extend([_copy.deepcopy(name_to_node[node])])
+
+ # Create any stacks to aggregate arguments into to a single input
+ # i.e. for static_rnn's.
+ # TODO(aselle): Check that the inputs are complete i.e. 0 to n-1
+ sorted_input_indices = list(call.inputs.keys())
+ sorted_input_indices.sort()
+ sorted_output_indices = list(call.outputs.keys())
+ sorted_output_indices.sort()
+ new_node = _node_def_pb2.NodeDef()
+ # Delegate to each operand to produce the proper new input for this stub node.
+ # In particular, an aggregate input will now be a Pack of some previously
+ # non-fused things.
+ for input_index in sorted_input_indices:
+ inputs = call.inputs[input_index]
+ new_node.input.append(inputs.aggregate_and_return_name_for_input(out))
+ new_node.attr[OpHint.TFLITE_INPUT_INDICES].list.i.extend(sorted_input_indices)
+
+ # Ceate the function
+ new_node.op = call.function_name
+ new_node.name = call.uuid
+ out.node.extend([new_node])
+
+ # Now call each output argument to give them a chance to make the proper
+ # output type and add it to our new_node.
+ output_dtypes = []
+ for output_index in sorted_output_indices:
+ output = call.outputs[output_index]
+ output_dtype = (
+ output.aggregate_and_return_name_for_output(new_node.name, output_index,
+ out))
+ output_dtypes.append(output_dtype)
+ new_node.attr["_output_types"].list.type[:] = output_dtypes
+ # TODO(aselle): what is right here?
+ new_node.attr["_output_quantized"].b = False
+
+ # Add post output nodes that do not depend on the outputs
+ for n in nodes_after_fuse:
+ should_keep = True
+ for input_name in name_to_input_name[n]:
+ if input_name in nodes_deleted_by_fuse:
+ should_keep = False
+ if should_keep:
+ out.node.extend([_copy.deepcopy(name_to_node[n])])
+
+ # Misc. graph_def data that needs copying.
+ out.library.CopyFrom(graph_def.library)
+ out.versions.CopyFrom(graph_def.versions)
+
+ return out
+
+
+# TODO(aselle): This should be converted to grappler in the future.
+def _remove_one_redundant_stack_unstack(in_graph_def):
+ """Removes a stack->unstack pattern from in_graph_def in a returned graph.
+
+ Args:
+ in_graph_def: Graph def to use as input.
+ Returns:
+ Simplified tuple (graph_def, changed_something) where changed_something
+ is true if anything was done.
+ """
+ name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(
+ in_graph_def)
+ del name_to_seq_num
+
+ # TODO(aselle): Make this not hardcoded.
+ do_generic_pack_unpack = True
+
+ out = _graph_pb2.GraphDef()
+ out.library.CopyFrom(in_graph_def.library)
+ out.versions.CopyFrom(in_graph_def.versions)
+ for n in in_graph_def.node:
+ node_name = _tensor_name_base(n.name)
+ if not node_name.startswith("OpHintStack") and not n.op.startswith("Pack"):
+ continue
+ next_to_visit = [node_name]
+ visited = set()
+
+ unpack_nodes = set()
+ pack_node = node_name
+
+ # Find a pattern of unstack connected to a stack (with identities
+ # in between.
+ matches_pattern = True
+ is_hint_created_stack = False
+ while next_to_visit:
+ current_node_name = next_to_visit[0]
+ visited.add(current_node_name)
+ del next_to_visit[0]
+ node = name_to_node[current_node_name]
+ is_op_hint_stack = node.name.startswith("OpHintStack")
+ is_op_hint_unstack = node.name.startswith("OpHintUnstack")
+ if (node.op == "Identity" or is_op_hint_stack
+ or (do_generic_pack_unpack and node.op == "Pack")):
+ is_hint_created_stack |= is_op_hint_stack
+ next_to_visit += [
+ input_node for input_node in name_to_input_name[current_node_name]
+ if input_node not in visited
+ ]
+ elif (is_op_hint_unstack
+ or (do_generic_pack_unpack and node.op == "Unpack")):
+ unpack_nodes.add(node.name)
+ is_hint_created_stack &= is_op_hint_unstack
+ else:
+ matches_pattern = False
+ break
+ visited.add(node.name)
+
+ if matches_pattern and len(unpack_nodes) == 1:
+ pack_node = node_name
+
+ # Check to see if anyone depends on the intermediate identity or the
+ # Unstacked form
+ no_external_dependency = True
+ for other_n in in_graph_def.node:
+ if other_n.name in visited: continue
+ for input_tensor in name_to_input_name[other_n.name]:
+ input_op = _tensor_name_base(input_tensor)
+ if input_op in visited and input_op != pack_node:
+ no_external_dependency = False
+ # Proceed with the substitution if the stack/unstack pair was created
+ # through hints, or that it was not, but nobody is consuming things
+ # between the stack and unstack.
+ if is_hint_created_stack or no_external_dependency:
+ end = unpack_nodes.pop()
+ end_input = name_to_node[end].input[0]
+ # All nodes that depend on the final stack need to be redone to use
+ for other_n in in_graph_def.node:
+ node_name = _tensor_name_base(other_n.name)
+ if node_name not in visited:
+ new_node = _copy.deepcopy(other_n)
+ new_node.input[:] = [
+ (end_input if stripped == pack_node else
+ non_stripped) for stripped, non_stripped in zip(
+ name_to_input_name[node_name], new_node.input[:])
+ ]
+ out.node.extend([new_node])
+ return out, True
+ return in_graph_def, False
+
+
+def _remove_redundant_stack_unstack(graph_def):
+ curr = graph_def
+ del graph_def
+ changed_stuff = True
+ while changed_stuff:
+ curr, changed_stuff = _remove_one_redundant_stack_unstack(curr)
+ return curr
+
+
+def _convert_op_hints_to_stubs_helper(
+ graph_def, write_callback=lambda sess, graph_def: None):
+ """Converts a graph_def to a new graph_def where all op hints are stubbed.
+
+ Args:
+ graph_def: A graph def that we should convert.
+ write_callback: A function pointer that can be used to write intermediate
+ steps of graph transformation (optional).
+ Returns:
+ A new stubbed graph_def.
+ """
+
+ hints = _find_all_hints_in_graph_def(graph_def)
+ curr_graph_def = graph_def
+ del graph_def # prevent using graph_def again (common source of error)
+ for hint in _six.itervalues(hints):
+ curr_graph_def = _convert_single_op_hint_to_stub(
+ hint, curr_graph_def)
+ write_callback(curr_graph_def, "initial")
+ # The stubbing process can create stacks/unstacks in the case of LSTMs
+ # remove them.
+ curr_graph_def = _remove_redundant_stack_unstack(curr_graph_def)
+ return curr_graph_def
+
+
+def convert_op_hints_to_stubs(session=None,
+ graph_def=None,
+ write_callback=lambda graph_def, comments: None):
"""Converts a graphdef with LiteOp hints into stub operations.
This is used to prepare for toco conversion of complex intrinsic usages.
+ Note: only one of session or graph_def should be used, not both.
Args:
session: A TensorFlow session that contains the graph to convert.
+ graph_def: A graph def that we should convert.
+ write_callback: A function pointer that can be used to write intermediate
+ steps of graph transformation (optional).
Returns:
A new graphdef with all ops contained in OpHints being replaced by
a single op call with the right parameters.
+ Raises:
+ ValueError: If both session and graph_def are provided.
"""
- hints = _find_all_hints_in_graph_def(session)
- current_graph_def = session.graph_def
- for call in hints.values():
- input_names = [None] * len(call.inputs)
- output_names = [None] * len(call.outputs)
- output_dtypes = [None] * len(call.outputs)
- output_quantized = False
- for input_index, tensor in call.inputs.items():
- input_names[input_index] = _tensor_name_base(tensor)
- for output_index, tensor in call.outputs.items():
- output_names[output_index] = _tensor_name_base(tensor)
- output_dtypes[output_index] = tensor.dtype.as_datatype_enum
- # TODO(aselle): Support quantized flag properly
- current_graph_def = _framework.fuse_op(
- current_graph_def, input_names, output_names, output_dtypes,
- output_quantized, call.uuid, call.function_name)
- for node in current_graph_def.node:
- if node.name == call.uuid:
- for param, tensor in call.params.items():
- node.attr[param].tensor.CopyFrom(tensor)
- return current_graph_def
-
-
-_allowed_symbols = ["OpHint", "convert_op_hints_to_stubs"]
+
+ if session is not None and graph_def is not None:
+ raise ValueError("Provide only one of session and graph_def.")
+
+ if session is not None:
+ return _convert_op_hints_to_stubs_helper(session.graph_def, write_callback)
+ elif graph_def is not None:
+ return _convert_op_hints_to_stubs_helper(graph_def, write_callback)
+ else:
+ raise ValueError("Must specify session or graph_def as input.")
+
+
+_allowed_symbols = [
+ "OpHint", "convert_op_hints_to_stubs", "convert_op_hints_to_stubs_new"
+]
remove_undocumented(__name__, _allowed_symbols)
diff --git a/tensorflow/contrib/lite/python/tflite_convert.py b/tensorflow/contrib/lite/python/tflite_convert.py
index d17482e601..7d7a4ba94a 100644
--- a/tensorflow/contrib/lite/python/tflite_convert.py
+++ b/tensorflow/contrib/lite/python/tflite_convert.py
@@ -47,6 +47,9 @@ def _get_toco_converter(flags):
Returns:
TocoConverter object.
+
+ Raises:
+ ValueError: Invalid flags.
"""
# Parse input and output arrays.
input_arrays = _parse_array(flags.input_arrays)
@@ -77,6 +80,9 @@ def _get_toco_converter(flags):
elif flags.keras_model_file:
converter_fn = lite.TocoConverter.from_keras_model_file
converter_kwargs["model_file"] = flags.keras_model_file
+ else:
+ raise ValueError("--graph_def_file, --saved_model_dir, or "
+ "--keras_model_file must be specified.")
return converter_fn(**converter_kwargs)
@@ -203,8 +209,9 @@ def _check_flags(flags, unparsed):
raise ValueError("--default_ranges_min and --default_ranges_max must be "
"used together")
- if flags.dump_graphviz_video and not flags.dump_graphviz:
- raise ValueError("--dump_graphviz_video must be used with --dump_graphviz")
+ if flags.dump_graphviz_video and not flags.dump_graphviz_dir:
+ raise ValueError("--dump_graphviz_video must be used with "
+ "--dump_graphviz_dir")
def run_main(_):
diff --git a/tensorflow/contrib/lite/rpi_makefile.inc b/tensorflow/contrib/lite/rpi_makefile.inc
deleted file mode 100644
index 832ef5824b..0000000000
--- a/tensorflow/contrib/lite/rpi_makefile.inc
+++ /dev/null
@@ -1,33 +0,0 @@
-# Settings for Raspberry Pi.
-ifeq ($(TARGET), RPI)
- ifeq ($(TARGET_ARCH), armv7)
- CXXFLAGS += \
- -march=armv7-a \
- -mfpu=neon-vfpv4 \
- -funsafe-math-optimizations \
- -ftree-vectorize
-
- CCFLAGS += \
- -march=armv7-a \
- -mfpu=neon-vfpv4 \
- -funsafe-math-optimizations \
- -ftree-vectorize
-
- LDFLAGS := \
- -Wl,--no-export-dynamic \
- -Wl,--exclude-libs,ALL \
- -Wl,--gc-sections \
- -Wl,--as-needed
- endif
-
- LIBS := \
- -lstdc++ \
- -lpthread \
- -lm \
- -ldl
-
- OBJDIR := $(OBJDIR)rpi_$(TARGET_ARCH)/
- LIBDIR := $(LIBDIR)rpi_$(TARGET_ARCH)/
- BINDIR := $(BINDIR)rpi_$(TARGET_ARCH)/
- DEPDIR := $(DEPDIR)rpi_$(TARGET_ARCH)/
-endif
diff --git a/tensorflow/contrib/lite/schema/upgrade_schema.py b/tensorflow/contrib/lite/schema/upgrade_schema.py
index e0b36d3d3e..a2ddf62950 100644
--- a/tensorflow/contrib/lite/schema/upgrade_schema.py
+++ b/tensorflow/contrib/lite/schema/upgrade_schema.py
@@ -99,9 +99,9 @@ class Converter(object):
# dispatch function table.
self._schemas.sort()
self._new_version, self._new_schema = self._schemas[-1][:2]
- self._upgrade_dispatch = dict(
- (version, dispatch)
- for version, unused1, unused2, dispatch in self._schemas)
+ self._upgrade_dispatch = {
+ version: dispatch
+ for version, unused1, unused2, dispatch in self._schemas}
def _Read(self, input_file, schema, raw_binary=False):
"""Read a tflite model assuming the given flatbuffer schema.
diff --git a/tensorflow/contrib/lite/string.h b/tensorflow/contrib/lite/string.h
index 7f8f4e851e..af3fadfcb3 100644
--- a/tensorflow/contrib/lite/string.h
+++ b/tensorflow/contrib/lite/string.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Abstract string. We don't want even absl at this level.
-#ifndef _THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_STRING_H_
-#define _THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_STRING_H_
+#ifndef TENSORFLOW_CONTRIB_LITE_STRING_H_
+#define TENSORFLOW_CONTRIB_LITE_STRING_H_
#include <string>
@@ -26,4 +26,4 @@ using std::string;
} // namespace tflite
-#endif // _THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_STRING_H_
+#endif // TENSORFLOW_CONTRIB_LITE_STRING_H_
diff --git a/tensorflow/contrib/lite/testing/BUILD b/tensorflow/contrib/lite/testing/BUILD
index a788d41ba7..89912fd116 100644
--- a/tensorflow/contrib/lite/testing/BUILD
+++ b/tensorflow/contrib/lite/testing/BUILD
@@ -162,11 +162,12 @@ cc_library(
":test_runner",
"//tensorflow/contrib/lite:builtin_op_data",
"//tensorflow/contrib/lite:framework",
+ "//tensorflow/contrib/lite/delegates/eager:delegate",
"//tensorflow/contrib/lite/kernels:builtin_ops",
],
)
-cc_test(
+tf_cc_test(
name = "tflite_driver_test",
size = "small",
srcs = ["tflite_driver_test.cc"],
diff --git a/tensorflow/contrib/lite/testing/generate_examples.py b/tensorflow/contrib/lite/testing/generate_examples.py
index 52ef0d5b86..597ee8fb1e 100644
--- a/tensorflow/contrib/lite/testing/generate_examples.py
+++ b/tensorflow/contrib/lite/testing/generate_examples.py
@@ -1255,6 +1255,140 @@ def make_conv_tests(zip_path):
make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)
+# Note: This is a regression test for a bug (b/112436267) that Toco incorrectly
+# fuses weights when multiple Conv2D/FULLY_CONNECTED ops share the same constant
+# weight tensor.
+def make_conv_with_shared_weights_tests(zip_path):
+ """Make a test where 2 Conv ops shared the same constant weight tensor."""
+
+ test_parameters = [{
+ "input_shape": [[1, 10, 10, 3]],
+ "filter_shape": [[3, 3]],
+ "strides": [[1, 1, 1, 1]],
+ "dilations": [[1, 1, 1, 1]],
+ "padding": ["SAME"],
+ "data_format": ["NHWC"],
+ "channel_multiplier": [1],
+ }]
+
+ def get_tensor_shapes(parameters):
+ input_shape = parameters["input_shape"]
+ filter_size = parameters["filter_shape"]
+ filter_shape = filter_size + [
+ input_shape[3], parameters["channel_multiplier"]
+ ]
+ return [input_shape, filter_shape]
+
+ def build_graph(parameters):
+ """Build a conv graph given `parameters`."""
+ input_shape, filter_shape = get_tensor_shapes(parameters)
+ input_tensor = tf.placeholder(
+ dtype=tf.float32, name="input", shape=input_shape)
+
+ # Construct a constant weights tensor which will be used by both Conv2D.
+ filter_tensor = tf.constant(
+ create_tensor_data(np.float32, filter_shape), dtype=tf.float32)
+ input_tensors = [input_tensor]
+
+ # Construct 2 Conv2D operations which use exactly the same input and
+ # weights.
+ result1 = tf.nn.conv2d(
+ input_tensor,
+ filter_tensor,
+ strides=parameters["strides"],
+ dilations=parameters["dilations"],
+ padding=parameters["padding"],
+ data_format=parameters["data_format"])
+ result2 = tf.nn.conv2d(
+ input_tensor,
+ filter_tensor,
+ strides=parameters["strides"],
+ dilations=parameters["dilations"],
+ padding=parameters["padding"],
+ data_format=parameters["data_format"])
+ # Add MUL ops after Conv2D ops. These MUL ops should be fused into the
+ # weights of Conv2D.
+ result1 = result1 * 2
+ result2 = result2 * 3
+ # Add the 2 results up.
+ out = result1 + result2
+ return input_tensors, [out]
+
+ def build_inputs(parameters, sess, inputs, outputs):
+ # Build list of input values either containing 1 tensor (input) or 2 tensors
+ # (input, filter) based on whether filter is constant or variable input.
+ input_shape, unused_filter_shape = get_tensor_shapes(parameters)
+ values = [create_tensor_data(np.float32, input_shape)]
+ return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))
+
+ make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)
+
+
+# Note: This is a regression test for a bug (b/112303004) that Toco incorrectly
+# transforms Conv into DepthwiseConv when two Conv ops share the same constant
+# weight tensor.
+def make_conv_to_depthwiseconv_with_shared_weights_tests(zip_path):
+ """Make a test where 2 Conv ops shared the same constant weight tensor."""
+
+ test_parameters = [{
+ "input_shape": [[1, 10, 10, 1]],
+ "filter_shape": [[3, 3]],
+ "strides": [[1, 1, 1, 1]],
+ "dilations": [[1, 1, 1, 1]],
+ "padding": ["SAME"],
+ "data_format": ["NHWC"],
+ "channel_multiplier": [3],
+ }]
+
+ def get_tensor_shapes(parameters):
+ input_shape = parameters["input_shape"]
+ filter_size = parameters["filter_shape"]
+ filter_shape = filter_size + [
+ input_shape[3], parameters["channel_multiplier"]
+ ]
+ return [input_shape, filter_shape]
+
+ def build_graph(parameters):
+ """Build a conv graph given `parameters`."""
+ input_shape, filter_shape = get_tensor_shapes(parameters)
+ input_tensor = tf.placeholder(
+ dtype=tf.float32, name="input", shape=input_shape)
+
+ # Construct a constant weights tensor which will be used by both Conv2D.
+ filter_tensor = tf.constant(
+ create_tensor_data(np.float32, filter_shape), dtype=tf.float32)
+ input_tensors = [input_tensor]
+
+ # Construct 2 Conv2D operations which use exactly the same input and
+ # weights.
+ result1 = tf.nn.conv2d(
+ input_tensor,
+ filter_tensor,
+ strides=parameters["strides"],
+ dilations=parameters["dilations"],
+ padding=parameters["padding"],
+ data_format=parameters["data_format"])
+ result2 = tf.nn.conv2d(
+ input_tensor,
+ filter_tensor,
+ strides=parameters["strides"],
+ dilations=parameters["dilations"],
+ padding=parameters["padding"],
+ data_format=parameters["data_format"])
+ # Add the 2 results up.
+ out = result1 + result2
+ return input_tensors, [out]
+
+ def build_inputs(parameters, sess, inputs, outputs):
+ # Build list of input values either containing 1 tensor (input) or 2 tensors
+ # (input, filter) based on whether filter is constant or variable input.
+ input_shape, unused_filter_shape = get_tensor_shapes(parameters)
+ values = [create_tensor_data(np.float32, input_shape)]
+ return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))
+
+ make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)
+
+
def make_depthwiseconv_tests(zip_path):
"""Make a set of tests to do convolution."""
diff --git a/tensorflow/contrib/lite/testing/generate_testspec.cc b/tensorflow/contrib/lite/testing/generate_testspec.cc
index f29c188e6c..62cbeccd33 100644
--- a/tensorflow/contrib/lite/testing/generate_testspec.cc
+++ b/tensorflow/contrib/lite/testing/generate_testspec.cc
@@ -114,7 +114,13 @@ bool GenerateTestSpecFromTensorflowModel(
// different set.
std::vector<string> input_values =
GenerateInputValues(input_layer, input_layer_type, input_layer_shape);
- if (input_values.empty()) return false;
+ if (input_values.empty()) {
+ std::cerr << "Unable to generate input values for the TensorFlow model. "
+ "Make sure the correct values are defined for "
+ "input_layer, input_layer_type, and input_layer_shape."
+ << std::endl;
+ return false;
+ }
// Run TensorFlow.
for (int j = 0; j < input_values.size(); j++) {
diff --git a/tensorflow/contrib/lite/testing/generated_examples_zip_test.cc b/tensorflow/contrib/lite/testing/generated_examples_zip_test.cc
index e475f256c0..e67fee2a1c 100644
--- a/tensorflow/contrib/lite/testing/generated_examples_zip_test.cc
+++ b/tensorflow/contrib/lite/testing/generated_examples_zip_test.cc
@@ -33,13 +33,18 @@ namespace testing {
namespace {
bool FLAGS_ignore_known_bugs = true;
-// TODO(b/71769302) zip_files_dir should have a more accurate default, if
-// possible
-string* FLAGS_zip_file_path = new string("./");
+// As archive file names are test-specific, no default is possible.
+//
+// This test supports input as both zip and tar, as a stock android image does
+// not have unzip but does have tar.
+string* FLAGS_zip_file_path = new string;
+string* FLAGS_tar_file_path = new string;
#ifndef __ANDROID__
string* FLAGS_unzip_binary_path = new string("/usr/bin/unzip");
+string* FLAGS_tar_binary_path = new string("/bin/tar");
#else
string* FLAGS_unzip_binary_path = new string("/system/bin/unzip");
+string* FLAGS_tar_binary_path = new string("/system/bin/tar");
#endif
bool FLAGS_use_nnapi = false;
bool FLAGS_ignore_unsupported_nnapi = false;
@@ -98,11 +103,11 @@ std::map<string, string> kBrokenTests = {
"77546240"},
};
-// Allows test data to be unzipped into a temporary directory and makes
+// Allows test data to be unarchived into a temporary directory and makes
// sure those temporary directories are removed later.
-class ZipEnvironment : public ::testing::Environment {
+class ArchiveEnvironment : public ::testing::Environment {
public:
- ~ZipEnvironment() override {}
+ ~ArchiveEnvironment() override {}
// Delete all temporary directories on teardown.
void TearDown() override {
@@ -114,15 +119,26 @@ class ZipEnvironment : public ::testing::Environment {
temporary_directories_.clear();
}
- // Unzip `zip` file into a new temporary directory `out_dir`.
- tensorflow::Status UnZip(const string& zip, string* out_dir) {
+ // Unarchive `archive` file into a new temporary directory `out_dir`.
+ tensorflow::Status UnArchive(const string& zip, const string& tar,
+ string* out_dir) {
string dir;
TF_CHECK_OK(MakeTemporaryDirectory(&dir));
tensorflow::SubProcess proc;
- string unzip_binary = *FLAGS_unzip_binary_path;
- TF_CHECK_OK(env->FileExists(unzip_binary));
- TF_CHECK_OK(env->FileExists(zip));
- proc.SetProgram(unzip_binary, {"unzip", "-d", dir, zip});
+ if (!zip.empty()) {
+ string unzip_binary = *FLAGS_unzip_binary_path;
+ TF_CHECK_OK(env->FileExists(unzip_binary));
+ TF_CHECK_OK(env->FileExists(zip));
+ proc.SetProgram(unzip_binary, {"unzip", "-d", dir, zip});
+ } else {
+ string tar_binary = *FLAGS_tar_binary_path;
+ TF_CHECK_OK(env->FileExists(tar_binary));
+ TF_CHECK_OK(env->FileExists(tar));
+ // 'o' needs to be explicitly set on Android so that
+ // untarring works as non-root (otherwise tries to chown
+ // files, which fails)
+ proc.SetProgram(tar_binary, {"tar", "xfo", tar, "-C", dir});
+ }
proc.SetChannelAction(tensorflow::CHAN_STDOUT, tensorflow::ACTION_PIPE);
proc.SetChannelAction(tensorflow::CHAN_STDERR, tensorflow::ACTION_PIPE);
if (!proc.Start())
@@ -156,15 +172,15 @@ class ZipEnvironment : public ::testing::Environment {
std::vector<string> temporary_directories_;
};
-// Return the singleton zip_environment.
-ZipEnvironment* zip_environment() {
- static ZipEnvironment* env = new ZipEnvironment;
+// Return the singleton archive_environment.
+ArchiveEnvironment* archive_environment() {
+ static ArchiveEnvironment* env = new ArchiveEnvironment;
return env;
}
-// Read the manifest.txt out of the unarchived zip file. Specifically
+// Read the manifest.txt out of the unarchived archive file. Specifically
// `original_file` is the original zip file for error messages. `dir` is
-// the temporary directory where the zip file has been unarchived and
+// the temporary directory where the archive file has been unarchived and
// `test_paths` is the list of test prefixes that were in the manifest.
// Note, it is an error for a manifest to contain no tests.
tensorflow::Status ReadManifest(const string& original_file, const string& dir,
@@ -190,12 +206,22 @@ tensorflow::Status ReadManifest(const string& original_file, const string& dir,
return tensorflow::Status::OK();
}
-// Get a list of tests from a zip file `zip_file_name`.
-std::vector<string> UnarchiveZipAndFindTestNames(const string& zip_file) {
+// Get a list of tests from either zip or tar file
+std::vector<string> UnarchiveAndFindTestNames(const string& zip_file,
+ const string& tar_file) {
+ if (zip_file.empty() && tar_file.empty()) {
+ TF_CHECK_OK(tensorflow::Status(tensorflow::error::UNKNOWN,
+ "Neither zip_file nor tar_file was given"));
+ }
string decompress_tmp_dir;
- TF_CHECK_OK(zip_environment()->UnZip(zip_file, &decompress_tmp_dir));
+ TF_CHECK_OK(archive_environment()->UnArchive(zip_file, tar_file,
+ &decompress_tmp_dir));
std::vector<string> stuff;
- TF_CHECK_OK(ReadManifest(zip_file, decompress_tmp_dir, &stuff));
+ if (!zip_file.empty()) {
+ TF_CHECK_OK(ReadManifest(zip_file, decompress_tmp_dir, &stuff));
+ } else {
+ TF_CHECK_OK(ReadManifest(tar_file, decompress_tmp_dir, &stuff));
+ }
return stuff;
}
@@ -223,8 +249,7 @@ TEST_P(OpsTest, RunZipTests) {
string message = test_driver.GetErrorMessage();
if (bug_number.empty()) {
if (FLAGS_use_nnapi && FLAGS_ignore_unsupported_nnapi && !result) {
- EXPECT_EQ(message, string("Failed to invoke NNAPI interpreter"))
- << message;
+ EXPECT_EQ(message, string("Failed to invoke interpreter")) << message;
} else {
EXPECT_TRUE(result) << message;
}
@@ -256,27 +281,34 @@ struct ZipPathParamName {
}
};
-INSTANTIATE_TEST_CASE_P(
- tests, OpsTest,
- ::testing::ValuesIn(UnarchiveZipAndFindTestNames(*FLAGS_zip_file_path)),
- ZipPathParamName());
+INSTANTIATE_TEST_CASE_P(tests, OpsTest,
+ ::testing::ValuesIn(UnarchiveAndFindTestNames(
+ *FLAGS_zip_file_path, *FLAGS_tar_file_path)),
+ ZipPathParamName());
} // namespace testing
} // namespace tflite
int main(int argc, char** argv) {
- ::testing::AddGlobalTestEnvironment(tflite::testing::zip_environment());
+ ::testing::AddGlobalTestEnvironment(tflite::testing::archive_environment());
std::vector<tensorflow::Flag> flags = {
tensorflow::Flag(
"ignore_known_bugs", &tflite::testing::FLAGS_ignore_known_bugs,
"If a particular model is affected by a known bug, the "
"corresponding test should expect the outputs to not match."),
- tensorflow::Flag("zip_file_path", tflite::testing::FLAGS_zip_file_path,
- "Required: Location of the test zip file."),
+ tensorflow::Flag(
+ "tar_file_path", tflite::testing::FLAGS_tar_file_path,
+ "Required (or zip_file_path): Location of the test tar file."),
+ tensorflow::Flag(
+ "zip_file_path", tflite::testing::FLAGS_zip_file_path,
+ "Required (or tar_file_path): Location of the test zip file."),
tensorflow::Flag("unzip_binary_path",
tflite::testing::FLAGS_unzip_binary_path,
- "Required: Location of a suitable unzip binary."),
+ "Location of a suitable unzip binary."),
+ tensorflow::Flag("tar_binary_path",
+ tflite::testing::FLAGS_tar_binary_path,
+ "Location of a suitable tar binary."),
tensorflow::Flag("use_nnapi", &tflite::testing::FLAGS_use_nnapi,
"Whether to enable the NNAPI delegate"),
tensorflow::Flag("ignore_unsupported_nnapi",
diff --git a/tensorflow/contrib/lite/testing/tf_driver.cc b/tensorflow/contrib/lite/testing/tf_driver.cc
index ec435ca60d..30381ba028 100644
--- a/tensorflow/contrib/lite/testing/tf_driver.cc
+++ b/tensorflow/contrib/lite/testing/tf_driver.cc
@@ -179,7 +179,9 @@ void TfDriver::Invoke() {
auto status = session_->Run({input_tensors_.begin(), input_tensors_.end()},
output_names_, {}, &output_tensors_);
if (!status.ok()) {
- Invalidate("Failed to run input data on graph");
+ Invalidate(
+ "Failed to run input data on graph. Make sure the correct value is "
+ "defined for the input and output arrays.");
}
}
diff --git a/tensorflow/contrib/lite/testing/tflite_diff_flags.h b/tensorflow/contrib/lite/testing/tflite_diff_flags.h
index 695c2a3de6..3874bc31d7 100644
--- a/tensorflow/contrib/lite/testing/tflite_diff_flags.h
+++ b/tensorflow/contrib/lite/testing/tflite_diff_flags.h
@@ -33,6 +33,7 @@ DiffOptions ParseTfliteDiffFlags(int* argc, char** argv) {
string input_layer_shape;
string output_layer;
int32_t num_runs_per_pass = 100;
+ string delegate;
} values;
std::vector<tensorflow::Flag> flags = {
@@ -42,18 +43,21 @@ DiffOptions ParseTfliteDiffFlags(int* argc, char** argv) {
"Path of tensorflow lite model."),
tensorflow::Flag("input_layer", &values.input_layer,
"Names of input tensors, separated by comma. Example: "
- "input_1,input_2"),
+ "input_1,input_2."),
tensorflow::Flag("input_layer_type", &values.input_layer_type,
"Data types of input tensors, separated by comma. "
- "Example: float,int"),
+ "Example: float,int."),
tensorflow::Flag(
"input_layer_shape", &values.input_layer_shape,
- "Shapes of input tensors, separated by colon. Example: 1,3,4,1:2"),
+ "Shapes of input tensors, separated by colon. Example: 1,3,4,1:2."),
tensorflow::Flag("output_layer", &values.output_layer,
- "Names of output tensors, separated by comma. Example "
- "output_1,output_2"),
+ "Names of output tensors, separated by comma. Example: "
+ "output_1,output_2."),
tensorflow::Flag("num_runs_per_pass", &values.num_runs_per_pass,
- "Number of full runs in each pass."),
+ "[optional] Number of full runs in each pass."),
+ tensorflow::Flag("delegate", &values.delegate,
+ "[optional] Delegate to use for executing ops. Must be "
+ "`{\"\", EAGER}`"),
};
bool no_inputs = *argc == 1;
@@ -61,6 +65,14 @@ DiffOptions ParseTfliteDiffFlags(int* argc, char** argv) {
if (!success || no_inputs || (*argc == 2 && !strcmp(argv[1], "--helpfull"))) {
fprintf(stderr, "%s", tensorflow::Flags::Usage(argv[0], flags).c_str());
return {};
+ } else if (values.tensorflow_model.empty() || values.tflite_model.empty() ||
+ values.input_layer.empty() || values.input_layer_type.empty() ||
+ values.input_layer_shape.empty() || values.output_layer.empty()) {
+ fprintf(stderr, "%s", tensorflow::Flags::Usage(argv[0], flags).c_str());
+ return {};
+ } else if (!(values.delegate == "" || values.delegate == "EAGER")) {
+ fprintf(stderr, "%s", tensorflow::Flags::Usage(argv[0], flags).c_str());
+ return {};
}
return {values.tensorflow_model,
@@ -69,7 +81,8 @@ DiffOptions ParseTfliteDiffFlags(int* argc, char** argv) {
Split<string>(values.input_layer_type, ","),
Split<string>(values.input_layer_shape, ":"),
Split<string>(values.output_layer, ","),
- values.num_runs_per_pass};
+ values.num_runs_per_pass,
+ values.delegate};
}
} // namespace testing
diff --git a/tensorflow/contrib/lite/testing/tflite_diff_util.cc b/tensorflow/contrib/lite/testing/tflite_diff_util.cc
index 19f34c0a51..c6ca796ac2 100644
--- a/tensorflow/contrib/lite/testing/tflite_diff_util.cc
+++ b/tensorflow/contrib/lite/testing/tflite_diff_util.cc
@@ -33,7 +33,7 @@ bool RunDiffTest(const DiffOptions& options, int num_invocations) {
options.input_layer_shape, options.output_layer)) {
return false;
}
- TfLiteDriver tflite_driver(/*use_nnapi=*/true);
+ TfLiteDriver tflite_driver(/*use_nnapi=*/true, options.delegate);
tflite_driver.LoadModel(options.tflite_model);
return tflite::testing::ParseAndRunTests(&tflite_stream, &tflite_driver);
}
diff --git a/tensorflow/contrib/lite/testing/tflite_diff_util.h b/tensorflow/contrib/lite/testing/tflite_diff_util.h
index 4ab2f230fd..f67992139f 100644
--- a/tensorflow/contrib/lite/testing/tflite_diff_util.h
+++ b/tensorflow/contrib/lite/testing/tflite_diff_util.h
@@ -44,6 +44,9 @@ struct DiffOptions {
// each of the passes. The first pass has a single inference, while the
// second pass does multiple inferences back to back.
int num_runs_per_pass;
+ // Path to the delegate library to be loaded in order to execute ops. Must be
+ // `{"", EAGER}`.
+ string delegate;
};
// Run a single TensorFLow Lite diff test with a given options.
diff --git a/tensorflow/contrib/lite/testing/tflite_driver.cc b/tensorflow/contrib/lite/testing/tflite_driver.cc
index 4d08fb5458..4dacf9c84b 100644
--- a/tensorflow/contrib/lite/testing/tflite_driver.cc
+++ b/tensorflow/contrib/lite/testing/tflite_driver.cc
@@ -17,6 +17,7 @@ limitations under the License.
#include <iostream>
#include "tensorflow/contrib/lite/builtin_op_data.h"
+#include "tensorflow/contrib/lite/delegates/eager/delegate.h"
#include "tensorflow/contrib/lite/testing/split.h"
namespace tflite {
@@ -135,7 +136,13 @@ class TfLiteDriver::Expectation {
size_t num_elements_;
};
-TfLiteDriver::TfLiteDriver(bool use_nnapi) : use_nnapi_(use_nnapi) {}
+TfLiteDriver::TfLiteDriver(bool use_nnapi, const string& delegate_name)
+ : use_nnapi_(use_nnapi) {
+ if (delegate_name == "EAGER") {
+ delegate_ = EagerDelegate::Create();
+ }
+}
+
TfLiteDriver::~TfLiteDriver() {}
void TfLiteDriver::AllocateTensors() {
@@ -165,6 +172,15 @@ void TfLiteDriver::LoadModel(const string& bin_file_path) {
}
interpreter_->UseNNAPI(use_nnapi_);
+ if (delegate_) {
+ if (interpreter_->ModifyGraphWithDelegate(delegate_.get(),
+ /*allow_dynamic_tensors=*/true) !=
+ kTfLiteOk) {
+ Invalidate("Unable to the build graph using the delegate");
+ return;
+ }
+ }
+
must_allocate_tensors_ = true;
}
diff --git a/tensorflow/contrib/lite/testing/tflite_driver.h b/tensorflow/contrib/lite/testing/tflite_driver.h
index 5493ba3631..aed35f877d 100644
--- a/tensorflow/contrib/lite/testing/tflite_driver.h
+++ b/tensorflow/contrib/lite/testing/tflite_driver.h
@@ -17,6 +17,7 @@ limitations under the License.
#include <map>
+#include "tensorflow/contrib/lite/delegates/eager/delegate.h"
#include "tensorflow/contrib/lite/interpreter.h"
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
@@ -28,7 +29,7 @@ namespace testing {
// A test runner that feeds inputs into TF Lite and verifies its outputs.
class TfLiteDriver : public TestRunner {
public:
- explicit TfLiteDriver(bool use_nnapi);
+ explicit TfLiteDriver(bool use_nnapi, const string& delegate = "");
~TfLiteDriver() override;
void LoadModel(const string& bin_file_path) override;
@@ -52,6 +53,7 @@ class TfLiteDriver : public TestRunner {
class Expectation;
+ std::unique_ptr<EagerDelegate> delegate_;
bool use_nnapi_ = false;
std::unique_ptr<FlatBufferModel> model_;
std::unique_ptr<Interpreter> interpreter_;
diff --git a/tensorflow/contrib/lite/toco/BUILD b/tensorflow/contrib/lite/toco/BUILD
index 7243e584e9..02d0890a7a 100644
--- a/tensorflow/contrib/lite/toco/BUILD
+++ b/tensorflow/contrib/lite/toco/BUILD
@@ -242,9 +242,11 @@ cc_library(
"graph_transformations/resolve_constant_random_uniform.cc",
"graph_transformations/resolve_constant_range.cc",
"graph_transformations/resolve_constant_reshape.cc",
+ "graph_transformations/resolve_constant_select.cc",
"graph_transformations/resolve_constant_shape_or_rank.cc",
"graph_transformations/resolve_constant_slice.cc",
"graph_transformations/resolve_constant_strided_slice.cc",
+ "graph_transformations/resolve_constant_tile.cc",
"graph_transformations/resolve_constant_transpose.cc",
"graph_transformations/resolve_constant_unary.cc",
"graph_transformations/resolve_fake_quant_args_from_vars.cc",
@@ -361,6 +363,7 @@ cc_library(
"dump_graphviz.h",
"tooling_util.h",
],
+ copts = tf_copts(),
visibility = ["//visibility:public"],
deps = [
":model",
diff --git a/tensorflow/contrib/lite/toco/allocate_transient_arrays.cc b/tensorflow/contrib/lite/toco/allocate_transient_arrays.cc
index 1f3ea2e1c7..18c904c6d4 100644
--- a/tensorflow/contrib/lite/toco/allocate_transient_arrays.cc
+++ b/tensorflow/contrib/lite/toco/allocate_transient_arrays.cc
@@ -106,6 +106,17 @@ class Allocator {
// Core allocation routine.
void Allocate(std::size_t size, Alloc* result) {
+ if (size == 0) {
+ // zero-sized arrays get a dummy alloc of (0, 0) that does not
+ // need to be kept in the books (no need to insert that into
+ // live_allocs_).
+ // Note: zero-sized arrays shouldn't exist, but handling that case
+ // here allows such pathological cases to get a cleaner error message
+ // later instead of generating spurious allocator failures.
+ result->start = 0;
+ result->end = 0;
+ return;
+ }
// Naive algorithm: pick the first gap between live allocations,
// that is wide enough for the new array.
std::size_t pos = 0;
@@ -128,6 +139,11 @@ class Allocator {
}
void Deallocate(const Alloc& a) {
+ // Special-case dummy allocs for zero-sized arrays.
+ if (a.start == 0 && a.end == 0) {
+ // Nothing needs to be done, these aren't kept in the books.
+ return;
+ }
auto iter = std::lower_bound(live_allocs_.begin(), live_allocs_.end(), a);
CHECK(iter != live_allocs_.end());
CHECK(*iter == a);
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/convert_pure_conv_to_depthwise.cc b/tensorflow/contrib/lite/toco/graph_transformations/convert_pure_conv_to_depthwise.cc
index 1ea83abf8e..e88839be5d 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/convert_pure_conv_to_depthwise.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/convert_pure_conv_to_depthwise.cc
@@ -48,7 +48,17 @@ bool ConvertPureConvToDepthwise::Run(Model* model, std::size_t op_index) {
// dimension.
return false;
}
- auto& weights_array = model->GetArray(conv_op->inputs[1]);
+
+ const auto& weights_name = conv_op->inputs[1];
+ if (CountOpsWithInput(*model, weights_name) > 1) {
+ // TODO(yunluli): Come up with a way to do the weights shuffling only once.
+ AddMessageF(
+ "Not changing %s to DepthwiseConv because the weights is consumed by "
+ "another op.",
+ LogName(*conv_op));
+ return false;
+ }
+ auto& weights_array = model->GetArray(weights_name);
if (!weights_array.buffer) {
// Yield until the weights are resolved as a constant array.
return false;
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/fuse_binary_into_preceding_affine.cc b/tensorflow/contrib/lite/toco/graph_transformations/fuse_binary_into_preceding_affine.cc
index 76c6be00d4..b324631579 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/fuse_binary_into_preceding_affine.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/fuse_binary_into_preceding_affine.cc
@@ -274,8 +274,14 @@ bool FuseBinaryIntoPrecedingAffine::Run(Model* model, std::size_t op_index) {
return false;
}
- const auto& weights = model->GetArray(preceding_op->inputs[1]);
- const auto& bias = model->GetArray(preceding_op->inputs[2]);
+ const auto& weights_name = preceding_op->inputs[1];
+ const auto& bias_name = preceding_op->inputs[2];
+ const auto& weights = model->GetArray(weights_name);
+ const auto& bias = model->GetArray(bias_name);
+ const int count_ops_consuming_bias = CountOpsWithInput(*model, bias_name);
+ const int count_ops_consuming_weights =
+ CountOpsWithInput(*model, weights_name);
+
if (binary_op->type == OperatorType::kAdd ||
binary_op->type == OperatorType::kSub) {
if (!bias.buffer) {
@@ -285,6 +291,13 @@ bool FuseBinaryIntoPrecedingAffine::Run(Model* model, std::size_t op_index) {
LogName(*binary_op), LogName(*preceding_op));
return false;
}
+ if (count_ops_consuming_bias > 1) {
+ AddMessageF(
+ "Not fusing %s because the bias of the preceding %s is consumed by "
+ "another op",
+ LogName(*binary_op), LogName(*preceding_op));
+ return false;
+ }
} else {
if (!weights.buffer || !bias.buffer) {
AddMessageF(
@@ -293,6 +306,13 @@ bool FuseBinaryIntoPrecedingAffine::Run(Model* model, std::size_t op_index) {
LogName(*binary_op), LogName(*preceding_op));
return false;
}
+ if (count_ops_consuming_weights > 1 || count_ops_consuming_bias > 1) {
+ AddMessageF(
+ "Not fusing %s because the weights or bias of the preceding %s is "
+ "consumed by another op",
+ LogName(*binary_op), LogName(*preceding_op));
+ return false;
+ }
}
int count_ops_consuming_output =
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h b/tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h
index 8d9a4c4700..99f4a7d8f6 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h
+++ b/tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h
@@ -190,6 +190,8 @@ DECLARE_GRAPH_TRANSFORMATION(ResolveConstantSlice)
DECLARE_GRAPH_TRANSFORMATION(ResolveConstantStridedSlice)
DECLARE_GRAPH_TRANSFORMATION(ResolveConstantFill)
DECLARE_GRAPH_TRANSFORMATION(ResolveConstantGather)
+DECLARE_GRAPH_TRANSFORMATION(ResolveConstantSelect)
+DECLARE_GRAPH_TRANSFORMATION(ResolveConstantTile)
DECLARE_GRAPH_TRANSFORMATION(ResolveMultiplyByZero)
DECLARE_GRAPH_TRANSFORMATION(Dequantize)
DECLARE_GRAPH_TRANSFORMATION(UnpartitionEmbeddingLookup)
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/hardcode_min_max.cc b/tensorflow/contrib/lite/toco/graph_transformations/hardcode_min_max.cc
index d26c3b2878..502de88f7c 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/hardcode_min_max.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/hardcode_min_max.cc
@@ -274,6 +274,19 @@ bool PropagateMinMaxAmongArrays(Model* model,
return changed;
}
+bool HardcodeMinMaxForReshape(Model* model, Operator* op) {
+ Array& input = model->GetArray(op->inputs[0]);
+ Array& output = model->GetArray(op->outputs[0]);
+
+ // If input and output both exist or do not exist, do nothing.
+ if ((!input.minmax && !output.minmax) || (input.minmax && output.minmax)) {
+ return false;
+ }
+
+ // Otherwise propagate info amongst the input and output array.
+ return PropagateMinMaxAmongArrays(model, {op->inputs[0], op->outputs[0]});
+}
+
bool HardcodeMinMaxForLstmCell(Model* model, Operator* op) {
CHECK_EQ(op->inputs.size(), LstmCellOperator::NUM_INPUTS);
CHECK_EQ(op->outputs.size(), LstmCellOperator::NUM_OUTPUTS);
@@ -370,7 +383,6 @@ bool HardcodeMinMax::Run(Model* model, std::size_t op_index) {
case OperatorType::kSlice:
case OperatorType::kStridedSlice:
case OperatorType::kSqueeze:
- case OperatorType::kReshape:
case OperatorType::kExpandDims:
case OperatorType::kPad:
case OperatorType::kGather:
@@ -416,6 +428,10 @@ bool HardcodeMinMax::Run(Model* model, std::size_t op_index) {
changed = HardcodeMinMaxForLstmCell(model, op);
break;
+ case OperatorType::kReshape:
+ changed = HardcodeMinMaxForReshape(model, op);
+ break;
+
default:
break;
}
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc b/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc
index 9f5d8b9450..fc49fbda59 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc
@@ -48,20 +48,26 @@ void RerouteEdges(const string& from_array, const string& to_array,
} // namespace
bool RemoveTrivialPassthroughOp(GraphTransformation* transformation,
- Model* model, std::size_t op_index) {
+ Model* model, std::size_t op_index,
+ int input_index) {
const auto passthru_it = model->operators.begin() + op_index;
auto* passthru_op = passthru_it->get();
CHECK_EQ(passthru_op->outputs.size(), 1);
CHECK_GE(passthru_op->inputs.size(), 1);
- int count_nonconstant_input_arrays = 0;
- // We call 'main input' the unique nonconstant input array if there is one,
- // or else the 0-th input.
+
int main_input_array_index = 0;
- for (int i = 0; i < passthru_op->inputs.size(); i++) {
- if (!model->GetArray(passthru_op->inputs[i]).buffer) {
- count_nonconstant_input_arrays++;
- if (count_nonconstant_input_arrays == 1) {
- main_input_array_index = i;
+ if (input_index != -1) {
+ main_input_array_index = input_index;
+ } else {
+ // We call 'main input' the unique nonconstant input array if there is one,
+ // or else the 0-th input.
+ int count_nonconstant_input_arrays = 0;
+ for (int i = 0; i < passthru_op->inputs.size(); i++) {
+ if (!model->GetArray(passthru_op->inputs[i]).buffer) {
+ count_nonconstant_input_arrays++;
+ if (count_nonconstant_input_arrays == 1) {
+ main_input_array_index = i;
+ }
}
}
}
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.h b/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.h
index 9d448c3ee9..663704e5ac 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.h
+++ b/tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.h
@@ -50,7 +50,8 @@ namespace toco {
// and then discards it and returns true, or, if it's not trivial (if neither
// the input nor the output may be discarded), returns false.
bool RemoveTrivialPassthroughOp(GraphTransformation* transformation,
- Model* model, std::size_t op_index);
+ Model* model, std::size_t op_index,
+ int input_index = -1);
} // namespace toco
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_fake_quant.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_fake_quant.cc
index d395d7a6a0..f5f2f77460 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_fake_quant.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_fake_quant.cc
@@ -117,6 +117,7 @@ bool ResolveConstantFakeQuant::Run(Model* model, std::size_t op_index) {
&quantized_max);
if (fakequant_op->narrow_range) {
quantized_min++;
+ output_array.narrow_range = true;
}
// It is important for matching accuracy between TF training and TFLite
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_reshape.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_reshape.cc
index 41562ab393..a6f665b5f0 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_reshape.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_reshape.cc
@@ -100,13 +100,7 @@ bool ResolveConstantReshape::Run(Model* model, std::size_t op_index) {
AddMessageF("Resolving constant reshape of %s", LogName(*op));
- if (input_array.minmax) {
- output_array.GetOrCreateMinMax() = input_array.GetMinMax();
- }
- if (input_array.quantization_params) {
- output_array.GetOrCreateQuantizationParams() =
- input_array.GetQuantizationParams();
- }
+ CopyMinMaxAndQuantizationRelatedFields(input_array, &output_array);
// Erase input arrays if no longer used.
for (const auto& input : op->inputs) {
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_select.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_select.cc
new file mode 100644
index 0000000000..e880a3f44d
--- /dev/null
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_select.cc
@@ -0,0 +1,78 @@
+/* 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.
+==============================================================================*/
+#include <vector>
+
+#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
+#include "tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.h"
+#include "tensorflow/contrib/lite/toco/model.h"
+#include "tensorflow/contrib/lite/toco/tooling_util.h"
+#include "tensorflow/core/platform/logging.h"
+
+namespace toco {
+
+// Resolves a constant Select operation.
+//
+// This implementation is looking strictly for all-or-nothing on the select
+// condition. It's possible to enhance this by looking per-element and possibly
+// producing a Mul op.
+bool ResolveConstantSelect::Run(Model* model, std::size_t op_index) {
+ auto it = model->operators.begin() + op_index;
+ const auto* base_op = it->get();
+ if (base_op->type != OperatorType::kSelect) {
+ return false;
+ }
+ const auto* op = static_cast<const SelectOperator*>(base_op);
+
+ CHECK_GE(op->inputs.size(), 3);
+ CHECK_EQ(op->outputs.size(), 1);
+ auto& output_array = model->GetArray(op->outputs[0]);
+ if (output_array.data_type == ArrayDataType::kNone) {
+ // Yield until the output type has been set by PropagateArrayDataTypes.
+ return false;
+ }
+ if (!output_array.has_shape()) {
+ // Yield until the output shape has been set by PropagateFixedShapes.
+ return false;
+ }
+
+ // We require the cond input to be constant.
+ if (!IsConstantParameterArray(*model, op->inputs[0])) {
+ return false;
+ }
+ const Array& cond_array = model->GetArray(op->inputs[0]);
+ CHECK(cond_array.data_type == ArrayDataType::kBool)
+ << "Only bool conditions are supported";
+ const auto& cond_data = cond_array.GetBuffer<ArrayDataType::kBool>().data;
+ if (cond_data.empty()) {
+ return false;
+ }
+
+ // Check if the condition is the same for all elements.
+ bool cond_value = cond_data[0];
+ for (size_t i = 1; i < cond_data.size(); ++i) {
+ if (cond_data[i] != cond_value) {
+ AddMessageF(
+ "Cannot resolve %s as constant; cond_array has differing "
+ "per-element values",
+ LogName(*op));
+ return false;
+ }
+ }
+
+ // Pass-through the selected input.
+ return RemoveTrivialPassthroughOp(this, model, op_index, cond_value ? 1 : 2);
+}
+
+} // namespace toco
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_tile.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_tile.cc
new file mode 100644
index 0000000000..5cfa1a5582
--- /dev/null
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_tile.cc
@@ -0,0 +1,165 @@
+/* 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.
+==============================================================================*/
+#include <vector>
+
+#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
+#include "tensorflow/contrib/lite/toco/model.h"
+#include "tensorflow/contrib/lite/toco/tooling_util.h"
+#include "tensorflow/core/platform/logging.h"
+
+namespace toco {
+
+namespace {
+
+// NOTE: the Tile implementation here is taken from tflite's Tile kernel.
+
+template <typename T>
+void CopyMultipleTimes(const T* in_data, int32_t in_size, int32_t multiplier,
+ T* out_data) {
+ for (int i = 0; i < multiplier; ++i) {
+ const T* in_end = in_data + in_size;
+ T* new_out_data = std::copy(in_data, in_end, out_data);
+ in_data = out_data;
+ out_data = new_out_data;
+ }
+}
+
+template <typename T, typename M>
+std::pair<int, int> TileOneDimension(const Shape& in_dimensions,
+ const T* in_data, const M* multipliers,
+ T* out_data, int dimension) {
+ const int dimension_size = in_dimensions.dims(dimension);
+ if (dimension == in_dimensions.dimensions_count() - 1) {
+ CopyMultipleTimes(in_data, dimension_size, multipliers[dimension],
+ out_data);
+ return std::make_pair(
+ dimension_size,
+ dimension_size * static_cast<int>(multipliers[dimension]));
+ }
+ int total_stride_size = 0, total_tiled_stride_size = 0;
+ const T* copy_from_data = in_data;
+ T* copy_to_data = out_data;
+ for (int i = 0; i < dimension_size; ++i) {
+ int stride_size = 0, tiled_stride_size = 0;
+ std::tie(stride_size, tiled_stride_size) =
+ TileOneDimension(in_dimensions, copy_from_data, multipliers,
+ copy_to_data, dimension + 1);
+ copy_from_data += stride_size;
+ copy_to_data += tiled_stride_size;
+ total_stride_size += stride_size;
+ total_tiled_stride_size += tiled_stride_size;
+ }
+ CopyMultipleTimes(out_data, total_tiled_stride_size,
+ multipliers[dimension] - 1,
+ out_data + total_tiled_stride_size);
+ return std::make_pair(total_stride_size,
+ total_tiled_stride_size * multipliers[dimension]);
+}
+
+template <ArrayDataType Type>
+inline void Tile(const Array& input_array, const Array& multiples_array,
+ Array* output_array) {
+ // Allocate output storage.
+ auto& output_data = output_array->GetMutableBuffer<Type>().data;
+ output_data.resize(RequiredBufferSizeForShape(output_array->shape()));
+
+ switch (multiples_array.data_type) {
+ case ArrayDataType::kInt32:
+ TileOneDimension(
+ input_array.shape(), input_array.GetBuffer<Type>().data.data(),
+ multiples_array.GetBuffer<ArrayDataType::kInt32>().data.data(),
+ output_array->GetMutableBuffer<Type>().data.data(), 0);
+ break;
+ case ArrayDataType::kInt64:
+ TileOneDimension(
+ input_array.shape(), input_array.GetBuffer<Type>().data.data(),
+ multiples_array.GetBuffer<ArrayDataType::kInt64>().data.data(),
+ output_array->GetMutableBuffer<Type>().data.data(), 0);
+ break;
+ default:
+ CHECK(false);
+ break;
+ }
+}
+
+} // namespace
+
+// Resolves a constant Tile operation.
+bool ResolveConstantTile::Run(Model* model, std::size_t op_index) {
+ auto it = model->operators.begin() + op_index;
+ const auto* base_op = it->get();
+ if (base_op->type != OperatorType::kTile) {
+ return false;
+ }
+ const auto* op = static_cast<const TensorFlowTileOperator*>(base_op);
+
+ CHECK_GE(op->inputs.size(), 2);
+ CHECK_EQ(op->outputs.size(), 1);
+ auto& output_array = model->GetArray(op->outputs[0]);
+ if (output_array.data_type == ArrayDataType::kNone) {
+ // Yield until the output type has been set by PropagateArrayDataTypes.
+ return false;
+ }
+ if (!output_array.has_shape()) {
+ // Yield until the output shape has been set by PropagateFixedShapes.
+ return false;
+ }
+
+ // We require constant inputs.
+ if (!IsConstantParameterArray(*model, op->inputs[0]) ||
+ !IsConstantParameterArray(*model, op->inputs[1])) {
+ return false;
+ }
+ const Array& input_array = model->GetArray(op->inputs[0]);
+ const Array& multiples_array = model->GetArray(op->inputs[1]);
+ CHECK(multiples_array.data_type == ArrayDataType::kInt32 ||
+ multiples_array.data_type == ArrayDataType::kInt64)
+ << "Only int32/int64 indices are supported";
+
+ CopyMinMaxAndQuantizationRelatedFields(input_array, &output_array);
+
+ CHECK(!output_array.buffer);
+ switch (output_array.data_type) {
+ case ArrayDataType::kFloat:
+ Tile<ArrayDataType::kFloat>(input_array, multiples_array, &output_array);
+ break;
+ case ArrayDataType::kUint8:
+ Tile<ArrayDataType::kUint8>(input_array, multiples_array, &output_array);
+ break;
+ case ArrayDataType::kInt16:
+ Tile<ArrayDataType::kInt16>(input_array, multiples_array, &output_array);
+ break;
+ case ArrayDataType::kInt32:
+ Tile<ArrayDataType::kInt32>(input_array, multiples_array, &output_array);
+ break;
+ case ArrayDataType::kInt64:
+ Tile<ArrayDataType::kInt64>(input_array, multiples_array, &output_array);
+ break;
+ default:
+ LOG(FATAL) << "Unsupported data type given to Tile op with output \""
+ << op->outputs[0] << "\"";
+ break;
+ }
+
+ // Erase input arrays if no longer used after we remove the op.
+ DeleteArrayIfUsedOnce(op->inputs[0], model);
+ DeleteArrayIfUsedOnce(op->inputs[1], model);
+
+ // Erase the operator.
+ model->operators.erase(it);
+ return true;
+}
+
+} // namespace toco
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_transpose.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_transpose.cc
index 1fd20314b1..fe15dfa06f 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_transpose.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_transpose.cc
@@ -128,13 +128,7 @@ bool ResolveConstantTranspose::Run(Model* model, std::size_t op_index) {
}
const Array& input_array = model->GetArray(op->inputs[0]);
- if (input_array.minmax) {
- output_array.GetOrCreateMinMax() = input_array.GetMinMax();
- }
- if (input_array.quantization_params) {
- output_array.GetOrCreateQuantizationParams() =
- input_array.GetQuantizationParams();
- }
+ CopyMinMaxAndQuantizationRelatedFields(input_array, &output_array);
if (op->perm.empty()) {
// Yield until perm has been populated by ResolveTransposeAttributes.
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_unary.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_unary.cc
index fe3882c28d..475415e481 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_unary.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_unary.cc
@@ -246,8 +246,8 @@ bool ResolveConstantUnaryOperator::Run(Model* model, std::size_t op_index) {
}
output_float_data[i] = outval;
}
- } else if (unary_op->type == OperatorType::kRelu6 &&
- unary_op->type == OperatorType::kRelu1 &&
+ } else if (unary_op->type == OperatorType::kRelu6 ||
+ unary_op->type == OperatorType::kRelu1 ||
unary_op->type == OperatorType::kRelu) {
for (size_t i = 0; i < output_buffer_size; ++i) {
const float value = (*input_float_data)[i];
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/resolve_tensorflow_switch.cc b/tensorflow/contrib/lite/toco/graph_transformations/resolve_tensorflow_switch.cc
index da8e7a2d1c..8bef440afd 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/resolve_tensorflow_switch.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/resolve_tensorflow_switch.cc
@@ -92,7 +92,9 @@ bool ResolveTensorFlowSwitch::Run(Model* model, std::size_t op_index) {
if (*input_it == switch_op->outputs[nonselected_output_index]) {
// Let us guard our assumption that only Merge nodes consume the outputs
// of Switch nodes:
- CHECK(other_op->type == OperatorType::kMerge);
+ CHECK(other_op->type == OperatorType::kMerge)
+ << "Found " << HelpfulOperatorTypeName(*other_op)
+ << " as non-selected output from Switch, but only Merge supported.";
input_it = other_op->inputs.erase(input_it);
} else {
++input_it;
diff --git a/tensorflow/contrib/lite/toco/graph_transformations/unroll_batch_matmul.cc b/tensorflow/contrib/lite/toco/graph_transformations/unroll_batch_matmul.cc
index 5f0cece67a..fedf4441e2 100644
--- a/tensorflow/contrib/lite/toco/graph_transformations/unroll_batch_matmul.cc
+++ b/tensorflow/contrib/lite/toco/graph_transformations/unroll_batch_matmul.cc
@@ -154,6 +154,7 @@ bool UnrollBatchMatMul::Run(Model* model, std::size_t op_index) {
pack_op->inputs = pack_inputs;
pack_op->outputs = {batch_op->outputs[0]};
pack_op->axis = 0;
+ pack_op->values_count = pack_inputs.size();
model->operators.emplace(tail_it, pack_op);
// Remove the old batch matmul now that we've unrolled.
diff --git a/tensorflow/contrib/lite/toco/model.h b/tensorflow/contrib/lite/toco/model.h
index 18c78e32d0..412e14c4ad 100644
--- a/tensorflow/contrib/lite/toco/model.h
+++ b/tensorflow/contrib/lite/toco/model.h
@@ -2071,7 +2071,7 @@ class Model {
std::size_t transient_data_size = 0;
// For code-generation only: required alignment of the transient_data buffer
std::size_t transient_data_alignment = 0;
- // Arithmatic operations performed in the model.
+ // Arithmetic operations performed in the model.
int64 ops_count = 0;
private:
diff --git a/tensorflow/contrib/lite/toco/python/toco_python_api.h b/tensorflow/contrib/lite/toco/python/toco_python_api.h
index 7e8ad9c1da..ee054bbed9 100644
--- a/tensorflow/contrib/lite/toco/python/toco_python_api.h
+++ b/tensorflow/contrib/lite/toco/python/toco_python_api.h
@@ -12,8 +12,8 @@ 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.
==============================================================================*/
-#ifndef _THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_PYTHON_TOCO_PYTHON_API_H_
-#define _THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_PYTHON_TOCO_PYTHON_API_H_
+#ifndef TENSORFLOW_CONTRIB_LITE_TOCO_PYTHON_TOCO_PYTHON_API_H_
+#define TENSORFLOW_CONTRIB_LITE_TOCO_PYTHON_TOCO_PYTHON_API_H_
#include <Python.h>
#include <string>
@@ -33,4 +33,4 @@ PyObject* TocoConvert(PyObject* model_flags_proto_txt_raw,
} // namespace toco
-#endif // _THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_PYTHON_TOCO_PYTHON_API_H_
+#endif // TENSORFLOW_CONTRIB_LITE_TOCO_PYTHON_TOCO_PYTHON_API_H_
diff --git a/tensorflow/contrib/lite/toco/tflite/BUILD b/tensorflow/contrib/lite/toco/tflite/BUILD
index 83e977d7b3..709c53606b 100644
--- a/tensorflow/contrib/lite/toco/tflite/BUILD
+++ b/tensorflow/contrib/lite/toco/tflite/BUILD
@@ -27,6 +27,7 @@ cc_library(
"//tensorflow/contrib/lite/toco:graph_transformations",
"//tensorflow/contrib/lite/toco:model",
"//tensorflow/core:protos_all_cc",
+ "//tensorflow/core:ptr_util",
"@com_google_absl//absl/memory",
"@flatbuffers",
],
diff --git a/tensorflow/contrib/lite/toco/tflite/operator.cc b/tensorflow/contrib/lite/toco/tflite/operator.cc
index 9ff89e9a65..75808f2b69 100644
--- a/tensorflow/contrib/lite/toco/tflite/operator.cc
+++ b/tensorflow/contrib/lite/toco/tflite/operator.cc
@@ -21,9 +21,9 @@ limitations under the License.
#include "tensorflow/contrib/lite/toco/tflite/custom_operator.h"
#include "tensorflow/contrib/lite/toco/tflite/simple_operator.h"
#include "tensorflow/contrib/lite/toco/tflite/types.h"
-
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
+#include "tensorflow/core/util/ptr_util.h"
namespace toco {
@@ -1235,162 +1235,175 @@ namespace {
// Build a vector containing all the known operators.
std::vector<std::unique_ptr<BaseOperator>> BuildOperatorList() {
std::vector<std::unique_ptr<BaseOperator>> ops;
-
+ using tensorflow::MakeUnique;
// Builtin Operators.
- ops.emplace_back(new Add(::tflite::BuiltinOperator_ADD, OperatorType::kAdd));
- ops.emplace_back(new Div(::tflite::BuiltinOperator_DIV, OperatorType::kDiv));
- ops.emplace_back(new Sub(::tflite::BuiltinOperator_SUB, OperatorType::kSub));
- ops.emplace_back(new AveragePool(::tflite::BuiltinOperator_AVERAGE_POOL_2D,
- OperatorType::kAveragePool));
- ops.emplace_back(
- new SpaceToBatchND(::tflite::BuiltinOperator_SPACE_TO_BATCH_ND,
- OperatorType::kSpaceToBatchND));
- ops.emplace_back(
- new BatchToSpaceND(::tflite::BuiltinOperator_BATCH_TO_SPACE_ND,
- OperatorType::kBatchToSpaceND));
- ops.emplace_back(new Concatenation(::tflite::BuiltinOperator_CONCATENATION,
- OperatorType::kConcatenation));
- ops.emplace_back(
- new Convolution(::tflite::BuiltinOperator_CONV_2D, OperatorType::kConv));
- ops.emplace_back(
- new DepthwiseConvolution(::tflite::BuiltinOperator_DEPTHWISE_CONV_2D,
- OperatorType::kDepthwiseConv));
- ops.emplace_back(new FullyConnected(::tflite::BuiltinOperator_FULLY_CONNECTED,
- OperatorType::kFullyConnected));
- ops.emplace_back(
- new Gather(::tflite::BuiltinOperator_GATHER, OperatorType::kGather));
- ops.emplace_back(
- new L2Normalization(::tflite::BuiltinOperator_L2_NORMALIZATION,
- OperatorType::kL2Normalization));
- ops.emplace_back(
- new L2Pool(::tflite::BuiltinOperator_L2_POOL_2D, OperatorType::kL2Pool));
- ops.emplace_back(new LocalResponseNormalization(
+ ops.push_back(
+ MakeUnique<Add>(::tflite::BuiltinOperator_ADD, OperatorType::kAdd));
+ ops.push_back(
+ MakeUnique<Div>(::tflite::BuiltinOperator_DIV, OperatorType::kDiv));
+ ops.push_back(
+ MakeUnique<Sub>(::tflite::BuiltinOperator_SUB, OperatorType::kSub));
+ ops.push_back(MakeUnique<AveragePool>(
+ ::tflite::BuiltinOperator_AVERAGE_POOL_2D, OperatorType::kAveragePool));
+ ops.push_back(
+ MakeUnique<SpaceToBatchND>(::tflite::BuiltinOperator_SPACE_TO_BATCH_ND,
+ OperatorType::kSpaceToBatchND));
+ ops.push_back(
+ MakeUnique<BatchToSpaceND>(::tflite::BuiltinOperator_BATCH_TO_SPACE_ND,
+ OperatorType::kBatchToSpaceND));
+ ops.push_back(MakeUnique<Concatenation>(
+ ::tflite::BuiltinOperator_CONCATENATION, OperatorType::kConcatenation));
+ ops.push_back(MakeUnique<Convolution>(::tflite::BuiltinOperator_CONV_2D,
+ OperatorType::kConv));
+ ops.push_back(MakeUnique<DepthwiseConvolution>(
+ ::tflite::BuiltinOperator_DEPTHWISE_CONV_2D,
+ OperatorType::kDepthwiseConv));
+ ops.push_back(
+ MakeUnique<FullyConnected>(::tflite::BuiltinOperator_FULLY_CONNECTED,
+ OperatorType::kFullyConnected));
+ ops.push_back(MakeUnique<Gather>(::tflite::BuiltinOperator_GATHER,
+ OperatorType::kGather));
+ ops.push_back(
+ MakeUnique<L2Normalization>(::tflite::BuiltinOperator_L2_NORMALIZATION,
+ OperatorType::kL2Normalization));
+ ops.push_back(MakeUnique<L2Pool>(::tflite::BuiltinOperator_L2_POOL_2D,
+ OperatorType::kL2Pool));
+ ops.push_back(MakeUnique<LocalResponseNormalization>(
::tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION,
OperatorType::kLocalResponseNormalization));
- ops.emplace_back(new MaxPool(::tflite::BuiltinOperator_MAX_POOL_2D,
- OperatorType::kMaxPool));
- ops.emplace_back(new Mul(::tflite::BuiltinOperator_MUL, OperatorType::kMul));
- ops.emplace_back(new Pad(::tflite::BuiltinOperator_PAD, OperatorType::kPad));
- ops.emplace_back(
- new PadV2(::tflite::BuiltinOperator_PADV2, OperatorType::kPadV2));
- ops.emplace_back(
- new Reshape(::tflite::BuiltinOperator_RESHAPE, OperatorType::kReshape));
- ops.emplace_back(
- new Softmax(::tflite::BuiltinOperator_SOFTMAX, OperatorType::kSoftmax));
- ops.emplace_back(new SpaceToDepth(::tflite::BuiltinOperator_SPACE_TO_DEPTH,
- OperatorType::kSpaceToDepth));
- ops.emplace_back(
- new Svdf(::tflite::BuiltinOperator_SVDF, OperatorType::kSvdf));
- ops.emplace_back(new Transpose(::tflite::BuiltinOperator_TRANSPOSE,
- OperatorType::kTranspose));
- ops.emplace_back(
- new Mean(::tflite::BuiltinOperator_MEAN, OperatorType::kMean));
- ops.emplace_back(new Sum(::tflite::BuiltinOperator_SUM, OperatorType::kSum));
- ops.emplace_back(new ReduceProd(::tflite::BuiltinOperator_REDUCE_PROD,
- OperatorType::kReduceProd));
- ops.emplace_back(new ReduceMax(::tflite::BuiltinOperator_REDUCE_MAX,
- OperatorType::kReduceMax));
- ops.emplace_back(new ResizeBilinear(::tflite::BuiltinOperator_RESIZE_BILINEAR,
- OperatorType::kResizeBilinear));
- ops.emplace_back(
- new Squeeze(::tflite::BuiltinOperator_SQUEEZE, OperatorType::kSqueeze));
- ops.emplace_back(
- new Split(::tflite::BuiltinOperator_SPLIT, OperatorType::kSplit));
- ops.emplace_back(new StridedSlice(::tflite::BuiltinOperator_STRIDED_SLICE,
- OperatorType::kStridedSlice));
- ops.emplace_back(
- new TopK_V2(::tflite::BuiltinOperator_TOPK_V2, OperatorType::kTopK_V2));
- ops.emplace_back(
- new Lstm(::tflite::BuiltinOperator_LSTM, OperatorType::kLstmCell));
- ops.emplace_back(
- new Cast(::tflite::BuiltinOperator_CAST, OperatorType::kCast));
- ops.emplace_back(
- new ArgMax(::tflite::BuiltinOperator_ARG_MAX, OperatorType::kArgMax));
- ops.emplace_back(
- new ArgMin(::tflite::BuiltinOperator_ARG_MIN, OperatorType::kArgMin));
- ops.emplace_back(
- new Tile(::tflite::BuiltinOperator_TILE, OperatorType::kTile));
- ops.emplace_back(new ExpandDims(::tflite::BuiltinOperator_EXPAND_DIMS,
- OperatorType::kExpandDims));
- ops.emplace_back(new TransposeConv(::tflite::BuiltinOperator_TRANSPOSE_CONV,
- OperatorType::kTransposeConv));
- ops.emplace_back(new SparseToDense(::tflite::BuiltinOperator_SPARSE_TO_DENSE,
- OperatorType::kSparseToDense));
- ops.emplace_back(
- new Shape(::tflite::BuiltinOperator_SHAPE, OperatorType::kShape));
- ops.emplace_back(new FakeQuant(::tflite::BuiltinOperator_FAKE_QUANT,
- OperatorType::kFakeQuant));
- ops.emplace_back(
- new Pack(::tflite::BuiltinOperator_PACK, OperatorType::kPack));
- ops.emplace_back(
- new OneHot(::tflite::BuiltinOperator_ONE_HOT, OperatorType::kOneHot));
+ ops.push_back(MakeUnique<MaxPool>(::tflite::BuiltinOperator_MAX_POOL_2D,
+ OperatorType::kMaxPool));
+ ops.push_back(
+ MakeUnique<Mul>(::tflite::BuiltinOperator_MUL, OperatorType::kMul));
+ ops.push_back(
+ MakeUnique<Pad>(::tflite::BuiltinOperator_PAD, OperatorType::kPad));
+ ops.push_back(
+ MakeUnique<PadV2>(::tflite::BuiltinOperator_PADV2, OperatorType::kPadV2));
+ ops.push_back(MakeUnique<Reshape>(::tflite::BuiltinOperator_RESHAPE,
+ OperatorType::kReshape));
+ ops.push_back(MakeUnique<Softmax>(::tflite::BuiltinOperator_SOFTMAX,
+ OperatorType::kSoftmax));
+ ops.push_back(MakeUnique<SpaceToDepth>(
+ ::tflite::BuiltinOperator_SPACE_TO_DEPTH, OperatorType::kSpaceToDepth));
+ ops.push_back(
+ MakeUnique<Svdf>(::tflite::BuiltinOperator_SVDF, OperatorType::kSvdf));
+ ops.push_back(MakeUnique<Transpose>(::tflite::BuiltinOperator_TRANSPOSE,
+ OperatorType::kTranspose));
+ ops.push_back(
+ MakeUnique<Mean>(::tflite::BuiltinOperator_MEAN, OperatorType::kMean));
+ ops.push_back(
+ MakeUnique<Sum>(::tflite::BuiltinOperator_SUM, OperatorType::kSum));
+ ops.push_back(MakeUnique<ReduceProd>(::tflite::BuiltinOperator_REDUCE_PROD,
+ OperatorType::kReduceProd));
+ ops.push_back(MakeUnique<ReduceMax>(::tflite::BuiltinOperator_REDUCE_MAX,
+ OperatorType::kReduceMax));
+ ops.push_back(
+ MakeUnique<ResizeBilinear>(::tflite::BuiltinOperator_RESIZE_BILINEAR,
+ OperatorType::kResizeBilinear));
+ ops.push_back(MakeUnique<Squeeze>(::tflite::BuiltinOperator_SQUEEZE,
+ OperatorType::kSqueeze));
+ ops.push_back(
+ MakeUnique<Split>(::tflite::BuiltinOperator_SPLIT, OperatorType::kSplit));
+ ops.push_back(MakeUnique<StridedSlice>(
+ ::tflite::BuiltinOperator_STRIDED_SLICE, OperatorType::kStridedSlice));
+ ops.push_back(MakeUnique<TopK_V2>(::tflite::BuiltinOperator_TOPK_V2,
+ OperatorType::kTopK_V2));
+ ops.push_back(MakeUnique<Lstm>(::tflite::BuiltinOperator_LSTM,
+ OperatorType::kLstmCell));
+ ops.push_back(
+ MakeUnique<Cast>(::tflite::BuiltinOperator_CAST, OperatorType::kCast));
+ ops.push_back(MakeUnique<ArgMax>(::tflite::BuiltinOperator_ARG_MAX,
+ OperatorType::kArgMax));
+ ops.push_back(MakeUnique<ArgMin>(::tflite::BuiltinOperator_ARG_MIN,
+ OperatorType::kArgMin));
+ ops.push_back(
+ MakeUnique<Tile>(::tflite::BuiltinOperator_TILE, OperatorType::kTile));
+ ops.push_back(MakeUnique<ExpandDims>(::tflite::BuiltinOperator_EXPAND_DIMS,
+ OperatorType::kExpandDims));
+ ops.push_back(MakeUnique<TransposeConv>(
+ ::tflite::BuiltinOperator_TRANSPOSE_CONV, OperatorType::kTransposeConv));
+ ops.push_back(MakeUnique<SparseToDense>(
+ ::tflite::BuiltinOperator_SPARSE_TO_DENSE, OperatorType::kSparseToDense));
+ ops.push_back(
+ MakeUnique<Shape>(::tflite::BuiltinOperator_SHAPE, OperatorType::kShape));
+ ops.push_back(MakeUnique<FakeQuant>(::tflite::BuiltinOperator_FAKE_QUANT,
+ OperatorType::kFakeQuant));
+ ops.push_back(
+ MakeUnique<Pack>(::tflite::BuiltinOperator_PACK, OperatorType::kPack));
+ ops.push_back(MakeUnique<OneHot>(::tflite::BuiltinOperator_ONE_HOT,
+ OperatorType::kOneHot));
// Custom Operators.
- ops.emplace_back(
- new DepthToSpace("DEPTH_TO_SPACE", OperatorType::kDepthToSpace));
- ops.emplace_back(new CTCBeamSearchDecoder(
+ ops.push_back(
+ MakeUnique<DepthToSpace>("DEPTH_TO_SPACE", OperatorType::kDepthToSpace));
+ ops.push_back(MakeUnique<CTCBeamSearchDecoder>(
"CTC_BEAM_SEARCH_DECODER", OperatorType::kCTCBeamSearchDecoder));
- ops.emplace_back(new TensorFlowUnsupported("TENSORFLOW_UNSUPPORTED",
- OperatorType::kUnsupported));
+ ops.push_back(MakeUnique<TensorFlowUnsupported>("TENSORFLOW_UNSUPPORTED",
+ OperatorType::kUnsupported));
// There operators are supported by Toco, but not by TF Lite, and has no
// attributes.
- ops.emplace_back(
- new SimpleOperator<AddNOperator>("ADDN", OperatorType::kAddN));
+ ops.push_back(
+ MakeUnique<SimpleOperator<AddNOperator>>("ADDN", OperatorType::kAddN));
// Simple Operators.
- ops.emplace_back(new SimpleOperator<DequantizeOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<DequantizeOperator>>(
"DEQUANTIZE", OperatorType::kDequantize));
- ops.emplace_back(
- new SimpleOperator<FloorOperator>("FLOOR", OperatorType::kFloor));
- ops.emplace_back(
- new SimpleOperator<ReluOperator>("RELU", OperatorType::kRelu));
- ops.emplace_back(
- new SimpleOperator<Relu1Operator>("RELU_N1_TO_1", OperatorType::kRelu1));
- ops.emplace_back(
- new SimpleOperator<Relu6Operator>("RELU6", OperatorType::kRelu6));
- ops.emplace_back(
- new SimpleOperator<PReluOperator>("PRELU", OperatorType::kPRelu));
- ops.emplace_back(new SimpleOperator<LogisticOperator>(
+ ops.push_back(
+ MakeUnique<SimpleOperator<FloorOperator>>("FLOOR", OperatorType::kFloor));
+ ops.push_back(
+ MakeUnique<SimpleOperator<ReluOperator>>("RELU", OperatorType::kRelu));
+ ops.push_back(MakeUnique<SimpleOperator<Relu1Operator>>(
+ "RELU_N1_TO_1", OperatorType::kRelu1));
+ ops.push_back(
+ MakeUnique<SimpleOperator<Relu6Operator>>("RELU6", OperatorType::kRelu6));
+ ops.push_back(
+ MakeUnique<SimpleOperator<PReluOperator>>("PRELU", OperatorType::kPRelu));
+ ops.push_back(MakeUnique<SimpleOperator<LogisticOperator>>(
"LOGISTIC", OperatorType::kLogistic));
- ops.emplace_back(
- new SimpleOperator<TanhOperator>("TANH", OperatorType::kTanh));
- ops.emplace_back(new SimpleOperator<ExpOperator>("EXP", OperatorType::kExp));
- ops.emplace_back(new SimpleOperator<LogSoftmaxOperator>(
+ ops.push_back(
+ MakeUnique<SimpleOperator<TanhOperator>>("TANH", OperatorType::kTanh));
+ ops.push_back(
+ MakeUnique<SimpleOperator<ExpOperator>>("EXP", OperatorType::kExp));
+ ops.push_back(MakeUnique<SimpleOperator<LogSoftmaxOperator>>(
"LOG_SOFTMAX", OperatorType::kLogSoftmax));
- ops.emplace_back(new SimpleOperator<TensorFlowMaximumOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowMaximumOperator>>(
"MAXIMUM", OperatorType::kMaximum)); // Element-wise Maximum
- ops.emplace_back(new SimpleOperator<TensorFlowMinimumOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowMinimumOperator>>(
"MINIMUM", OperatorType::kMinimum)); // Element-wise Minimum
- ops.emplace_back(new SimpleOperator<TensorFlowGreaterOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowGreaterOperator>>(
"GREATER", OperatorType::kGreater));
- ops.emplace_back(new SimpleOperator<TensorFlowGreaterEqualOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowGreaterEqualOperator>>(
"GREATER_EQUAL", OperatorType::kGreaterEqual));
- ops.emplace_back(
- new SimpleOperator<TensorFlowLessOperator>("LESS", OperatorType::kLess));
- ops.emplace_back(new SimpleOperator<TensorFlowLessEqualOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowLessOperator>>(
+ "LESS", OperatorType::kLess));
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowLessEqualOperator>>(
"LESS_EQUAL", OperatorType::kLessEqual));
- ops.emplace_back(new SimpleOperator<TensorFlowEqualOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowEqualOperator>>(
"EQUAL", OperatorType::kEqual));
- ops.emplace_back(new SimpleOperator<TensorFlowNotEqualOperator>(
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowNotEqualOperator>>(
"NOT_EQUAL", OperatorType::kNotEqual));
- ops.emplace_back(new SimpleOperator<NegOperator>("NEG", OperatorType::kNeg));
- ops.emplace_back(
- new SimpleOperator<SelectOperator>("SELECT", OperatorType::kSelect));
- ops.emplace_back(
- new SimpleOperator<SliceOperator>("SLICE", OperatorType::kSlice));
- ops.emplace_back(new SimpleOperator<PowOperator>("POW", OperatorType::kPow));
- ops.emplace_back(new SimpleOperator<LogicalOrOperator>(
+ ops.push_back(
+ MakeUnique<SimpleOperator<NegOperator>>("NEG", OperatorType::kNeg));
+ ops.push_back(MakeUnique<SimpleOperator<SelectOperator>>(
+ "SELECT", OperatorType::kSelect));
+ ops.push_back(
+ MakeUnique<SimpleOperator<SliceOperator>>("SLICE", OperatorType::kSlice));
+ ops.push_back(
+ MakeUnique<SimpleOperator<PowOperator>>("POW", OperatorType::kPow));
+ ops.push_back(MakeUnique<SimpleOperator<LogicalOrOperator>>(
"LOGICAL_OR", OperatorType::kLogicalOr));
ops.emplace_back(new SimpleOperator<LogicalAndOperator>(
"LOGICAL_AND", OperatorType::kLogicalAnd));
ops.emplace_back(new SimpleOperator<LogicalNotOperator>(
"LOGICAL_NOT", OperatorType::kLogicalNot));
// Element-wise operator
- ops.emplace_back(new SimpleOperator<SinOperator>("SIN", OperatorType::kSin));
- ops.emplace_back(new SimpleOperator<LogOperator>("LOG", OperatorType::kLog));
- ops.emplace_back(
- new SimpleOperator<TensorFlowSqrtOperator>("SQRT", OperatorType::kSqrt));
- ops.emplace_back(new SimpleOperator<TensorFlowRsqrtOperator>(
+ ops.push_back(
+ MakeUnique<SimpleOperator<SinOperator>>("SIN", OperatorType::kSin));
+ ops.push_back(
+ MakeUnique<SimpleOperator<LogOperator>>("LOG", OperatorType::kLog));
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowSqrtOperator>>(
+ "SQRT", OperatorType::kSqrt));
+ ops.push_back(MakeUnique<SimpleOperator<TensorFlowRsqrtOperator>>(
"RSQRT", OperatorType::kRsqrt));
return ops;
diff --git a/tensorflow/contrib/lite/toco/toco_port.cc b/tensorflow/contrib/lite/toco/toco_port.cc
index 14168fa33f..204c0d101e 100644
--- a/tensorflow/contrib/lite/toco/toco_port.cc
+++ b/tensorflow/contrib/lite/toco/toco_port.cc
@@ -138,13 +138,15 @@ namespace port {
#define close _close
#define open _open
#define read _read
-#define O_RDONLY _O_RDONLY
-#define O_CREAT _O_CREAT
-#define O_WRONLY _O_WRONLY
-// Windows does not support the same set of file permissions as other platforms.
+// Windows does not support the same set of file permissions as other platforms,
+// and also requires an explicit flag for binary file read/write support.
constexpr int kFileCreateMode = _S_IREAD | _S_IWRITE;
+constexpr int kFileReadFlags = _O_RDONLY | _O_BINARY;
+constexpr int kFileWriteFlags = _O_WRONLY | _O_BINARY | _O_CREAT;
#else
constexpr int kFileCreateMode = 0664;
+constexpr int kFileReadFlags = O_RDONLY;
+constexpr int kFileWriteFlags = O_CREAT | O_WRONLY;
#endif // _WIN32
static bool port_initialized = false;
@@ -197,7 +199,7 @@ tensorflow::Status GetContents(const string& path, string* output,
const file::Options& options) {
output->clear();
- int fd = open(path.c_str(), O_RDONLY);
+ int fd = open(path.c_str(), kFileReadFlags);
if (fd == -1) {
return tensorflow::errors::NotFound("can't open() for read");
}
@@ -226,7 +228,7 @@ tensorflow::Status GetContents(const string& path, string* output,
tensorflow::Status SetContents(const string& filename, const string& contents,
const file::Options& options) {
- int fd = open(filename.c_str(), O_WRONLY | O_CREAT, kFileCreateMode);
+ int fd = open(filename.c_str(), kFileWriteFlags, kFileCreateMode);
if (fd == -1) {
return tensorflow::errors::Internal("can't open() for write");
}
diff --git a/tensorflow/contrib/lite/toco/toco_tooling.cc b/tensorflow/contrib/lite/toco/toco_tooling.cc
index fcd3cbab07..34130a02b0 100644
--- a/tensorflow/contrib/lite/toco/toco_tooling.cc
+++ b/tensorflow/contrib/lite/toco/toco_tooling.cc
@@ -90,8 +90,10 @@ void MakeGeneralGraphTransformationsSet(
transformations->Add(new ResolveConstantRandomUniform);
transformations->Add(new ResolveConstantRange);
transformations->Add(new ResolveConstantReshape);
+ transformations->Add(new ResolveConstantSelect);
transformations->Add(new ResolveConstantSlice);
transformations->Add(new ResolveConstantStridedSlice);
+ transformations->Add(new ResolveConstantTile);
transformations->Add(new ResolveConstantTranspose);
transformations->Add(new ResolveConstantUnaryOperator);
transformations->Add(new ResolveTensorFlowMerge);
diff --git a/tensorflow/contrib/lite/toco/tooling_util.cc b/tensorflow/contrib/lite/toco/tooling_util.cc
index 2ad2719811..3a4542f522 100644
--- a/tensorflow/contrib/lite/toco/tooling_util.cc
+++ b/tensorflow/contrib/lite/toco/tooling_util.cc
@@ -2278,4 +2278,14 @@ void UndoWeightsShuffling(Model* model) {
}
}
+void CopyMinMaxAndQuantizationRelatedFields(const Array& src, Array* dst) {
+ if (src.minmax) {
+ dst->GetOrCreateMinMax() = src.GetMinMax();
+ }
+ if (src.quantization_params) {
+ dst->GetOrCreateQuantizationParams() = src.GetQuantizationParams();
+ }
+ dst->narrow_range = src.narrow_range;
+}
+
} // namespace toco
diff --git a/tensorflow/contrib/lite/toco/tooling_util.h b/tensorflow/contrib/lite/toco/tooling_util.h
index b99e6111fe..bdeb203024 100644
--- a/tensorflow/contrib/lite/toco/tooling_util.h
+++ b/tensorflow/contrib/lite/toco/tooling_util.h
@@ -348,6 +348,9 @@ tensorflow::Status NumElements(const std::vector<T>& shape, U* num_elements) {
// so that the rest of toco doesn't need to know about shuffled weights.
void UndoWeightsShuffling(Model* model);
+// Copies minmax, quantization_params, and narrow_range.
+void CopyMinMaxAndQuantizationRelatedFields(const Array& src, Array* dst);
+
} // namespace toco
#endif // TENSORFLOW_CONTRIB_LITE_TOCO_TOOLING_UTIL_H_
diff --git a/tensorflow/contrib/lite/tools/benchmark/BUILD b/tensorflow/contrib/lite/tools/benchmark/BUILD
index 2cb07eb6ec..dc97d22401 100644
--- a/tensorflow/contrib/lite/tools/benchmark/BUILD
+++ b/tensorflow/contrib/lite/tools/benchmark/BUILD
@@ -5,8 +5,8 @@ package(default_visibility = [
licenses(["notice"]) # Apache 2.0
load("//tensorflow/contrib/lite:special_rules.bzl", "tflite_portable_test_suite")
-load("//tensorflow/contrib/lite:build_def.bzl", "tflite_linkopts")
load("//tensorflow/contrib/lite:build_def.bzl", "tflite_copts")
+load("//tensorflow/contrib/lite:build_def.bzl", "tflite_linkopts")
common_copts = ["-Wall"] + tflite_copts()
@@ -35,6 +35,25 @@ cc_binary(
],
)
+cc_binary(
+ name = "benchmark_model_plus_eager",
+ srcs = [
+ "benchmark_main.cc",
+ ],
+ copts = common_copts + ["-DTFLITE_EXTENDED"],
+ linkopts = tflite_linkopts() + select({
+ "//tensorflow:android": [
+ "-pie", # Android 5.0 and later supports only PIE
+ "-lm", # some builtin ops, e.g., tanh, need -lm
+ ],
+ "//conditions:default": [],
+ }),
+ deps = [
+ ":benchmark_tflite_model_plus_eager_lib",
+ ":logging",
+ ],
+)
+
cc_test(
name = "benchmark_test",
srcs = ["benchmark_test.cc"],
@@ -88,7 +107,25 @@ cc_library(
"//tensorflow/contrib/lite:string_util",
"//tensorflow/contrib/lite/kernels:builtin_ops",
"//tensorflow/contrib/lite/profiling:profile_summarizer",
- "//tensorflow/contrib/lite/profiling:profiler",
+ ],
+)
+
+cc_library(
+ name = "benchmark_tflite_model_plus_eager_lib",
+ srcs = [
+ "benchmark_tflite_model.cc",
+ "logging.h",
+ ],
+ hdrs = ["benchmark_tflite_model.h"],
+ copts = common_copts + ["-DTFLITE_EXTENDED"],
+ deps = [
+ ":benchmark_model_lib",
+ ":logging",
+ "//tensorflow/contrib/lite:framework",
+ "//tensorflow/contrib/lite:string_util",
+ "//tensorflow/contrib/lite/delegates/eager:delegate",
+ "//tensorflow/contrib/lite/kernels:builtin_ops",
+ "//tensorflow/contrib/lite/profiling:profile_summarizer",
],
)
diff --git a/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.cc b/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.cc
index 7f97f5d0cd..02039922b4 100644
--- a/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.cc
+++ b/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.cc
@@ -23,6 +23,9 @@ limitations under the License.
#include <unordered_set>
#include <vector>
+#ifdef TFLITE_EXTENDED
+#include "tensorflow/contrib/lite/delegates/eager/delegate.h"
+#endif // TFLITE_EXTENDED
#include "tensorflow/contrib/lite/kernels/register.h"
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/op_resolver.h"
@@ -261,6 +264,16 @@ void BenchmarkTfLiteModel::Init() {
bool use_nnapi = params_.Get<bool>("use_nnapi");
interpreter->UseNNAPI(use_nnapi);
+
+#ifdef TFLITE_EXTENDED
+ TFLITE_LOG(INFO) << "Instantiating Eager Delegate";
+ delegate_ = EagerDelegate::Create();
+ if (delegate_) {
+ interpreter->ModifyGraphWithDelegate(delegate_.get(),
+ /*allow_dynamic_tensors=*/true);
+ }
+#endif // TFLITE_EXTENDED
+
auto interpreter_inputs = interpreter->inputs();
if (!inputs.empty()) {
diff --git a/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.h b/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.h
index 9931dcbafe..4b22d80cbb 100644
--- a/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.h
+++ b/tensorflow/contrib/lite/tools/benchmark/benchmark_tflite_model.h
@@ -20,6 +20,9 @@ limitations under the License.
#include <string>
#include <vector>
+#ifdef TFLITE_EXTENDED
+#include "tensorflow/contrib/lite/delegates/eager/delegate.h"
+#endif // TFLITE_EXTENDED
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/profiling/profile_summarizer.h"
#include "tensorflow/contrib/lite/tools/benchmark/benchmark_model.h"
@@ -52,6 +55,7 @@ class BenchmarkTfLiteModel : public BenchmarkModel {
public:
BenchmarkTfLiteModel();
BenchmarkTfLiteModel(BenchmarkParams params);
+ virtual ~BenchmarkTfLiteModel() {}
std::vector<Flag> GetFlags() override;
void LogParams() override;
@@ -59,7 +63,6 @@ class BenchmarkTfLiteModel : public BenchmarkModel {
uint64_t ComputeInputBytes() override;
void Init() override;
void RunImpl() override;
- virtual ~BenchmarkTfLiteModel() {}
struct InputLayerInfo {
std::string name;
@@ -67,6 +70,9 @@ class BenchmarkTfLiteModel : public BenchmarkModel {
};
private:
+#ifdef TFLITE_EXTENDED
+ std::unique_ptr<EagerDelegate> delegate_;
+#endif // TFLITE_EXTENDED
std::unique_ptr<tflite::FlatBufferModel> model;
std::unique_ptr<tflite::Interpreter> interpreter;
std::vector<InputLayerInfo> inputs;
diff --git a/tensorflow/contrib/lite/Makefile b/tensorflow/contrib/lite/tools/make/Makefile
index 9cc8f10b42..e30cc1d70e 100644
--- a/tensorflow/contrib/lite/Makefile
+++ b/tensorflow/contrib/lite/tools/make/Makefile
@@ -6,120 +6,74 @@ endif
# Try to figure out the host system
HOST_OS :=
ifeq ($(OS),Windows_NT)
- HOST_OS = WINDOWS
+ HOST_OS = windows
else
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
- HOST_OS := LINUX
+ HOST_OS := linux
endif
ifeq ($(UNAME_S),Darwin)
- HOST_OS := OSX
+ HOST_OS := osx
endif
endif
HOST_ARCH := $(shell if [[ $(shell uname -m) =~ i[345678]86 ]]; then echo x86_32; else echo $(shell uname -m); fi)
-# Self-hosting
-TARGET_ARCH := ${HOST_ARCH}
+# Override these on the make command line to target a specific architecture. For example:
+# make -f tensorflow/contrib/lite/Makefile TARGET=rpi TARGET_ARCH=armv7l
+TARGET := $(HOST_OS)
+TARGET_ARCH := $(HOST_ARCH)
-# Cross compiling
-ifeq ($(CROSS),rpi)
- TARGET_ARCH := armv7l
- TARGET_TOOLCHAIN_PREFIX := arm-linux-gnueabihf-
-endif
-
-ifeq ($(CROSS),riscv)
- TARGET_ARCH := riscv
- TARGET_TOOLCHAIN_PREFIX := riscv32-unknown-elf-
-endif
-ifeq ($(CROSS),stm32f7)
- TARGET_ARCH := armf7
- TARGET_TOOLCHAIN_PREFIX := arm-none-eabi-
-endif
-ifeq ($(CROSS),stm32f1)
- TARGET_ARCH := armm1
- TARGET_TOOLCHAIN_PREFIX := arm-none-eabi-
-endif
-
-# Where compiled objects are stored.
-OBJDIR := $(MAKEFILE_DIR)/gen/obj/
-BINDIR := $(MAKEFILE_DIR)/gen/bin/
-LIBDIR := $(MAKEFILE_DIR)/gen/lib/
-GENDIR := $(MAKEFILE_DIR)/gen/obj/
-
-LIBS :=
-ifeq ($(TARGET_ARCH),x86_64)
- CXXFLAGS += -fPIC -DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK -pthread # -msse4.2
-endif
-
-ifeq ($(TARGET_ARCH),armv7l)
- CXXFLAGS += -mfpu=neon -pthread -fPIC
- LIBS += -ldl
-endif
-
-ifeq ($(TARGET_ARCH),riscv)
-# CXXFLAGS += -march=gap8
- CXXFLAGS += -DTFLITE_MCU
- LIBS += -ldl
- BUILD_TYPE := micro
-endif
-
-ifeq ($(TARGET_ARCH),armf7)
- CXXFLAGS += -DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK -DTFLITE_MCU
- CXXFLAGS += -fno-rtti -fmessage-length=0 -fno-exceptions -fno-builtin -ffunction-sections -fdata-sections
- CXXFLAGS += -funsigned-char -MMD
- CXXFLAGS += -mcpu=cortex-m7 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=softfp
- CXXFLAGS += '-std=gnu++11' '-fno-rtti' '-Wvla' '-c' '-Wall' '-Wextra' '-Wno-unused-parameter' '-Wno-missing-field-initializers' '-fmessage-length=0' '-fno-exceptions' '-fno-builtin' '-ffunction-sections' '-fdata-sections' '-funsigned-char' '-MMD' '-fno-delete-null-pointer-checks' '-fomit-frame-pointer' '-Os'
- LIBS += -ldl
- BUILD_TYPE := micro
-endif
-ifeq ($(TARGET_ARCH),armm1)
- CXXFLAGS += -DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK -mcpu=cortex-m1 -mthumb -DTFLITE_MCU
- CXXFLAGS += -fno-rtti -fmessage-length=0 -fno-exceptions -fno-builtin -ffunction-sections -fdata-sections
- CXXFLAGS += -funsigned-char -MMD
- LIBS += -ldl
-endif
+# These are the default libraries needed, but they can be added to or
+# overridden by the platform-specific settings in target makefiles.
+LIBS := \
+-lstdc++ \
+-lpthread \
+-lm \
+-lz
-# Settings for the host compiler.
-CXX := $(CC_PREFIX) ${TARGET_TOOLCHAIN_PREFIX}g++
-CXXFLAGS += -O3 -DNDEBUG
+# There are no rules for compiling objects for the host system (since we don't
+# generate things like the protobuf compiler that require that), so all of
+# these settings are for the target compiler.
+CXXFLAGS := -O3 -DNDEBUG
CCFLAGS := ${CXXFLAGS}
CXXFLAGS += --std=c++11
-CC := $(CC_PREFIX) ${TARGET_TOOLCHAIN_PREFIX}gcc
-AR := $(CC_PREFIX) ${TARGET_TOOLCHAIN_PREFIX}ar
CFLAGS :=
-LDOPTS :=
-LDOPTS += -L/usr/local/lib
+LDOPTS := -L/usr/local/lib
ARFLAGS := -r
+TARGET_TOOLCHAIN_PREFIX :=
+CC_PREFIX :=
+
+# These target-specific makefiles should modify or replace options like
+# CXXFLAGS or LIBS to work for a specific targetted architecture. All logic
+# based on platforms or architectures should happen within these files, to
+# keep this main makefile focused on the sources and dependencies.
+include $(wildcard $(MAKEFILE_DIR)/targets/*_makefile.inc)
+
+# Where compiled objects are stored.
+GENDIR := $(MAKEFILE_DIR)/gen/$(TARGET)_$(TARGET_ARCH)/
+OBJDIR := $(GENDIR)obj/
+BINDIR := $(GENDIR)bin/
+LIBDIR := $(GENDIR)lib/
INCLUDES := \
-I. \
--I$(MAKEFILE_DIR)/../../../ \
--I$(MAKEFILE_DIR)/../../../../ \
+-I$(MAKEFILE_DIR)/../../../../../ \
+-I$(MAKEFILE_DIR)/../../../../../../ \
-I$(MAKEFILE_DIR)/downloads/ \
-I$(MAKEFILE_DIR)/downloads/eigen \
-I$(MAKEFILE_DIR)/downloads/gemmlowp \
-I$(MAKEFILE_DIR)/downloads/neon_2_sse \
-I$(MAKEFILE_DIR)/downloads/farmhash/src \
-I$(MAKEFILE_DIR)/downloads/flatbuffers/include \
--I$(GENDIR)
+-I$(OBJDIR)
# This is at the end so any globally-installed frameworks like protobuf don't
# override local versions in the source tree.
INCLUDES += -I/usr/local/include
-LIBS += \
--lstdc++ \
--lpthread \
--lm \
--lz
-
-# If we're on Linux, also link in the dl library.
-ifeq ($(HOST_OS),LINUX)
- LIBS += -ldl
-endif
-
-include $(MAKEFILE_DIR)/ios_makefile.inc
-include $(MAKEFILE_DIR)/rpi_makefile.inc
+CXX := $(CC_PREFIX)${TARGET_TOOLCHAIN_PREFIX}g++
+CC := $(CC_PREFIX)${TARGET_TOOLCHAIN_PREFIX}gcc
+AR := $(CC_PREFIX)${TARGET_TOOLCHAIN_PREFIX}ar
# This library is the main target for this makefile. It will contain a minimal
# runtime that can be linked in to other programs.
@@ -163,8 +117,8 @@ $(wildcard tensorflow/contrib/lite/kernels/*.c) \
$(wildcard tensorflow/contrib/lite/kernels/internal/*.c) \
$(wildcard tensorflow/contrib/lite/kernels/internal/optimized/*.c) \
$(wildcard tensorflow/contrib/lite/kernels/internal/reference/*.c) \
-$(wildcard tensorflow/contrib/lite/downloads/farmhash/src/farmhash.cc) \
-$(wildcard tensorflow/contrib/lite/downloads/fft2d/fftsg.c)
+$(wildcard tensorflow/contrib/lite/tools/make/downloads/farmhash/src/farmhash.cc) \
+$(wildcard tensorflow/contrib/lite/tools/make/downloads/fft2d/fftsg.c)
endif
# Remove any duplicates.
CORE_CC_ALL_SRCS := $(sort $(CORE_CC_ALL_SRCS))
@@ -179,10 +133,6 @@ ifeq ($(BUILD_TYPE),micro)
CORE_CC_EXCLUDE_SRCS += \
tensorflow/contrib/lite/mmap_allocation.cc \
tensorflow/contrib/lite/nnapi_delegate.cc
-else
-CORE_CC_EXCLUDE_SRCS += \
-tensorflow/contrib/lite/mmap_allocation_disabled.cc \
-tensorflow/contrib/lite/nnapi_delegate_disabled.cc
endif
# Filter out all the excluded files.
TF_LITE_CC_SRCS := $(filter-out $(CORE_CC_EXCLUDE_SRCS), $(CORE_CC_ALL_SRCS))
diff --git a/tensorflow/contrib/lite/build_ios_universal_lib.sh b/tensorflow/contrib/lite/tools/make/build_ios_universal_lib.sh
index 31df43a175..fe056945a6 100755
--- a/tensorflow/contrib/lite/build_ios_universal_lib.sh
+++ b/tensorflow/contrib/lite/tools/make/build_ios_universal_lib.sh
@@ -17,23 +17,23 @@
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-cd "$SCRIPT_DIR/../../.."
+cd "$SCRIPT_DIR/../../../../.."
# Build library for supported architectures and packs them in a fat binary.
make_library() {
for arch in x86_64 armv7 armv7s arm64
do
- make -f tensorflow/contrib/lite/Makefile TARGET=IOS IOS_ARCH=${arch} \
- -j 8 \
- $SCRIPT_DIR/gen/lib/ios_${arch}/${1}
+ make -f tensorflow/contrib/lite/tools/make/Makefile TARGET=ios TARGET_ARCH=${arch} \
+ -j 8
done
+ mkdir -p tensorflow/contrib/lite/tools/make/gen/lib
lipo \
- tensorflow/contrib/lite/gen/lib/ios_x86_64/${1} \
- tensorflow/contrib/lite/gen/lib/ios_armv7/${1} \
- tensorflow/contrib/lite/gen/lib/ios_armv7s/${1} \
- tensorflow/contrib/lite/gen/lib/ios_arm64/${1} \
+ tensorflow/contrib/lite/tools/make/gen/ios_x86_64/lib/${1} \
+ tensorflow/contrib/lite/tools/make/gen/ios_armv7/lib/${1} \
+ tensorflow/contrib/lite/tools/make/gen/ios_armv7s/lib/${1} \
+ tensorflow/contrib/lite/tools/make/gen/ios_arm64/lib/${1} \
-create \
- -output tensorflow/contrib/lite/gen/lib/${1}
+ -output tensorflow/contrib/lite/tools/make/gen/lib/${1}
}
make_library libtensorflow-lite.a
diff --git a/tensorflow/contrib/lite/build_rpi_lib.sh b/tensorflow/contrib/lite/tools/make/build_rpi_lib.sh
index 3824b16412..24ecd4356d 100755
--- a/tensorflow/contrib/lite/build_rpi_lib.sh
+++ b/tensorflow/contrib/lite/tools/make/build_rpi_lib.sh
@@ -17,6 +17,6 @@
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-cd "$SCRIPT_DIR/../../.."
+cd "$SCRIPT_DIR/../../../../.."
-CC_PREFIX=arm-linux-gnueabihf- make -j 3 -f tensorflow/contrib/lite/Makefile TARGET=RPI TARGET_ARCH=armv7
+CC_PREFIX=arm-linux-gnueabihf- make -j 3 -f tensorflow/contrib/lite/tools/make/Makefile TARGET=rpi TARGET_ARCH=armv7l
diff --git a/tensorflow/contrib/lite/download_dependencies.sh b/tensorflow/contrib/lite/tools/make/download_dependencies.sh
index 8c7df474d5..29afa45133 100755
--- a/tensorflow/contrib/lite/download_dependencies.sh
+++ b/tensorflow/contrib/lite/tools/make/download_dependencies.sh
@@ -17,9 +17,9 @@
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-cd "$SCRIPT_DIR/../../.."
+cd "$SCRIPT_DIR/../../../../.."
-DOWNLOADS_DIR=tensorflow/contrib/lite/downloads
+DOWNLOADS_DIR=tensorflow/contrib/lite/tools/make/downloads
BZL_FILE_PATH=tensorflow/workspace.bzl
# Ensure it is being run from repo root
diff --git a/tensorflow/contrib/lite/ios_makefile.inc b/tensorflow/contrib/lite/tools/make/targets/ios_makefile.inc
index 079320586f..7f36b8ecef 100644
--- a/tensorflow/contrib/lite/ios_makefile.inc
+++ b/tensorflow/contrib/lite/tools/make/targets/ios_makefile.inc
@@ -1,11 +1,11 @@
# Settings for iOS.
-ifeq ($(TARGET), IOS)
- BUILD_FOR_IOS_SIMULATOR := false
- ifeq ($(IOS_ARCH), x86_64)
- BUILD_FOR_IOS_SIMULATOR := true
+ifeq ($(TARGET), ios)
+ BUILD_FOR_IOS_SIMULATOR := false
+ ifeq ($(TARGET_ARCH), x86_64)
+ BUILD_FOR_IOS_SIMULATOR := true
endif
- ifeq ($(IOS_ARCH), i386)
- BUILD_FOR_IOS_SIMULATOR := true
+ ifeq ($(TARGET_ARCH), i386)
+ BUILD_FOR_IOS_SIMULATOR := true
endif
ifeq ($(BUILD_FOR_IOS_SIMULATOR), true)
IPHONEOS_PLATFORM := $(shell xcrun --sdk iphonesimulator \
@@ -18,8 +18,8 @@ ifeq ($(TARGET), IOS)
endif
IOS_SDK_VERSION := $(shell xcrun --sdk iphoneos --show-sdk-version)
MIN_SDK_VERSION := 9.0
- # Override IOS_ARCH with armv7, armv7s, arm64, i386, or x86_64.
- IOS_ARCH := x86_64
+ # Override TARGET_ARCH with armv7, armv7s, arm64, i386, or x86_64.
+ TARGET_ARCH := x86_64
CXXFLAGS += -miphoneos-version-min=$(MIN_SDK_VERSION) \
-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK \
-DTFLITE_USE_APPLE_ACCELERATE_FOR_CONV \
@@ -29,21 +29,17 @@ ifeq ($(TARGET), IOS)
-fno-exceptions \
-isysroot \
${IPHONEOS_SYSROOT} \
- -arch $(IOS_ARCH) \
+ -arch $(TARGET_ARCH) \
-O3
CCFLAGS += -miphoneos-version-min=$(MIN_SDK_VERSION) \
-fembed-bitcode \
-mno-thumb \
-isysroot \
${IPHONEOS_SYSROOT} \
- -arch $(IOS_ARCH) \
+ -arch $(TARGET_ARCH) \
-O3
LDFLAGS := -fembed-bitcode \
-miphoneos-version-min=${MIN_SDK_VERSION} \
-framework Accelerate \
- -arch $(IOS_ARCH)
- OBJDIR := $(OBJDIR)ios_$(IOS_ARCH)/
- LIBDIR := $(LIBDIR)ios_$(IOS_ARCH)/
- BINDIR := $(BINDIR)ios_$(IOS_ARCH)/
- DEPDIR := $(DEPDIR)ios_$(IOS_ARCH)/
+ -arch $(TARGET_ARCH)
endif
diff --git a/tensorflow/contrib/lite/tools/make/targets/linux_makefile.inc b/tensorflow/contrib/lite/tools/make/targets/linux_makefile.inc
new file mode 100644
index 0000000000..86499da99e
--- /dev/null
+++ b/tensorflow/contrib/lite/tools/make/targets/linux_makefile.inc
@@ -0,0 +1,10 @@
+# Settings for Linux.
+ifeq ($(TARGET), linux)
+ CXXFLAGS += \
+ -fPIC \
+ -DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK \
+ -pthread
+ # TODO(petewarden): In the future we may want to add architecture-specific
+ # flags like -msse4.2
+ LIBS += -ldl
+endif
diff --git a/tensorflow/contrib/lite/tools/make/targets/riscv_makefile.inc b/tensorflow/contrib/lite/tools/make/targets/riscv_makefile.inc
new file mode 100644
index 0000000000..1a82afec33
--- /dev/null
+++ b/tensorflow/contrib/lite/tools/make/targets/riscv_makefile.inc
@@ -0,0 +1,10 @@
+# Settings for RiscV platforms.
+ifeq ($(TARGET), riscv)
+ TARGET_ARCH := riscv
+ TARGET_TOOLCHAIN_PREFIX := riscv32-unknown-elf-
+
+ #CXXFLAGS += -march=gap8
+ CXXFLAGS += -DTFLITE_MCU
+ LIBS += -ldl
+ BUILD_TYPE := micro
+endif
diff --git a/tensorflow/contrib/lite/tools/make/targets/rpi_makefile.inc b/tensorflow/contrib/lite/tools/make/targets/rpi_makefile.inc
new file mode 100644
index 0000000000..1ad0c50237
--- /dev/null
+++ b/tensorflow/contrib/lite/tools/make/targets/rpi_makefile.inc
@@ -0,0 +1,60 @@
+# Settings for Raspberry Pi.
+ifeq ($(TARGET),rpi)
+ # Default to the architecture used on the Pi Two/Three (ArmV7), but override this
+ # with TARGET_ARCH=armv6 to build for the Pi Zero or One.
+ TARGET_ARCH := armv7l
+ TARGET_TOOLCHAIN_PREFIX := arm-linux-gnueabihf-
+
+ ifeq ($(TARGET_ARCH), armv7l)
+ CXXFLAGS += \
+ -march=armv7-a \
+ -mfpu=neon-vfpv4 \
+ -funsafe-math-optimizations \
+ -ftree-vectorize \
+ -fPIC
+
+ CCFLAGS += \
+ -march=armv7-a \
+ -mfpu=neon-vfpv4 \
+ -funsafe-math-optimizations \
+ -ftree-vectorize \
+ -fPIC
+
+ LDFLAGS := \
+ -Wl,--no-export-dynamic \
+ -Wl,--exclude-libs,ALL \
+ -Wl,--gc-sections \
+ -Wl,--as-needed
+ endif
+
+ # TODO(petewarden) In the future, we'll want to use OpenBLAS as a faster
+ # alternative to Eigen on non-NEON ARM hardware like armv6.
+ ifeq ($(TARGET_ARCH), armv6)
+ CXXFLAGS += \
+ -march=armv6 \
+ -mfpu=vfp \
+ -funsafe-math-optimizations \
+ -ftree-vectorize \
+ -fPIC
+
+ CCFLAGS += \
+ -march=armv6 \
+ -mfpu=vfp \
+ -funsafe-math-optimizations \
+ -ftree-vectorize \
+ -fPIC
+
+ LDFLAGS := \
+ -Wl,--no-export-dynamic \
+ -Wl,--exclude-libs,ALL \
+ -Wl,--gc-sections \
+ -Wl,--as-needed
+ endif
+
+ LIBS := \
+ -lstdc++ \
+ -lpthread \
+ -lm \
+ -ldl
+
+endif
diff --git a/tensorflow/contrib/lite/tools/make/targets/stm32f1_makefile.inc b/tensorflow/contrib/lite/tools/make/targets/stm32f1_makefile.inc
new file mode 100644
index 0000000000..7418e4d196
--- /dev/null
+++ b/tensorflow/contrib/lite/tools/make/targets/stm32f1_makefile.inc
@@ -0,0 +1,21 @@
+# Settings for STM32F1 platforms.
+ifeq ($(TARGET), stm32f1)
+ TARGET_ARCH := armm1
+ TARGET_TOOLCHAIN_PREFIX := arm-none-eabi-
+
+ CXXFLAGS += \
+ -DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK \
+ -mcpu=cortex-m1 \
+ -mthumb \
+ -DTFLITE_MCU \
+ -fno-rtti \
+ -fmessage-length=0 \
+ -fno-exceptions \
+ -fno-builtin \
+ -ffunction-sections \
+ -fdata-sections \
+ -funsigned-char \
+ -MMD
+ LIBS += -ldl
+ BUILD_TYPE := micro
+endif
diff --git a/tensorflow/contrib/lite/tools/make/targets/stm32f7_makefile.inc b/tensorflow/contrib/lite/tools/make/targets/stm32f7_makefile.inc
new file mode 100644
index 0000000000..48af71e5b4
--- /dev/null
+++ b/tensorflow/contrib/lite/tools/make/targets/stm32f7_makefile.inc
@@ -0,0 +1,41 @@
+# Settings for STM32F7 platforms.
+ifeq ($(TARGET), stm32f7)
+ TARGET_ARCH := armf7
+ TARGET_TOOLCHAIN_PREFIX := arm-none-eabi-
+
+ CXXFLAGS += \
+ -DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK \
+ -DTFLITE_MCU \
+ -fno-rtti \
+ -fmessage-length=0 \
+ -fno-exceptions \
+ -fno-builtin \
+ -ffunction-sections \
+ -fdata-sections \
+ -funsigned-char \
+ -MMD \
+ -mcpu=cortex-m7 \
+ -mthumb \
+ -mfpu=fpv5-sp-d16 \
+ -mfloat-abi=softfp \
+ -std=gnu++11 \
+ -fno-rtti \
+ -Wvla \
+ -c \
+ -Wall \
+ -Wextra \
+ -Wno-unused-parameter \
+ -Wno-missing-field-initializers \
+ -fmessage-length=0 \
+ -fno-exceptions \
+ -fno-builtin \
+ -ffunction-sections \
+ -fdata-sections \
+ -funsigned-char \
+ -MMD \
+ -fno-delete-null-pointer-checks \
+ -fomit-frame-pointer \
+ -Os
+ LIBS += -ldl
+ BUILD_TYPE := micro
+endif
diff --git a/tensorflow/contrib/lite/util.cc b/tensorflow/contrib/lite/util.cc
index 8ccb65c24f..7950653da9 100644
--- a/tensorflow/contrib/lite/util.cc
+++ b/tensorflow/contrib/lite/util.cc
@@ -14,8 +14,15 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/lite/util.h"
+#include <cstring>
+
namespace tflite {
+bool IsEagerOp(const char* custom_name) {
+ return custom_name && strncmp(custom_name, kEagerCustomCodePrefix,
+ strlen(kEagerCustomCodePrefix)) == 0;
+}
+
TfLiteIntArray* ConvertVectorToTfLiteIntArray(const std::vector<int>& input) {
return ConvertArrayToTfLiteIntArray(input.size(), input.data());
}
diff --git a/tensorflow/contrib/lite/util.h b/tensorflow/contrib/lite/util.h
index 3c4801183b..f5b208afbb 100644
--- a/tensorflow/contrib/lite/util.h
+++ b/tensorflow/contrib/lite/util.h
@@ -26,6 +26,16 @@ limitations under the License.
namespace tflite {
+// The prefix of Eager op custom code.
+// This will be matched agains the `custom_code` field in `OperatorCode`
+// Flatbuffer Table.
+// WARNING: This is an experimental API and subject to change.
+constexpr char kEagerCustomCodePrefix[] = "Eager";
+
+// Checks whether the prefix of the custom name indicates the operation is an
+// Eager operation.
+bool IsEagerOp(const char* custom_name);
+
// Converts a `std::vector` to a `TfLiteIntArray`. The caller takes ownership
// of the returned pointer.
TfLiteIntArray* ConvertVectorToTfLiteIntArray(const std::vector<int>& input);
diff --git a/tensorflow/contrib/lite/util_test.cc b/tensorflow/contrib/lite/util_test.cc
index 04579c53aa..32bf917a59 100644
--- a/tensorflow/contrib/lite/util_test.cc
+++ b/tensorflow/contrib/lite/util_test.cc
@@ -41,6 +41,16 @@ TEST(ConvertVectorToTfLiteIntArray, TestWithEmptyVector) {
TfLiteIntArrayFree(output);
}
+TEST(UtilTest, IsEagerOp) {
+ EXPECT_TRUE(IsEagerOp("Eager"));
+ EXPECT_TRUE(IsEagerOp("EagerOp"));
+ EXPECT_FALSE(IsEagerOp("eager"));
+ EXPECT_FALSE(IsEagerOp("Eage"));
+ EXPECT_FALSE(IsEagerOp("OpEager"));
+ EXPECT_FALSE(IsEagerOp(nullptr));
+ EXPECT_FALSE(IsEagerOp(""));
+}
+
} // namespace
} // namespace tflite
diff --git a/tensorflow/contrib/lookup/BUILD b/tensorflow/contrib/lookup/BUILD
index e3928a82a2..83e80f25bc 100644
--- a/tensorflow/contrib/lookup/BUILD
+++ b/tensorflow/contrib/lookup/BUILD
@@ -34,6 +34,7 @@ tf_py_test(
":lookup_py",
"//third_party/py/numpy",
"@six_archive//:six",
+ "//tensorflow/contrib/data",
"//tensorflow/python:array_ops",
"//tensorflow/python:client_testlib",
"//tensorflow/python:errors",
diff --git a/tensorflow/contrib/lookup/lookup_ops.py b/tensorflow/contrib/lookup/lookup_ops.py
index 4942d94176..f83765a48d 100644
--- a/tensorflow/contrib/lookup/lookup_ops.py
+++ b/tensorflow/contrib/lookup/lookup_ops.py
@@ -18,9 +18,11 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import functools
+
+from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
-from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import gen_lookup_ops
from tensorflow.python.ops import lookup_ops
# pylint: disable=unused-import
@@ -40,6 +42,7 @@ from tensorflow.python.ops.lookup_ops import TextFileIndex
from tensorflow.python.ops.lookup_ops import TextFileInitializer
from tensorflow.python.ops.lookup_ops import TextFileStringTableInitializer
# pylint: enable=unused-import
+from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.training.saver import BaseSaverBuilder
from tensorflow.python.util.deprecation import deprecated
@@ -286,7 +289,7 @@ def index_to_string(tensor, mapping, default_value="UNK", name=None):
return table.lookup(tensor)
-class MutableHashTable(LookupInterface):
+class MutableHashTable(LookupInterface, checkpointable.CheckpointableBase):
"""A generic mutable hash table implementation.
Data can be inserted by calling the insert method. It does not support
@@ -337,6 +340,13 @@ class MutableHashTable(LookupInterface):
dtype=value_dtype)
self._value_shape = self._default_value.get_shape()
+ executing_eagerly = context.executing_eagerly()
+ if executing_eagerly and shared_name is None:
+ # TODO(allenl): This will leak memory due to kernel caching by the
+ # shared_name attribute value (but is better than the alternative of
+ # sharing everything by default when executing eagerly; hopefully creating
+ # tables in a loop is uncommon).
+ shared_name = "table_%d" % (ops.uid(),)
# The table must be shared if checkpointing is requested for multi-worker
# training to work correctly. Use the node name if no shared_name has been
# explicitly specified.
@@ -356,9 +366,12 @@ class MutableHashTable(LookupInterface):
value_dtype=value_dtype,
value_shape=self._default_value.get_shape(),
name=name)
+ if executing_eagerly:
+ op_name = None
+ else:
+ op_name = self._table_ref.op.name.split("/")[-1]
super(MutableHashTable, self).__init__(key_dtype, value_dtype,
- self._table_ref.op.name.split(
- "/")[-1])
+ op_name)
if checkpoint:
saveable = MutableHashTable._Saveable(self, name)
@@ -395,17 +408,12 @@ class MutableHashTable(LookupInterface):
Raises:
TypeError: when `keys` do not match the table data types.
"""
- if keys.dtype.base_dtype != self._key_dtype:
- raise TypeError("Signature mismatch. Keys must be dtype %s, got %s." %
- (self._key_dtype, keys.dtype))
-
with ops.name_scope(name, "%s_lookup_table_find" % self._name,
(self._table_ref, keys, self._default_value)) as name:
+ keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys")
with ops.colocate_with(self._table_ref):
values = gen_lookup_ops.lookup_table_find_v2(
self._table_ref, keys, self._default_value, name=name)
-
- values.set_shape(keys.get_shape().concatenate(self._value_shape))
return values
def insert(self, keys, values, name=None):
@@ -425,11 +433,10 @@ class MutableHashTable(LookupInterface):
TypeError: when `keys` or `values` doesn't match the table data
types.
"""
- # pylint: disable=protected-access
- lookup_ops._check_table_dtypes(self, keys.dtype, values.dtype)
- # pylint: enable=protected-access
with ops.name_scope(name, "%s_lookup_table_insert" % self._name,
[self._table_ref, keys, values]) as name:
+ keys = ops.convert_to_tensor(keys, self._key_dtype, name="keys")
+ values = ops.convert_to_tensor(values, self._value_dtype, name="values")
with ops.colocate_with(self._table_ref):
# pylint: disable=protected-access
op = gen_lookup_ops.lookup_table_insert_v2(
@@ -451,11 +458,12 @@ class MutableHashTable(LookupInterface):
with ops.colocate_with(self._table_ref):
exported_keys, exported_values = gen_lookup_ops.lookup_table_export_v2(
self._table_ref, self._key_dtype, self._value_dtype, name=name)
-
- exported_values.set_shape(exported_keys.get_shape().concatenate(
- self._value_shape))
return exported_keys, exported_values
+ def _gather_saveables_for_checkpoint(self):
+ """For object-based checkpointing."""
+ return {"table": functools.partial(MutableHashTable._Saveable, table=self)}
+
class _Saveable(BaseSaverBuilder.SaveableObject):
"""SaveableObject implementation for MutableHashTable."""
@@ -468,14 +476,15 @@ class MutableHashTable(LookupInterface):
# pylint: disable=protected-access
super(MutableHashTable._Saveable, self).__init__(table, specs, name)
- def restore(self, restored_tensors, unused_restored_shapes):
+ def restore(self, restored_tensors, restored_shapes):
+ del restored_shapes # unused
# pylint: disable=protected-access
with ops.colocate_with(self.op._table_ref):
return gen_lookup_ops.lookup_table_import_v2(
self.op._table_ref, restored_tensors[0], restored_tensors[1])
-class MutableDenseHashTable(LookupInterface):
+class MutableDenseHashTable(LookupInterface, checkpointable.CheckpointableBase):
"""A generic mutable hash table implementation using tensors as backing store.
Data can be inserted by calling the insert method. It does not support
@@ -537,14 +546,22 @@ class MutableDenseHashTable(LookupInterface):
ValueError: If checkpoint is True and no name was specified.
"""
self._default_value = ops.convert_to_tensor(
- default_value, dtype=value_dtype)
+ default_value, dtype=value_dtype, name="default_value")
self._value_shape = self._default_value.get_shape()
# The table must be shared if checkpointing is requested for multi-worker
# training to work correctly. Use the node name if no shared_name has been
# explicitly specified.
use_node_name_sharing = checkpoint and shared_name is None
- empty_key = ops.convert_to_tensor(empty_key, dtype=key_dtype)
+ empty_key = ops.convert_to_tensor(
+ empty_key, dtype=key_dtype, name="empty_key")
+ executing_eagerly = context.executing_eagerly()
+ if executing_eagerly and shared_name is None:
+ # TODO(allenl): This will leak memory due to kernel caching by the
+ # shared_name attribute value (but is better than the alternative of
+ # sharing everything by default when executing eagerly; hopefully creating
+ # tables in a loop is uncommon).
+ shared_name = "table_%d" % (ops.uid(),)
self._table_ref = gen_lookup_ops.mutable_dense_hash_table_v2(
empty_key=empty_key,
shared_name=shared_name,
@@ -553,8 +570,12 @@ class MutableDenseHashTable(LookupInterface):
value_shape=self._value_shape,
initial_num_buckets=initial_num_buckets,
name=name)
+ if executing_eagerly:
+ op_name = None
+ else:
+ op_name = self._table_ref.op.name.split("/")[-1]
super(MutableDenseHashTable, self).__init__(
- key_dtype, value_dtype, self._table_ref.op.name.split("/")[-1])
+ key_dtype, value_dtype, op_name)
if checkpoint:
saveable = MutableDenseHashTable._Saveable(self, name)
@@ -591,20 +612,13 @@ class MutableDenseHashTable(LookupInterface):
Raises:
TypeError: when `keys` do not match the table data types.
"""
- if keys.dtype.base_dtype != self._key_dtype:
- raise TypeError("Signature mismatch. Keys must be dtype %s, got %s." %
- (self._key_dtype, keys.dtype))
-
with ops.name_scope(name, "%s_lookup_table_find" % self._name,
[self._table_ref, keys]) as name:
+ keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys")
with ops.colocate_with(self._table_ref):
values = gen_lookup_ops.lookup_table_find_v2(
self._table_ref, keys, self._default_value, name=name)
- if keys.get_shape().ndims is not None and keys.get_shape().ndims > 0:
- values.set_shape(
- tensor_shape.TensorShape([keys.get_shape().dims[0]]).concatenate(
- self._value_shape))
return values
def insert(self, keys, values, name=None):
@@ -624,11 +638,11 @@ class MutableDenseHashTable(LookupInterface):
TypeError: when `keys` or `values` doesn't match the table data
types.
"""
- # pylint: disable=protected-access
- lookup_ops._check_table_dtypes(self, keys.dtype, values.dtype)
- # pylint: enable=protected-access
with ops.name_scope(name, "%s_lookup_table_insert" % self._name,
[self._table_ref, keys, values]) as name:
+ keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys")
+ values = ops.convert_to_tensor(
+ values, dtype=self._value_dtype, name="values")
with ops.colocate_with(self._table_ref):
op = gen_lookup_ops.lookup_table_insert_v2(
self._table_ref, keys, values, name=name)
@@ -650,10 +664,13 @@ class MutableDenseHashTable(LookupInterface):
exported_keys, exported_values = gen_lookup_ops.lookup_table_export_v2(
self._table_ref, self._key_dtype, self._value_dtype, name=name)
- exported_values.set_shape(exported_keys.get_shape().concatenate(
- self._value_shape))
return exported_keys, exported_values
+ def _gather_saveables_for_checkpoint(self):
+ """For object-based checkpointing."""
+ return {"table": functools.partial(
+ MutableDenseHashTable._Saveable, table=self)}
+
class _Saveable(BaseSaverBuilder.SaveableObject):
"""SaveableObject implementation for MutableDenseHashTable."""
@@ -666,7 +683,8 @@ class MutableDenseHashTable(LookupInterface):
# pylint: disable=protected-access
super(MutableDenseHashTable._Saveable, self).__init__(table, specs, name)
- def restore(self, restored_tensors, unused_restored_shapes):
+ def restore(self, restored_tensors, restored_shapes):
+ del restored_shapes # unused
# pylint: disable=protected-access
with ops.colocate_with(self.op._table_ref):
return gen_lookup_ops.lookup_table_import_v2(
diff --git a/tensorflow/contrib/lookup/lookup_ops_test.py b/tensorflow/contrib/lookup/lookup_ops_test.py
index 8d510ede58..f9b0358a36 100644
--- a/tensorflow/contrib/lookup/lookup_ops_test.py
+++ b/tensorflow/contrib/lookup/lookup_ops_test.py
@@ -23,6 +23,7 @@ import numpy as np
import six
from tensorflow.contrib import lookup
+from tensorflow.contrib.data.python.ops import counter
from tensorflow.python.client import session
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
@@ -37,6 +38,7 @@ from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import saver
from tensorflow.python.training import server_lib
+from tensorflow.python.training.checkpointable import util as checkpointable
class HashTableOpTest(test.TestCase):
@@ -382,6 +384,59 @@ class MutableHashTableOpTest(test.TestCase):
output = table.lookup(input_string)
self.assertAllEqual([-1, 0, 1, 2, -1], output.eval())
+ @test_util.run_in_graph_and_eager_modes
+ def testObjectSaveRestore(self):
+ save_dir = os.path.join(self.get_temp_dir(), "save_restore")
+ save_prefix = os.path.join(tempfile.mkdtemp(prefix=save_dir), "hash")
+
+ v0 = variables.Variable(10.0, name="v0")
+ v1 = variables.Variable(20.0, name="v1")
+
+ default_val = -1
+ keys = constant_op.constant(["b", "c", "d"], dtypes.string)
+ values = constant_op.constant([0, 1, 2], dtypes.int64)
+ table = lookup.MutableHashTable(
+ dtypes.string, dtypes.int64, default_val, name="t1", checkpoint=True)
+
+ checkpoint = checkpointable.Checkpoint(table=table, v0=v0, v1=v1)
+ self.evaluate([v0.initializer, v1.initializer])
+
+ # Check that the parameter nodes have been initialized.
+ self.assertEqual(10.0, self.evaluate(v0))
+ self.assertEqual(20.0, self.evaluate(v1))
+
+ self.assertAllEqual(0, self.evaluate(table.size()))
+ self.evaluate(table.insert(keys, values))
+ self.assertAllEqual(3, self.evaluate(table.size()))
+
+ save_path = checkpoint.save(save_prefix)
+ del table, checkpoint, v0, v1
+
+ v0 = variables.Variable(-1.0, name="v0")
+ v1 = variables.Variable(-1.0, name="v1")
+ default_val = -1
+ table = lookup.MutableHashTable(
+ dtypes.string, dtypes.int64, default_val, name="t1", checkpoint=True)
+ self.evaluate(table.insert(
+ constant_op.constant(["a", "c"], dtypes.string),
+ constant_op.constant([12, 24], dtypes.int64)))
+ self.assertAllEqual(2, self.evaluate(table.size()))
+
+ checkpoint = checkpointable.Checkpoint(table=table, v0=v0, v1=v1)
+
+ # Restore the saved values in the parameter nodes.
+ checkpoint.restore(save_path).run_restore_ops()
+ # Check that the parameter nodes have been restored.
+ self.assertEqual(10.0, self.evaluate(v0))
+ self.assertEqual(20.0, self.evaluate(v1))
+
+ self.assertAllEqual(3, self.evaluate(table.size()))
+
+ input_string = constant_op.constant(["a", "b", "c", "d", "e"],
+ dtypes.string)
+ output = table.lookup(input_string)
+ self.assertAllEqual([-1, 0, 1, 2, -1], self.evaluate(output))
+
def testSharing(self):
# Start a server to store the table state
server = server_lib.Server(
@@ -434,8 +489,10 @@ class MutableHashTableOpTest(test.TestCase):
self.assertAllEqual([[0, 1], [2, 3], [-1, -1]], result)
exported_keys, exported_values = table.export()
- self.assertAllEqual([None], exported_keys.get_shape().as_list())
- self.assertAllEqual([None, 2], exported_values.get_shape().as_list())
+ self.assertAllEqual([None], exported_keys.get_shape().as_list(),
+ msg="Saw shape %s" % exported_keys.shape)
+ self.assertAllEqual([None, 2], exported_values.get_shape().as_list(),
+ msg="Saw shape %s" % exported_values.shape)
# exported data is in the order of the internal map, i.e. undefined
sorted_keys = np.sort(exported_keys.eval())
sorted_values = np.sort(exported_values.eval())
@@ -644,11 +701,11 @@ class MutableHashTableOpTest(test.TestCase):
default_val)
# insert with keys of the wrong type
- with self.assertRaises(TypeError):
+ with self.assertRaises(ValueError):
table.insert(constant_op.constant([4, 5, 6]), values).run()
# insert with values of the wrong type
- with self.assertRaises(TypeError):
+ with self.assertRaises(ValueError):
table.insert(keys, constant_op.constant(["a", "b", "c"])).run()
self.assertAllEqual(0, table.size().eval())
@@ -669,7 +726,7 @@ class MutableHashTableOpTest(test.TestCase):
# lookup with keys of the wrong type
input_string = constant_op.constant([1, 2, 3], dtypes.int64)
- with self.assertRaises(TypeError):
+ with self.assertRaises(ValueError):
table.lookup(input_string).eval()
# default value of the wrong type
@@ -853,7 +910,8 @@ class MutableDenseHashTableOpTest(test.TestCase):
input_string = constant_op.constant([11, 12, 15], dtypes.int64)
output = table.lookup(input_string)
- self.assertAllEqual([3, 4], output.get_shape())
+ self.assertAllEqual(
+ [3, 4], output.shape, msg="Saw shape: %s" % output.shape)
result = output.eval()
self.assertAllEqual([[0, 1, 2, 3], [3, 4, 5, 6], [-1, -2, -3, -4]],
@@ -1006,6 +1064,60 @@ class MutableDenseHashTableOpTest(test.TestCase):
output = table.lookup(input_string)
self.assertAllEqual([-1, 0, 1, 2, -1], output.eval())
+ @test_util.run_in_graph_and_eager_modes
+ def testObjectSaveRestore(self):
+ save_dir = os.path.join(self.get_temp_dir(), "save_restore")
+ save_prefix = os.path.join(tempfile.mkdtemp(prefix=save_dir), "hash")
+
+ default_value = -1
+ empty_key = 0
+ keys = constant_op.constant([11, 12, 13], dtypes.int64)
+ values = constant_op.constant([0, 1, 2], dtypes.int64)
+ save_table = lookup.MutableDenseHashTable(
+ dtypes.int64,
+ dtypes.int64,
+ default_value=default_value,
+ empty_key=empty_key,
+ name="t1",
+ checkpoint=True,
+ initial_num_buckets=32)
+
+ save_checkpoint = checkpointable.Checkpoint(table=save_table)
+
+ self.assertAllEqual(0, self.evaluate(save_table.size()))
+ self.evaluate(save_table.insert(keys, values))
+ self.assertAllEqual(3, self.evaluate(save_table.size()))
+ self.assertAllEqual(32, len(self.evaluate(save_table.export()[0])))
+
+ save_path = save_checkpoint.save(save_prefix)
+ del save_table, save_checkpoint
+
+ load_table = lookup.MutableDenseHashTable(
+ dtypes.int64,
+ dtypes.int64,
+ default_value=default_value,
+ empty_key=empty_key,
+ name="t1",
+ checkpoint=True,
+ initial_num_buckets=64)
+ self.evaluate(load_table.insert(
+ constant_op.constant([11, 14], dtypes.int64),
+ constant_op.constant([12, 24], dtypes.int64)))
+ self.assertAllEqual(2, self.evaluate(load_table.size()))
+ self.assertAllEqual(64, len(self.evaluate(load_table.export()[0])))
+
+ restore_checkpoint = checkpointable.Checkpoint(table=load_table)
+
+ # Restore the saved values in the parameter nodes.
+ restore_checkpoint.restore(save_path).run_restore_ops()
+
+ self.assertAllEqual(3, self.evaluate(load_table.size()))
+ self.assertAllEqual(32, len(self.evaluate(load_table.export()[0])))
+
+ input_string = constant_op.constant([10, 11, 12, 13, 14], dtypes.int64)
+ output = load_table.lookup(input_string)
+ self.assertAllEqual([-1, 0, 1, 2, -1], self.evaluate(output))
+
def testVectorSaveRestore(self):
save_dir = os.path.join(self.get_temp_dir(), "vector_save_restore")
save_path = os.path.join(tempfile.mkdtemp(prefix=save_dir), "hash")
@@ -2394,5 +2506,60 @@ class IdTableWithHashBucketsTest(test.TestCase):
hasher_spec=lookup.StrongHashSpec([None, 2]))
+class MutableHashTableBenchmark(test.Benchmark):
+
+ def _create_table(self):
+ return lookup.MutableHashTable(dtypes.int64, dtypes.float32, 0.0)
+
+ def benchmark_single_repeated_scalar_insert_scalar(self):
+ table = self._create_table()
+ value = variables.Variable(1.0)
+ insert = table.insert(0, value)
+ size = table.size()
+ with session.Session() as sess:
+ sess.run(value.initializer)
+ self.run_op_benchmark(sess, insert, burn_iters=10, min_iters=10000)
+ assert sess.run(size) == 1
+
+ def benchmark_many_repeated_scalar_insert_scalar(self):
+ table = self._create_table()
+ c = counter.Counter().make_one_shot_iterator().get_next()
+ value = variables.Variable(1.0)
+ insert = table.insert(c, value)
+ size = table.size()
+ with session.Session() as sess:
+ sess.run(value.initializer)
+ self.run_op_benchmark(sess, insert, burn_iters=10, min_iters=10000)
+ assert sess.run(size) >= 10000
+
+ def benchmark_single_repeated_batch_32_insert_scalar(self):
+ table = self._create_table()
+ value = variables.Variable([1.0] * 32)
+ insert = table.insert(list(range(32)), value)
+ size = table.size()
+ with session.Session() as sess:
+ sess.run(value.initializer)
+ self.run_op_benchmark(sess, insert, burn_iters=10, min_iters=1000)
+ assert sess.run(size) == 32
+
+ def benchmark_many_repeated_batch_32_insert_scalar(self):
+ table = self._create_table()
+ c = counter.Counter().make_one_shot_iterator().get_next()
+ value = variables.Variable([1.0] * 32)
+ insert = table.insert(32 * c + list(range(32)), value)
+ size = table.size()
+ with session.Session() as sess:
+ sess.run(value.initializer)
+ self.run_op_benchmark(sess, insert, burn_iters=10, min_iters=1000)
+ assert sess.run(size) >= 1000*32
+
+
+class MutableDenseHashTableBenchmark(MutableHashTableBenchmark):
+
+ def _create_table(self):
+ return lookup.MutableDenseHashTable(
+ dtypes.int64, dtypes.float32, default_value=0.0, empty_key=-1)
+
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/losses/__init__.py b/tensorflow/contrib/losses/__init__.py
index db58647d48..92b380df53 100644
--- a/tensorflow/contrib/losses/__init__.py
+++ b/tensorflow/contrib/losses/__init__.py
@@ -15,7 +15,7 @@
"""Ops for building neural network losses.
-See @{$python/contrib.losses}.
+See [Contrib Losses](https://tensorflow.org/api_guides/python/contrib.losses).
"""
from __future__ import absolute_import
diff --git a/tensorflow/contrib/losses/python/losses/__init__.py b/tensorflow/contrib/losses/python/losses/__init__.py
index 6e9d1d4a77..1675387227 100644
--- a/tensorflow/contrib/losses/python/losses/__init__.py
+++ b/tensorflow/contrib/losses/python/losses/__init__.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""Ops for building neural network losses.
-See @{$python/contrib.losses}.
+See [Contrib Losses](https://tensorflow.org/api_guides/python/contrib.losses).
"""
from __future__ import absolute_import
diff --git a/tensorflow/contrib/losses/python/metric_learning/__init__.py b/tensorflow/contrib/losses/python/metric_learning/__init__.py
index 4e551d6aca..3d93a4d0ac 100644
--- a/tensorflow/contrib/losses/python/metric_learning/__init__.py
+++ b/tensorflow/contrib/losses/python/metric_learning/__init__.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""Ops for building neural network losses.
-See @{$python/contrib.losses}.
+See [Contrib Losses](https://tensorflow.org/api_guides/python/contrib.losses).
"""
from __future__ import absolute_import
@@ -35,5 +35,3 @@ _allowed_symbols = [
'triplet_semihard_loss',
]
remove_undocumented(__name__, _allowed_symbols)
-
-
diff --git a/tensorflow/contrib/makefile/compile_nsync.sh b/tensorflow/contrib/makefile/compile_nsync.sh
index a28fc3a87f..cb4c94d92f 100755
--- a/tensorflow/contrib/makefile/compile_nsync.sh
+++ b/tensorflow/contrib/makefile/compile_nsync.sh
@@ -256,6 +256,7 @@ for arch in $archs; do
esac
makefile='
+ AR := ${NDK_ROOT}/toolchains/'"$toolchain"'/prebuilt/'"$android_os_arch"'/bin/'"$bin_prefix"'-ar
CC=${CC_PREFIX} \
${NDK_ROOT}/toolchains/'"$toolchain"'/prebuilt/'"$android_os_arch"'/bin/'"$bin_prefix"'-g++
PLATFORM_CPPFLAGS=--sysroot \
diff --git a/tensorflow/contrib/makefile/download_dependencies.sh b/tensorflow/contrib/makefile/download_dependencies.sh
index 448ae6d22e..dc9b17a627 100755
--- a/tensorflow/contrib/makefile/download_dependencies.sh
+++ b/tensorflow/contrib/makefile/download_dependencies.sh
@@ -35,7 +35,9 @@ NSYNC_URL="$(grep -o 'https://mirror.bazel.build/github.com/google/nsync/.*tar\.
# process. For now we're hardcoding to the version which is used by
# TensorFlow 1.9.
PROTOBUF_URL="https://mirror.bazel.build/github.com/google/protobuf/archive/396336eb961b75f03b25824fe86cf6490fb75e3a.tar.gz"
-RE2_URL="$(grep -o 'https://mirror.bazel.build/github.com/google/re2/.*tar\.gz' "${BZL_FILE_PATH}" | head -n1)"
+# TODO (yongtang): Replace the following with 'https://mirror.bazel.build/github.com/google/re2/.*tar\.gz' once
+# the archive has been propagated in mirror.bazel.build.
+RE2_URL="$(grep -o 'https://github.com/google/re2/.*tar\.gz' "${BZL_FILE_PATH}" | head -n1)"
FFT2D_URL="$(grep -o 'http.*fft\.tgz' "${BZL_FILE_PATH}" | grep -v bazel-mirror | head -n1)"
DOUBLE_CONVERSION_URL="$(grep -o "https.*google/double-conversion.*\.zip" "${BZL_FILE_PATH}" | head -n1)"
ABSL_URL="$(grep -o 'https://github.com/abseil/abseil-cpp/.*tar.gz' "${BZL_FILE_PATH}" | head -n1)"
diff --git a/tensorflow/contrib/metrics/__init__.py b/tensorflow/contrib/metrics/__init__.py
index 88798d61b7..5645784f8d 100644
--- a/tensorflow/contrib/metrics/__init__.py
+++ b/tensorflow/contrib/metrics/__init__.py
@@ -14,7 +14,9 @@
# ==============================================================================
"""Ops for evaluation metrics and summary statistics.
-See the @{$python/contrib.metrics} guide.
+See the
+[Contrib Metrics](https://tensorflow.org/api_guides/python/contrib.metrics)
+guide.
@@auc_with_confidence_intervals
@@streaming_accuracy
diff --git a/tensorflow/contrib/metrics/python/metrics/classification.py b/tensorflow/contrib/metrics/python/metrics/classification.py
index e553612269..7053907da0 100644
--- a/tensorflow/contrib/metrics/python/metrics/classification.py
+++ b/tensorflow/contrib/metrics/python/metrics/classification.py
@@ -24,7 +24,7 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import metrics_impl
from tensorflow.python.ops import variable_scope
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
# TODO(nsilberman): move into metrics/python/ops/
@@ -174,7 +174,7 @@ def f1_score(labels, predictions, weights=None, num_thresholds=200,
ops.add_to_collections(metrics_collections, best_f1)
return best_f1
- best_f1 = distribute_lib.get_tower_context().merge_call(
+ best_f1 = distribution_strategy_context.get_tower_context().merge_call(
f1_across_towers, values)
update_op = compute_best_f1_score(tp=update_ops['tp'], fp=update_ops['fp'],
diff --git a/tensorflow/contrib/mixed_precision/python/loss_scale_manager.py b/tensorflow/contrib/mixed_precision/python/loss_scale_manager.py
index be7377b151..eba505881f 100644
--- a/tensorflow/contrib/mixed_precision/python/loss_scale_manager.py
+++ b/tensorflow/contrib/mixed_precision/python/loss_scale_manager.py
@@ -41,12 +41,12 @@ class LossScaleManager(object):
applied on variables.
This class is used together with
- @{tf.contrib.mixed_precision.LossScaleOptimizer} for mixed precision training
+ `tf.contrib.mixed_precision.LossScaleOptimizer` for mixed precision training
(float32 variables and float16 ops) on Nvidia GPUs in order to achieve the
same model quality as single precision training, with the benefits of
potential higher throughput.
- See @{tf.contrib.mixed_precision.LossScaleOptimizer} for more details.
+ See `tf.contrib.mixed_precision.LossScaleOptimizer` for more details.
"""
@abc.abstractmethod
diff --git a/tensorflow/contrib/mixed_precision/python/loss_scale_optimizer.py b/tensorflow/contrib/mixed_precision/python/loss_scale_optimizer.py
index 93050a3ae3..fcce52a07a 100644
--- a/tensorflow/contrib/mixed_precision/python/loss_scale_optimizer.py
+++ b/tensorflow/contrib/mixed_precision/python/loss_scale_optimizer.py
@@ -103,7 +103,7 @@ class LossScaleOptimizer(optimizer.Optimizer):
Args:
opt: The actual optimizer that will be used to compute and apply the
- gradients. Must be an implementation of the @{tf.train.Optimizer}
+ gradients. Must be an implementation of the `tf.train.Optimizer`
interface.
loss_scale_manager: A LossScaleManager object.
"""
@@ -117,7 +117,7 @@ class LossScaleOptimizer(optimizer.Optimizer):
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None):
- """Compute gradients. See base class @{tf.train.Optimizer}."""
+ """Compute gradients. See base class `tf.train.Optimizer`."""
loss_scale = self._loss_scale_manager.get_loss_scale()
if context.executing_eagerly():
@@ -141,7 +141,7 @@ class LossScaleOptimizer(optimizer.Optimizer):
return self._down_scale(grads_and_vars, loss_scale)
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
- """Apply gradients. See base class @{tf.train.Optimizer}."""
+ """Apply gradients. See base class `tf.train.Optimizer`."""
grads = [g for (g, _) in grads_and_vars]
is_finite_grad = []
diff --git a/tensorflow/contrib/model_pruning/BUILD b/tensorflow/contrib/model_pruning/BUILD
index 16ddc38f5a..e662b11be8 100644
--- a/tensorflow/contrib/model_pruning/BUILD
+++ b/tensorflow/contrib/model_pruning/BUILD
@@ -119,6 +119,7 @@ py_test(
deps = [
":pruning_utils",
"//tensorflow/python:client_testlib",
+ "@absl_py//absl/testing:parameterized",
],
)
diff --git a/tensorflow/contrib/model_pruning/python/layers/layers.py b/tensorflow/contrib/model_pruning/python/layers/layers.py
index 466daf204a..d453e350f0 100644
--- a/tensorflow/contrib/model_pruning/python/layers/layers.py
+++ b/tensorflow/contrib/model_pruning/python/layers/layers.py
@@ -139,7 +139,7 @@ def masked_convolution(inputs,
with "NC".
num_outputs: Integer, the number of output filters.
kernel_size: A sequence of N positive integers specifying the spatial
- dimensions of of the filters. Can be a single integer to specify the same
+ dimensions of the filters. Can be a single integer to specify the same
value for all spatial dimensions.
stride: A sequence of N positive integers specifying the stride at which to
compute output. Can be a single integer to specify the same value for all
diff --git a/tensorflow/contrib/model_pruning/python/layers/rnn_cells.py b/tensorflow/contrib/model_pruning/python/layers/rnn_cells.py
index a5b050d25d..5f6c6aea74 100644
--- a/tensorflow/contrib/model_pruning/python/layers/rnn_cells.py
+++ b/tensorflow/contrib/model_pruning/python/layers/rnn_cells.py
@@ -48,7 +48,7 @@ class MaskedBasicLSTMCell(tf_rnn.BasicLSTMCell):
It does not allow cell clipping, a projection layer, and does not
use peep-hole connections: it is the basic baseline.
- For advanced models, please use the full @{tf.nn.rnn_cell.LSTMCell}
+ For advanced models, please use the full `tf.nn.rnn_cell.LSTMCell`
that follows.
"""
diff --git a/tensorflow/contrib/model_pruning/python/pruning.py b/tensorflow/contrib/model_pruning/python/pruning.py
index cd58526ed3..a81abac2fa 100644
--- a/tensorflow/contrib/model_pruning/python/pruning.py
+++ b/tensorflow/contrib/model_pruning/python/pruning.py
@@ -476,8 +476,8 @@ class Pruning(object):
smoothed_threshold, new_mask = self._update_mask(pooled_weights,
threshold)
- updated_mask = pruning_utils.kronecker_product(
- new_mask, array_ops.ones(self._block_dim))
+
+ updated_mask = pruning_utils.expand_tensor(new_mask, self._block_dim)
sliced_mask = array_ops.slice(
updated_mask, [0, 0],
[squeezed_weights.get_shape()[0],
diff --git a/tensorflow/contrib/model_pruning/python/pruning_utils.py b/tensorflow/contrib/model_pruning/python/pruning_utils.py
index ef6c6a3f5d..b50a372e9d 100644
--- a/tensorflow/contrib/model_pruning/python/pruning_utils.py
+++ b/tensorflow/contrib/model_pruning/python/pruning_utils.py
@@ -69,7 +69,7 @@ def weight_threshold_variable(var, scope):
scope: The variable scope of the variable var
Returns:
- a scalar threshold variable initialized to 0.
+ A scalar threshold variable initialized to 0.
"""
with variable_scope.variable_scope(scope):
threshold = variable_scope.get_variable(
@@ -97,6 +97,74 @@ def kronecker_product(mat1, mat2):
return array_ops.reshape(mat1_rsh * mat2_rsh, [m1 * m2, n1 * n2])
+def expand_tensor(tensor, block_dims):
+ """Expands a 2D tensor by replicating the tensor values.
+
+ This is equivalent to the kronecker product of the tensor and a matrix of
+ ones of size block_dims.
+
+ Example:
+
+ tensor = [[1,2]
+ [3,4]]
+ block_dims = [2,2]
+
+ result = [[1 1 2 2]
+ [1 1 2 2]
+ [3 3 4 4]
+ [3 3 4 4]]
+
+ Args:
+ tensor: A 2D tensor that needs to be expanded.
+ block_dims: List of integers specifying the expansion factor.
+
+ Returns:
+ The expanded tensor
+
+ Raises:
+ ValueError: if tensor is not rank-2 or block_dims is does not have 2
+ elements.
+ """
+ if tensor.get_shape().ndims != 2:
+ raise ValueError('Input tensor must be rank 2')
+
+ if len(block_dims) != 2:
+ raise ValueError('block_dims must have 2 elements')
+
+ block_height, block_width = block_dims
+
+ def _tile_rows(tensor, multiple):
+ """Create a new tensor by tiling the tensor along rows."""
+ return array_ops.tile(tensor, [multiple, 1])
+
+ def _generate_indices(num_rows, block_dim):
+ indices = np.zeros(shape=[num_rows * block_dim, 1], dtype=np.int32)
+ for k in range(block_dim):
+ for r in range(num_rows):
+ indices[k * num_rows + r] = r * block_dim + k
+ return indices
+
+ def _replicate_rows(tensor, multiple):
+ tensor_shape = tensor.shape.as_list()
+ expanded_shape = [tensor_shape[0] * multiple, tensor_shape[1]]
+ indices = constant_op.constant(_generate_indices(tensor_shape[0], multiple))
+ return array_ops.scatter_nd(indices, _tile_rows(tensor, multiple),
+ expanded_shape)
+
+ expanded_tensor = tensor
+
+ # Expand rows by factor block_height.
+ if block_height > 1:
+ expanded_tensor = _replicate_rows(tensor, block_height)
+
+ # Transpose and expand by factor block_width. Transpose the result.
+ if block_width > 1:
+ expanded_tensor = array_ops.transpose(
+ _replicate_rows(array_ops.transpose(expanded_tensor), block_width))
+
+ return expanded_tensor
+
+
def _histogram(values, value_range, nbins=100, dtype=dtypes.int32, name=None):
"""Return histogram of values.
diff --git a/tensorflow/contrib/model_pruning/python/pruning_utils_test.py b/tensorflow/contrib/model_pruning/python/pruning_utils_test.py
index ccde5b4e8a..06d7f97437 100644
--- a/tensorflow/contrib/model_pruning/python/pruning_utils_test.py
+++ b/tensorflow/contrib/model_pruning/python/pruning_utils_test.py
@@ -18,6 +18,7 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+from absl.testing import parameterized
import numpy as np
from tensorflow.contrib.model_pruning.python import pruning_utils
@@ -26,6 +27,7 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
+from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
@@ -43,20 +45,6 @@ class PruningUtilsTest(test.TestCase):
cdf = pruning_utils.compute_cdf(abs_values, [0.0, max_value])
self.assertAllEqual(cdf.eval(), cdf_from_histogram.eval())
- def _compare_pooling_methods(self, weights, pooling_kwargs):
- with self.test_session():
- variables.global_variables_initializer().run()
- pooled_weights_tf = array_ops.squeeze(
- nn_ops.pool(
- array_ops.reshape(
- weights,
- [1, weights.get_shape()[0],
- weights.get_shape()[1], 1]), **pooling_kwargs))
- pooled_weights_factorized_pool = pruning_utils.factorized_pool(
- weights, **pooling_kwargs)
- self.assertAllClose(pooled_weights_tf.eval(),
- pooled_weights_factorized_pool.eval())
-
def testHistogram(self):
width = 10
height = 10
@@ -95,26 +83,60 @@ class PruningUtilsTest(test.TestCase):
weights = variable_scope.get_variable("weights", shape=[5, 5, 128, 128])
self._compare_cdf(weights)
- def testFactorizedAvgPool(self):
+
+@parameterized.named_parameters(
+ ("1x1", [1, 1]), ("4x4", [4, 4]), ("6x6", [6, 6]), ("1x4", [1, 4]),
+ ("4x1", [4, 1]), ("1x8", [1, 8]), ("8x1", [8, 1]))
+class PruningUtilsParameterizedTest(test.TestCase, parameterized.TestCase):
+
+ def _compare_pooling_methods(self, weights, pooling_kwargs):
+ with self.test_session():
+ variables.global_variables_initializer().run()
+ pooled_weights_tf = array_ops.squeeze(
+ nn_ops.pool(
+ array_ops.reshape(
+ weights,
+ [1, weights.get_shape()[0],
+ weights.get_shape()[1], 1]), **pooling_kwargs))
+ pooled_weights_factorized_pool = pruning_utils.factorized_pool(
+ weights, **pooling_kwargs)
+ self.assertAllClose(pooled_weights_tf.eval(),
+ pooled_weights_factorized_pool.eval())
+
+ def _compare_expand_tensor_with_kronecker_product(self, tensor, block_dim):
+ with self.test_session() as session:
+ variables.global_variables_initializer().run()
+ expanded_tensor = pruning_utils.expand_tensor(tensor, block_dim)
+ kronecker_product = pruning_utils.kronecker_product(
+ tensor, array_ops.ones(block_dim))
+ expanded_tensor_val, kronecker_product_val = session.run(
+ [expanded_tensor, kronecker_product])
+ self.assertAllEqual(expanded_tensor_val, kronecker_product_val)
+
+ def testFactorizedAvgPool(self, window_shape):
weights = variable_scope.get_variable("weights", shape=[1024, 2048])
pooling_kwargs = {
- "window_shape": [2, 4],
+ "window_shape": window_shape,
"pooling_type": "AVG",
- "strides": [2, 4],
+ "strides": window_shape,
"padding": "SAME"
}
self._compare_pooling_methods(weights, pooling_kwargs)
- def testFactorizedMaxPool(self):
+ def testFactorizedMaxPool(self, window_shape):
weights = variable_scope.get_variable("weights", shape=[1024, 2048])
pooling_kwargs = {
- "window_shape": [2, 4],
+ "window_shape": window_shape,
"pooling_type": "MAX",
- "strides": [2, 4],
+ "strides": window_shape,
"padding": "SAME"
}
self._compare_pooling_methods(weights, pooling_kwargs)
+ def testExpandTensor(self, block_dim):
+ weights = random_ops.random_normal(shape=[1024, 512])
+ self._compare_expand_tensor_with_kronecker_product(weights, block_dim)
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/contrib/nccl/kernels/nccl_manager.h b/tensorflow/contrib/nccl/kernels/nccl_manager.h
index 57a96c5d33..09fad35d23 100644
--- a/tensorflow/contrib/nccl/kernels/nccl_manager.h
+++ b/tensorflow/contrib/nccl/kernels/nccl_manager.h
@@ -20,6 +20,13 @@ limitations under the License.
#include <unordered_map>
#include <vector>
+// TODO(rmlarsen): Get rid of this workaround. "gpu_assert" is defined when
+// setting EIGEN_USE_THREADS. But when defining EIGEN_USE_THREADS here,
+// incAtomic and other CUDA specific symbols are no longer recognized.
+#ifndef gpu_assert
+#define gpu_assert(x)
+#endif
+
#include "third_party/nccl/nccl.h"
#include "tensorflow/core/common_runtime/gpu/gpu_event_mgr.h"
#include "tensorflow/core/framework/tensor.h"
diff --git a/tensorflow/contrib/nn/python/ops/alpha_dropout.py b/tensorflow/contrib/nn/python/ops/alpha_dropout.py
index 2f92d05ba8..98f4264fe0 100644
--- a/tensorflow/contrib/nn/python/ops/alpha_dropout.py
+++ b/tensorflow/contrib/nn/python/ops/alpha_dropout.py
@@ -43,7 +43,7 @@ def alpha_dropout(x, keep_prob, noise_shape=None, seed=None, name=None): # pylin
noise_shape: A 1-D `Tensor` of type `int32`, representing the
shape for randomly generated keep/drop flags.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
name: A name for this operation (optional).
Returns:
diff --git a/tensorflow/contrib/nn/python/ops/sampling_ops.py b/tensorflow/contrib/nn/python/ops/sampling_ops.py
index e65925610c..de71b0845e 100644
--- a/tensorflow/contrib/nn/python/ops/sampling_ops.py
+++ b/tensorflow/contrib/nn/python/ops/sampling_ops.py
@@ -123,15 +123,15 @@ def rank_sampled_softmax_loss(weights,
"""Computes softmax loss using rank-based adaptive resampling.
This has been shown to improve rank loss after training compared to
- @{tf.nn.sampled_softmax_loss}. For a description of the algorithm and some
+ `tf.nn.sampled_softmax_loss`. For a description of the algorithm and some
experimental results, please see: [TAPAS: Two-pass Approximate Adaptive
Sampling for Softmax](https://arxiv.org/abs/1707.03073).
Sampling follows two phases:
* In the first phase, `num_sampled` classes are selected using
- @{tf.nn.learned_unigram_candidate_sampler} or supplied `sampled_values`.
+ `tf.nn.learned_unigram_candidate_sampler` or supplied `sampled_values`.
The logits are calculated on those sampled classes. This phases is
- similar to @{tf.nn.sampled_softmax_loss}.
+ similar to `tf.nn.sampled_softmax_loss`.
* In the second phase, the `num_resampled` classes with highest predicted
probability are kept. Probabilities are
`LogSumExp(logits / resampling_temperature)`, where the sum is over
@@ -142,7 +142,7 @@ def rank_sampled_softmax_loss(weights,
picks more candidates close to the predicted classes. A common strategy is
to decrease the temperature as training proceeds.
- See @{tf.nn.sampled_softmax_loss} for more documentation on sampling and
+ See `tf.nn.sampled_softmax_loss` for more documentation on sampling and
for typical default values for some of the parameters.
This operation is for training only. It is generally an underestimate of
@@ -197,7 +197,7 @@ def rank_sampled_softmax_loss(weights,
where a sampled class equals one of the target classes.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
- See @{tf.nn.embedding_lookup} for more details.
+ See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
Returns:
diff --git a/tensorflow/contrib/opt/BUILD b/tensorflow/contrib/opt/BUILD
index 778b710d78..5319a8b655 100644
--- a/tensorflow/contrib/opt/BUILD
+++ b/tensorflow/contrib/opt/BUILD
@@ -20,6 +20,7 @@ py_library(
"python/training/elastic_average_optimizer.py",
"python/training/external_optimizer.py",
"python/training/ggt.py",
+ "python/training/lars_optimizer.py",
"python/training/lazy_adam_optimizer.py",
"python/training/model_average_optimizer.py",
"python/training/moving_average_optimizer.py",
@@ -365,3 +366,18 @@ py_test(
"@absl_py//absl/testing:parameterized",
],
)
+
+py_test(
+ name = "lars_optimizer_test",
+ srcs = ["python/training/lars_optimizer_test.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":opt_py",
+ "//tensorflow/python:client",
+ "//tensorflow/python:client_testlib",
+ "//tensorflow/python:dtypes",
+ "//tensorflow/python:variables",
+ "//third_party/py/numpy",
+ "@six_archive//:six",
+ ],
+)
diff --git a/tensorflow/contrib/opt/__init__.py b/tensorflow/contrib/opt/__init__.py
index 9471fb0181..781621dba0 100644
--- a/tensorflow/contrib/opt/__init__.py
+++ b/tensorflow/contrib/opt/__init__.py
@@ -24,6 +24,7 @@ from tensorflow.contrib.opt.python.training.addsign import *
from tensorflow.contrib.opt.python.training.drop_stale_gradient_optimizer import *
from tensorflow.contrib.opt.python.training.elastic_average_optimizer import *
from tensorflow.contrib.opt.python.training.external_optimizer import *
+from tensorflow.contrib.opt.python.training.lars_optimizer import *
from tensorflow.contrib.opt.python.training.ggt import *
from tensorflow.contrib.opt.python.training.lazy_adam_optimizer import *
from tensorflow.contrib.opt.python.training.model_average_optimizer import *
@@ -46,6 +47,7 @@ _allowed_symbols = [
'DelayCompensatedGradientDescentOptimizer',
'DropStaleGradientOptimizer',
'ExternalOptimizerInterface',
+ 'LARSOptimizer',
'LazyAdamOptimizer',
'NadamOptimizer',
'MovingAverageOptimizer',
diff --git a/tensorflow/contrib/opt/python/training/elastic_average_optimizer.py b/tensorflow/contrib/opt/python/training/elastic_average_optimizer.py
index 5763593b81..bbafd59aae 100644
--- a/tensorflow/contrib/opt/python/training/elastic_average_optimizer.py
+++ b/tensorflow/contrib/opt/python/training/elastic_average_optimizer.py
@@ -17,22 +17,23 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
-from tensorflow.python.ops import math_ops
-
-from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import control_flow_ops
+from tensorflow.python.ops import data_flow_ops
+from tensorflow.python.ops import gen_nn_ops
+from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.training import optimizer
+from tensorflow.python.training import saver
from tensorflow.python.training import session_run_hook
-from tensorflow.python.ops import state_ops
-from tensorflow.python.ops import data_flow_ops
-from tensorflow.python.framework import dtypes
-from tensorflow.python.framework import constant_op
LOCAL_VARIABLE_NAME = 'local_center_variable'
GLOBAL_VARIABLE_NAME = 'global_center_variable'
+GLOBAL_STEP = 'global_step'
class ElasticAverageCustomGetter(object):
@@ -52,16 +53,32 @@ class ElasticAverageCustomGetter(object):
with tf.device(
tf.train.replica_device_setter(
worker_device=worker_device,
- ps_device="/job:ps/cpu:0",
+ ps_device="/job:ps",
cluster=cluster)),
tf.variable_scope('',custom_getter=ea_custom_getter):
- hid_w = tf.get_variable(
- initializer=tf.truncated_normal(
- [IMAGE_PIXELS * IMAGE_PIXELS, FLAGS.hidden_units],
- stddev=1.0 / IMAGE_PIXELS),
- name="hid_w")
- hid_b = tf.get_variable(initializer=tf.zeros([FLAGS.hidden_units]),
- name="hid_b")
+ ...
+ create your model here
+ ...
+ with tf.device(worker_device):
+ opt = tf.train.MomentumOptimizer(...)
+ optimizer = ElasticAverageOptimizer(
+ opt,
+ num_worker=2,
+ moving_rate=0.01, # or use default value
+ communication_period=20,
+ ea_custom_getter=ea_custom_getter)
+ ...
+ train_op = optimizer.apply_gradients(
+ grads_vars,
+ global_step=global_step)
+ ...
+ hooks = [optimizer.make_session_run_hook(is_chief, task_index)]
+ ...
+ with tf.train.MonitoredTrainingSession(master=server.target,
+ is_chief=is_chief,
+ checkpoint_dir=("...),
+ save_checkpoint_secs=600,
+ hooks=hooks) as mon_sess:
"""
def __init__(self, worker_device):
@@ -83,24 +100,40 @@ class ElasticAverageCustomGetter(object):
collections=[ops.GraphKeys.LOCAL_VARIABLES],
*args,
**kwargs)
- global_center_variable = variable_scope.variable(
+ if kwargs['reuse'] == True:
+ return local_var
+ global_center_variable = getter(
name='%s/%s' % (GLOBAL_VARIABLE_NAME, name),
- initial_value=local_var.initialized_value(),
trainable=False,
- collections=[ops.GraphKeys.GLOBAL_VARIABLES])
+ collections=[ops.GraphKeys.GLOBAL_VARIABLES],
+ *args,
+ **kwargs)
with ops.device(self._worker_device):
- local_center_variable = variable_scope.variable(
+ local_center_variable = getter(
name='%s/%s' % (LOCAL_VARIABLE_NAME, name),
- initial_value=local_var.initialized_value(),
trainable=False,
- collections=[ops.GraphKeys.LOCAL_VARIABLES])
-
- self._local_map[local_var] = local_center_variable
- self._global_map[local_var] = global_center_variable
+ collections=[ops.GraphKeys.LOCAL_VARIABLES],
+ *args,
+ **kwargs)
+ if kwargs['partitioner'] is None:
+ self._local_map[local_var] = local_center_variable
+ self._global_map[local_var] = global_center_variable
+ else:
+ v_list = list(local_var)
+ for i in range(len(v_list)):
+ self._local_map[v_list[i]] \
+ = list(local_center_variable)[i]
+ self._global_map[v_list[i]] \
+ = list(global_center_variable)[i]
return local_var
else:
- return getter(name, trainable, collections, *args, **kwargs)
+ return getter(
+ name,
+ trainable=trainable,
+ collections=collections,
+ *args,
+ **kwargs)
class ElasticAverageOptimizer(optimizer.Optimizer):
@@ -125,6 +158,7 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
moving_rate=None,
rho=None,
use_locking=True,
+ synchronous=False,
name='ElasticAverageOptimizer'):
"""Construct a new gradient descent optimizer.
@@ -136,9 +170,16 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
communication_period: An int point value to controls the frequency
of the communication between every worker and the ps.
moving_rate: A floating point value to control the elastic difference.
- rho: the amount of exploration we allow ine the model. The default
+ rho: the amount of exploration we allow in the model. The default
value is moving_rate/learning_rate
+ rho=0.0 is suggested in async mode.
use_locking: If True use locks for update operations.
+ synchronous: Add_sync_queues_and_barrier or not.
+ True: all workers will wait for each other before start training
+ False: worker can start training when its initilization is done,
+ no need to wait for everyone is ready.
+ in case one worker is restarted, it can join and continue
+ training without being blocked.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "ElasticAverageOptimizer".
"""
@@ -148,6 +189,7 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
self._period = communication_period
self._local_map = ea_custom_getter._local_map
self._global_map = ea_custom_getter._global_map
+ self._synchronous = synchronous
if moving_rate is None:
self._moving_rate = self.BETA / communication_period / num_worker
@@ -241,11 +283,29 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
TypeError: If `grads_and_vars` is malformed.
ValueError: If none of the variables have gradients.
"""
+ global_old = set(n.op.name for n in variables.global_variables())
apply_updates = self._opt.apply_gradients(grads_and_vars)
+ global_new = set(n.op.name for n in variables.global_variables())
with ops.control_dependencies([apply_updates]):
local_update = state_ops.assign_add(
self._local_step, 1, name='local_step_update').op
+ # this is for place the variables created by optimizer to local collection
+ # e.g., AdamOptimizer will create beta as global variables
+ def _adjust_optimizer_variable_collection(opt_vars):
+ g = ops.get_default_graph()
+ idx = 0
+ for _ in range(len(g._collections[ops.GraphKeys.GLOBAL_VARIABLES])):
+ var = g.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES)[idx]
+ name = var.op.name
+ if name in opt_vars:
+ ops.add_to_collection(ops.GraphKeys.LOCAL_VARIABLES, var)
+ del g.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES)[idx]
+ else:
+ idx += 1
+
+ _adjust_optimizer_variable_collection(global_new - global_old)
+
# update global variables.
def _Update_global_variables():
local_vars = [v for g, v in grads_and_vars if g is not None]
@@ -290,7 +350,7 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
variables equal to the global center variables before the training begins"""
def _Add_sync_queues_and_barrier(enqueue_after_list):
- """Adds ops to enqueu on all worker queues"""
+ """Adds ops to enqueue on all worker queues"""
sync_queues = [
data_flow_ops.FIFOQueue(
self._num_worker, [dtypes.bool],
@@ -324,6 +384,9 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
init_ops.append(state_ops.assign(lc_var, gc_var))
init_op = control_flow_ops.group(*(init_ops))
+ if self._synchronous == False:
+ return init_op
+
sync_queue_op = _Add_sync_queues_and_barrier([init_op])
return sync_queue_op
@@ -331,6 +394,51 @@ class ElasticAverageOptimizer(optimizer.Optimizer):
"""Creates a hook to handle ElasticAverageOptimizerHook ops such as initialization."""
return _ElasticAverageOptimizerHook(self, is_chief, task_index)
+ def swapping_saver(self, var_list=None, name='swapping_saver', **kwargs):
+ """Create a saver copy global_center_variable to trainable variables
+ Please call this function after all your variables created with
+ ElasticAverageCustomGetter. For evaluations or inference, use this saver
+ during training. It will save the global_center_variable of the trained
+ parameters under the original parameter names.
+ Args:
+ var_list: List of variables to save, as per `Saver()`.
+ If set to None, save all the trainable_variables that have
+ been created before this call.
+ name: The name of the saver.
+ **kwargs: Keyword arguments of `Saver()`.
+ Returns:
+ A `tf.train.Saver` object.
+ Raises:
+ RuntimeError: global_center_variable is empty, please make sure
+ this is called after model created and
+ ElasticAverageCustomGetter is used when declaring you model
+ """
+ if not self._global_map:
+ raise RuntimeError('global_center_variable is empty, please make sure '
+ 'this is called after model created and '
+ 'ElasticAverageCustomGetter is used when declaring '
+ 'you model')
+
+ if var_list is None:
+ var_list = variables.trainable_variables()
+ if not isinstance(var_list, dict):
+ var_list = saver.BaseSaverBuilder.OpListToDict(var_list)
+
+ swapped_var_list = {}
+ for key, var in var_list.items():
+ tensor = var
+
+ if not isinstance(var, list):
+ for tvar in variables.trainable_variables():
+ if tvar.op.name == var.op.name:
+ tensor = self._global_map.get(tvar, var)
+ break
+ else: #partitioned variable
+ tensor = [self._global_map.get(lvar, lvar) for lvar in var]
+
+ swapped_var_list[key] = tensor
+
+ return saver.Saver(swapped_var_list, name=name, **kwargs)
class _ElasticAverageOptimizerHook(session_run_hook.SessionRunHook):
@@ -351,3 +459,7 @@ class _ElasticAverageOptimizerHook(session_run_hook.SessionRunHook):
if self._is_chief:
self._global_init_op = variables.global_variables_initializer()
self._variable_init_op = self._ea_optimizer.get_init_op(self._task_index)
+
+ def after_create_session(self, session, coord):
+ """Run initialization ops"""
+ session.run(self._variable_init_op) \ No newline at end of file
diff --git a/tensorflow/contrib/opt/python/training/elastic_average_optimizer_test.py b/tensorflow/contrib/opt/python/training/elastic_average_optimizer_test.py
index 5ed8057b86..5bf6a08de1 100644
--- a/tensorflow/contrib/opt/python/training/elastic_average_optimizer_test.py
+++ b/tensorflow/contrib/opt/python/training/elastic_average_optimizer_test.py
@@ -17,17 +17,22 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import os
import portpicker
+from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
+from tensorflow.python.ops import init_ops
+from tensorflow.python.ops import partitioned_variables
+from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
+from tensorflow.python.training import device_setter
from tensorflow.python.training import gradient_descent
+from tensorflow.python.training import saver
from tensorflow.python.training import server_lib
from tensorflow.python.training import training
from tensorflow.python.training import training_util
-from tensorflow.python.ops import variable_scope
-from tensorflow.python.training import device_setter
from tensorflow.contrib.opt.python.training.elastic_average_optimizer import \
ElasticAverageOptimizer, ElasticAverageCustomGetter, GLOBAL_VARIABLE_NAME
@@ -59,29 +64,49 @@ def create_local_cluster(num_workers, num_ps, protocol="grpc"):
# Creates the workers and return their sessions, graphs, train_ops.
# Chief worker will update at last
-def _get_workers(num_workers, period, workers, moving_rate):
+def _get_workers(num_workers, period, workers, moving_rate, num_ps=1):
sessions = []
graphs = []
train_ops = []
+ savers = []
for worker_id in range(num_workers):
graph = ops.Graph()
is_chief = (worker_id == 0)
with graph.as_default():
worker_device = "/job:worker/task:%d/cpu:0" % (worker_id)
- ea_coustom = ElasticAverageCustomGetter(worker_device=worker_device)
+ ea_custom = ElasticAverageCustomGetter(worker_device=worker_device)
with variable_scope.variable_scope(
- "", custom_getter=ea_coustom), ops.device(
+ "", custom_getter=ea_custom), ops.device(
device_setter.replica_device_setter(
worker_device=worker_device,
ps_device="/job:ps/task:0/cpu:0",
ps_tasks=1)):
- global_step = variables.Variable(0, name="global_step", trainable=False)
+ global_step = training_util.get_or_create_global_step()
var_0 = variable_scope.get_variable(initializer=0.0, name="v0")
var_1 = variable_scope.get_variable(initializer=1.0, name="v1")
+ if num_ps > 1:
+ with variable_scope.variable_scope(
+ "",
+ partitioner=partitioned_variables.fixed_size_partitioner(
+ num_ps, axis=0),
+ custom_getter=ea_custom), ops.device(
+ device_setter.replica_device_setter(
+ worker_device=worker_device,
+ ps_device="/job:ps/task:0/cpu:0",
+ ps_tasks=num_ps)):
+
+ partition_var = variable_scope.get_variable(
+ 'partition_var',
+ shape=[2, 4],
+ initializer=init_ops.ones_initializer)
+ part_0 = list(partition_var)[0]
+ part_1 = list(partition_var)[1]
with ops.device("/job:worker/task:" + str(worker_id)):
grads_0 = constant_op.constant(-1.0)
grads_1 = constant_op.constant(-1.0)
+ grads_part_0 = constant_op.constant([[-1., -1., -1., -1.]])
+ grads_part_1 = constant_op.constant([[-1., -1., -1., -1.]])
sgd_opt = gradient_descent.GradientDescentOptimizer(1.0)
opt = ElasticAverageOptimizer(
@@ -89,12 +114,22 @@ def _get_workers(num_workers, period, workers, moving_rate):
num_worker=num_workers,
moving_rate=moving_rate,
communication_period=period,
- ea_custom_getter=ea_coustom)
- train_op = [
- opt.apply_gradients(([grads_0, var_0], [grads_1, var_1]),
- global_step)
- ]
+ ea_custom_getter=ea_custom)
+ if num_ps == 1:
+ train_op = [
+ opt.apply_gradients(([grads_0, var_0], [grads_1, var_1]),
+ global_step)
+ ]
+ else:
+ train_op = [
+ opt.apply_gradients(([grads_0, var_0],
+ [grads_1, var_1],
+ [grads_part_0, part_0],
+ [grads_part_1, part_1]),
+ global_step)
+ ]
easgd_hook = opt.make_session_run_hook(is_chief, worker_id)
+ saver = opt.swapping_saver()
# Creates MonitoredSession
sess = training.MonitoredTrainingSession(
workers[worker_id].target, hooks=[easgd_hook])
@@ -102,8 +137,9 @@ def _get_workers(num_workers, period, workers, moving_rate):
sessions.append(sess)
graphs.append(graph)
train_ops.append(train_op)
+ savers.append(saver)
- return sessions, graphs, train_ops
+ return sessions, graphs, train_ops, savers
class ElasticAverageOptimizerTest(test.TestCase):
@@ -118,7 +154,7 @@ class ElasticAverageOptimizerTest(test.TestCase):
cluster, workers, _ = create_local_cluster(
num_workers=num_workers, num_ps=num_ps)
- sessions, graphs, train_ops = _get_workers(
+ sessions, graphs, train_ops, savers = _get_workers(
num_workers, communication_period, workers, 1.0)
var_0 = graphs[0].get_tensor_by_name("v0:0")
@@ -158,6 +194,21 @@ class ElasticAverageOptimizerTest(test.TestCase):
self.assertAllEqual(2.0, sessions[0].run(var_0_g))
self.assertAllEqual(3.0, sessions[0].run(var_1_g))
self.assertAllEqual(1, sessions[0].run(global_step))
+ sessions[0].run(train_ops[0])
+
+ # save, data will be global value
+ outfile = os.path.join(test.get_temp_dir(), "model")
+ savers[0].save(sessions[0]._sess._sess._sess._sess,
+ save_path=outfile)
+ ops.reset_default_graph() # restore on a new graph
+ with session.Session() as sess:
+ v0 = variable_scope.get_variable(initializer=0.0, name="v0")
+ v1 = variable_scope.get_variable(initializer=1.0, name="v1")
+ sess.run(variables.local_variables_initializer())
+ saver_opt = saver.Saver(var_list=[v1, v0])
+ saver_opt.restore(sess, outfile)
+ self.assertAllEqual(2.0, sess.run(v0))
+ self.assertAllEqual(3.0, sess.run(v1))
def test2Worker1Period(self):
num_workers = 2
@@ -166,8 +217,8 @@ class ElasticAverageOptimizerTest(test.TestCase):
cluster, workers, _ = create_local_cluster(
num_workers=num_workers, num_ps=num_ps)
- sessions, graphs, train_ops = _get_workers(
- num_workers, communication_period, workers, 0.5)
+ sessions, graphs, train_ops, savers = _get_workers(
+ num_workers, communication_period, workers, 0.5, num_ps=2)
var_0 = graphs[0].get_tensor_by_name("v0:0")
var_1 = graphs[0].get_tensor_by_name("v1:0")
@@ -177,6 +228,9 @@ class ElasticAverageOptimizerTest(test.TestCase):
var_0_g = graphs[0].get_tensor_by_name(GLOBAL_VARIABLE_NAME + "/v0:0")
var_1_g = graphs[0].get_tensor_by_name(GLOBAL_VARIABLE_NAME + "/v1:0")
+ part_0_g = graphs[0].get_tensor_by_name(
+ GLOBAL_VARIABLE_NAME + "/partition_var/part_0:0")
+
# Verify the initialized value.
self.assertAllEqual(0.0, sessions[0].run(var_0))
self.assertAllEqual(1.0, sessions[0].run(var_1))
@@ -194,22 +248,45 @@ class ElasticAverageOptimizerTest(test.TestCase):
self.assertAllEqual(1.75, sessions[0].run(var_1_g))
self.assertAllEqual(0.75, sessions[1].run(var_0_1))
self.assertAllEqual(1.75, sessions[1].run(var_1_1))
+ # part_0 of global_center copy
+ part_0_g = sessions[0].run(part_0_g)
+
+ outfile = os.path.join(test.get_temp_dir(), "model")
+ savers[0].save(sessions[0]._sess._sess._sess._sess,
+ save_path=outfile)
+
+ # verify restore of partitioned_variables
+ ops.reset_default_graph() # restore on a new graph
+ g = ops.get_default_graph()
+ with session.Session() as sess, g.as_default():
+ with variable_scope.variable_scope(
+ "",
+ partitioner=partitioned_variables.fixed_size_partitioner(
+ num_ps, axis=0)):
+ partition_var = variable_scope.get_variable(
+ 'partition_var',
+ shape=[2, 4],
+ initializer=init_ops.ones_initializer)
+ s = saver.Saver(var_list=[partition_var])
+ s.restore(sess, outfile)
+ part_0 = g.get_tensor_by_name('partition_var/part_0:0')
+ self.assertAllEqual(part_0_g, sess.run(part_0))
def testPS2TasksWithClusterSpecClass(self):
cluster_spec = server_lib.ClusterSpec({
"ps": ["ps0:2222", "ps1:2222"],
"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]
})
- ea_coustom = ElasticAverageCustomGetter(worker_device="/job:worker/task:0")
+ ea_custom = ElasticAverageCustomGetter(worker_device="/job:worker/task:0")
from tensorflow.python.training import device_setter
with ops.device(
device_setter.replica_device_setter(cluster=cluster_spec,
worker_device="/job:worker/task:0",
ps_device="/job:ps")), \
- variable_scope.variable_scope("", custom_getter=ea_coustom):
+ variable_scope.variable_scope("", custom_getter=ea_custom):
v = variable_scope.get_variable(initializer=[1, 2], name="v")
w = variable_scope.get_variable(initializer=[2, 1], name="w")
- v_g, w_g = ea_coustom._global_map[v], ea_coustom._global_map[w]
+ v_g, w_g = ea_custom._global_map[v], ea_custom._global_map[w]
self.assertDeviceEqual("/job:worker/task:0", v.device)
self.assertDeviceEqual("job:ps/task:0", v_g.device)
self.assertDeviceEqual("/job:worker/task:0", w.device)
diff --git a/tensorflow/contrib/opt/python/training/lars_optimizer.py b/tensorflow/contrib/opt/python/training/lars_optimizer.py
new file mode 100644
index 0000000000..a8dafd9a4c
--- /dev/null
+++ b/tensorflow/contrib/opt/python/training/lars_optimizer.py
@@ -0,0 +1,164 @@
+# 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.
+# ==============================================================================
+"""Layer-wise Adaptive Rate Scaling optimizer for large-batch training."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import linalg_ops
+from tensorflow.python.ops import math_ops
+from tensorflow.python.training import optimizer
+from tensorflow.python.training import training_ops
+
+
+class LARSOptimizer(optimizer.Optimizer):
+ """Layer-wise Adaptive Rate Scaling for large batch training.
+
+ Introduced by "Large Batch Training of Convolutional Networks" by Y. You,
+ I. Gitman, and B. Ginsburg. (https://arxiv.org/abs/1708.03888)
+
+ Implements the LARS learning rate scheme presented in the paper above. This
+ optimizer is useful when scaling the batch size to up to 32K without
+ significant performance degradation. It is recommended to use the optimizer
+ in conjunction with:
+ - Gradual learning rate warm-up
+ - Linear learning rate scaling
+ - Poly rule learning rate decay
+
+ Note, LARS scaling is currently only enabled for dense tensors. Sparse tensors
+ use the default momentum optimizer.
+ """
+
+ def __init__(
+ self,
+ learning_rate,
+ momentum=0.9,
+ weight_decay=0.0001,
+ # The LARS coefficient is a hyperparameter
+ eeta=0.001,
+ epsilon=0.0,
+ name="LARSOptimizer",
+ # Enable skipping variables from LARS scaling.
+ # TODO(sameerkm): Enable a direct mechanism to pass a
+ # subset of variables to the optimizer.
+ skip_list=None,
+ use_nesterov=False):
+ """Construct a new LARS Optimizer.
+
+ Args:
+ learning_rate: A `Tensor` or floating point value. The base learning rate.
+ momentum: A floating point value. Momentum hyperparameter.
+ weight_decay: A floating point value. Weight decay hyperparameter.
+ eeta: LARS coefficient as used in the paper. Dfault set to LARS
+ coefficient from the paper. (eeta / weight_decay) determines the highest
+ scaling factor in LARS.
+ epsilon: Optional epsilon parameter to be set in models that have very
+ small gradients. Default set to 0.0.
+ name: Optional name prefix for variables and ops created by LARSOptimizer.
+ skip_list: List of strings to enable skipping variables from LARS scaling.
+ If any of the strings in skip_list is a subset of var.name, variable
+ 'var' is skipped from LARS scaling. For a typical classification model
+ with batch normalization, the skip_list is ['batch_normalization',
+ 'bias']
+ use_nesterov: when set to True, nesterov momentum will be enabled
+
+ Raises:
+ ValueError: If a hyperparameter is set to a non-sensical value.
+ """
+ if momentum < 0.0:
+ raise ValueError("momentum should be positive: %s" % momentum)
+ if weight_decay < 0.0:
+ raise ValueError("weight_decay should be positive: %s" % weight_decay)
+ super(LARSOptimizer, self).__init__(use_locking=False, name=name)
+
+ self._learning_rate = learning_rate
+ self._momentum = momentum
+ self._weight_decay = weight_decay
+ self._eeta = eeta
+ self._epsilon = epsilon
+ self._name = name
+ self._skip_list = skip_list
+ self._use_nesterov = use_nesterov
+
+ def _create_slots(self, var_list):
+ for v in var_list:
+ self._zeros_slot(v, "momentum", self._name)
+
+ def compute_lr(self, grad, var):
+ scaled_lr = self._learning_rate
+ if self._skip_list is None or not any(v in var.name
+ for v in self._skip_list):
+ w_norm = linalg_ops.norm(var, ord=2)
+ g_norm = linalg_ops.norm(grad, ord=2)
+ trust_ratio = array_ops.where(
+ math_ops.greater(w_norm, 0),
+ array_ops.where(
+ math_ops.greater(g_norm, 0),
+ (self._eeta * w_norm /
+ (g_norm + self._weight_decay * w_norm + self._epsilon)), 1.0),
+ 1.0)
+ scaled_lr = self._learning_rate * trust_ratio
+ return scaled_lr
+
+ def _apply_dense(self, grad, var):
+ scaled_lr = self.compute_lr(grad, var)
+ mom = self.get_slot(var, "momentum")
+ return training_ops.apply_momentum(
+ var,
+ mom,
+ scaled_lr,
+ grad,
+ self._momentum,
+ use_locking=False,
+ use_nesterov=self._use_nesterov)
+
+ def _resource_apply_dense(self, grad, var):
+ scaled_lr = self.compute_lr(grad, var)
+ mom = self.get_slot(var, "momentum")
+ return training_ops.resource_apply_momentum(
+ var.handle,
+ mom.handle,
+ scaled_lr,
+ grad,
+ self._momentum,
+ use_locking=False,
+ use_nesterov=self._use_nesterov)
+
+ # Fallback to momentum optimizer for sparse tensors
+ def _apply_sparse(self, grad, var):
+ mom = self.get_slot(var, "momentum")
+ return training_ops.sparse_apply_momentum(
+ var,
+ mom,
+ math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
+ grad.values,
+ grad.indices,
+ math_ops.cast(self._momentum_tensor, var.dtype.base_dtype),
+ use_locking=self._use_locking,
+ use_nesterov=self._use_nesterov).op
+
+ def _resource_apply_sparse(self, grad, var, indices):
+ mom = self.get_slot(var, "momentum")
+ return training_ops.resource_sparse_apply_momentum(
+ var.handle,
+ mom.handle,
+ math_ops.cast(self._learning_rate_tensor, grad.dtype),
+ grad,
+ indices,
+ math_ops.cast(self._momentum_tensor, grad.dtype),
+ use_locking=self._use_locking,
+ use_nesterov=self._use_nesterov)
diff --git a/tensorflow/contrib/opt/python/training/lars_optimizer_test.py b/tensorflow/contrib/opt/python/training/lars_optimizer_test.py
new file mode 100644
index 0000000000..d94249b994
--- /dev/null
+++ b/tensorflow/contrib/opt/python/training/lars_optimizer_test.py
@@ -0,0 +1,127 @@
+# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0. Licensed to the Apache
+# Software Foundation. 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.
+# ==============================================================================
+"""Test for Layer-wise Adaptive Rate Scaling optimizer."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import numpy as np
+
+from tensorflow.contrib.opt.python.training import lars_optimizer as lo
+from tensorflow.python.framework import dtypes
+from tensorflow.python.ops import variables
+from tensorflow.python.platform import test
+
+
+class LARSOptimizerTest(test.TestCase):
+
+ def testLARSGradientOneStep(self):
+ for _ in range(10):
+ for dtype in [dtypes.float32, dtypes.float64]:
+ with self.test_session() as sess:
+ shape = [3, 3]
+ var_np = np.ones(shape)
+ grad_np = np.ones(shape)
+ lr_np = 0.1
+ m_np = 0.9
+ wd_np = 0.1
+ ep_np = 1e-5
+ eeta = 0.1
+ vel_np = np.zeros(shape)
+
+ var = variables.Variable(var_np, dtype=dtype)
+ grad = variables.Variable(grad_np, dtype=dtype)
+ opt = lo.LARSOptimizer(
+ learning_rate=lr_np,
+ momentum=m_np,
+ weight_decay=wd_np,
+ eeta=eeta,
+ epsilon=ep_np)
+
+ step = opt.apply_gradients([(grad, var)])
+ variables.global_variables_initializer().run()
+
+ pre_var = sess.run(var)
+ pre_vel = sess.run(opt.get_slot(var, 'momentum'))
+ self.assertAllClose(var_np, pre_var)
+ self.assertAllClose(vel_np, pre_vel)
+
+ step.run()
+ post_var = sess.run(var)
+ post_vel = sess.run(opt.get_slot(var, 'momentum'))
+
+ w_norm = np.linalg.norm(var_np.flatten(), ord=2)
+ g_norm = np.linalg.norm(grad_np.flatten(), ord=2)
+ trust_ratio = eeta * w_norm / (g_norm + wd_np * w_norm + ep_np)
+ scaled_lr = lr_np * trust_ratio
+
+ vel_np = m_np * vel_np + grad_np
+ var_np -= scaled_lr * vel_np
+
+ self.assertAllClose(var_np, post_var)
+ self.assertAllClose(vel_np, post_vel)
+
+ def testLARSGradientMultiStep(self):
+ for _ in range(10):
+ for dtype in [dtypes.float32, dtypes.float64]:
+ with self.test_session() as sess:
+ shape = [3, 3]
+ var_np = np.ones(shape)
+ grad_np = np.ones(shape)
+ lr_np = 0.1
+ m_np = 0.9
+ wd_np = 0.1
+ ep_np = 1e-5
+ eeta = 0.1
+ vel_np = np.zeros(shape)
+
+ var = variables.Variable(var_np, dtype=dtype)
+ grad = variables.Variable(grad_np, dtype=dtype)
+ opt = lo.LARSOptimizer(
+ learning_rate=lr_np,
+ momentum=m_np,
+ eeta=eeta,
+ weight_decay=wd_np,
+ epsilon=ep_np)
+
+ step = opt.apply_gradients([(grad, var)])
+ variables.global_variables_initializer().run()
+
+ pre_var = sess.run(var)
+ pre_vel = sess.run(opt.get_slot(var, 'momentum'))
+ self.assertAllClose(var_np, pre_var)
+ self.assertAllClose(vel_np, pre_vel)
+
+ for _ in range(10):
+ step.run()
+
+ post_var = sess.run(var)
+ post_vel = sess.run(opt.get_slot(var, 'momentum'))
+
+ w_norm = np.linalg.norm(var_np.flatten(), ord=2)
+ g_norm = np.linalg.norm(grad_np.flatten(), ord=2)
+ trust_ratio = eeta * w_norm / (g_norm + wd_np * w_norm + ep_np)
+ scaled_lr = lr_np * trust_ratio
+
+ vel_np = m_np * vel_np + grad_np
+ var_np -= scaled_lr * vel_np
+
+ self.assertAllClose(var_np, post_var)
+ self.assertAllClose(vel_np, post_vel)
+
+
+if __name__ == '__main__':
+ test.main()
diff --git a/tensorflow/contrib/opt/python/training/shampoo.py b/tensorflow/contrib/opt/python/training/shampoo.py
index a98866b180..294627f42a 100644
--- a/tensorflow/contrib/opt/python/training/shampoo.py
+++ b/tensorflow/contrib/opt/python/training/shampoo.py
@@ -139,7 +139,7 @@ class ShampooOptimizer(optimizer.Optimizer):
shape = np.array(v.get_shape())
for i, d in enumerate(shape):
d_tensor = ops.convert_to_tensor(d)
- if d < self._max_matrix_size:
+ if d <= self._max_matrix_size:
mat_g_init = array_ops.zeros_like(linalg_ops.eye(d_tensor))
if self._svd_interval > 1:
_ = self._get_or_make_slot(v, linalg_ops.eye(d_tensor),
@@ -163,7 +163,7 @@ class ShampooOptimizer(optimizer.Optimizer):
return self._apply_sparse_shared(grad.values, grad.indices, var)
def _apply_sparse_shared(self, grad_values, grad_indices, var):
- if var.get_shape()[0] < self._max_matrix_size or self._gbar_decay != 0.0:
+ if var.get_shape()[0] <= self._max_matrix_size or self._gbar_decay != 0.0:
# The dimension is small enough, we can make the variable dense and
# do a dense update
dense_grad = array_ops.scatter_nd(
@@ -408,7 +408,7 @@ class ShampooOptimizer(optimizer.Optimizer):
for i, mat_g in enumerate(mat_g_list):
# axes is the list of indices to reduce - everything but the current i.
axes = list(range(i)) + list(range(i+1, v_rank))
- if shape[i] < self._max_matrix_size:
+ if shape[i] <= self._max_matrix_size:
# If the tensor size is sufficiently small perform full Shampoo update
# Note if precond_update_interval > 1 and mat_gbar_decay_t != 1, this
# is not strictly correct. However we will use it for now, and
diff --git a/tensorflow/contrib/optimizer_v2/optimizer_v2.py b/tensorflow/contrib/optimizer_v2/optimizer_v2.py
index 8c11d8bcfd..f6ecaba834 100644
--- a/tensorflow/contrib/optimizer_v2/optimizer_v2.py
+++ b/tensorflow/contrib/optimizer_v2/optimizer_v2.py
@@ -34,6 +34,7 @@ from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import optimizer as optimizer_v1
from tensorflow.python.training import slot_creator
from tensorflow.python.training.checkpointable import base as checkpointable
@@ -620,7 +621,7 @@ class OptimizerV2(optimizer_v1.Optimizer):
# Map from graph_key to state for that graph. We use the graph_key
# since it works in both eager and graph mode, and gives the outer
# graph inside functions.
- tower_context = distribute_lib.get_tower_context()
+ tower_context = distribution_strategy_context.get_tower_context()
if tower_context is None:
# In a cross-tower context for a DistributionStrategy, which means
# only one Optimizer will be created, not one per tower.
@@ -769,7 +770,8 @@ class OptimizerV2(optimizer_v1.Optimizer):
distribute_lib.get_loss_reduction() ==
variable_scope.VariableAggregation.MEAN)
if scale_loss_by_num_towers:
- num_towers = distribute_lib.get_distribution_strategy().num_towers
+ num_towers = distribution_strategy_context.get_distribution_strategy(
+ ).num_towers
if num_towers > 1:
loss_value *= 1. / num_towers
@@ -788,7 +790,8 @@ class OptimizerV2(optimizer_v1.Optimizer):
distribute_lib.get_loss_reduction() ==
variable_scope.VariableAggregation.MEAN)
if scale_loss_by_num_towers:
- num_towers = distribute_lib.get_distribution_strategy().num_towers
+ num_towers = distribution_strategy_context.get_distribution_strategy(
+ ).num_towers
if num_towers > 1:
loss *= 1. / num_towers
@@ -862,7 +865,7 @@ class OptimizerV2(optimizer_v1.Optimizer):
if not filtered:
raise ValueError("No gradients provided for any variable: %s." %
([str(v) for _, v in grads_and_vars],))
- return distribute_lib.get_tower_context().merge_call(
+ return distribution_strategy_context.get_tower_context().merge_call(
self._distributed_apply, filtered, global_step=global_step, name=name)
def _get_or_create_state(self, var_list=None):
diff --git a/tensorflow/contrib/optimizer_v2/rmsprop.py b/tensorflow/contrib/optimizer_v2/rmsprop.py
index 164ff0ea06..3de53405ec 100644
--- a/tensorflow/contrib/optimizer_v2/rmsprop.py
+++ b/tensorflow/contrib/optimizer_v2/rmsprop.py
@@ -22,7 +22,7 @@ A detailed description of rmsprop.
- divide gradient by the root of this average
mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2
-mom = momentum * mom{t-1} + learning_rate * g_t / sqrt(mean_square + epsilon)
+mom = momentum * mom{t-1} + learning_rate * g_t / sqrt(mean_square)
delta = - mom
This implementation of RMSProp uses plain momentum, not Nesterov momentum.
@@ -33,7 +33,7 @@ gradients, and uses that average to estimate the variance:
mean_grad = decay * mean_square{t-1} + (1-decay) * gradient
mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2
mom = momentum * mom{t-1} + learning_rate * g_t /
- sqrt(mean_square - mean_grad**2 + epsilon)
+ sqrt(mean_square - mean_grad**2)
delta = - mom
"""
@@ -43,7 +43,6 @@ from __future__ import print_function
from tensorflow.contrib.optimizer_v2 import optimizer_v2
from tensorflow.python.ops import array_ops
-from tensorflow.python.ops import init_ops
from tensorflow.python.training import training_ops
@@ -87,7 +86,8 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
decay: A float hyperparameter. Discounting factor for the history/coming
gradient.
momentum: A float hyperparameter.
- epsilon: A float hyperparameter. Small value to avoid zero denominator.
+ epsilon: A float hyperparameter. Small value to initialize the average
+ square gradient variable and avoid zero denominator.
use_locking: If True use locks for update operation.
centered: If True, gradients are normalized by the estimated variance of
the gradient; if False, by the uncentered second moment. Setting this to
@@ -106,10 +106,8 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
def _create_vars(self, var_list, state):
for v in var_list:
- if v.get_shape().is_fully_defined():
- init_rms = init_ops.ones_initializer(dtype=v.dtype.base_dtype)
- else:
- init_rms = array_ops.ones_like(v)
+ init_rms = state.get_hyper(
+ "epsilon", v.dtype.base_dtype) * array_ops.ones_like(v)
state.create_slot_with_initializer(v, init_rms, v.get_shape(),
v.dtype.base_dtype, "rms")
if self._centered:
@@ -129,7 +127,9 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ # epsilon is now the rms initial value and is not added to the
+ # denominator anymore, hence calling the kernel op with epsilon=0.
+ 0,
grad,
use_locking=self._use_locking).op
else:
@@ -140,7 +140,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad,
use_locking=self._use_locking).op
@@ -157,7 +157,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad,
use_locking=self._use_locking)
else:
@@ -168,7 +168,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad,
use_locking=self._use_locking)
@@ -185,7 +185,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad.values,
grad.indices,
use_locking=self._use_locking)
@@ -197,7 +197,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad.values,
grad.indices,
use_locking=self._use_locking)
@@ -215,7 +215,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad,
indices,
use_locking=self._use_locking)
@@ -227,7 +227,7 @@ class RMSPropOptimizer(optimizer_v2.OptimizerV2):
state.get_hyper("learning_rate", var.dtype.base_dtype),
state.get_hyper("decay", var.dtype.base_dtype),
state.get_hyper("momentum", var.dtype.base_dtype),
- state.get_hyper("epsilon", var.dtype.base_dtype),
+ 0,
grad,
indices,
use_locking=self._use_locking)
diff --git a/tensorflow/contrib/optimizer_v2/rmsprop_test.py b/tensorflow/contrib/optimizer_v2/rmsprop_test.py
index dc23ef241a..628d0418dd 100644
--- a/tensorflow/contrib/optimizer_v2/rmsprop_test.py
+++ b/tensorflow/contrib/optimizer_v2/rmsprop_test.py
@@ -39,34 +39,34 @@ _DATA_TYPES = [dtypes.half, dtypes.float32]
_TEST_PARAM_VALUES = [
# learning_rate, decay, momentum, epsilon, centered, use_resource
- [0.5, 0.9, 0.0, 1e-3, True, False],
- [0.5, 0.9, 0.0, 1e-3, False, False],
- [0.5, 0.9, 0.0, 1e-3, True, True],
- [0.5, 0.9, 0.0, 1e-3, False, True],
- [0.1, 0.9, 0.0, 1e-3, True, False],
- [0.5, 0.95, 0.0, 1e-3, False, False],
- [0.5, 0.95, 0.0, 1e-5, True, False],
- [0.5, 0.95, 0.9, 1e-5, True, False],
+ [0.5, 0.9, 0.0, 1.0, True, False],
+ [0.5, 0.9, 0.0, 1.0, False, False],
+ [0.5, 0.9, 0.0, 1.0, True, True],
+ [0.5, 0.9, 0.0, 1.0, False, True],
+ [0.1, 0.9, 0.0, 1.0, True, False],
+ [0.5, 0.95, 0.0, 1.0, False, False],
+ [0.5, 0.8, 0.0, 1e-3, True, False],
+ [0.5, 0.8, 0.9, 1e-3, True, False],
]
class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
def _rmsprop_update_numpy(self, var, g, mg, rms, mom, lr, decay, momentum,
- epsilon, centered):
+ centered):
rms_t = rms * decay + (1 - decay) * g * g
- denom_t = rms_t + epsilon
if centered:
mg_t = mg * decay + (1 - decay) * g
- denom_t -= mg_t * mg_t
+ denom_t = rms_t - mg_t * mg_t
else:
mg_t = mg
+ denom_t = rms_t
mom_t = momentum * mom + lr * g / np.sqrt(denom_t, dtype=denom_t.dtype)
var_t = var - mom_t
return var_t, mg_t, rms_t, mom_t
def _sparse_rmsprop_update_numpy(self, var, gindexs, gvalues, mg, rms, mom,
- lr, decay, momentum, epsilon, centered):
+ lr, decay, momentum, centered):
mg_t = copy.deepcopy(mg)
rms_t = copy.deepcopy(rms)
mom_t = copy.deepcopy(mom)
@@ -75,7 +75,7 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
gindex = gindexs[i]
gvalue = gvalues[i]
rms_t[gindex] = rms[gindex] * decay + (1 - decay) * gvalue * gvalue
- denom_t = rms_t[gindex] + epsilon
+ denom_t = rms_t[gindex]
if centered:
mg_t[gindex] = mg_t[gindex] * decay + (1 - decay) * gvalue
denom_t -= mg_t[gindex] * mg_t[gindex]
@@ -129,8 +129,8 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
- rms0_np = np.array([1.0, 1.0], dtype=dtype.as_numpy_dtype)
- rms1_np = np.array([1.0, 1.0], dtype=dtype.as_numpy_dtype)
+ rms0_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
+ rms1_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
@@ -144,10 +144,10 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(
var0_np, grads0_np, mg0_np, rms0_np, mom0_np, learning_rate,
- decay, momentum, epsilon, centered)
+ decay, momentum, centered)
var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(
var1_np, grads1_np, mg1_np, rms1_np, mom1_np, learning_rate,
- decay, momentum, epsilon, centered)
+ decay, momentum, centered)
# Validate updated params
if centered:
@@ -191,7 +191,7 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
loss = pred * pred
sgd_op = rmsprop.RMSPropOptimizer(
learning_rate=1.0,
- decay=0.0,
+ decay=0.1,
momentum=0.0,
epsilon=1.0,
centered=True).minimize(loss)
@@ -202,7 +202,7 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType(
- [[-111, -138]], var0.eval(), atol=0.01)
+ [[-7/3.0, -4/3.0]], var0.eval(), atol=0.01)
@parameterized.named_parameters(
*test_util.generate_combinations_with_testcase_name(
@@ -251,8 +251,8 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
- rms0_np = np.array([1.0, 1.0], dtype=dtype.as_numpy_dtype)
- rms1_np = np.array([1.0, 1.0], dtype=dtype.as_numpy_dtype)
+ rms0_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
+ rms1_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
@@ -266,10 +266,10 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
var0_np, mg0_np, rms0_np, mom0_np = self._sparse_rmsprop_update_numpy(
var0_np, grads0_np_indices, grads0_np, mg0_np, rms0_np, mom0_np,
- learning_rate, decay, momentum, epsilon, centered)
+ learning_rate, decay, momentum, centered)
var1_np, mg1_np, rms1_np, mom1_np = self._sparse_rmsprop_update_numpy(
var1_np, grads1_np_indices, grads1_np, mg1_np, rms1_np, mom1_np,
- learning_rate, decay, momentum, epsilon, centered)
+ learning_rate, decay, momentum, centered)
# Validate updated params
if centered:
@@ -317,13 +317,13 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
- 1.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1.0)),
- 2.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1.0))
+ 1.0 - (0.1 * 2.0 / math.sqrt(0.901)),
+ 2.0 - (0.1 * 2.0 / math.sqrt(0.901))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
- 3.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1.0)),
- 4.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1.0))
+ 3.0 - (0.01 * 2.0 / math.sqrt(0.90001)),
+ 4.0 - (0.01 * 2.0 / math.sqrt(0.90001))
]), var1.eval())
# Step 2: the root mean square accumulators contain the previous update.
update.run()
@@ -335,17 +335,17 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
- 1.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1.0)) -
- (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001 + 1.0)),
- 2.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1.0)) -
- (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001 + 1.0))
+ 1.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
+ (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)),
+ 2.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
+ (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
- 3.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1.0)) -
- (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5 + 1.0)),
- 4.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1.0)) -
- (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5 + 1.0))
+ 3.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
+ (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)),
+ 4.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
+ (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))
]), var1.eval())
@parameterized.parameters(_DATA_TYPES)
@@ -357,7 +357,7 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
opt = rmsprop.RMSPropOptimizer(
- learning_rate=2.0, decay=0.9, momentum=0.5, epsilon=1e-5)
+ learning_rate=2.0, decay=0.9, momentum=0.5, epsilon=1.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
@@ -383,22 +383,22 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
np.array([0.90001, 0.90001]), rms1.eval())
# Check the momentum accumulators
self.assertAllCloseAccordingToType(
- np.array([(0.1 * 2.0 / math.sqrt(0.901 + 1e-5)),
- (0.1 * 2.0 / math.sqrt(0.901 + 1e-5))]), mom0.eval())
+ np.array([(0.1 * 2.0 / math.sqrt(0.901)),
+ (0.1 * 2.0 / math.sqrt(0.901))]), mom0.eval())
self.assertAllCloseAccordingToType(
- np.array([(0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)),
- (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5))]), mom1.eval())
+ np.array([(0.01 * 2.0 / math.sqrt(0.90001)),
+ (0.01 * 2.0 / math.sqrt(0.90001))]), mom1.eval())
# Check that the parameters.
self.assertAllCloseAccordingToType(
np.array([
- 1.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)),
- 2.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1e-5))
+ 1.0 - (0.1 * 2.0 / math.sqrt(0.901)),
+ 2.0 - (0.1 * 2.0 / math.sqrt(0.901))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
- 3.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)),
- 4.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5))
+ 3.0 - (0.01 * 2.0 / math.sqrt(0.90001)),
+ 4.0 - (0.01 * 2.0 / math.sqrt(0.90001))
]), var1.eval())
# Step 2: the root mean square accumulators contain the previous update.
@@ -410,38 +410,38 @@ class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
np.array([0.90001 * 0.9 + 1e-5, 0.90001 * 0.9 + 1e-5]), rms1.eval())
self.assertAllCloseAccordingToType(
np.array([
- 0.5 * (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)) +
- (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001 + 1e-5)),
- 0.5 * (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)) +
- (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001 + 1e-5))
+ 0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
+ (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)),
+ 0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
+ (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))
]), mom0.eval())
self.assertAllCloseAccordingToType(
np.array([
- 0.5 * (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)) +
- (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 2e-5)),
- 0.5 * (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)) +
- (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 2e-5))
+ 0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
+ (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)),
+ 0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
+ (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))
]), mom1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
- 1.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)) -
- (0.5 * (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)) +
- (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001 + 1e-5))),
- 2.0 - (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)) -
- (0.5 * (0.1 * 2.0 / math.sqrt(0.901 + 1e-5)) +
- (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001 + 1e-5)))
+ 1.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
+ (0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
+ (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))),
+ 2.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
+ (0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
+ (0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
- 3.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)) -
- (0.5 * (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)) +
- (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 2e-5))),
- 4.0 - (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)) -
- (0.5 * (0.01 * 2.0 / math.sqrt(0.90001 + 1e-5)) +
- (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 2e-5)))
+ 3.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
+ (0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
+ (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))),
+ 4.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
+ (0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
+ (0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)))
]), var1.eval())
diff --git a/tensorflow/contrib/predictor/BUILD b/tensorflow/contrib/predictor/BUILD
index 36e21af618..72ea777ca7 100644
--- a/tensorflow/contrib/predictor/BUILD
+++ b/tensorflow/contrib/predictor/BUILD
@@ -60,7 +60,7 @@ py_library(
":base_predictor",
"//tensorflow/python:framework_ops",
"//tensorflow/python:training",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/saved_model:signature_constants",
],
)
@@ -90,9 +90,7 @@ py_library(
"//tensorflow/python:framework_ops",
"//tensorflow/python:math_ops",
"//tensorflow/python/estimator",
- "//tensorflow/python/estimator:export",
- "//tensorflow/python/estimator:export_output",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/saved_model:signature_constants",
],
)
diff --git a/tensorflow/contrib/quantize/BUILD b/tensorflow/contrib/quantize/BUILD
index 23363617ed..499fec4ffa 100644
--- a/tensorflow/contrib/quantize/BUILD
+++ b/tensorflow/contrib/quantize/BUILD
@@ -244,7 +244,9 @@ py_test(
"//tensorflow/python:framework_ops",
"//tensorflow/python:framework_test_lib",
"//tensorflow/python:init_ops",
+ "//tensorflow/python:math_ops",
"//tensorflow/python:nn_ops",
"//tensorflow/python:platform_test",
+ "//tensorflow/python:training",
],
)
diff --git a/tensorflow/contrib/quantize/python/quant_ops_test.py b/tensorflow/contrib/quantize/python/quant_ops_test.py
index c2a8def480..a45840009b 100644
--- a/tensorflow/contrib/quantize/python/quant_ops_test.py
+++ b/tensorflow/contrib/quantize/python/quant_ops_test.py
@@ -75,7 +75,7 @@ class QuantOpsTest(googletest.TestCase):
self.assertGreater(max_value, 0.0)
self.assertLess(max_value, 1.0)
- def testVariablesNotParitioned_LastValue(self):
+ def testVariablesNotPartitioned_LastValue(self):
# Variables added should not use a default partiioner since they are
# scalar. There would be a tensorflow error thrown if the partitioner was
# respected by the rewrite.
@@ -90,7 +90,7 @@ class QuantOpsTest(googletest.TestCase):
is_training=True,
vars_collection=_MIN_MAX_VARS)
- def testVariablesNotParitioned_MovingAvg(self):
+ def testVariablesNotPartitioned_MovingAvg(self):
# Variables added should not use a default partiioner since they are
# scalar. There would be a tensorflow error thrown if the partitioner was
# respected by the rewrite.
diff --git a/tensorflow/contrib/quantize/python/quantize.py b/tensorflow/contrib/quantize/python/quantize.py
index cb66fd1f76..2ddbd73ea6 100644
--- a/tensorflow/contrib/quantize/python/quantize.py
+++ b/tensorflow/contrib/quantize/python/quantize.py
@@ -455,6 +455,24 @@ class _LayerMatch(object):
return self._bias_add_op
+def _FollowedByFakeQuant(tensor):
+ """Returns True if the tensor is followed by a FakeQuant."""
+ fake_quant_ops = set([
+ 'FakeQuantWithMinMaxVars', 'FakeQuantWithMinMaxArgs',
+ 'FakeQuantWithMinMaxVarsPerChannel'
+ ])
+ pass_through_ops = set(['Reshape', 'Identity'])
+ consumers = tensor.consumers()
+ while consumers:
+ c = consumers.pop()
+ if c.type in fake_quant_ops:
+ return True
+ elif c.type in pass_through_ops:
+ for output in c.outputs:
+ consumers.extend(output.consumers())
+ return False
+
+
def _InsertQuantOp(context,
name,
producer,
@@ -535,11 +553,7 @@ def _InsertQuantOp(context,
# Prevent ops from being quantized multiple times. Bypass ops can sometimes
# overlap between multiple matches, so we need to ensure that we don't
# add duplicate FakeQuant operations.
- fake_quant_ops = set([
- 'FakeQuantWithMinMaxVars',
- 'FakeQuantWithMinMaxArgs'
- ])
- if fake_quant_ops.intersection(set([c.type for c in inputs.consumers()])):
+ if _FollowedByFakeQuant(inputs):
return
if moving_avg:
diff --git a/tensorflow/contrib/quantize/python/quantize_graph.py b/tensorflow/contrib/quantize/python/quantize_graph.py
index 2944f964c7..484493f1b2 100644
--- a/tensorflow/contrib/quantize/python/quantize_graph.py
+++ b/tensorflow/contrib/quantize/python/quantize_graph.py
@@ -59,6 +59,10 @@ def _create_graph(input_graph=None,
if input_graph is None:
input_graph = ops.get_default_graph()
+
+ # Add check to see if graph has training ops, if so provide error message and
+ # exit
+ _check_for_training_ops(input_graph)
with input_graph.as_default():
fold_batch_norms.FoldBatchNorms(
input_graph,
@@ -78,6 +82,9 @@ def create_training_graph(input_graph=None, quant_delay=0):
Variables added by the rewrite get added to the global variables collection.
+ This function must be invoked prior to insertion of gradient ops in a graph
+ as quantization should be modeled in both forward and backward passes.
+
The graph has fake quantization ops inserted to simulate the error
introduced by quantization. Since the graph is transformed in place,
the expected behavior of previously held references to nodes and tensors may
@@ -104,7 +111,6 @@ def create_training_graph(input_graph=None, quant_delay=0):
# Currently the values below are hardcoded for mobilenetV1 on imagenet
# Please use the experimental API if you need to tune these values.
freeze_bn_delay = None
-
_create_graph(
input_graph=input_graph,
is_training=True,
@@ -141,6 +147,9 @@ def experimental_create_training_graph(input_graph=None,
scope=None):
"""Rewrites a training input_graph in place for simulated quantization.
+ This function must be invoked prior to insertion of gradient ops in a graph
+ as quantization should be modeled in both forward and backward passes.
+
Variables added by the rewrite get added to the global variables collection.
This function has additional experimental options not (yet) available to
@@ -226,3 +235,45 @@ def experimental_create_eval_graph(input_graph=None,
activation_bits=activation_bits,
quant_delay=quant_delay,
scope=scope)
+
+
+def _check_for_training_ops(g):
+ """Check if training ops are present in the graph.
+
+ Args:
+ g: The tf.Graph on which the check for training ops needs to be
+ performed.
+
+ Raises:
+ ValueError: If a training op is seen in the graph;
+ """
+
+ # The list here is obtained
+ # from https://www.tensorflow.org/api_docs/cc/group/training-ops
+ training_ops = frozenset([
+ 'ApplyAdagrad', 'ApplyAdagradDA', 'ApplyAdam', 'ApplyAddSign',
+ 'ApplyCenteredRMSProp', 'ApplyFtrl', 'ApplyFtrlV2',
+ 'ApplyGradientDescent', 'ApplyMomentum', 'ApplyPowerSign',
+ 'ApplyProximalAdagrad', 'ApplyProximalGradientDescent', 'ApplyRMSProp',
+ 'ResourceApplyAdadelta', 'ResourceApplyAdagrad', 'ResourceApplyAdagradDA',
+ 'ResourceApplyAdam', 'ResourceApplyAddSign',
+ 'ResourceApplyCenteredRMSProp', 'ResourceApplyFtrl',
+ 'ResourceApplyFtrlV2', 'ResourceApplyGradientDescent',
+ 'ResourceApplyMomentum', 'ResourceApplyPowerSign',
+ 'ResourceApplyProximalAdagrad', 'ResourceApplyProximalGradientDescent',
+ 'ResourceApplyRMSProp', 'ResourceSparseApplyAdadelta',
+ 'ResourceSparseApplyAdagrad', 'ResourceSparseApplyAdagradDA',
+ 'ResourceSparseApplyCenteredRMSProp', 'ResourceSparseApplyFtrl',
+ 'ResourceSparseApplyFtrlV2', 'ResourceSparseApplyMomentum',
+ 'ResourceSparseApplyProximalAdagrad',
+ 'ResourceSparseApplyProximalGradientDescent',
+ 'ResourceSparseApplyRMSProp', 'SparseApplyAdadelta', 'SparseApplyAdagrad',
+ 'SparseApplyAdagradDA', 'SparseApplyCenteredRMSProp', 'SparseApplyFtrl',
+ 'SparseApplyFtrlV2', 'SparseApplyMomentum', 'SparseApplyProximalAdagrad',
+ 'SparseApplyProximalGradientDescent', 'SparseApplyRMSProp'
+ ])
+
+ op_types = set([op.type for op in g.get_operations()])
+ train_op_list = op_types.intersection(training_ops)
+ if train_op_list:
+ raise ValueError('Training op found in graph, exiting %s' % train_op_list)
diff --git a/tensorflow/contrib/quantize/python/quantize_graph_test.py b/tensorflow/contrib/quantize/python/quantize_graph_test.py
index 54faf582f1..e80d2183a6 100644
--- a/tensorflow/contrib/quantize/python/quantize_graph_test.py
+++ b/tensorflow/contrib/quantize/python/quantize_graph_test.py
@@ -20,10 +20,12 @@ from __future__ import print_function
from tensorflow.contrib.layers.python.layers import layers
from tensorflow.contrib.quantize.python import quantize_graph
+from tensorflow.python import training
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
+from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import googletest
@@ -145,6 +147,19 @@ class QuantizeGraphTest(test_util.TensorFlowTestCase):
self.assertTrue(('int64_val: %i' % quant_delay) in const_value)
self.assertTrue(quant_delay_found)
+ def testTrainingOpsCheck(self):
+ self._RunTestOverTrainingRewrites(self._TestTrainingOpsCheck)
+
+ def _TestTrainingOpsCheck(self, rewrite_fn):
+ with ops.Graph().as_default():
+ output = self._ConvLayer()
+ output_scalar = math_ops.reduce_sum(output)
+ loss = math_ops.square(output_scalar - 1)
+ opt = training.gradient_descent.GradientDescentOptimizer(0.0001)
+ opt.minimize(loss)
+ with self.assertRaisesRegexp(ValueError, 'Training op found in graph'):
+ rewrite_fn()
+
def testWeightBits(self):
self._RunTestOverExperimentalRewrites(self._TestWeightBits)
diff --git a/tensorflow/contrib/quantize/python/quantize_test.py b/tensorflow/contrib/quantize/python/quantize_test.py
index 06ebcdfee1..212d902a3c 100644
--- a/tensorflow/contrib/quantize/python/quantize_test.py
+++ b/tensorflow/contrib/quantize/python/quantize_test.py
@@ -471,6 +471,60 @@ class QuantizeTest(test_util.TensorFlowTestCase):
self.assertTrue(
'part/test/test/weights_quant/FakeQuantWithMinMaxVars' in op_names)
+ def testSkipReshapeQuantization(self):
+ self._RunTestOverParameters(self._TestSkipReshapeQuantization)
+
+ def _TestSkipReshapeQuantization(self, is_training):
+ graph = ops.Graph()
+ with graph.as_default():
+ batch_size, height, width, depth = 5, 128, 128, 3
+ input1 = array_ops.zeros((batch_size, height, width, depth))
+ conv = conv2d(
+ input1,
+ 32, [5, 5],
+ stride=2,
+ padding='SAME',
+ weights_initializer=self._WeightInit(0.09),
+ activation_fn=nn_ops.relu6,
+ scope='test/test')
+
+ reshape = array_ops.reshape(
+ conv, (int(10), int(height / 2), int(width / 2), int(16)))
+
+ # Insert a fake quant node after the reshape. We will check that one isn't
+ # insert before.
+ array_ops.fake_quant_with_min_max_vars(reshape, -1, 1)
+
+ quantize.Quantize(graph, is_training, weight_bits=8, activation_bits=8)
+
+ # Ensure that there isn't a FakeQuant added before the reshape.
+ self.assertFalse(
+ 'FakeQuantWithMinMaxVars' in [i.op.type for i in reshape.op.inputs])
+
+ graph = ops.Graph()
+ with graph.as_default():
+ batch_size, height, width, depth = 5, 128, 128, 3
+ input1 = array_ops.zeros((batch_size, height, width, depth))
+ conv = conv2d(
+ input1,
+ 32, [5, 5],
+ stride=2,
+ padding='SAME',
+ weights_initializer=self._WeightInit(0.09),
+ activation_fn=nn_ops.relu6,
+ scope='test/test')
+
+ reshape = array_ops.reshape(
+ conv, (int(10), int(height / 2), int(width / 2), int(16)))
+
+ # If no fake quant is added after the reshape, a FakeQuant should be added
+ # before the reshape.
+ quantize.Quantize(graph, is_training, weight_bits=8, activation_bits=8)
+
+ # Ensure that there isn't a FakeQuant added before the reshape.
+ self.assertTrue(
+ 'FakeQuantWithMinMaxVars' in [i.op.type for i in reshape.op.inputs])
+
def _WeightInit(self, stddev):
"""Returns truncated normal variable initializer.
diff --git a/tensorflow/contrib/rnn/BUILD b/tensorflow/contrib/rnn/BUILD
index 2a84629080..5874245d58 100644
--- a/tensorflow/contrib/rnn/BUILD
+++ b/tensorflow/contrib/rnn/BUILD
@@ -149,7 +149,7 @@ cuda_py_tests(
cuda_py_tests(
name = "core_rnn_test",
- size = "large",
+ size = "medium",
srcs = ["python/kernel_tests/core_rnn_test.py"],
additional_deps = [
":rnn_py",
@@ -175,7 +175,7 @@ cuda_py_tests(
tf_py_test(
name = "fused_rnn_cell_test",
- size = "small",
+ size = "medium",
srcs = ["python/kernel_tests/fused_rnn_cell_test.py"],
additional_deps = [
":rnn_py",
@@ -192,10 +192,6 @@ tf_py_test(
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
],
- tags = [
- "manual",
- "notap",
- ],
)
cuda_py_tests(
diff --git a/tensorflow/contrib/rnn/__init__.py b/tensorflow/contrib/rnn/__init__.py
index cb437f2a2f..026bf08ced 100644
--- a/tensorflow/contrib/rnn/__init__.py
+++ b/tensorflow/contrib/rnn/__init__.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""RNN Cells and additional RNN operations.
-See @{$python/contrib.rnn} guide.
+See [Contrib RNN](https://tensorflow.org/api_guides/python/contrib.rnn) guide.
<!--From core-->
@@RNNCell
diff --git a/tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py b/tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
index 1c20d88fe4..d62ec45d18 100644
--- a/tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
+++ b/tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
@@ -1288,7 +1288,10 @@ class LSTMTest(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def testDynamicEquivalentToStaticRNN(self):
self._testDynamicEquivalentToStaticRNN(use_sequence_length=False)
- self._testDynamicEquivalentToStaticRNN(use_sequence_length=False)
+
+ @test_util.run_in_graph_and_eager_modes
+ def testDynamicEquivalentToStaticRNNWithSequenceLength(self):
+ self._testDynamicEquivalentToStaticRNN(use_sequence_length=True)
class BidirectionalRNNTest(test.TestCase):
diff --git a/tensorflow/contrib/rnn/python/ops/rnn_cell.py b/tensorflow/contrib/rnn/python/ops/rnn_cell.py
index 1816b469ee..f74c95f962 100644
--- a/tensorflow/contrib/rnn/python/ops/rnn_cell.py
+++ b/tensorflow/contrib/rnn/python/ops/rnn_cell.py
@@ -3276,7 +3276,7 @@ class IndyLSTMCell(rnn_cell_impl.LayerRNNCell):
It does not allow cell clipping, a projection layer, and does not
use peep-hole connections: it is the basic baseline.
- For advanced models, please use the full @{tf.nn.rnn_cell.LSTMCell}
+ For advanced models, please use the full `tf.nn.rnn_cell.LSTMCell`
that follows.
TODO(gonnet): Write a paper describing this and add a reference here.
diff --git a/tensorflow/contrib/saved_model/BUILD b/tensorflow/contrib/saved_model/BUILD
index fbb50befdf..e7eb4ac563 100644
--- a/tensorflow/contrib/saved_model/BUILD
+++ b/tensorflow/contrib/saved_model/BUILD
@@ -113,7 +113,6 @@ py_test(
size = "small",
srcs = ["python/saved_model/keras_saved_model_test.py"],
srcs_version = "PY2AND3",
- tags = ["no_windows"],
deps = [
":saved_model_py",
"//tensorflow/python:client_testlib",
diff --git a/tensorflow/contrib/seq2seq/BUILD b/tensorflow/contrib/seq2seq/BUILD
index 1a1591d798..18b56cd219 100644
--- a/tensorflow/contrib/seq2seq/BUILD
+++ b/tensorflow/contrib/seq2seq/BUILD
@@ -177,7 +177,7 @@ cuda_py_test(
cuda_py_test(
name = "beam_search_decoder_test",
- size = "small",
+ size = "medium",
srcs = ["python/kernel_tests/beam_search_decoder_test.py"],
additional_deps = [
":seq2seq_py",
diff --git a/tensorflow/contrib/seq2seq/__init__.py b/tensorflow/contrib/seq2seq/__init__.py
index a7279bc339..674f7cdb22 100644
--- a/tensorflow/contrib/seq2seq/__init__.py
+++ b/tensorflow/contrib/seq2seq/__init__.py
@@ -15,7 +15,9 @@
"""Ops for building neural network seq2seq decoders and losses.
-See the @{$python/contrib.seq2seq} guide.
+See the
+[Contrib Seq2seq](https://tensorflow.org/api_guides/python/contrib.seq2seq)
+guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py b/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py
index 1c9d179e3c..0ba32cd3bf 100644
--- a/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py
+++ b/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py
@@ -382,8 +382,8 @@ class LuongAttention(_BaseAttentionMechanism):
for values past the respective sequence lengths.
scale: Python boolean. Whether to scale the energy term.
probability_fn: (optional) A `callable`. Converts the score to
- probabilities. The default is @{tf.nn.softmax}. Other options include
- @{tf.contrib.seq2seq.hardmax} and @{tf.contrib.sparsemax.sparsemax}.
+ probabilities. The default is `tf.nn.softmax`. Other options include
+ `tf.contrib.seq2seq.hardmax` and `tf.contrib.sparsemax.sparsemax`.
Its signature should be: `probabilities = probability_fn(score)`.
score_mask_value: (optional) The mask value for score before passing into
`probability_fn`. The default is -inf. Only used if
@@ -529,8 +529,8 @@ class BahdanauAttention(_BaseAttentionMechanism):
for values past the respective sequence lengths.
normalize: Python boolean. Whether to normalize the energy term.
probability_fn: (optional) A `callable`. Converts the score to
- probabilities. The default is @{tf.nn.softmax}. Other options include
- @{tf.contrib.seq2seq.hardmax} and @{tf.contrib.sparsemax.sparsemax}.
+ probabilities. The default is `tf.nn.softmax`. Other options include
+ `tf.contrib.seq2seq.hardmax` and `tf.contrib.sparsemax.sparsemax`.
Its signature should be: `probabilities = probability_fn(score)`.
score_mask_value: (optional): The mask value for score before passing into
`probability_fn`. The default is -inf. Only used if
@@ -1091,7 +1091,7 @@ class AttentionWrapper(rnn_cell_impl.RNNCell):
`AttentionWrapper`, then you must ensure that:
- The encoder output has been tiled to `beam_width` via
- @{tf.contrib.seq2seq.tile_batch} (NOT `tf.tile`).
+ `tf.contrib.seq2seq.tile_batch` (NOT `tf.tile`).
- The `batch_size` argument passed to the `zero_state` method of this
wrapper is equal to `true_batch_size * beam_width`.
- The initial state created with `zero_state` above contains a
diff --git a/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py b/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py
index f17dbb0fe3..74741a7bd6 100644
--- a/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py
+++ b/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py
@@ -234,7 +234,7 @@ class BeamSearchDecoder(decoder.Decoder):
`AttentionWrapper`, then you must ensure that:
- The encoder output has been tiled to `beam_width` via
- @{tf.contrib.seq2seq.tile_batch} (NOT `tf.tile`).
+ `tf.contrib.seq2seq.tile_batch` (NOT `tf.tile`).
- The `batch_size` argument passed to the `zero_state` method of this
wrapper is equal to `true_batch_size * beam_width`.
- The initial state created with `zero_state` above contains a
diff --git a/tensorflow/contrib/signal/__init__.py b/tensorflow/contrib/signal/__init__.py
index 6a2080bcec..d088e74434 100644
--- a/tensorflow/contrib/signal/__init__.py
+++ b/tensorflow/contrib/signal/__init__.py
@@ -14,7 +14,9 @@
# ==============================================================================
"""Signal processing operations.
-See the @{$python/contrib.signal} guide.
+See the
+[Contrib Signal](https://tensorflow.org/api_guides/python/contrib.signal)
+guide.
@@frame
@@hamming_window
diff --git a/tensorflow/contrib/signal/python/kernel_tests/test_util.py b/tensorflow/contrib/signal/python/kernel_tests/test_util.py
index 7d6289532a..b4422a4988 100644
--- a/tensorflow/contrib/signal/python/kernel_tests/test_util.py
+++ b/tensorflow/contrib/signal/python/kernel_tests/test_util.py
@@ -27,15 +27,15 @@ def grappler_optimize(graph, fetches=None, rewriter_config=None):
"""Tries to optimize the provided graph using grappler.
Args:
- graph: A @{tf.Graph} instance containing the graph to optimize.
+ graph: A `tf.Graph` instance containing the graph to optimize.
fetches: An optional list of `Tensor`s to fetch (i.e. not optimize away).
Grappler uses the 'train_op' collection to look for fetches, so if not
provided this collection should be non-empty.
- rewriter_config: An optional @{tf.RewriterConfig} to use when rewriting the
+ rewriter_config: An optional `tf.RewriterConfig` to use when rewriting the
graph.
Returns:
- A @{tf.GraphDef} containing the rewritten graph.
+ A `tf.GraphDef` containing the rewritten graph.
"""
if rewriter_config is None:
rewriter_config = rewriter_config_pb2.RewriterConfig()
diff --git a/tensorflow/contrib/signal/python/ops/mel_ops.py b/tensorflow/contrib/signal/python/ops/mel_ops.py
index 062d84aea1..ecc2fedb9f 100644
--- a/tensorflow/contrib/signal/python/ops/mel_ops.py
+++ b/tensorflow/contrib/signal/python/ops/mel_ops.py
@@ -108,7 +108,7 @@ def linear_to_mel_weight_matrix(num_mel_bins=20,
# `M` has shape [frames, num_mel_bins]
M = tf.matmul(S, A)
- The matrix can be used with @{tf.tensordot} to convert an arbitrary rank
+ The matrix can be used with `tf.tensordot` to convert an arbitrary rank
`Tensor` of linear-scale spectral bins into the mel scale.
# S has shape [..., num_spectrogram_bins].
diff --git a/tensorflow/contrib/signal/python/ops/reconstruction_ops.py b/tensorflow/contrib/signal/python/ops/reconstruction_ops.py
index 653c030a04..4db8dc2ca0 100644
--- a/tensorflow/contrib/signal/python/ops/reconstruction_ops.py
+++ b/tensorflow/contrib/signal/python/ops/reconstruction_ops.py
@@ -90,22 +90,28 @@ def overlap_and_add(signal, frame_step, name=None):
raise ValueError("frame_step must be an integer. Got %s" %
frame_step.dtype)
- # If frame_length and frame_step are known at graph construction time, check
- # frame_step is less than or equal to frame_length.
- frame_step_static = tensor_util.constant_value(frame_step)
- if (frame_step_static is not None and signal.shape.ndims is not None and
- signal.shape[-1].value is not None and
- frame_step_static > signal.shape[-1].value):
- raise ValueError(
- "frame_step (%d) must be less than or equal to frame_length (%d)" % (
- frame_step_static, signal.shape[-1].value))
-
signal_shape = array_ops.shape(signal)
# All dimensions that are not part of the overlap-and-add. Can be empty for
# rank 2 inputs.
outer_dimensions = signal_shape[:-2]
+ # If frame_length and frame_step are known at graph construction time, check
+ # frame_step is less than or equal to frame_length.
+ frame_step_static = tensor_util.constant_value(frame_step)
+ if (frame_step_static is not None and signal.shape.ndims is not None and
+ signal.shape[-1].value is not None):
+ if frame_step_static > signal.shape[-1].value:
+ raise ValueError(
+ "frame_step (%d) must be less than or equal to "
+ "frame_length (%d)" % (
+ frame_step_static, signal.shape[-1].value))
+ # If frame_length is equal to frame_step, there's no overlap so just
+ # reshape the tensor.
+ if frame_step_static == signal.shape[-1].value:
+ return array_ops.reshape(signal, array_ops.concat(
+ [outer_dimensions, [-1]], 0))
+
signal_rank = array_ops.rank(signal)
frames = signal_shape[-2]
frame_length = signal_shape[-1]
diff --git a/tensorflow/contrib/slim/python/slim/evaluation.py b/tensorflow/contrib/slim/python/slim/evaluation.py
index 5cfd5ee82e..0feb3925eb 100644
--- a/tensorflow/contrib/slim/python/slim/evaluation.py
+++ b/tensorflow/contrib/slim/python/slim/evaluation.py
@@ -22,7 +22,8 @@ modules using a variety of metrics and summarizing the results.
**********************
In the simplest use case, we use a model to create the predictions, then specify
-the metrics and finally call the `evaluation` method:
+the metrics and choose one model checkpoint, finally call the`evaluation_once`
+method:
# Create model and obtain the predictions:
images, labels = LoadData(...)
@@ -34,20 +35,24 @@ the metrics and finally call the `evaluation` method:
"mse": slim.metrics.mean_squared_error(predictions, labels),
})
+ checkpoint_path = '/tmp/my_model_dir/my_checkpoint'
+ log_dir = '/tmp/my_model_eval/'
+
initial_op = tf.group(
tf.global_variables_initializer(),
tf.local_variables_initializer())
- with tf.Session() as sess:
- metric_values = slim.evaluation(
- sess,
- num_evals=1,
- initial_op=initial_op,
- eval_op=names_to_updates.values(),
- final_op=name_to_values.values())
+ metric_values = slim.evaluate_once(
+ master='',
+ checkpoint_path=checkpoint_path,
+ log_dir=log_dir,
+ num_evals=1,
+ initial_op=initial_op,
+ eval_op=names_to_updates.values(),
+ final_op=name_to_values.values())
- for metric, value in zip(names_to_values.keys(), metric_values):
- logging.info('Metric %s has value: %f', metric, value)
+ for metric, value in zip(names_to_values.keys(), metric_values):
+ logging.info('Metric %s has value: %f', metric, value)
************************************************
* Evaluating a Checkpointed Model with Metrics *
diff --git a/tensorflow/contrib/stat_summarizer/BUILD b/tensorflow/contrib/stat_summarizer/BUILD
index 0b8fc0cdc6..412a2c81a1 100644
--- a/tensorflow/contrib/stat_summarizer/BUILD
+++ b/tensorflow/contrib/stat_summarizer/BUILD
@@ -31,8 +31,5 @@ tf_py_test(
"//tensorflow/python:math_ops",
"//tensorflow/python:variables",
],
- tags = [
- "no_windows",
- "notap", # TODO(b/80546574): test is flaky
- ],
+ tags = ["notap"], # TODO(b/80546574): test is flaky
)
diff --git a/tensorflow/contrib/summary/summary.py b/tensorflow/contrib/summary/summary.py
index d22b80ac88..42898e797c 100644
--- a/tensorflow/contrib/summary/summary.py
+++ b/tensorflow/contrib/summary/summary.py
@@ -17,7 +17,7 @@
The operations in this package are safe to use with eager execution turned on or
off. It has a more flexible API that allows summaries to be written directly
from ops to places other than event log files, rather than propagating protos
-from @{tf.summary.merge_all} to @{tf.summary.FileWriter}.
+from `tf.summary.merge_all` to `tf.summary.FileWriter`.
To use with eager execution enabled, write your code as follows:
diff --git a/tensorflow/contrib/tensor_forest/BUILD b/tensorflow/contrib/tensor_forest/BUILD
index 164f3e58e6..22d6e499d2 100644
--- a/tensorflow/contrib/tensor_forest/BUILD
+++ b/tensorflow/contrib/tensor_forest/BUILD
@@ -515,6 +515,7 @@ py_library(
srcs_version = "PY2AND3",
deps = [
":client_lib",
+ "//tensorflow/contrib/estimator:head",
"//tensorflow/contrib/layers:layers_py",
"//tensorflow/contrib/learn",
"//tensorflow/python:array_ops",
diff --git a/tensorflow/contrib/tensor_forest/client/random_forest.py b/tensorflow/contrib/tensor_forest/client/random_forest.py
index 35e8c92aba..db970deff5 100644
--- a/tensorflow/contrib/tensor_forest/client/random_forest.py
+++ b/tensorflow/contrib/tensor_forest/client/random_forest.py
@@ -18,14 +18,16 @@ from __future__ import division
from __future__ import print_function
from tensorflow.contrib import layers
+from tensorflow.contrib.estimator.python.estimator import head as core_head_lib
from tensorflow.contrib.learn.python.learn.estimators import constants
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
-
from tensorflow.contrib.tensor_forest.client import eval_metrics
from tensorflow.contrib.tensor_forest.python import tensor_forest
-
+from tensorflow.python.estimator import estimator as core_estimator
+from tensorflow.python.estimator.export.export_output import PredictOutput
+from tensorflow.python.feature_column import feature_column as fc_core
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
@@ -34,12 +36,12 @@ from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
+from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary
from tensorflow.python.training import session_run_hook
from tensorflow.python.training import training_util
-
KEYS_NAME = 'keys'
LOSS_NAME = 'rf_training_loss'
TREE_PATHS_PREDICTION_KEY = 'tree_paths'
@@ -48,6 +50,11 @@ ALL_SERVING_KEY = 'tensorforest_all'
EPSILON = 0.000001
+class ModelBuilderOutputType(object):
+ MODEL_FN_OPS = 0
+ ESTIMATOR_SPEC = 1
+
+
class TensorForestRunOpAtEndHook(session_run_hook.SessionRunHook):
def __init__(self, op_dict):
@@ -106,20 +113,40 @@ class TensorForestLossHook(session_run_hook.SessionRunHook):
run_context.request_stop()
-def get_default_head(params, weights_name, name=None):
- if params.regression:
- return head_lib.regression_head(
- weight_column_name=weights_name,
- label_dimension=params.num_outputs,
- enable_centered_bias=False,
- head_name=name)
+def _get_default_head(params, weights_name, output_type, name=None):
+ """Creates a default head based on a type of a problem."""
+ if output_type == ModelBuilderOutputType.MODEL_FN_OPS:
+ if params.regression:
+ return head_lib.regression_head(
+ weight_column_name=weights_name,
+ label_dimension=params.num_outputs,
+ enable_centered_bias=False,
+ head_name=name)
+ else:
+ return head_lib.multi_class_head(
+ params.num_classes,
+ weight_column_name=weights_name,
+ enable_centered_bias=False,
+ head_name=name)
else:
- return head_lib.multi_class_head(
- params.num_classes,
- weight_column_name=weights_name,
- enable_centered_bias=False,
- head_name=name)
-
+ if params.regression:
+ return core_head_lib.regression_head(
+ weight_column=weights_name,
+ label_dimension=params.num_outputs,
+ name=name,
+ loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
+ else:
+ if params.num_classes == 2:
+ return core_head_lib.binary_classification_head(
+ weight_column=weights_name,
+ name=name,
+ loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
+ else:
+ return core_head_lib.multi_class_head(
+ n_classes=params.num_classes,
+ weight_column=weights_name,
+ name=name,
+ loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
def get_model_fn(params,
graph_builder_class,
@@ -135,19 +162,27 @@ def get_model_fn(params,
report_feature_importances=False,
local_eval=False,
head_scope=None,
- include_all_in_serving=False):
+ include_all_in_serving=False,
+ output_type=ModelBuilderOutputType.MODEL_FN_OPS):
"""Return a model function given a way to construct a graph builder."""
if model_head is None:
- model_head = get_default_head(params, weights_name)
+ model_head = _get_default_head(params, weights_name, output_type)
def _model_fn(features, labels, mode):
"""Function that returns predictions, training loss, and training op."""
+
if (isinstance(features, ops.Tensor) or
isinstance(features, sparse_tensor.SparseTensor)):
features = {'features': features}
if feature_columns:
features = features.copy()
- features.update(layers.transform_features(features, feature_columns))
+
+ if output_type == ModelBuilderOutputType.MODEL_FN_OPS:
+ features.update(layers.transform_features(features, feature_columns))
+ else:
+ for fc in feature_columns:
+ tensor = fc_core._transform_features(features, [fc])[fc] # pylint: disable=protected-access
+ features[fc.name] = tensor
weights = None
if weights_name and weights_name in features:
@@ -201,52 +236,95 @@ def get_model_fn(params,
def _train_fn(unused_loss):
return training_graph
- model_ops = model_head.create_model_fn_ops(
- features=features,
- labels=labels,
- mode=mode,
- train_op_fn=_train_fn,
- logits=logits,
- scope=head_scope)
# Ops are run in lexigraphical order of their keys. Run the resource
# clean-up op last.
all_handles = graph_builder.get_all_resource_handles()
ops_at_end = {
- '9: clean up resources': control_flow_ops.group(
- *[resource_variable_ops.destroy_resource_op(handle)
- for handle in all_handles])}
+ '9: clean up resources':
+ control_flow_ops.group(*[
+ resource_variable_ops.destroy_resource_op(handle)
+ for handle in all_handles
+ ])
+ }
if report_feature_importances:
ops_at_end['1: feature_importances'] = (
graph_builder.feature_importances())
- training_hooks.append(TensorForestRunOpAtEndHook(ops_at_end))
-
- if early_stopping_rounds:
- training_hooks.append(
- TensorForestLossHook(
- early_stopping_rounds,
- early_stopping_loss_threshold=early_stopping_loss_threshold,
- loss_op=model_ops.loss))
-
- model_ops.training_hooks.extend(training_hooks)
-
- if keys is not None:
- model_ops.predictions[keys_name] = keys
-
- if params.inference_tree_paths:
- model_ops.predictions[TREE_PATHS_PREDICTION_KEY] = tree_paths
-
- model_ops.predictions[VARIANCE_PREDICTION_KEY] = regression_variance
- if include_all_in_serving:
- # In order to serve the variance we need to add the prediction dict
- # to output_alternatives dict.
- if not model_ops.output_alternatives:
- model_ops.output_alternatives = {}
- model_ops.output_alternatives[ALL_SERVING_KEY] = (
- constants.ProblemType.UNSPECIFIED, model_ops.predictions)
- return model_ops
+ training_hooks = [TensorForestRunOpAtEndHook(ops_at_end)]
+
+ if output_type == ModelBuilderOutputType.MODEL_FN_OPS:
+ model_ops = model_head.create_model_fn_ops(
+ features=features,
+ labels=labels,
+ mode=mode,
+ train_op_fn=_train_fn,
+ logits=logits,
+ scope=head_scope)
+
+ if early_stopping_rounds:
+ training_hooks.append(
+ TensorForestLossHook(
+ early_stopping_rounds,
+ early_stopping_loss_threshold=early_stopping_loss_threshold,
+ loss_op=model_ops.loss))
+
+ model_ops.training_hooks.extend(training_hooks)
+
+ if keys is not None:
+ model_ops.predictions[keys_name] = keys
+
+ if params.inference_tree_paths:
+ model_ops.predictions[TREE_PATHS_PREDICTION_KEY] = tree_paths
+
+ model_ops.predictions[VARIANCE_PREDICTION_KEY] = regression_variance
+
+ if include_all_in_serving:
+ # In order to serve the variance we need to add the prediction dict
+ # to output_alternatives dict.
+ if not model_ops.output_alternatives:
+ model_ops.output_alternatives = {}
+ model_ops.output_alternatives[ALL_SERVING_KEY] = (
+ constants.ProblemType.UNSPECIFIED, model_ops.predictions)
+
+ return model_ops
+
+ else:
+ # Estimator spec
+ estimator_spec = model_head.create_estimator_spec(
+ features=features,
+ mode=mode,
+ labels=labels,
+ train_op_fn=_train_fn,
+ logits=logits)
+
+ if early_stopping_rounds:
+ training_hooks.append(
+ TensorForestLossHook(
+ early_stopping_rounds,
+ early_stopping_loss_threshold=early_stopping_loss_threshold,
+ loss_op=estimator_spec.loss))
+
+ estimator_spec = estimator_spec._replace(
+ training_hooks=training_hooks + list(estimator_spec.training_hooks))
+ if keys is not None:
+ estimator_spec.predictions[keys_name] = keys
+ if params.inference_tree_paths:
+ estimator_spec.predictions[TREE_PATHS_PREDICTION_KEY] = tree_paths
+ estimator_spec.predictions[VARIANCE_PREDICTION_KEY] = regression_variance
+
+ if include_all_in_serving:
+ outputs = estimator_spec.export_outputs
+ if not outputs:
+ outputs = {}
+ outputs = {ALL_SERVING_KEY: PredictOutput(estimator_spec.predictions)}
+ print(estimator_spec.export_outputs)
+ # In order to serve the variance we need to add the prediction dict
+ # to output_alternatives dict.
+ estimator_spec = estimator_spec._replace(export_outputs=outputs)
+
+ return estimator_spec
return _model_fn
@@ -493,8 +571,11 @@ class MultiForestMultiHeadEstimator(estimator.Estimator):
params,
graph_builder_class,
device_assigner,
- model_head=get_default_head(
- params, weight_column, name='head{0}'.format(i)),
+ model_head=_get_default_head(
+ params,
+ weight_column,
+ name='head{0}'.format(i),
+ output_type=ModelBuilderOutputType.MODEL_FN_OPS),
weights_name=weight_column,
keys_name=keys_column,
early_stopping_rounds=early_stopping_rounds,
@@ -509,3 +590,142 @@ class MultiForestMultiHeadEstimator(estimator.Estimator):
model_dir=model_dir,
config=config,
feature_engineering_fn=feature_engineering_fn)
+
+
+class CoreTensorForestEstimator(core_estimator.Estimator):
+ """A CORE estimator that can train and evaluate a random forest.
+
+ Example:
+
+ ```python
+ params = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams(
+ num_classes=2, num_features=40, num_trees=10, max_nodes=1000)
+
+ # Estimator using the default graph builder.
+ estimator = CoreTensorForestEstimator(params, model_dir=model_dir)
+
+ # Or estimator using TrainingLossForest as the graph builder.
+ estimator = CoreTensorForestEstimator(
+ params, graph_builder_class=tensor_forest.TrainingLossForest,
+ model_dir=model_dir)
+
+ # Input builders
+ def input_fn_train: # returns x, y
+ ...
+ def input_fn_eval: # returns x, y
+ ...
+ estimator.train(input_fn=input_fn_train)
+ estimator.evaluate(input_fn=input_fn_eval)
+
+ # Predict returns an iterable of dicts.
+ results = list(estimator.predict(x=x))
+ prob0 = results[0][eval_metrics.INFERENCE_PROB_NAME]
+ prediction0 = results[0][eval_metrics.INFERENCE_PRED_NAME]
+ ```
+ """
+
+ def __init__(self,
+ params,
+ device_assigner=None,
+ model_dir=None,
+ feature_columns=None,
+ graph_builder_class=tensor_forest.RandomForestGraphs,
+ config=None,
+ weight_column=None,
+ keys_column=None,
+ feature_engineering_fn=None,
+ early_stopping_rounds=100,
+ early_stopping_loss_threshold=0.001,
+ num_trainers=1,
+ trainer_id=0,
+ report_feature_importances=False,
+ local_eval=False,
+ version=None,
+ head=None,
+ include_all_in_serving=False):
+ """Initializes a TensorForestEstimator instance.
+
+ Args:
+ params: ForestHParams object that holds random forest hyperparameters.
+ These parameters will be passed into `model_fn`.
+ device_assigner: An `object` instance that controls how trees get
+ assigned to devices. If `None`, will use
+ `tensor_forest.RandomForestDeviceAssigner`.
+ model_dir: Directory to save model parameters, graph, etc. To continue
+ training a previously saved model, load checkpoints saved to this
+ directory into an estimator.
+ feature_columns: An iterable containing all the feature columns used by
+ the model. All items in the set should be instances of classes derived
+ from `_FeatureColumn`.
+ graph_builder_class: An `object` instance that defines how TF graphs for
+ random forest training and inference are built. By default will use
+ `tensor_forest.RandomForestGraphs`. Can be overridden by version
+ kwarg.
+ config: `RunConfig` object to configure the runtime settings.
+ weight_column: A string defining feature column name representing
+ weights. Will be multiplied by the loss of the example. Used to
+ downweight or boost examples during training.
+ keys_column: A string naming one of the features to strip out and
+ pass through into the inference/eval results dict. Useful for
+ associating specific examples with their prediction.
+ feature_engineering_fn: Feature engineering function. Takes features and
+ labels which are the output of `input_fn` and returns features and
+ labels which will be fed into the model.
+ early_stopping_rounds: Allows training to terminate early if the forest is
+ no longer growing. 100 by default. Set to a Falsy value to disable
+ the default training hook.
+ early_stopping_loss_threshold: Percentage (as fraction) that loss must
+ improve by within early_stopping_rounds steps, otherwise training will
+ terminate.
+ num_trainers: Number of training jobs, which will partition trees
+ among them.
+ trainer_id: Which trainer this instance is.
+ report_feature_importances: If True, print out feature importances
+ during evaluation.
+ local_eval: If True, don't use a device assigner for eval. This is to
+ support some common setups where eval is done on a single machine, even
+ though training might be distributed.
+ version: Unused.
+ head: A heads_lib.Head object that calculates losses and such. If None,
+ one will be automatically created based on params.
+ include_all_in_serving: if True, allow preparation of the complete
+ prediction dict including the variance to be exported for serving with
+ the Servo lib; and it also requires calling export_savedmodel with
+ default_output_alternative_key=ALL_SERVING_KEY, i.e.
+ estimator.export_savedmodel(export_dir_base=your_export_dir,
+ serving_input_fn=your_export_input_fn,
+ default_output_alternative_key=ALL_SERVING_KEY)
+ if False, resort to default behavior, i.e. export scores and
+ probabilities but no variances. In this case
+ default_output_alternative_key should be None while calling
+ export_savedmodel().
+ Note, that due to backward compatibility we cannot always set
+ include_all_in_serving to True because in this case calling
+ export_saved_model() without
+ default_output_alternative_key=ALL_SERVING_KEY (legacy behavior) the
+ saved_model_export_utils.get_output_alternatives() would raise
+ ValueError.
+
+ Returns:
+ A `TensorForestEstimator` instance.
+ """
+
+ super(CoreTensorForestEstimator, self).__init__(
+ model_fn=get_model_fn(
+ params.fill(),
+ graph_builder_class,
+ device_assigner,
+ feature_columns=feature_columns,
+ model_head=head,
+ weights_name=weight_column,
+ keys_name=keys_column,
+ early_stopping_rounds=early_stopping_rounds,
+ early_stopping_loss_threshold=early_stopping_loss_threshold,
+ num_trainers=num_trainers,
+ trainer_id=trainer_id,
+ report_feature_importances=report_feature_importances,
+ local_eval=local_eval,
+ include_all_in_serving=include_all_in_serving,
+ output_type=ModelBuilderOutputType.ESTIMATOR_SPEC),
+ model_dir=model_dir,
+ config=config)
diff --git a/tensorflow/contrib/tensor_forest/client/random_forest_test.py b/tensorflow/contrib/tensor_forest/client/random_forest_test.py
index ac42364d25..aa0016b740 100644
--- a/tensorflow/contrib/tensor_forest/client/random_forest_test.py
+++ b/tensorflow/contrib/tensor_forest/client/random_forest_test.py
@@ -23,7 +23,39 @@ import numpy as np
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.contrib.tensor_forest.client import random_forest
from tensorflow.contrib.tensor_forest.python import tensor_forest
+from tensorflow.python.estimator.canned import head as head_lib
+from tensorflow.python.estimator.inputs import numpy_io
+from tensorflow.python.feature_column import feature_column_lib as core_feature_column
+from tensorflow.python.framework import ops
+from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import test
+from tensorflow.python.training import checkpoint_utils
+
+
+def _get_classification_input_fns():
+ iris = base.load_iris()
+ data = iris.data.astype(np.float32)
+ labels = iris.target.astype(np.int32)
+
+ train_input_fn = numpy_io.numpy_input_fn(
+ x=data, y=labels, batch_size=150, num_epochs=None, shuffle=False)
+
+ predict_input_fn = numpy_io.numpy_input_fn(
+ x=data[:1,], y=None, batch_size=1, num_epochs=1, shuffle=False)
+ return train_input_fn, predict_input_fn
+
+
+def _get_regression_input_fns():
+ boston = base.load_boston()
+ data = boston.data.astype(np.float32)
+ labels = boston.target.astype(np.int32)
+
+ train_input_fn = numpy_io.numpy_input_fn(
+ x=data, y=labels, batch_size=506, num_epochs=None, shuffle=False)
+
+ predict_input_fn = numpy_io.numpy_input_fn(
+ x=data[:1,], y=None, batch_size=1, num_epochs=1, shuffle=False)
+ return train_input_fn, predict_input_fn
class TensorForestTrainerTests(test.TestCase):
@@ -39,32 +71,287 @@ class TensorForestTrainerTests(test.TestCase):
inference_tree_paths=True)
classifier = random_forest.TensorForestEstimator(hparams.fill())
+ input_fn, predict_input_fn = _get_classification_input_fns()
+ classifier.fit(input_fn=input_fn, steps=100)
+ res = classifier.evaluate(input_fn=input_fn, steps=10)
+
+ self.assertEqual(1.0, res['accuracy'])
+ self.assertAllClose(0.55144483, res['loss'])
+
+ predictions = list(classifier.predict(input_fn=predict_input_fn))
+ self.assertAllClose([[0.576117, 0.211942, 0.211942]],
+ [pred['probabilities'] for pred in predictions])
+
+ def testRegression(self):
+ """Tests regression using matrix data as input."""
+
+ hparams = tensor_forest.ForestHParams(
+ num_trees=5,
+ max_nodes=1000,
+ num_classes=1,
+ num_features=13,
+ regression=True,
+ split_after_samples=20)
+
+ regressor = random_forest.TensorForestEstimator(hparams.fill())
+
+ input_fn, predict_input_fn = _get_regression_input_fns()
+
+ regressor.fit(input_fn=input_fn, steps=100)
+ res = regressor.evaluate(input_fn=input_fn, steps=10)
+ self.assertGreaterEqual(0.1, res['loss'])
+
+ predictions = list(regressor.predict(input_fn=predict_input_fn))
+ self.assertAllClose([24.], [pred['scores'] for pred in predictions], atol=1)
+
+ def testAdditionalOutputs(self):
+ """Tests multi-class classification using matrix data as input."""
+ hparams = tensor_forest.ForestHParams(
+ num_trees=1,
+ max_nodes=100,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
+ classifier = random_forest.TensorForestEstimator(
+ hparams.fill(), keys_column='keys', include_all_in_serving=True)
+
iris = base.load_iris()
data = iris.data.astype(np.float32)
labels = iris.target.astype(np.int32)
- classifier.fit(x=data, y=labels, steps=100, batch_size=50)
- classifier.evaluate(x=data, y=labels, steps=10)
+ input_fn = numpy_io.numpy_input_fn(
+ x={
+ 'x': data,
+ 'keys': np.arange(len(iris.data)).reshape(150, 1)
+ },
+ y=labels,
+ batch_size=10,
+ num_epochs=1,
+ shuffle=False)
- def testRegression(self):
+ classifier.fit(input_fn=input_fn, steps=100)
+ predictions = list(classifier.predict(input_fn=input_fn))
+ # Check that there is a key column, tree paths and var.
+ for pred in predictions:
+ self.assertTrue('keys' in pred)
+ self.assertTrue('tree_paths' in pred)
+ self.assertTrue('prediction_variance' in pred)
+
+ def _assert_checkpoint(self, model_dir, global_step):
+ reader = checkpoint_utils.load_checkpoint(model_dir)
+ self.assertLessEqual(
+ reader.get_tensor(ops.GraphKeys.GLOBAL_STEP), global_step)
+
+ def testEarlyStopping(self):
"""Tests multi-class classification using matrix data as input."""
+ hparams = tensor_forest.ForestHParams(
+ num_trees=100,
+ max_nodes=10000,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
+ classifier = random_forest.TensorForestEstimator(
+ hparams.fill(),
+ # Set a crazy threshold - 30% loss change.
+ early_stopping_loss_threshold=0.3,
+ early_stopping_rounds=2)
+
+ input_fn, _ = _get_classification_input_fns()
+ classifier.fit(input_fn=input_fn, steps=100)
+
+ # We stopped early.
+ self._assert_checkpoint(classifier.model_dir, global_step=5)
+
+
+class CoreTensorForestTests(test.TestCase):
+
+ def testTrainEvaluateInferDoesNotThrowErrorForClassifier(self):
+ head_fn = head_lib._multi_class_head_with_softmax_cross_entropy_loss(
+ n_classes=3, loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
hparams = tensor_forest.ForestHParams(
num_trees=3,
max_nodes=1000,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
+
+ est = random_forest.CoreTensorForestEstimator(hparams.fill(), head=head_fn)
+
+ input_fn, predict_input_fn = _get_classification_input_fns()
+
+ est.train(input_fn=input_fn, steps=100)
+ res = est.evaluate(input_fn=input_fn, steps=1)
+
+ self.assertEqual(1.0, res['accuracy'])
+ self.assertAllClose(0.55144483, res['loss'])
+
+ predictions = list(est.predict(input_fn=predict_input_fn))
+ self.assertAllClose([[0.576117, 0.211942, 0.211942]],
+ [pred['probabilities'] for pred in predictions])
+
+ def testRegression(self):
+ """Tests regression using matrix data as input."""
+ head_fn = head_lib._regression_head(
+ label_dimension=1,
+ loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
+
+ hparams = tensor_forest.ForestHParams(
+ num_trees=5,
+ max_nodes=1000,
num_classes=1,
num_features=13,
regression=True,
split_after_samples=20)
- regressor = random_forest.TensorForestEstimator(hparams.fill())
+ regressor = random_forest.CoreTensorForestEstimator(
+ hparams.fill(), head=head_fn)
+
+ input_fn, predict_input_fn = _get_regression_input_fns()
+
+ regressor.train(input_fn=input_fn, steps=100)
+ res = regressor.evaluate(input_fn=input_fn, steps=10)
+ self.assertGreaterEqual(0.1, res['loss'])
+
+ predictions = list(regressor.predict(input_fn=predict_input_fn))
+ self.assertAllClose(
+ [[24.]], [pred['predictions'] for pred in predictions], atol=1)
+
+ def testWithFeatureColumns(self):
+ head_fn = head_lib._multi_class_head_with_softmax_cross_entropy_loss(
+ n_classes=3, loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
+
+ hparams = tensor_forest.ForestHParams(
+ num_trees=3,
+ max_nodes=1000,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
+
+ est = random_forest.CoreTensorForestEstimator(
+ hparams.fill(),
+ head=head_fn,
+ feature_columns=[core_feature_column.numeric_column('x')])
+
+ iris = base.load_iris()
+ data = {'x': iris.data.astype(np.float32)}
+ labels = iris.target.astype(np.int32)
+
+ input_fn = numpy_io.numpy_input_fn(
+ x=data, y=labels, batch_size=150, num_epochs=None, shuffle=False)
+
+ est.train(input_fn=input_fn, steps=100)
+ res = est.evaluate(input_fn=input_fn, steps=1)
+
+ self.assertEqual(1.0, res['accuracy'])
+ self.assertAllClose(0.55144483, res['loss'])
+
+ def testAutofillsClassificationHead(self):
+ hparams = tensor_forest.ForestHParams(
+ num_trees=3,
+ max_nodes=1000,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
+
+ est = random_forest.CoreTensorForestEstimator(hparams.fill())
+
+ input_fn, _ = _get_classification_input_fns()
+
+ est.train(input_fn=input_fn, steps=100)
+ res = est.evaluate(input_fn=input_fn, steps=1)
+
+ self.assertEqual(1.0, res['accuracy'])
+ self.assertAllClose(0.55144483, res['loss'])
+
+ def testAutofillsRegressionHead(self):
+ hparams = tensor_forest.ForestHParams(
+ num_trees=5,
+ max_nodes=1000,
+ num_classes=1,
+ num_features=13,
+ regression=True,
+ split_after_samples=20)
+
+ regressor = random_forest.CoreTensorForestEstimator(hparams.fill())
+
+ input_fn, predict_input_fn = _get_regression_input_fns()
+
+ regressor.train(input_fn=input_fn, steps=100)
+ res = regressor.evaluate(input_fn=input_fn, steps=10)
+ self.assertGreaterEqual(0.1, res['loss'])
+
+ predictions = list(regressor.predict(input_fn=predict_input_fn))
+ self.assertAllClose(
+ [[24.]], [pred['predictions'] for pred in predictions], atol=1)
+
+ def testAdditionalOutputs(self):
+ """Tests multi-class classification using matrix data as input."""
+ hparams = tensor_forest.ForestHParams(
+ num_trees=1,
+ max_nodes=100,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
+ classifier = random_forest.CoreTensorForestEstimator(
+ hparams.fill(), keys_column='keys', include_all_in_serving=True)
+
+ iris = base.load_iris()
+ data = iris.data.astype(np.float32)
+ labels = iris.target.astype(np.int32)
+
+ input_fn = numpy_io.numpy_input_fn(
+ x={
+ 'x': data,
+ 'keys': np.arange(len(iris.data)).reshape(150, 1)
+ },
+ y=labels,
+ batch_size=10,
+ num_epochs=1,
+ shuffle=False)
+
+ classifier.train(input_fn=input_fn, steps=100)
+ predictions = list(classifier.predict(input_fn=input_fn))
+ # Check that there is a key column, tree paths and var.
+ for pred in predictions:
+ self.assertTrue('keys' in pred)
+ self.assertTrue('tree_paths' in pred)
+ self.assertTrue('prediction_variance' in pred)
+
+ def _assert_checkpoint(self, model_dir, global_step):
+ reader = checkpoint_utils.load_checkpoint(model_dir)
+ self.assertLessEqual(
+ reader.get_tensor(ops.GraphKeys.GLOBAL_STEP), global_step)
+
+ def testEarlyStopping(self):
+ head_fn = head_lib._multi_class_head_with_softmax_cross_entropy_loss(
+ n_classes=3, loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
+
+ hparams = tensor_forest.ForestHParams(
+ num_trees=3,
+ max_nodes=1000,
+ num_classes=3,
+ num_features=4,
+ split_after_samples=20,
+ inference_tree_paths=True)
- boston = base.load_boston()
- data = boston.data.astype(np.float32)
- labels = boston.target.astype(np.int32)
+ est = random_forest.CoreTensorForestEstimator(
+ hparams.fill(),
+ head=head_fn,
+ # Set a crazy threshold - 30% loss change.
+ early_stopping_loss_threshold=0.3,
+ early_stopping_rounds=2)
- regressor.fit(x=data, y=labels, steps=100, batch_size=50)
- regressor.evaluate(x=data, y=labels, steps=10)
+ input_fn, _ = _get_classification_input_fns()
+ est.train(input_fn=input_fn, steps=100)
+ # We stopped early.
+ self._assert_checkpoint(est.model_dir, global_step=8)
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.cc b/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.cc
index 6cb2c881e2..7716536ba4 100644
--- a/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.cc
+++ b/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.cc
@@ -54,17 +54,24 @@ InequalityDecisionNodeEvaluator::InequalityDecisionNodeEvaluator(
CHECK(safe_strto32(test.feature_id().id().value(), &feature_num_))
<< "Invalid feature ID: [" << test.feature_id().id().value() << "]";
threshold_ = test.threshold().float_value();
- include_equals_ =
- test.type() == decision_trees::InequalityTest::LESS_OR_EQUAL;
+ _test_type = test.type();
}
int32 InequalityDecisionNodeEvaluator::Decide(
const std::unique_ptr<TensorDataSet>& dataset, int example) const {
const float val = dataset->GetExampleValue(example, feature_num_);
- if (val < threshold_ || (include_equals_ && val == threshold_)) {
- return left_child_id_;
- } else {
- return right_child_id_;
+ switch (_test_type) {
+ case decision_trees::InequalityTest::LESS_OR_EQUAL:
+ return val <= threshold_ ? left_child_id_ : right_child_id_;
+ case decision_trees::InequalityTest::LESS_THAN:
+ return val < threshold_ ? left_child_id_ : right_child_id_;
+ case decision_trees::InequalityTest::GREATER_OR_EQUAL:
+ return val >= threshold_ ? left_child_id_ : right_child_id_;
+ case decision_trees::InequalityTest::GREATER_THAN:
+ return val > threshold_ ? left_child_id_ : right_child_id_;
+ default:
+ LOG(ERROR) << "Unknown split test type: " << _test_type;
+ return -1;
}
}
diff --git a/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.h b/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.h
index 3db351c328..6497787f84 100644
--- a/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.h
+++ b/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator.h
@@ -55,9 +55,7 @@ class InequalityDecisionNodeEvaluator : public BinaryDecisionNodeEvaluator {
protected:
int32 feature_num_;
float threshold_;
-
- // If decision is '<=' as opposed to '<'.
- bool include_equals_;
+ ::tensorflow::decision_trees::InequalityTest_Type _test_type;
};
// Evaluator for splits with multiple weighted features.
diff --git a/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator_test.cc b/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator_test.cc
index af5cf72a3c..3db1335563 100644
--- a/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator_test.cc
+++ b/tensorflow/contrib/tensor_forest/kernels/v4/decision_node_evaluator_test.cc
@@ -60,6 +60,40 @@ TEST(InequalityDecisionNodeEvaluatorTest, TestStrictlyLess) {
ASSERT_EQ(eval->Decide(dataset, 4), 1);
}
+TEST(InequalityDecisionNodeEvaluatorTest, TestGreaterOrEqual) {
+ InequalityTest test;
+ test.mutable_feature_id()->mutable_id()->set_value("0");
+ test.mutable_threshold()->set_float_value(3.0);
+ test.set_type(InequalityTest::GREATER_OR_EQUAL);
+ std::unique_ptr<InequalityDecisionNodeEvaluator> eval(
+ new InequalityDecisionNodeEvaluator(test, 0, 1));
+
+ std::unique_ptr<tensorflow::tensorforest::TensorDataSet> dataset(
+ new tensorflow::tensorforest::TestableDataSet(
+ {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}, 1));
+
+ ASSERT_EQ(eval->Decide(dataset, 2), 1);
+ ASSERT_EQ(eval->Decide(dataset, 3), 0);
+ ASSERT_EQ(eval->Decide(dataset, 4), 0);
+}
+
+TEST(InequalityDecisionNodeEvaluatorTest, TestStrictlyGreater) {
+ InequalityTest test;
+ test.mutable_feature_id()->mutable_id()->set_value("0");
+ test.mutable_threshold()->set_float_value(3.0);
+ test.set_type(InequalityTest::GREATER_THAN);
+ std::unique_ptr<InequalityDecisionNodeEvaluator> eval(
+ new InequalityDecisionNodeEvaluator(test, 0, 1));
+
+ std::unique_ptr<tensorflow::tensorforest::TensorDataSet> dataset(
+ new tensorflow::tensorforest::TestableDataSet(
+ {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}, 1));
+
+ ASSERT_EQ(eval->Decide(dataset, 2), 1);
+ ASSERT_EQ(eval->Decide(dataset, 3), 1);
+ ASSERT_EQ(eval->Decide(dataset, 4), 0);
+}
+
TEST(MatchingDecisionNodeEvaluatorTest, Basic) {
MatchingValuesTest test;
test.mutable_feature_id()->mutable_id()->set_value("0");
diff --git a/tensorflow/contrib/tensorrt/BUILD b/tensorflow/contrib/tensorrt/BUILD
index fc0d22d112..26236a0435 100644
--- a/tensorflow/contrib/tensorrt/BUILD
+++ b/tensorflow/contrib/tensorrt/BUILD
@@ -387,17 +387,19 @@ cuda_py_tests(
name = "tf_trt_integration_test",
srcs = [
"test/base_test.py",
- # "test/batch_matmul_test.py",
- # "test/biasadd_matmul_test.py",
- # "test/binary_tensor_weight_broadcast_test.py", # Blocked by trt4 installation
- # "test/concatenation_test.py", # Blocked by trt4 installation
+ "test/batch_matmul_test.py",
+ "test/biasadd_matmul_test.py",
+ "test/binary_tensor_weight_broadcast_test.py",
+ "test/concatenation_test.py",
"test/const_broadcast_test.py",
+ "test/manual_test.py",
+ "test/memory_alignment_test.py",
"test/multi_connection_neighbor_engine_test.py",
"test/neighboring_engine_test.py",
- # "test/unary_test.py", # Blocked by trt4 installation
- # "test/vgg_block_nchw_test.py",
- # "test/vgg_block_test.py",
- "test/memory_alignment_test.py",
+ "test/rank_two_test.py",
+ "test/unary_test.py",
+ "test/vgg_block_nchw_test.py",
+ "test/vgg_block_test.py",
],
additional_deps = [
":tf_trt_integration_test_base",
diff --git a/tensorflow/contrib/tensorrt/convert/convert_nodes.cc b/tensorflow/contrib/tensorrt/convert/convert_nodes.cc
index 35fa590254..863074e773 100644
--- a/tensorflow/contrib/tensorrt/convert/convert_nodes.cc
+++ b/tensorflow/contrib/tensorrt/convert/convert_nodes.cc
@@ -155,12 +155,22 @@ tensorflow::Status ValidateInputProperties(const PartialTensorShape& shape,
for (int d = 1; d < shape.dims(); ++d) {
if (shape.dim_size(d) < 0) {
return tensorflow::errors::InvalidArgument(
- "Input tensor has a unknown non-batch dimemension at dim ", d);
+ "Input tensor with shape ", shape.DebugString(),
+ " has an unknown non-batch dimemension at dim ", d);
}
}
return Status::OK();
}
+string DebugString(const nvinfer1::Dims& dims) {
+ string out = StrCat("nvinfer1::Dims(nbDims=", dims.nbDims, ", d=");
+ for (int i = 0; i < nvinfer1::Dims::MAX_DIMS; ++i) {
+ StrAppend(&out, dims.d[i], ",");
+ }
+ StrAppend(&out, ")");
+ return out;
+}
+
// Return whether or not the broadcast is feasible;
bool TensorRTGetBroadcastShape(const nvinfer1::Dims& operand_l,
const bool operand_l_is_tensor,
@@ -353,6 +363,13 @@ class TRT_ShapedWeights {
// Default converter
operator nvinfer1::Weights() const { return GetWeightsForTRT(); }
+ string DebugString() const {
+ return StrCat(
+ "TRT_ShapedWeights(shape=", convert::DebugString(shape_), ", type=",
+ type_, ", values=", reinterpret_cast<uintptr_t>(values_),
+ ", empty_weight_flag=", empty_weight_flag_, ")");
+ }
+
// TODO(aaroey): make these private.
nvinfer1::Dims shape_;
tensorflow::DataType type_;
@@ -367,11 +384,14 @@ class TRT_TensorOrWeights {
public:
explicit TRT_TensorOrWeights(nvinfer1::ITensor* tensor)
: tensor_(tensor), weights_(DT_FLOAT), variant_(TRT_NODE_TENSOR) {}
+
explicit TRT_TensorOrWeights(const TRT_ShapedWeights& weights)
: tensor_(nullptr), weights_(weights), variant_(TRT_NODE_WEIGHTS) {}
+
// TODO(aaroey): use rvalue reference.
TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs)
: tensor_(rhs.tensor_), weights_(rhs.weights_), variant_(rhs.variant_) {}
+
~TRT_TensorOrWeights() {}
bool is_tensor() const { return variant_ == TRT_NODE_TENSOR; }
@@ -381,18 +401,22 @@ class TRT_TensorOrWeights {
CHECK(is_tensor());
return tensor_;
}
+
const nvinfer1::ITensor* tensor() const {
CHECK(is_tensor());
return tensor_;
}
+
TRT_ShapedWeights& weights() {
CHECK(is_weights());
return weights_;
}
+
const TRT_ShapedWeights& weights() const {
CHECK(is_weights());
return weights_;
}
+
nvinfer1::Dims shape() const {
if (is_tensor()) {
return tensor()->getDimensions();
@@ -401,6 +425,18 @@ class TRT_TensorOrWeights {
}
}
+ string DebugString() const {
+ string output = "TRT_TensorOrWeights(type=";
+ if (is_tensor()) {
+ StrAppend(&output, "tensor @", reinterpret_cast<uintptr_t>(tensor_),
+ ", shape=", convert::DebugString(tensor_->getDimensions()));
+ } else {
+ StrAppend(&output, "weights=", weights_.DebugString());
+ }
+ StrAppend(&output, ")");
+ return output;
+ }
+
private:
nvinfer1::ITensor* tensor_;
TRT_ShapedWeights weights_;
@@ -555,7 +591,7 @@ void ReorderCKtoKC(const TRT_ShapedWeights& iweights,
}
void ReorderRSCKToKCRS(const TRT_ShapedWeights& iweights,
- TRT_ShapedWeights* oweights, int num_groups) {
+ TRT_ShapedWeights* oweights, const int num_groups) {
CHECK_EQ(iweights.type_, oweights->type_);
CHECK_EQ(iweights.size_bytes(), oweights->size_bytes());
// K indexes over output channels, C over input channels, and R and S over the
@@ -563,13 +599,13 @@ void ReorderRSCKToKCRS(const TRT_ShapedWeights& iweights,
const int r = iweights.shape_.d[0];
const int s = iweights.shape_.d[1];
// TRT requires GKcRS, while TF depthwise has RSCK where c=1, C=G
- VLOG(2) << "num_groups: " << num_groups;
const int c = iweights.shape_.d[2] / num_groups;
- VLOG(2) << "c" << iweights.shape_.d[2] << " then " << c;
const int k = iweights.shape_.d[3] * num_groups;
- VLOG(2) << "k" << iweights.shape_.d[3] << " then " << k;
- VLOG(2) << "r" << iweights.shape_.d[0] << " then " << r;
- VLOG(2) << "s" << iweights.shape_.d[1] << " then " << s;
+ VLOG(2) << "num_groups: " << num_groups
+ << "c" << iweights.shape_.d[2] << " then " << c
+ << "k" << iweights.shape_.d[3] << " then " << k
+ << "r" << iweights.shape_.d[0] << " then " << r
+ << "s" << iweights.shape_.d[1] << " then " << s;
oweights->shape_.d[0] = k / num_groups;
oweights->shape_.d[1] = c * num_groups;
oweights->shape_.d[2] = r;
@@ -607,63 +643,15 @@ using OpConverter =
std::vector<TRT_TensorOrWeights>*)>;
class Converter {
- // TODO(aaroey): fix the order of members.
- std::unordered_map<string, TRT_TensorOrWeights> trt_tensors_;
- std::unordered_map<string, OpConverter> op_registry_;
- OpConverter plugin_converter_;
- nvinfer1::INetworkDefinition* trt_network_;
- std::list<std::vector<uint8_t>> temp_bufs_;
- // TODO(aaroey): inline the definition of TRTWeightStore here, and add APIs to
- // operate the stored weights instead of operating it directly.
- TRTWeightStore* weight_store_;
- bool fp16_;
- void register_op_converters();
- tensorflow::Status get_inputs(const tensorflow::NodeDef& node_def,
- std::vector<TRT_TensorOrWeights>* inputs) {
- for (auto const& input_name : node_def.input()) {
- /*************************************************************************
- * TODO(jie): handle case 1) here.
- * Normalizes the inputs and extracts associated metadata:
- * 1) Inputs can contain a colon followed by a suffix of characters.
- * That suffix may be a single number (e.g. inputName:1) or several
- * word characters separated from a number by a colon
- * (e.g. inputName:foo:1). The
- * latter case is used to denote inputs and outputs of functions.
- * 2) Control dependency inputs contain caret at the beginning and we
- * remove this and annotate the edge as a control dependency.
- ************************************************************************/
- // skip control nodes
- if (input_name[0] == '^') continue;
- string name = input_name;
- auto first = name.find_first_of(':');
- // TODO(aaroey): why removing the colon but not the zero? A bug?
- if (first != string::npos && first + 2 == name.size() &&
- name[first + 1] == '0')
- name.erase(first);
-
- VLOG(2) << "retrieve input: " << name;
- if (trt_tensors_.count(name)) {
- inputs->push_back(trt_tensors_.at(name));
- } else {
- // TODO(aaroey): this should not happen, make it a CHECK.
- // TODO(aaroey): use StrCat for pattern like this.
- string msg("Node ");
- StrAppend(&msg, node_def.name(), " should have an input named '", name,
- "' but it is not available");
- LOG(ERROR) << msg;
- return tensorflow::errors::InvalidArgument(msg);
- }
- }
- return tensorflow::Status::OK();
- }
-
public:
explicit Converter(nvinfer1::INetworkDefinition* trt_network,
TRTWeightStore* ws, bool fp16)
: trt_network_(trt_network), weight_store_(ws), fp16_(fp16) {
this->register_op_converters();
}
+
TRTWeightStore* weight_store() { return weight_store_; }
+
TRT_ShapedWeights get_temp_weights(tensorflow::DataType type,
nvinfer1::Dims shape) {
TRT_ShapedWeights weights(type, nullptr, shape);
@@ -672,8 +660,10 @@ class Converter {
weights.SetValues(weight_store_->store_.back().data());
return weights;
}
+
// TODO(aaroey): fix all the namings.
bool isFP16() { return fp16_; }
+
TRT_ShapedWeights get_temp_weights_like(const TRT_ShapedWeights& weights) {
return this->get_temp_weights(weights.type_, weights.shape_);
}
@@ -684,7 +674,6 @@ class Converter {
const string& op = node_def.op();
std::vector<TRT_TensorOrWeights> outputs;
if (PluginFactoryTensorRT::GetInstance()->IsPlugin(op)) {
- // TODO(aaroey): plugin_converter_ is not set, fix it.
TF_RETURN_IF_ERROR(plugin_converter_(*this, node_def, inputs, &outputs));
} else {
if (!op_registry_.count(op)) {
@@ -702,7 +691,8 @@ class Converter {
if (output.is_tensor()) {
output.tensor()->setName(output_name.c_str());
}
- VLOG(2) << "Write out tensor: " << output_name;
+ VLOG(2) << "Adding out tensor " << output_name << ": "
+ << output.DebugString();
if (!trt_tensors_.insert({output_name, output}).second) {
return tensorflow::errors::AlreadyExists(
"Output tensor already exists for op: " + op);
@@ -751,6 +741,63 @@ class Converter {
layer->setReshapeDimensions(reshape_dims);
return layer->getOutput(0);
}
+
+ private:
+ std::unordered_map<string, TRT_TensorOrWeights> trt_tensors_;
+ std::unordered_map<string, OpConverter> op_registry_;
+ OpConverter plugin_converter_;
+ nvinfer1::INetworkDefinition* trt_network_;
+ std::list<std::vector<uint8_t>> temp_bufs_;
+
+ // TODO(aaroey): inline the definition of TRTWeightStore here, and add APIs to
+ // operate the stored weights instead of operating it directly.
+ TRTWeightStore* weight_store_;
+
+ bool fp16_;
+
+ void register_op_converters();
+
+ tensorflow::Status get_inputs(const tensorflow::NodeDef& node_def,
+ std::vector<TRT_TensorOrWeights>* inputs) {
+ for (auto const& input_name : node_def.input()) {
+ /*************************************************************************
+ * TODO(jie): handle case 1) here.
+ * Normalizes the inputs and extracts associated metadata:
+ * 1) Inputs can contain a colon followed by a suffix of characters.
+ * That suffix may be a single number (e.g. inputName:1) or several
+ * word characters separated from a number by a colon
+ * (e.g. inputName:foo:1). The
+ * latter case is used to denote inputs and outputs of functions.
+ * 2) Control dependency inputs contain caret at the beginning and we
+ * remove this and annotate the edge as a control dependency.
+ ************************************************************************/
+ // skip control nodes
+ if (input_name[0] == '^') continue;
+ string name = input_name;
+ auto first = name.find_first_of(':');
+ // TODO(aaroey): why removing the colon but not the zero? A bug?
+ // TODO(aaroey): use TensorId
+ if (first != string::npos && first + 2 == name.size() &&
+ name[first + 1] == '0') {
+ name.erase(first);
+ }
+
+ if (trt_tensors_.count(name)) {
+ TRT_TensorOrWeights& input = trt_tensors_.at(name);
+ inputs->push_back(input);
+ VLOG(2) << "Retrieved input " << name << ": " << input.DebugString();
+ } else {
+ // TODO(aaroey): this should not happen, make it a CHECK.
+ // TODO(aaroey): use StrCat for pattern like this.
+ string msg("Node ");
+ StrAppend(&msg, node_def.name(), " should have an input named '", name,
+ "' but it is not available");
+ LOG(ERROR) << msg;
+ return tensorflow::errors::InvalidArgument(msg);
+ }
+ }
+ return tensorflow::Status::OK();
+ }
};
TRT_ShapedWeights ConvertFP32ToFP16(Converter& ctx,
@@ -1187,17 +1234,11 @@ tensorflow::Status ConvertConv2DHelper(
VLOG(2) << "groups count: " << num_groups;
TRT_ShapedWeights weights_rsck = inputs.at(1).weights();
-
- VLOG(2) << "weight shape: " << weights_rsck.shape_.nbDims;
- for (int i = 0; i < weights_rsck.shape_.nbDims; i++) {
- VLOG(2) << weights_rsck.shape_.d[i];
- }
-
+ VLOG(2) << "weight shape: " << weights_rsck.DebugString();
if (weights_rsck.shape_.nbDims != 4) {
return tensorflow::errors::Internal(
"Conv2D expects kernel of dimension 4, at: " + node_def.name());
}
-
if (ctx.isFP16()) {
weights_rsck = ConvertFP32ToFP16(ctx, inputs.at(1).weights());
}
@@ -1209,16 +1250,13 @@ tensorflow::Status ConvertConv2DHelper(
nvinfer1::DimsHW kernel_size;
kernel_size.h() = weights.shape_.d[2];
kernel_size.w() = weights.shape_.d[3];
- VLOG(2) << "RSCK: ";
- for (int i = 0; i < 4; i++) {
- VLOG(2) << " " << weights.shape_.d[i];
- }
+ VLOG(2) << "RSCK: " << weights.DebugString();
VLOG(2) << "kernel size: " << kernel_size.h() << ", " << kernel_size.w();
// TODO(jie): stride. (NHWC/NCHW)
const auto tf_stride = attrs.get<std::vector<int>>("strides");
VLOG(2) << "h_INDEX" << h_index << ", w_index " << w_index;
- VLOG(2) << "stride!!!: " << tf_stride[0] << tf_stride[1] << tf_stride[2]
+ VLOG(2) << "stride: " << tf_stride[0] << tf_stride[1] << tf_stride[2]
<< tf_stride[3];
const nvinfer1::DimsHW stride(tf_stride[h_index], tf_stride[w_index]);
@@ -1240,10 +1278,7 @@ tensorflow::Status ConvertConv2DHelper(
// TODO(jie): handle asymmetric padding
VLOG(2) << "Padding!!!: " << padding[0].first << padding[0].second
<< padding[1].first << padding[1].second;
-
- auto dim_before = tensor->getDimensions();
- VLOG(2) << "TENSOR before: " << dim_before.d[0] << ", " << dim_before.d[1]
- << dim_before.d[2] << ", " << dim_before.d[3];
+ VLOG(2) << "TENSOR before: " << DebugString(tensor->getDimensions());
auto pad_layer = ctx.network()->addPadding(
*const_cast<nvinfer1::ITensor*>(tensor),
nvinfer1::DimsHW(padding[0].first, padding[1].first),
@@ -1251,9 +1286,7 @@ tensorflow::Status ConvertConv2DHelper(
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();
- VLOG(2) << "TENSOR after: " << dim_after.d[0] << ", " << dim_after.d[1]
- << dim_after.d[2] << ", " << dim_after.d[3];
+ VLOG(2) << "TENSOR after: " << DebugString(tensor->getDimensions());
}
nvinfer1::IConvolutionLayer* layer =
@@ -1266,17 +1299,12 @@ tensorflow::Status ConvertConv2DHelper(
layer->setName(node_def.name().c_str());
layer->setNbGroups(num_groups);
nvinfer1::ITensor* output_tensor = layer->getOutput(0);
-
- auto dim_after = output_tensor->getDimensions();
- VLOG(2) << "TENSOR out: " << dim_after.d[0] << ", " << dim_after.d[1] << ", "
- << dim_after.d[2] << ", " << dim_after.d[3];
-
+ VLOG(2) << "TENSOR out: " << DebugString(output_tensor->getDimensions());
+ VLOG(2) << "data_format: " << data_format;
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 !!!!";
}
outputs->push_back(TRT_TensorOrWeights(output_tensor));
return tensorflow::Status::OK();
@@ -1990,22 +2018,22 @@ tensorflow::Status ConvertReduce(Converter& ctx,
return tensorflow::errors::Unimplemented("Tidx supports only DT_INT32");
}
- const auto keep_dims = attrs.get<bool>("keep_dims");
- auto index_list_data =
- static_cast<int*>(const_cast<void*>(index_list.GetValues()));
-
int axes = 0;
if (index_list.count() == 0) {
return tensorflow::errors::InvalidArgument(
"TRT cannot support reduce on all (batch) dimensions, at",
node_def.name());
} else {
+ auto index_list_data =
+ static_cast<int*>(const_cast<void*>(index_list.GetValues()));
for (int i = 0; i < index_list.count(); i++) {
- if (index_list_data[i] == 0) {
+ int axis = index_list_data[i];
+ if (axis < 0) axis += tensor->getDimensions().nbDims + 1;
+ if (axis == 0) {
return tensorflow::errors::InvalidArgument(
"TRT cannot reduce at batch dimension, at", node_def.name());
}
- axes |= (1 << (index_list_data[i] - 1));
+ axes |= (1 << (axis - 1));
}
}
@@ -2025,6 +2053,7 @@ tensorflow::Status ConvertReduce(Converter& ctx,
" , at ", node_def.name());
}
+ const auto keep_dims = attrs.get<bool>("keep_dims");
nvinfer1::ILayer* layer =
ctx.network()->addReduce(*const_cast<nvinfer1::ITensor*>(tensor),
reduce_operation, axes, keep_dims);
@@ -2694,8 +2723,6 @@ tensorflow::Status ConvertGraphDefToEngine(
VLOG(2) << "Converting op name=" << node_name << ", op=" << node_def.op();
if (tensorflow::str_util::StartsWith(node_name, kInputPHName) &&
(node_def.op() == "Placeholder")) {
- nvinfer1::DimsCHW input_dim_pseudo_chw;
- for (int i = 0; i < 8; i++) input_dim_pseudo_chw.d[i] = 0;
int32 slot_number = -1;
if (!tensorflow::strings::safe_strto32(
node_name.c_str() + strlen(kInputPHName), &slot_number)) {
@@ -2713,28 +2740,25 @@ tensorflow::Status ConvertGraphDefToEngine(
LOG(WARNING) << error_message;
return Status(status.code(), error_message);
}
- if (VLOG_IS_ON(1)) {
- string dim_str("dims=");
- StrAppend(&dim_str, "[ ", shape.dim_size(0));
- for (int i = 1; i < shape.dims(); i++) {
- StrAppend(&dim_str, ", ", shape.dim_size(i));
- }
- StrAppend(&dim_str, " ]");
- VLOG(1) << dim_str;
- }
+
+#if NV_TENSORRT_MAJOR == 3
+ nvinfer1::DimsCHW input_dim;
+#elif NV_TENSORRT_MAJOR > 3
+ nvinfer1::Dims input_dim;
+#endif
for (int i = 1; i < shape.dims(); i++) {
- input_dim_pseudo_chw.d[i - 1] = shape.dim_size(i);
+ input_dim.d[i - 1] = shape.dim_size(i);
}
-
- input_dim_pseudo_chw.nbDims = shape.dims() - 1;
- nvinfer1::ITensor* input_tensor = converter.network()->addInput(
- node_name.c_str(), dtype, input_dim_pseudo_chw);
+ input_dim.nbDims = shape.dims() - 1;
+ nvinfer1::ITensor* input_tensor =
+ converter.network()->addInput(node_name.c_str(), dtype, input_dim);
if (!input_tensor) {
return tensorflow::errors::InvalidArgument(
"Failed to create Input layer tensor ", node_name,
" rank=", shape.dims() - 1);
}
- VLOG(1) << "Input tensor name :" << node_name;
+ VLOG(2) << "Adding engine input tensor " << node_name << " with shape "
+ << DebugString(input_dim);
if (!converter.insert_input_tensor(node_name, input_tensor)) {
return tensorflow::errors::AlreadyExists(
"Output tensor already exists for op: " + node_name);
@@ -2937,10 +2961,25 @@ bool InputEdgeValidator::operator()(const tensorflow::Edge* in_edge) const {
<< ": " << status;
return false;
}
- if (shape.dims() < 3 && in_edge->src()->type_string() != "Const") {
+
+
+ if (in_edge->src()->type_string() != "Const" &&
+#if NV_TENSORRT_MAJOR == 3
+ // TRT 3.x only support 4 dimensional input tensor.
+ shape.dims() != 4) {
+#else
+ // Single dimensional input tensor is not supported since the first
+ // dimension is treated as batch dimension.
+ shape.dims() < 2) {
+#endif
VLOG(1) << "--> Need to remove input node " << in_edge->dst()->name()
- << " which has an input at port " << in_edge->dst_input()
- << " with #dim<3 and is not a const: " << shape;
+ << " which has an input at port " << in_edge->dst_input() << " with"
+#if NV_TENSORRT_MAJOR == 3
+ << " #dim!=4"
+#else
+ << " #dim<2"
+#endif
+ << " and is not a const: " << shape;
return false;
}
return true;
diff --git a/tensorflow/contrib/tensorrt/custom_plugin_examples/inc_op_kernel.cu.cc b/tensorflow/contrib/tensorrt/custom_plugin_examples/inc_op_kernel.cu.cc
index 2de7973750..11335d7da6 100644
--- a/tensorflow/contrib/tensorrt/custom_plugin_examples/inc_op_kernel.cu.cc
+++ b/tensorflow/contrib/tensorrt/custom_plugin_examples/inc_op_kernel.cu.cc
@@ -13,14 +13,15 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#if GOOGLE_CUDA
+#if GOOGLE_TENSORRT
+
#include "tensorflow/contrib/tensorrt/custom_plugin_examples/inc_op_kernel.h"
#include <vector>
+#define EIGEN_USE_GPU
#include "tensorflow/core/framework/op_kernel.h"
-
-#if GOOGLE_CUDA
-#if GOOGLE_TENSORRT
#include "cuda/include/cuda_runtime_api.h"
#include "tensorflow/core/platform/stream_executor.h"
@@ -80,5 +81,5 @@ REGISTER_KERNEL_BUILDER(Name("IncPluginTRT").Device(DEVICE_GPU), IncPluginTRT);
} // namespace tensorrt
} // namespace tensorflow
-#endif // GOOGLE_CUDA
#endif // GOOGLE_TENSORRT
+#endif // GOOGLE_CUDA
diff --git a/tensorflow/contrib/tensorrt/segment/segment.cc b/tensorflow/contrib/tensorrt/segment/segment.cc
index b43f1b190f..c82d4a0183 100644
--- a/tensorflow/contrib/tensorrt/segment/segment.cc
+++ b/tensorflow/contrib/tensorrt/segment/segment.cc
@@ -74,6 +74,7 @@ class SimpleNode {
const std::vector<SimpleEdge*>& in_edges() const { return in_edges_; }
const std::vector<SimpleEdge*>& out_edges() const { return out_edges_; }
+
std::vector<SimpleNode*> in_nodes() const {
std::vector<SimpleNode*> res;
res.reserve(in_edges_.size());
@@ -82,6 +83,16 @@ class SimpleNode {
}
return res;
}
+
+ std::vector<SimpleNode*> out_nodes() const {
+ std::vector<SimpleNode*> res;
+ res.reserve(out_edges_.size());
+ for (const auto e : out_edges_) {
+ if (e) res.push_back(e->dst());
+ }
+ return res;
+ }
+
const string& name() const { return node_->name(); }
const tensorflow::Node* tf_node() const { return node_; }
int id() const { return id_; }
@@ -215,45 +226,53 @@ SimpleGraph::~SimpleGraph() {
namespace {
-bool CheckCycles(const std::unique_ptr<SimpleGraph>& g, const SimpleNode* src,
- const std::vector<SimpleNode*>& start) {
- // Copied from TF ReverseDFS, which only works for tensorflow::Graph.
+// Copied from TF ReverseDFS, which only works for tensorflow::Graph.
+void StableDFS(const SimpleGraph& g, bool reverse,
+ const std::vector<const SimpleNode*>& start,
+ const std::function<bool(const SimpleNode*)>& enter,
+ const std::function<bool(const SimpleNode*)>& leave) {
+ // Stack of work to do.
struct Work {
- SimpleNode* node;
+ const SimpleNode* node;
bool leave; // Are we entering or leaving n?
};
-
std::vector<Work> stack(start.size());
for (int i = 0; i < start.size(); ++i) {
stack[i] = Work{start[i], false};
}
- std::vector<bool> visited(g->num_node_ids(), false);
+ auto get_nodes = reverse ? [](const SimpleNode* n) { return n->in_nodes(); }
+ : [](const SimpleNode* n) { return n->out_nodes(); };
+ std::vector<bool> visited(g.num_node_ids(), false);
while (!stack.empty()) {
Work w = stack.back();
stack.pop_back();
auto n = w.node;
if (w.leave) {
- if (n == src) {
- return true;
- }
+ if (leave && !leave(n)) return;
continue;
}
if (visited[n->id()]) continue;
visited[n->id()] = true;
- // Arrange to call leave(n) when all done with descendants.
- stack.push_back(Work{n, true});
+ if (enter && !enter(n)) return;
- auto nodes = n->in_nodes();
- for (const auto node : nodes) {
+ // Arrange to call leave(n) when all done with descendants.
+ if (leave) stack.push_back(Work{n, true});
+
+ auto nodes = get_nodes(n);
+ std::vector<const SimpleNode*> nodes_sorted(nodes.begin(), nodes.end());
+ std::sort(nodes_sorted.begin(), nodes_sorted.end(),
+ [](const SimpleNode* lhs, const SimpleNode* rhs) {
+ return lhs->name() < rhs->name();
+ });
+ for (const SimpleNode* node : nodes_sorted) {
if (!visited[node->id()]) {
stack.push_back(Work{node, false});
}
}
}
- return false;
}
bool CanContractEdge(const SimpleEdge* edge,
@@ -289,14 +308,21 @@ bool CanContractEdge(const SimpleEdge* edge,
// To achieve this goal, the correct way seems to be:
// 1. remove any direct edge from src->dst;
// 2. detect if src can reach dst, if so they cannot be merged.
- std::vector<SimpleNode*> dfs_start_nodes;
- for (SimpleNode* node : dst->in_nodes()) {
+ std::vector<const SimpleNode*> dfs_start_nodes;
+ for (const SimpleNode* node : dst->in_nodes()) {
if (node != src) {
dfs_start_nodes.push_back(node);
}
}
-
- const bool has_cycle = CheckCycles(graph, src, dfs_start_nodes);
+ bool has_cycle = false;
+ StableDFS(*graph, /*reverse=*/true, dfs_start_nodes, /*enter=*/nullptr,
+ [&has_cycle, src](const SimpleNode* n) {
+ if (n == src) {
+ has_cycle = true;
+ return false;
+ }
+ return true;
+ });
return !has_cycle;
}
} // namespace
@@ -403,15 +429,13 @@ tensorflow::Status SegmentGraph(
// In the future if we have a measure of how beneficial it is to include a
// given node in a TRT subgraph then we can revisit this algorithm to take
// advantage of that information.
- std::vector<tensorflow::Node*> tforder;
- tensorflow::GetPostOrder(*tf_graph, &tforder);
- // use postorder implementation from tensorflow and construct mirror in
- // internal format
- std::vector<SimpleNode*> order;
- order.reserve(tforder.size());
- for (const auto tfnode : tforder) {
- order.push_back(graph->FindNodeId(tfnode->id()));
- }
+ std::vector<const SimpleNode*> order;
+ order.reserve(graph->num_node_ids());
+ StableDFS(*graph, /*reverse=*/false, {graph->source_node()},
+ /*enter=*/nullptr, [&order](const SimpleNode* n) {
+ order.push_back(n);
+ return true;
+ });
for (const SimpleNode* node : order) {
// All output nodes of 'node' have been visited...
VLOG(3) << "Trying node " << node->name() << " id=" << node->id();
diff --git a/tensorflow/contrib/tensorrt/test/base_test.py b/tensorflow/contrib/tensorrt/test/base_test.py
index 8ea5a63735..e9ac833d55 100644
--- a/tensorflow/contrib/tensorrt/test/base_test.py
+++ b/tensorflow/contrib/tensorrt/test/base_test.py
@@ -40,6 +40,7 @@ class SimpleSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [100, 24, 24, 2]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -62,19 +63,21 @@ class SimpleSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
identity = array_ops.identity(relu, "identity")
pool = nn_ops.max_pool(
identity, [1, 2, 2, 1], [1, 2, 2, 1], "VALID", name="max_pool")
- array_ops.squeeze(pool, name=self.output_name)
+ array_ops.squeeze(pool, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- # TODO(aaroey): LayoutOptimizer adds additional nodes to the graph which
- # breaks the connection check, fix it.
- # - my_trt_op_0 should have ["weights", "conv", "bias", "bias_add",
- # "relu", "identity", "max_pool"]
- expected_engines=["my_trt_op_0"],
- expected_output_dims=(100, 6, 6, 6),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(100, 6, 6, 6)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ # TODO(aaroey): LayoutOptimizer adds additional nodes to the graph which
+ # breaks the connection check, fix it.
+ # - my_trt_op_0 should have ["weights", "conv", "bias", "bias_add",
+ # "relu", "identity", "max_pool"]
+ return ["my_trt_op_0"]
class SimpleMultiEnginesTest(trt_test.TfTrtIntegrationTestBase):
@@ -85,6 +88,7 @@ class SimpleMultiEnginesTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [100, 24, 24, 2]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -115,20 +119,22 @@ class SimpleMultiEnginesTest(trt_test.TfTrtIntegrationTestBase):
q = math_ops.mul(q, edge, name="mul1")
s = math_ops.add(p, q, name="add1")
s = math_ops.sub(s, r, name="sub1")
- array_ops.squeeze(s, name=self.output_name)
+ array_ops.squeeze(s, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- # TODO(aaroey): LayoutOptimizer adds additional nodes to the graph which
- # breaks the connection check, fix it.
- # - my_trt_op_0 should have ["mul", "sub", "div1", "mul1", "add1",
- # "add", "sub1"];
- # - my_trt_op_1 should have ["weights","conv", "div"]
- expected_engines=["my_trt_op_0", "my_trt_op_1"],
- expected_output_dims=(100, 12, 12, 6),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(100, 12, 12, 6)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ # TODO(aaroey): LayoutOptimizer adds additional nodes to the graph which
+ # breaks the connection check, fix it.
+ # - my_trt_op_0 should have ["mul", "sub", "div1", "mul1", "add1",
+ # "add", "sub1"];
+ # - my_trt_op_1 should have ["weights","conv", "div"]
+ return ["my_trt_op_0", "my_trt_op_1"]
class PartiallyConvertedTestA(trt_test.TfTrtIntegrationTestBase):
@@ -143,6 +149,7 @@ class PartiallyConvertedTestA(trt_test.TfTrtIntegrationTestBase):
"""Create a graph containing two segment."""
input_name = "input"
input_dims = [2, 32, 32, 3]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -161,18 +168,20 @@ class PartiallyConvertedTestA(trt_test.TfTrtIntegrationTestBase):
c = constant_op.constant(1.0, name="c3")
n = math_ops.add(n, c, name="add3")
n = math_ops.mul(n, n, name="mul3")
- array_ops.squeeze(n, name=self.output_name)
+ array_ops.squeeze(n, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines={
- # Only the first engine is built.
- "my_trt_op_0": ["c0", "c1", "add0", "add1", "mul0", "mul1"]
- },
- expected_output_dims=tuple(input_dims),
- allclose_atol=1.e-06,
- allclose_rtol=1.e-06)
+ output_names=[output_name],
+ expected_output_dims=[tuple(input_dims)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ # Only the first engine is built.
+ "my_trt_op_0": ["c0", "c1", "add0", "add1", "mul0", "mul1"]
+ }
class PartiallyConvertedTestB(PartiallyConvertedTestA):
@@ -184,13 +193,12 @@ class PartiallyConvertedTestB(PartiallyConvertedTestA):
trt_convert.clear_test_values("")
trt_convert.add_test_value("my_trt_op_0:CreateTRTNode", "fail")
- def GetParams(self):
- """Create a graph containing two segment."""
- return super(PartiallyConvertedTestB, self).GetParams()._replace(
- expected_engines={
- # Only the second engine is built.
- "my_trt_op_1": ["c2", "c3", "add2", "add3", "mul2", "mul3"]
- })
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ # Only the second engine is built.
+ "my_trt_op_1": ["c2", "c3", "add2", "add3", "mul2", "mul3"]
+ }
class ConstInputTest(trt_test.TfTrtIntegrationTestBase):
@@ -199,6 +207,7 @@ class ConstInputTest(trt_test.TfTrtIntegrationTestBase):
"""Create a graph containing multiple segment."""
input_name = "input"
input_dims = [2, 32, 32, 3]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -221,18 +230,20 @@ class ConstInputTest(trt_test.TfTrtIntegrationTestBase):
n = math_ops.add(n, c, name="add2")
n = math_ops.mul(n, n, name="mul1")
n = math_ops.add(n, n, name="add3")
- array_ops.squeeze(n, name=self.output_name)
+ array_ops.squeeze(n, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines={
- "my_trt_op_0": ["add", "add1", "mul"],
- "my_trt_op_1": ["add2", "add3", "mul1"]
- },
- expected_output_dims=tuple(input_dims),
- allclose_atol=1.e-06,
- allclose_rtol=1.e-06)
+ output_names=[output_name],
+ expected_output_dims=[tuple(input_dims)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ "my_trt_op_0": ["add", "add1", "mul"],
+ "my_trt_op_1": ["add2", "add3", "mul1"]
+ }
class ConstDataInputSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
@@ -241,6 +252,7 @@ class ConstDataInputSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
"""Create a graph containing single segment."""
input_name = "input"
input_dims = [2, 32, 32, 3]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -251,15 +263,17 @@ class ConstDataInputSingleEngineTest(trt_test.TfTrtIntegrationTestBase):
n = math_ops.add(n, c, name="add")
n = math_ops.mul(n, n, name="mul")
n = math_ops.add(n, n, name="add1")
- array_ops.squeeze(n, name=self.output_name)
+ array_ops.squeeze(n, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines={"my_trt_op_0": ["c", "add", "add1", "mul"]},
- expected_output_dims=tuple(input_dims),
- allclose_atol=1.e-06,
- allclose_rtol=1.e-06)
+ output_names=[output_name],
+ expected_output_dims=[tuple(input_dims)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {"my_trt_op_0": ["c", "add", "add1", "mul"]}
class ConstDataInputMultipleEnginesTest(trt_test.TfTrtIntegrationTestBase):
@@ -268,6 +282,7 @@ class ConstDataInputMultipleEnginesTest(trt_test.TfTrtIntegrationTestBase):
"""Create a graph containing multiple segment."""
input_name = "input"
input_dims = [2, 32, 32, 3]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -282,22 +297,24 @@ class ConstDataInputMultipleEnginesTest(trt_test.TfTrtIntegrationTestBase):
n = math_ops.add(n, c, name="add2")
n = math_ops.mul(n, n, name="mul1")
n = math_ops.add(n, n, name="add3")
- array_ops.squeeze(n, name=self.output_name)
+ array_ops.squeeze(n, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines={
- "my_trt_op_0": ["add2", "add3", "mul1"],
- # Why segment ["add", "add1", "mul"] was assigned segment id 1
- # instead of 0: the parent node of this segment is actually const
- # node 'c', but it's removed later since it's const output of the
- # segment which is not allowed.
- "my_trt_op_1": ["add", "add1", "mul"]
- },
- expected_output_dims=tuple(input_dims),
- allclose_atol=1.e-06,
- allclose_rtol=1.e-06)
+ output_names=[output_name],
+ expected_output_dims=[tuple(input_dims)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ "my_trt_op_0": ["add2", "add3", "mul1"],
+ # Why segment ["add", "add1", "mul"] was assigned segment id 1
+ # instead of 0: the parent node of this segment is actually const
+ # node 'c', but it's removed later since it's const output of the
+ # segment which is not allowed.
+ "my_trt_op_1": ["add", "add1", "mul"]
+ }
class ControlDependencyTest(trt_test.TfTrtIntegrationTestBase):
@@ -306,6 +323,7 @@ class ControlDependencyTest(trt_test.TfTrtIntegrationTestBase):
"""Create a graph containing multiple segment."""
input_name = "input"
input_dims = [2, 32, 32, 3]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -328,18 +346,20 @@ class ControlDependencyTest(trt_test.TfTrtIntegrationTestBase):
mul1 = math_ops.mul(add2, add2, name="mul1")
with g.control_dependencies([d1, d2, add, add1]):
add3 = math_ops.add(mul1, mul1, name="add3")
- array_ops.squeeze(add3, name=self.output_name)
+ array_ops.squeeze(add3, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines={
- "my_trt_op_0": ["c1", "add", "add1", "mul"],
- "my_trt_op_1": ["c2", "add2", "add3", "mul1"]
- },
- expected_output_dims=tuple(input_dims),
- allclose_atol=1.e-06,
- allclose_rtol=1.e-06)
+ output_names=[output_name],
+ expected_output_dims=[tuple(input_dims)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ "my_trt_op_0": ["c1", "add", "add1", "mul"],
+ "my_trt_op_1": ["c2", "add2", "add3", "mul1"]
+ }
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/batch_matmul_test.py b/tensorflow/contrib/tensorrt/test/batch_matmul_test.py
index 2e1107e303..2f153c6f2f 100644
--- a/tensorflow/contrib/tensorrt/test/batch_matmul_test.py
+++ b/tensorflow/contrib/tensorrt/test/batch_matmul_test.py
@@ -37,6 +37,7 @@ class BatchMatMulTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [12, 5, 8, 12]
+ output_name = "output"
w1_name = "matmul_w1"
w1_dims = [12, 5, 12, 7]
w2_name = "matmul_w2"
@@ -61,15 +62,46 @@ class BatchMatMulTest(trt_test.TfTrtIntegrationTestBase):
x3 = x3 + f
x3 = gen_array_ops.reshape(x3, [12, 5, 8, 7])
out = x1 + x2 + x3
- array_ops.squeeze(out, name=self.output_name)
+ array_ops.squeeze(out, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name, w1_name, w2_name],
input_dims=[input_dims, w1_dims, w2_dims],
- expected_engines=["my_trt_op_0"],
- expected_output_dims=(12, 5, 8, 7),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(12, 5, 8, 7)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ if (run_params.dynamic_engine and
+ not trt_test.IsQuantizationMode(run_params.precision_mode)):
+ return ["my_trt_op_0", "my_trt_op_1"]
+ return ["my_trt_op_1"]
+
+ def ExpectedEnginesToRun(self, run_params):
+ """Return the expected engines to run."""
+ return ["my_trt_op_1"]
+
+ def ShouldRunTest(self, run_params):
+ """Whether to run the test."""
+ # TODO(aaroey): Trt library will fail like:
+ #
+ # ../builder/cudnnBuilder2.cpp:685:
+ # virtual std::vector<nvinfer1::query::Ports<
+ # nvinfer1::query::TensorRequirements>>
+ # nvinfer1::builder::Node::getSupportedFormats(
+ # const nvinfer1::query::Ports<nvinfer1::query::AbstractTensor>&,
+ # const nvinfer1::cudnn::HardwareContext&,
+ # nvinfer1::builder::Format::Type,
+ # const nvinfer1::builder::FormatTypeHack&) const:
+ # Assertion `sf' failed.
+ #
+ # To reproduce, run:
+ # bazel test -c opt --copt=-mavx \
+ # --test_arg=BatchMatMulTest.testTfTrt_ToolConversion_INT8_DynamicEngine \
+ # tensorflow/contrib/tensorrt:batch_matmul_test
+ #
+ # Investigate and fix it.
+ return not trt_test.IsQuantizationMode(run_params.precision_mode)
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/biasadd_matmul_test.py b/tensorflow/contrib/tensorrt/test/biasadd_matmul_test.py
index 8be32f59b4..62f4e525f7 100644
--- a/tensorflow/contrib/tensorrt/test/biasadd_matmul_test.py
+++ b/tensorflow/contrib/tensorrt/test/biasadd_matmul_test.py
@@ -38,6 +38,7 @@ class BiasaddMatMulTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [48, 12]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
@@ -97,18 +98,59 @@ class BiasaddMatMulTest(trt_test.TfTrtIntegrationTestBase):
out = array_ops.concat(
[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11], axis=-1)
- out = array_ops.squeeze(out, name=self.output_name)
+ out = array_ops.squeeze(out, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=[
- "my_trt_op_0", "my_trt_op_1", "my_trt_op_2", "my_trt_op_3",
- "my_trt_op_4", "my_trt_op_5", "my_trt_op_6"
- ],
- expected_output_dims=(48, 89),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(48, 89)])
+
+ def GetConversionParams(self, run_params):
+ """Return a ConversionParams for test."""
+ return super(BiasaddMatMulTest,
+ self).GetConversionParams(run_params)._replace(
+ max_batch_size=48, maximum_cached_engines=2)
+
+ def _ValidEngines(self):
+ """Engines expected to build and run."""
+ return [
+ "my_trt_op_0", "my_trt_op_1", "my_trt_op_2", "my_trt_op_6",
+ "my_trt_op_7", "my_trt_op_8", "my_trt_op_9"
+ ]
+
+ def _InvalidEngines(self):
+ """Engines that will cause conversion error at building time."""
+ return ["my_trt_op_3", "my_trt_op_4", "my_trt_op_5"]
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ # In dynamic engine mode the engines are built in execution time, not in
+ # conversion time, so build errors occurs later. Here three of the engines
+ # will be failed to built but the corresponding engine op are still created.
+ # TODO(aaroey, jjsjann123): fix this.
+ if (run_params.dynamic_engine and
+ not trt_test.IsQuantizationMode(run_params.precision_mode)):
+ return self._ValidEngines() + self._InvalidEngines()
+ return self._ValidEngines()
+
+ def ExpectedEnginesToRun(self, run_params):
+ """Return the expected engines to run."""
+ return self._ValidEngines()
+
+ def ShouldRunTest(self, run_params):
+ """Whether to run the test."""
+ # TODO(aaroey): Trt 4.0 forbids conversion for tensors with rank <3 in int8
+ # mode, which is a bug. Re-enable this when trt library is fixed.
+ return not trt_test.IsQuantizationMode(run_params.precision_mode)
+
+ def ExpectedAbsoluteTolerance(self, run_params):
+ """The absolute tolerance to compare floating point results."""
+ return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-03
+
+ def ExpectedRelativeTolerance(self, run_params):
+ """The relative tolerance to compare floating point results."""
+ return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-03
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/binary_tensor_weight_broadcast_test.py b/tensorflow/contrib/tensorrt/test/binary_tensor_weight_broadcast_test.py
index 9316b14da0..f126ed4238 100644
--- a/tensorflow/contrib/tensorrt/test/binary_tensor_weight_broadcast_test.py
+++ b/tensorflow/contrib/tensorrt/test/binary_tensor_weight_broadcast_test.py
@@ -37,6 +37,7 @@ class BinaryTensorWeightBroadcastTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [10, 24, 24, 20]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
@@ -104,32 +105,34 @@ class BinaryTensorWeightBroadcastTest(trt_test.TfTrtIntegrationTestBase):
a = constant_op.constant(np.random.randn(24, 20), dtype=dtype)
f = x + a
x = math_ops.sigmoid(f)
- gen_array_ops.reshape(x, [5, -1], name=self.output_name)
+ gen_array_ops.reshape(x, [5, -1], name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=[
- "my_trt_op_0",
- "my_trt_op_1",
- "my_trt_op_2",
- "my_trt_op_3",
- "my_trt_op_4",
- "my_trt_op_5",
- "my_trt_op_6",
- "my_trt_op_7",
- "my_trt_op_8",
- "my_trt_op_9",
- "my_trt_op_10",
- "my_trt_op_11",
- "my_trt_op_12",
- "my_trt_op_13",
- "my_trt_op_14",
- "my_trt_op_15",
- ],
- expected_output_dims=(5, 23040),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(5, 23040)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return [
+ "my_trt_op_0",
+ "my_trt_op_1",
+ "my_trt_op_2",
+ "my_trt_op_3",
+ "my_trt_op_4",
+ "my_trt_op_5",
+ "my_trt_op_6",
+ "my_trt_op_7",
+ "my_trt_op_8",
+ "my_trt_op_9",
+ "my_trt_op_10",
+ "my_trt_op_11",
+ "my_trt_op_12",
+ "my_trt_op_13",
+ "my_trt_op_14",
+ "my_trt_op_15",
+ ]
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/concatenation_test.py b/tensorflow/contrib/tensorrt/test/concatenation_test.py
index 1874b9dd45..465cb02296 100644
--- a/tensorflow/contrib/tensorrt/test/concatenation_test.py
+++ b/tensorflow/contrib/tensorrt/test/concatenation_test.py
@@ -37,6 +37,7 @@ class ConcatenationTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [2, 3, 3, 1]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
@@ -68,15 +69,17 @@ class ConcatenationTest(trt_test.TfTrtIntegrationTestBase):
concat1 = array_ops.concat([r1, r2, r3, r4, r5, r6], axis=-1)
concat2 = array_ops.concat([r7, r8, r9, r10, r11, r12], axis=3)
x = array_ops.concat([concat1, concat2], axis=-1)
- gen_array_ops.reshape(x, [2, -1], name=self.output_name)
+ gen_array_ops.reshape(x, [2, -1], name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=["my_trt_op_0"],
- expected_output_dims=(2, 126),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(2, 126)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return ["my_trt_op_0"]
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/const_broadcast_test.py b/tensorflow/contrib/tensorrt/test/const_broadcast_test.py
index 8c59000b70..e32f047866 100644
--- a/tensorflow/contrib/tensorrt/test/const_broadcast_test.py
+++ b/tensorflow/contrib/tensorrt/test/const_broadcast_test.py
@@ -36,6 +36,7 @@ class ConstBroadcastTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = 'input'
input_dims = [5, 12, 12, 2]
+ output_name = 'output'
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
@@ -53,15 +54,25 @@ class ConstBroadcastTest(trt_test.TfTrtIntegrationTestBase):
dtype=dtype,
name='filt3')
y3 = nn.conv2d(z2, filt3, strides=[1, 1, 1, 1], padding='SAME', name='y3')
- nn.relu(y3, name='output')
+ nn.relu(y3, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=['my_trt_op_0'],
- expected_output_dims=(5, 12, 12, 1),
- allclose_atol=1.e-02,
- allclose_rtol=1.e-02)
+ output_names=[output_name],
+ expected_output_dims=[(5, 12, 12, 1)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return ['my_trt_op_0']
+
+ def ExpectedAbsoluteTolerance(self, run_params):
+ """The absolute tolerance to compare floating point results."""
+ return 1.e-04 if run_params.precision_mode == 'FP32' else 1.e-02
+
+ def ExpectedRelativeTolerance(self, run_params):
+ """The relative tolerance to compare floating point results."""
+ return 1.e-04 if run_params.precision_mode == 'FP32' else 1.e-02
if __name__ == '__main__':
diff --git a/tensorflow/contrib/tensorrt/test/manual_test.py b/tensorflow/contrib/tensorrt/test/manual_test.py
new file mode 100644
index 0000000000..1187c759b4
--- /dev/null
+++ b/tensorflow/contrib/tensorrt/test/manual_test.py
@@ -0,0 +1,114 @@
+# 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.
+# ==============================================================================
+"""Basic tests for TF-TensorRT integration."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import ast
+import os
+
+from tensorflow.contrib.tensorrt.test import tf_trt_integration_test_base as trt_test
+from tensorflow.core.framework import graph_pb2
+from tensorflow.python.platform import gfile
+from tensorflow.python.platform import test
+
+
+class ManualTest(trt_test.TfTrtIntegrationTestBase):
+
+ def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
+ super(ManualTest, self).__init__(methodName)
+ self._params_map = None
+
+ def _GetEnv(self):
+ """Get an environment variable specifying the manual test parameters.
+
+ The value of the environment variable is the string representation of a dict
+ which should contain the following keys:
+ - 'graph_path': the file path to the serialized frozen graphdef
+ - 'input_names': TfTrtIntegrationTestParams.input_names
+ - 'input_dims': TfTrtIntegrationTestParams.input_dims
+ - 'expected_output_dims': TfTrtIntegrationTestParams.expected_output_dims
+ - 'output_name': the name of op to fetch
+ - 'expected_engines_to_run': ExpectedEnginesToRun() will return this
+ - 'expected_engines_to_build': ExpectedEnginesToBuild() will return this
+ - 'max_batch_size': ConversionParams.max_batch_size
+
+ Returns:
+ The value of the environment variable.
+ """
+ return os.getenv('TRT_MANUAL_TEST_PARAMS', '')
+
+ def _GetParamsMap(self):
+ """Parse the environment variable as a dict and return it."""
+ if self._params_map is None:
+ self._params_map = ast.literal_eval(self._GetEnv())
+ return self._params_map
+
+ def GetParams(self):
+ """Testing conversion of manually provided frozen graph."""
+ params_map = self._GetParamsMap()
+ gdef = graph_pb2.GraphDef()
+ with gfile.Open(params_map['graph_path'], 'rb') as f:
+ gdef.ParseFromString(f.read())
+ return trt_test.TfTrtIntegrationTestParams(
+ gdef=gdef,
+ input_names=params_map['input_names'],
+ input_dims=params_map['input_dims'],
+ output_names=params_map['output_names'],
+ expected_output_dims=params_map['expected_output_dims'])
+
+ def GetConversionParams(self, run_params):
+ """Return a ConversionParams for test."""
+ conversion_params = super(ManualTest, self).GetConversionParams(run_params)
+ params_map = self._GetParamsMap()
+ if 'max_batch_size' in params_map:
+ conversion_params = conversion_params._replace(
+ max_batch_size=params_map['max_batch_size'])
+ return conversion_params
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return self._GetParamsMap()['expected_engines_to_build']
+
+ def ExpectedEnginesToRun(self, run_params):
+ """Return the expected engines to run."""
+ params_map = self._GetParamsMap()
+ if 'expected_engines_to_run' in params_map:
+ return params_map['expected_engines_to_run']
+ return self.ExpectedEnginesToBuild(run_params)
+
+ def ExpectedAbsoluteTolerance(self, run_params):
+ """The absolute tolerance to compare floating point results."""
+ params_map = self._GetParamsMap()
+ if 'atol' in params_map:
+ return params_map['atol']
+ return 1.e-3
+
+ def ExpectedRelativeTolerance(self, run_params):
+ """The relative tolerance to compare floating point results."""
+ params_map = self._GetParamsMap()
+ if 'rtol' in params_map:
+ return params_map['rtol']
+ return 1.e-3
+
+ def ShouldRunTest(self, run_params):
+ """Whether to run the test."""
+ return len(self._GetEnv())
+
+
+if __name__ == '__main__':
+ test.main()
diff --git a/tensorflow/contrib/tensorrt/test/memory_alignment_test.py b/tensorflow/contrib/tensorrt/test/memory_alignment_test.py
index 66eb6be757..bc7c90081f 100644
--- a/tensorflow/contrib/tensorrt/test/memory_alignment_test.py
+++ b/tensorflow/contrib/tensorrt/test/memory_alignment_test.py
@@ -36,6 +36,7 @@ class MemoryAlignmentTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [2, 15, 15, 3]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
inp = array_ops.placeholder(
@@ -57,15 +58,25 @@ class MemoryAlignmentTest(trt_test.TfTrtIntegrationTestBase):
strides=[1, 1, 1, 1],
padding="VALID",
name="conv_2")
- array_ops.squeeze(out, name=self.output_name)
+ array_ops.squeeze(out, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=["my_trt_op_0"],
- expected_output_dims=(2, 15, 15, 10),
- allclose_atol=1.e-02,
- allclose_rtol=1.e-02)
+ output_names=[output_name],
+ expected_output_dims=[(2, 15, 15, 10)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return ["my_trt_op_0"]
+
+ def ExpectedAbsoluteTolerance(self, run_params):
+ """The absolute tolerance to compare floating point results."""
+ return 1.e-06 if run_params.precision_mode == "FP32" else 1.e-02
+
+ def ExpectedRelativeTolerance(self, run_params):
+ """The relative tolerance to compare floating point results."""
+ return 0.1
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/multi_connection_neighbor_engine_test.py b/tensorflow/contrib/tensorrt/test/multi_connection_neighbor_engine_test.py
index fd55b8cd99..11be4feaf7 100644
--- a/tensorflow/contrib/tensorrt/test/multi_connection_neighbor_engine_test.py
+++ b/tensorflow/contrib/tensorrt/test/multi_connection_neighbor_engine_test.py
@@ -38,6 +38,7 @@ class MultiConnectionNeighborEngineTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [2, 3, 7, 5]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
@@ -72,15 +73,17 @@ class MultiConnectionNeighborEngineTest(trt_test.TfTrtIntegrationTestBase):
t = t + q
t = t + d
t = t - edge3
- array_ops.squeeze(t, name=self.output_name)
+ array_ops.squeeze(t, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=["my_trt_op_0", "my_trt_op_1"],
- expected_output_dims=(2, 4, 5, 4),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(2, 4, 5, 4)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return ["my_trt_op_0", "my_trt_op_1"]
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/neighboring_engine_test.py b/tensorflow/contrib/tensorrt/test/neighboring_engine_test.py
index 51c905a50b..eddeafa38b 100644
--- a/tensorflow/contrib/tensorrt/test/neighboring_engine_test.py
+++ b/tensorflow/contrib/tensorrt/test/neighboring_engine_test.py
@@ -37,6 +37,7 @@ class NeighboringEngineTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [2, 3, 7, 5]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
@@ -54,18 +55,20 @@ class NeighboringEngineTest(trt_test.TfTrtIntegrationTestBase):
t = math_ops.mul(conv, b, name="mul")
e = self.trt_incompatible_op(conv, name="incompatible")
t = math_ops.sub(t, e, name="sub")
- array_ops.squeeze(t, name=self.output_name)
+ array_ops.squeeze(t, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines={
- "my_trt_op_0": ["bias", "mul", "sub"],
- "my_trt_op_1": ["weights", "conv"]
- },
- expected_output_dims=(2, 4, 5, 4),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(2, 4, 5, 4)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ "my_trt_op_0": ["bias", "mul", "sub"],
+ "my_trt_op_1": ["weights", "conv"]
+ }
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/rank_two_test.py b/tensorflow/contrib/tensorrt/test/rank_two_test.py
new file mode 100644
index 0000000000..74a4a05925
--- /dev/null
+++ b/tensorflow/contrib/tensorrt/test/rank_two_test.py
@@ -0,0 +1,89 @@
+# 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.
+# ==============================================================================
+"""Model script to test TF-TensorRT integration."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.contrib.tensorrt.test import tf_trt_integration_test_base as trt_test
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import ops
+from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import gen_math_ops
+from tensorflow.python.ops import math_ops
+from tensorflow.python.platform import test
+
+
+class RankTwoTest(trt_test.TfTrtIntegrationTestBase):
+
+ def GetParams(self):
+ """Test for rank 2 input in TF-TRT."""
+ input_names = ["input", "input2"]
+ # Two paths: first with rank 2 input, second with rank 4 input.
+ input_dims = [[12, 5], [12, 5, 2, 2]]
+ output_name = "output"
+ g = ops.Graph()
+ with g.as_default():
+ outputs = []
+ for i in range(2):
+ x = array_ops.placeholder(
+ dtype=dtypes.float32, shape=input_dims[i], name=input_names[i])
+ c = constant_op.constant(1.0, name="c%d_1" % i)
+ q = math_ops.add(x, c, name="add%d_1" % i)
+ q = math_ops.abs(q, name="abs%d_1" % i)
+ c = constant_op.constant(2.2, name="c%d_2" % i)
+ q = math_ops.add(q, c, name="add%d_2" % i)
+ q = math_ops.abs(q, name="abs%d_2" % i)
+ c = constant_op.constant(3.0, name="c%d_3" % i)
+ q = math_ops.add(q, c, name="add%d_3" % i)
+ if i == 0:
+ for j in range(2):
+ q = array_ops.expand_dims(q, -1, name="expand%d_%d" % (i, j))
+ q = gen_math_ops.reciprocal(q, name="reciprocal%d" % i)
+ outputs.append(q)
+ # Combine both paths
+ q = math_ops.add(outputs[0], outputs[1], name="add")
+ array_ops.squeeze(q, name=output_name)
+ return trt_test.TfTrtIntegrationTestParams(
+ gdef=g.as_graph_def(),
+ input_names=input_names,
+ input_dims=input_dims,
+ output_names=[output_name],
+ expected_output_dims=[tuple(input_dims[1])])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return {
+ "my_trt_op_0": [
+ "add0_1", "add0_2", "add0_3", "c0_1", "c0_2", "c0_3", "abs0_1",
+ "abs0_2"
+ ],
+ "my_trt_op_1": [
+ "add", "add1_1", "add1_2", "add1_3", "c1_1", "c1_2", "c1_3",
+ "abs1_1", "abs1_2", "reciprocal0", "reciprocal1"
+ ],
+ }
+
+ def ShouldRunTest(self, run_params):
+ """Whether to run the test."""
+ # TODO(aaroey): Trt 4.0 forbids conversion for tensors with rank <3 in int8
+ # mode, which is a bug. Re-enable this when trt library is fixed.
+ return not trt_test.IsQuantizationMode(run_params.precision_mode)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/contrib/tensorrt/test/tf_trt_integration_test_base.py b/tensorflow/contrib/tensorrt/test/tf_trt_integration_test_base.py
index 6f85ada464..65ca21cf37 100644
--- a/tensorflow/contrib/tensorrt/test/tf_trt_integration_test_base.py
+++ b/tensorflow/contrib/tensorrt/test/tf_trt_integration_test_base.py
@@ -31,6 +31,7 @@ from tensorflow.contrib.tensorrt.python.ops import trt_engine_op
# pylint: enable=unused-import
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
+from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_io
from tensorflow.python.framework import importer
from tensorflow.python.framework import ops
@@ -39,18 +40,23 @@ from tensorflow.python.ops import math_ops
from tensorflow.python.platform import tf_logging as logging
TfTrtIntegrationTestParams = namedtuple("TfTrtIntegrationTestParams", [
- "gdef", "input_names", "input_dims", "expected_engines",
- "expected_output_dims", "allclose_atol", "allclose_rtol"
+ "gdef", "input_names", "input_dims", "output_names", "expected_output_dims"
])
RunParams = namedtuple(
"RunParams",
["use_optimizer", "precision_mode", "dynamic_engine", "test_name"])
+ConversionParams = namedtuple("ConversionParams", [
+ "max_batch_size", "max_workspace_size_bytes", "precision_mode",
+ "minimum_segment_size", "is_dynamic_op", "maximum_cached_engines",
+ "cached_engine_batches"
+])
+
PRECISION_MODES = ["FP32", "FP16", "INT8"]
-def _IsQuantizationMode(mode):
+def IsQuantizationMode(mode):
return mode == "INT8"
@@ -64,10 +70,6 @@ class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase):
"""Class to test Tensorflow-TensorRT integration."""
@property
- def output_name(self):
- return "output"
-
- @property
def trt_incompatible_op(self):
return math_ops.sin
@@ -112,6 +114,10 @@ class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase):
super(TfTrtIntegrationTestBase, cls).setUpClass()
trt_convert.enable_test_value()
+ def __init__(self, methodName="runTest"): # pylint: disable=invalid-name
+ super(TfTrtIntegrationTestBase, self).__init__(methodName)
+ self._trt_test_params = None
+
def setUp(self):
"""Setup method."""
super(TfTrtIntegrationTestBase, self).setUp()
@@ -122,43 +128,97 @@ class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase):
"""Return a TfTrtIntegrationTestParams for test, implemented by subclass."""
raise NotImplementedError()
- def _PrepareRun(self, params, graph_state):
+ def GetConversionParams(self, run_params):
+ """Return a ConversionParams for test."""
+ return ConversionParams(
+ max_batch_size=max([
+ dims[0] for dims in self._GetParamsCached().input_dims if len(dims)
+ ]),
+ max_workspace_size_bytes=1 << 25,
+ precision_mode=self._ToBytes(run_params.precision_mode),
+ minimum_segment_size=2,
+ is_dynamic_op=run_params.dynamic_engine,
+ maximum_cached_engines=1,
+ cached_engine_batches=None)
+
+ def ShouldRunTest(self, run_params):
+ """Whether to run the test."""
+ return True
+
+ def VerifyRunForEngine(self, engine_name, graph_state, expect_run=True):
+ """Verify the state of a particular engine after sess.run()."""
+ if graph_state == GraphState.ORIGINAL:
+ self._ExpectCalibration(engine_name, "")
+ self._ExpectNativeSegment(engine_name, "")
+ self._ExpectTrtEngine(engine_name, "")
+ elif graph_state == GraphState.CALIBRATE:
+ self._ExpectCalibration(engine_name, "done")
+ self._ExpectNativeSegment(engine_name, "done")
+ self._ExpectTrtEngine(engine_name, "")
+ elif graph_state == GraphState.INFERENCE:
+ self._ExpectCalibration(engine_name, "")
+ if expect_run:
+ self._ExpectNativeSegment(engine_name, "")
+ self._ExpectTrtEngine(engine_name, "done")
+ else:
+ self._ExpectNativeSegment(engine_name, "done")
+ self._ExpectTrtEngine(engine_name, "")
+
+ def VerifyRun(self, run_params, graph_state):
+ """Verify the state of all engines after sess.run()."""
+ for engine_name in self.ExpectedEnginesToBuild(run_params):
+ expect_run = (engine_name in self.ExpectedEnginesToRun(run_params))
+ self.VerifyRunForEngine(engine_name, graph_state, expect_run)
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build, implemented by subclass."""
+ raise NotImplementedError()
+
+ def ExpectedEnginesToRun(self, run_params):
+ """Return the expected engines to run."""
+ return self.ExpectedEnginesToBuild(run_params)
+
+ def ExpectedAbsoluteTolerance(self, run_params):
+ """The absolute tolerance to compare floating point results."""
+ return 1.e-06 if run_params.precision_mode == "FP32" else 1.e-03
+
+ def ExpectedRelativeTolerance(self, run_params):
+ """The relative tolerance to compare floating point results."""
+ return 1.e-06 if run_params.precision_mode == "FP32" else 1.e-03
+
+ def _GetParamsCached(self):
+ if self._trt_test_params is None:
+ self._trt_test_params = self.GetParams()
+ return self._trt_test_params
+
+ def _PrepareRun(self, graph_state):
"""Set up necessary testing environment before calling sess.run()."""
# Clear test values added by TRTEngineOp.
trt_convert.clear_test_values("my_trt_op_.*:ExecuteTrtEngine")
trt_convert.clear_test_values("my_trt_op_.*:ExecuteCalibration")
trt_convert.clear_test_values("my_trt_op_.*:ExecuteNativeSegment")
- def _VerifyRun(self, params, graph_state):
- """Verify the state after sess.run()."""
- for engine_name in params.expected_engines:
- if graph_state == GraphState.ORIGINAL:
- self._ExpectCalibration(engine_name, "")
- self._ExpectNativeSegment(engine_name, "")
- self._ExpectTrtEngine(engine_name, "")
- elif graph_state == GraphState.CALIBRATE:
- self._ExpectCalibration(engine_name, "done")
- self._ExpectNativeSegment(engine_name, "done")
- self._ExpectTrtEngine(engine_name, "")
- elif graph_state == GraphState.INFERENCE:
- self._ExpectCalibration(engine_name, "")
- self._ExpectNativeSegment(engine_name, "")
- self._ExpectTrtEngine(engine_name, "done")
-
- def _GetConfigProto(self, params, run_params, graph_state):
+ def _GetConfigProto(self, run_params, graph_state):
"""Get config proto based on specific settings."""
if graph_state != GraphState.ORIGINAL and run_params.use_optimizer:
rewriter_cfg = rewriter_config_pb2.RewriterConfig()
rewriter_cfg.optimizers.extend(["constfold", "layout"])
custom_op = rewriter_cfg.custom_optimizers.add()
custom_op.name = "TensorRTOptimizer"
- custom_op.parameter_map["minimum_segment_size"].i = 2
- custom_op.parameter_map["max_batch_size"].i = max(
- [dims[0] for dims in params.input_dims])
- custom_op.parameter_map["is_dynamic_op"].b = run_params.dynamic_engine
- custom_op.parameter_map["max_workspace_size_bytes"].i = 1 << 25
- custom_op.parameter_map["precision_mode"].s = self._ToBytes(
- run_params.precision_mode)
+ trt_params = self.GetConversionParams(run_params)
+ custom_op.parameter_map["max_batch_size"].i = trt_params.max_batch_size
+ custom_op.parameter_map["max_workspace_size_bytes"].i = (
+ trt_params.max_workspace_size_bytes)
+ custom_op.parameter_map["precision_mode"].s = trt_params.precision_mode
+ custom_op.parameter_map["minimum_segment_size"].i = (
+ trt_params.minimum_segment_size)
+ custom_op.parameter_map["is_dynamic_op"].b = trt_params.is_dynamic_op
+ custom_op.parameter_map["maximum_cached_engines"].i = (
+ trt_params.maximum_cached_engines)
+ if trt_params.cached_engine_batches:
+ custom_op.parameter_map["cached_engine_batches"].list.i.extend(
+ trt_params.cached_engine_batches)
+
graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_cfg)
else:
graph_options = config_pb2.GraphOptions()
@@ -190,53 +250,67 @@ class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase):
def _ExpectNativeSegment(self, engine_name, value):
self._ExpectTestValue(engine_name, "ExecuteNativeSegment", value)
- def _RunGraph(self, params, gdef, input_data, config, graph_state,
+ def _RunGraph(self,
+ run_params,
+ gdef,
+ input_data,
+ config,
+ graph_state,
num_runs=2):
"""Run given graphdef multiple times."""
+ params = self._GetParamsCached()
assert len(params.input_names) == len(input_data)
g = ops.Graph()
with g.as_default():
io_ops = importer.import_graph_def(
graph_def=gdef,
- return_elements=params.input_names + [self.output_name],
+ return_elements=params.input_names + params.output_names,
name="")
- inp = [i.outputs[0] for i in io_ops[:-1]]
- assert len(inp) == len(input_data)
- out = io_ops[-1].outputs[0]
+ inputs = [op.outputs[0] for op in io_ops[:len(params.input_names)]]
+ assert len(inputs) == len(input_data)
+ outputs = [op.outputs[0] for op in io_ops[len(params.input_names):]]
with self.test_session(
graph=g, config=config, use_gpu=True, force_gpu=True) as sess:
val = None
# Defaults to 2 runs to verify result across multiple runs is same.
for _ in range(num_runs):
- self._PrepareRun(params, graph_state)
- new_val = sess.run(out,
- {inp[i]: input_data[i] for i in range(len(inp))})
- self.assertEqual(params.expected_output_dims, new_val.shape)
+ self._PrepareRun(graph_state)
+ new_val = sess.run(
+ outputs, {inputs[i]: input_data[i] for i in range(len(inputs))})
+ output_len = len(params.expected_output_dims)
+ self.assertEqual(output_len, len(new_val))
+ for i in range(output_len):
+ self.assertEqual(params.expected_output_dims[i], new_val[i].shape)
if val is not None:
- self.assertAllEqual(val, new_val)
+ self.assertAllClose(val, new_val, atol=1.e-06, rtol=1.e-06)
val = new_val
- self._VerifyRun(params, graph_state)
+ self.VerifyRun(run_params, graph_state)
return val
# Use real data that is representative of the inference dataset
# for calibration. For this test script it is random data.
- def _RunCalibration(self, params, gdef, input_data, config):
+ def _RunCalibration(self, run_params, gdef, input_data, config):
"""Run calibration on given graph."""
return self._RunGraph(
- params, gdef, input_data, config, GraphState.CALIBRATE, num_runs=5)
+ run_params, gdef, input_data, config, GraphState.CALIBRATE, num_runs=5)
- def _GetTrtGraphDef(self, params, run_params, gdef):
+ def _GetTrtGraphDef(self, run_params, gdef):
"""Return trt converted graphdef."""
+ params = self._GetParamsCached()
+ trt_params = self.GetConversionParams(run_params)
+ logging.info(trt_params)
return trt_convert.create_inference_graph(
input_graph_def=gdef,
- outputs=[self.output_name],
- max_batch_size=max([dims[0] for dims in params.input_dims]),
- max_workspace_size_bytes=1 << 25,
- precision_mode=run_params.precision_mode,
- minimum_segment_size=2,
- is_dynamic_op=run_params.dynamic_engine)
-
- def _WriteGraph(self, params, run_params, gdef, graph_state):
+ outputs=params.input_names + params.output_names,
+ max_batch_size=trt_params.max_batch_size,
+ max_workspace_size_bytes=trt_params.max_workspace_size_bytes,
+ precision_mode=trt_params.precision_mode,
+ minimum_segment_size=trt_params.minimum_segment_size,
+ is_dynamic_op=trt_params.is_dynamic_op,
+ maximum_cached_engines=trt_params.maximum_cached_engines,
+ cached_engine_batches=trt_params.cached_engine_batches)
+
+ def _WriteGraph(self, run_params, gdef, graph_state):
if graph_state == GraphState.ORIGINAL:
label = "Original"
elif graph_state == GraphState.CALIBRATE:
@@ -247,15 +321,17 @@ class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase):
self.__class__.__name__ + "_" + run_params.test_name + "_" + label +
".pbtxt")
temp_dir = os.getenv("TRT_TEST_TMPDIR", self.get_temp_dir())
- logging.info("Writing graph to %s/%s", temp_dir, graph_name)
- graph_io.write_graph(gdef, temp_dir, graph_name)
+ if temp_dir:
+ logging.info("Writing graph to %s/%s", temp_dir, graph_name)
+ graph_io.write_graph(gdef, temp_dir, graph_name)
- def _VerifyConnections(self, params, converted_gdef):
+ def _VerifyConnections(self, expected_engines, converted_gdef):
+ params = self._GetParamsCached()
old_to_new_node_map = {
self._ToString(node.name): self._ToString(node.name)
for node in params.gdef.node
}
- for engine_name, node_names in params.expected_engines.items():
+ for engine_name, node_names in expected_engines.items():
for node_name in node_names:
old_to_new_node_map[node_name] = engine_name
name_to_node_map = {
@@ -310,97 +386,114 @@ class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase):
msg="expected:\n%s\nvs actual:\n%s" % (sorted(
expected_input_map.items()), sorted(actual_input_map.items())))
- def _VerifyGraphDef(self, params, run_params, gdef, graph_state):
- self._WriteGraph(params, run_params, gdef, graph_state)
+ def _VerifyGraphDef(self, run_params, gdef, graph_state):
+ self._WriteGraph(run_params, gdef, graph_state)
+ expected_engines = self.ExpectedEnginesToBuild(run_params)
num_engines = 0
for node in gdef.node:
if node.op == "TRTEngineOp":
+ logging.info("Found TRTEngineOp: " + node.name)
+ for node in gdef.node:
+ if node.op == "TRTEngineOp":
num_engines += 1
- self.assertTrue(node.name in params.expected_engines)
- self.assertTrue(len(node.attr["serialized_segment"].s))
- self.assertTrue(len(node.attr["segment_funcdef_name"].s))
+ self.assertTrue(node.name in expected_engines, node.name)
+ self.assertTrue(len(node.attr["serialized_segment"].s), node.name)
+ self.assertTrue(len(node.attr["segment_funcdef_name"].s), node.name)
self.assertEqual(
self._ToBytes(run_params.precision_mode),
- node.attr["precision_mode"].s)
+ node.attr["precision_mode"].s, node.name)
is_dynamic_engine = not node.attr["static_engine"].b
- self.assertEqual(run_params.dynamic_engine, is_dynamic_engine)
+ self.assertEqual(run_params.dynamic_engine, is_dynamic_engine,
+ node.name)
has_calibration_data = len(node.attr["calibration_data"].s)
- if (_IsQuantizationMode(run_params.precision_mode) and
+ if (IsQuantizationMode(run_params.precision_mode) and
graph_state == GraphState.INFERENCE):
- self.assertTrue(has_calibration_data)
+ self.assertTrue(has_calibration_data, node.name)
else:
- self.assertFalse(has_calibration_data)
+ self.assertFalse(has_calibration_data, node.name)
if graph_state == GraphState.ORIGINAL:
self.assertEqual(0, num_engines)
else:
- self.assertEqual(num_engines, len(params.expected_engines))
- if isinstance(params.expected_engines, dict):
- self._VerifyConnections(params, gdef)
+ self.assertEqual(num_engines, len(expected_engines))
+ if isinstance(expected_engines, dict):
+ self._VerifyConnections(expected_engines, gdef)
# TODO(aaroey): consider verifying the corresponding TF function.
- def RunTest(self, params, run_params):
+ def RunTest(self, run_params):
+ if not self.ShouldRunTest(run_params):
+ return
assert run_params.precision_mode in PRECISION_MODES
- input_data = [np.random.random_sample(dims) for dims in params.input_dims]
+
+ params = self._GetParamsCached()
input_gdef = params.gdef
- self._VerifyGraphDef(params, run_params, input_gdef, GraphState.ORIGINAL)
+ input_dtypes = {}
+ for node in input_gdef.node:
+ if self._ToString(node.name) in params.input_names:
+ assert self._ToString(node.op) == "Placeholder"
+ input_dtypes[self._ToString(node.name)] = (
+ dtypes.as_dtype(node.attr["dtype"].type).as_numpy_dtype())
+ assert len(params.input_names) == len(input_dtypes)
+
+ input_data = []
+ for i in range(len(params.input_names)):
+ dtype = input_dtypes[params.input_names[i]]
+ # Multiply the input by some constant to avoid all zeros input for integer
+ # types.
+ scale = 10.0 if np.issubdtype(dtype, np.integer) else 1.0
+ dims = params.input_dims[i]
+ input_data.append((scale * np.random.random_sample(dims)).astype(dtype))
+ self._VerifyGraphDef(run_params, input_gdef, GraphState.ORIGINAL)
# Get reference result without running trt.
- config_no_trt = self._GetConfigProto(params, run_params,
- GraphState.ORIGINAL)
+ config_no_trt = self._GetConfigProto(run_params, GraphState.ORIGINAL)
logging.info("Running original graph w/o trt, config:\n%s",
str(config_no_trt))
- ref_result = self._RunGraph(params, input_gdef, input_data, config_no_trt,
- GraphState.ORIGINAL)
+ ref_result = self._RunGraph(run_params, input_gdef, input_data,
+ config_no_trt, GraphState.ORIGINAL)
# Run calibration if necessary.
- if _IsQuantizationMode(run_params.precision_mode):
+ if IsQuantizationMode(run_params.precision_mode):
- calib_config = self._GetConfigProto(params, run_params,
- GraphState.CALIBRATE)
+ calib_config = self._GetConfigProto(run_params, GraphState.CALIBRATE)
logging.info("Running calibration graph, config:\n%s", str(calib_config))
if run_params.use_optimizer:
- result = self._RunCalibration(params, input_gdef, input_data,
+ result = self._RunCalibration(run_params, input_gdef, input_data,
calib_config)
else:
- calib_gdef = self._GetTrtGraphDef(params, run_params, input_gdef)
- self._VerifyGraphDef(params, run_params, calib_gdef,
- GraphState.CALIBRATE)
- result = self._RunCalibration(params, calib_gdef, input_data,
+ calib_gdef = self._GetTrtGraphDef(run_params, input_gdef)
+ self._VerifyGraphDef(run_params, calib_gdef, GraphState.CALIBRATE)
+ result = self._RunCalibration(run_params, calib_gdef, input_data,
calib_config)
- infer_gdef = trt_convert.calib_graph_to_infer_graph(calib_gdef)
- self._VerifyGraphDef(params, run_params, infer_gdef, GraphState.INFERENCE)
+ infer_gdef = trt_convert.calib_graph_to_infer_graph(
+ calib_gdef, run_params.dynamic_engine)
+ self._VerifyGraphDef(run_params, infer_gdef, GraphState.INFERENCE)
self.assertAllClose(
ref_result,
result,
- atol=params.allclose_atol,
- rtol=params.allclose_rtol)
+ atol=self.ExpectedAbsoluteTolerance(run_params),
+ rtol=self.ExpectedRelativeTolerance(run_params))
else:
infer_gdef = input_gdef
# Run inference.
- infer_config = self._GetConfigProto(params, run_params,
- GraphState.INFERENCE)
+ infer_config = self._GetConfigProto(run_params, GraphState.INFERENCE)
logging.info("Running final inference graph, config:\n%s",
str(infer_config))
- if run_params.use_optimizer:
- result = self._RunGraph(params, infer_gdef, input_data, infer_config,
- GraphState.INFERENCE)
- else:
- trt_infer_gdef = self._GetTrtGraphDef(params, run_params, infer_gdef)
- self._VerifyGraphDef(params, run_params, trt_infer_gdef,
- GraphState.INFERENCE)
- result = self._RunGraph(params, trt_infer_gdef, input_data, infer_config,
- GraphState.INFERENCE)
+ if not run_params.use_optimizer:
+ infer_gdef = self._GetTrtGraphDef(run_params, infer_gdef)
+ self._VerifyGraphDef(run_params, infer_gdef, GraphState.INFERENCE)
+ result = self._RunGraph(run_params, infer_gdef, input_data, infer_config,
+ GraphState.INFERENCE)
self.assertAllClose(
ref_result,
result,
- atol=params.allclose_atol,
- rtol=params.allclose_rtol)
+ atol=self.ExpectedAbsoluteTolerance(run_params),
+ rtol=self.ExpectedRelativeTolerance(run_params))
def testIdempotence(self):
# Test that applying tensorrt optimizer or offline conversion tools multiple
@@ -421,13 +514,12 @@ def _AddTests(test_class):
"""Gets a single test method based on the parameters."""
def _Test(self):
- params = self.GetParams()
logging.info(
"Running test %s with parameters: use_optimizer=%s, "
"precision_mode=%s, dynamic_engine=%s",
"testTfTrt_" + run_params.test_name, run_params.use_optimizer,
run_params.precision_mode, run_params.dynamic_engine)
- self.RunTest(params, run_params)
+ self.RunTest(run_params)
return _Test
@@ -435,7 +527,7 @@ def _AddTests(test_class):
dynamic_engine_options = [False, True]
for (use_optimizer, precision_mode, dynamic_engine) in itertools.product(
use_optimizer_options, PRECISION_MODES, dynamic_engine_options):
- if _IsQuantizationMode(precision_mode):
+ if IsQuantizationMode(precision_mode):
if use_optimizer:
# TODO(aaroey): if use_optimizer is True we need to get the inference
# graphdef using custom python wrapper class, which is not currently
diff --git a/tensorflow/contrib/tensorrt/test/unary_test.py b/tensorflow/contrib/tensorrt/test/unary_test.py
index 500057a36d..8736bfb644 100644
--- a/tensorflow/contrib/tensorrt/test/unary_test.py
+++ b/tensorflow/contrib/tensorrt/test/unary_test.py
@@ -38,6 +38,7 @@ class UnaryTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [12, 5, 8, 1, 1, 12]
+ output_name = "output"
input2_name = "input_2"
input2_dims = [12, 5, 8, 1, 12, 1, 1]
g = ops.Graph()
@@ -95,18 +96,20 @@ class UnaryTest(trt_test.TfTrtIntegrationTestBase):
q = a * b
q = q / c
- array_ops.squeeze(q, name=self.output_name)
+ array_ops.squeeze(q, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name, input2_name],
input_dims=[input_dims, input2_dims],
- expected_engines=[
- "my_trt_op_0", "my_trt_op_1", "my_trt_op_2", "my_trt_op_3",
- "my_trt_op_4"
- ],
- expected_output_dims=(12, 5, 8, 12),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(12, 5, 8, 12)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return [
+ "my_trt_op_0", "my_trt_op_1", "my_trt_op_2", "my_trt_op_3",
+ "my_trt_op_4"
+ ]
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/vgg_block_nchw_test.py b/tensorflow/contrib/tensorrt/test/vgg_block_nchw_test.py
index ab4d224db4..b0271a04b3 100644
--- a/tensorflow/contrib/tensorrt/test/vgg_block_nchw_test.py
+++ b/tensorflow/contrib/tensorrt/test/vgg_block_nchw_test.py
@@ -38,15 +38,14 @@ class VGGBlockNCHWTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [5, 2, 8, 8]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
x, _, _ = nn_impl.fused_batch_norm(
- x,
- np.random.randn(2).astype(np.float32),
- np.random.randn(2).astype(np.float32),
- mean=np.random.randn(2).astype(np.float32),
- variance=np.random.randn(2).astype(np.float32),
+ x, [1.0, 1.0], [0.0, 0.0],
+ mean=[0.5, 0.5],
+ variance=[1.0, 1.0],
data_format="NCHW",
is_training=False)
e = constant_op.constant(
@@ -67,15 +66,17 @@ class VGGBlockNCHWTest(trt_test.TfTrtIntegrationTestBase):
"VALID",
data_format="NCHW",
name="max_pool")
- array_ops.squeeze(v, name="output")
+ array_ops.squeeze(v, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=["my_trt_op_0"],
- expected_output_dims=(5, 6, 2, 2),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(5, 6, 2, 2)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return ["my_trt_op_0"]
if __name__ == "__main__":
diff --git a/tensorflow/contrib/tensorrt/test/vgg_block_test.py b/tensorflow/contrib/tensorrt/test/vgg_block_test.py
index 56bdf848ea..d7c165784b 100644
--- a/tensorflow/contrib/tensorrt/test/vgg_block_test.py
+++ b/tensorflow/contrib/tensorrt/test/vgg_block_test.py
@@ -38,15 +38,14 @@ class VGGBlockTest(trt_test.TfTrtIntegrationTestBase):
dtype = dtypes.float32
input_name = "input"
input_dims = [5, 8, 8, 2]
+ output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, shape=input_dims, name=input_name)
x, _, _ = nn_impl.fused_batch_norm(
- x,
- np.random.randn(2).astype(np.float32),
- np.random.randn(2).astype(np.float32),
- mean=np.random.randn(2).astype(np.float32),
- variance=np.random.randn(2).astype(np.float32),
+ x, [1.0, 1.0], [0.0, 0.0],
+ mean=[0.5, 0.5],
+ variance=[1.0, 1.0],
is_training=False)
e = constant_op.constant(
np.random.randn(1, 1, 2, 6), name="weights", dtype=dtype)
@@ -58,15 +57,17 @@ class VGGBlockTest(trt_test.TfTrtIntegrationTestBase):
idty = array_ops.identity(relu, "ID")
v = nn_ops.max_pool(
idty, [1, 2, 2, 1], [1, 2, 2, 1], "VALID", name="max_pool")
- array_ops.squeeze(v, name="output")
+ array_ops.squeeze(v, name=output_name)
return trt_test.TfTrtIntegrationTestParams(
gdef=g.as_graph_def(),
input_names=[input_name],
input_dims=[input_dims],
- expected_engines=["my_trt_op_0"],
- expected_output_dims=(5, 2, 2, 6),
- allclose_atol=1.e-03,
- allclose_rtol=1.e-03)
+ output_names=[output_name],
+ expected_output_dims=[(5, 2, 2, 6)])
+
+ def ExpectedEnginesToBuild(self, run_params):
+ """Return the expected engines to build."""
+ return ["my_trt_op_0"]
if __name__ == "__main__":
diff --git a/tensorflow/contrib/timeseries/examples/BUILD b/tensorflow/contrib/timeseries/examples/BUILD
index 355303acf6..71b0d48798 100644
--- a/tensorflow/contrib/timeseries/examples/BUILD
+++ b/tensorflow/contrib/timeseries/examples/BUILD
@@ -16,6 +16,7 @@ config_setting(
py_binary(
name = "predict",
srcs = ["predict.py"],
+ data = ["data/period_trend.csv"],
srcs_version = "PY2AND3",
tags = ["no_pip"],
deps = select({
@@ -31,7 +32,6 @@ py_test(
name = "predict_test",
timeout = "long", # Moderate but for asan
srcs = ["predict_test.py"],
- data = ["data/period_trend.csv"],
srcs_version = "PY2AND3",
tags = [
"no_windows", # TODO: needs investigation on Windows
diff --git a/tensorflow/contrib/timeseries/examples/predict.py b/tensorflow/contrib/timeseries/examples/predict.py
index 8147d40caa..b036911314 100644
--- a/tensorflow/contrib/timeseries/examples/predict.py
+++ b/tensorflow/contrib/timeseries/examples/predict.py
@@ -19,6 +19,7 @@ from __future__ import division
from __future__ import print_function
import argparse
+import os
import sys
import numpy as np
@@ -40,6 +41,10 @@ except ImportError:
FLAGS = None
+_MODULE_PATH = os.path.dirname(__file__)
+_DEFAULT_DATA_FILE = os.path.join(_MODULE_PATH, "data/period_trend.csv")
+
+
def structural_ensemble_train_and_predict(csv_file_name):
# Cycle between 5 latent values over a period of 100. This leads to a very
# smooth periodic component (and a small model), which is a good fit for our
@@ -115,9 +120,12 @@ def main(unused_argv):
if not HAS_MATPLOTLIB:
raise ImportError(
"Please install matplotlib to generate a plot from this example.")
+ input_filename = FLAGS.input_filename
+ if input_filename is None:
+ input_filename = _DEFAULT_DATA_FILE
make_plot("Structural ensemble",
- *structural_ensemble_train_and_predict(FLAGS.input_filename))
- make_plot("AR", *ar_train_and_predict(FLAGS.input_filename))
+ *structural_ensemble_train_and_predict(input_filename))
+ make_plot("AR", *ar_train_and_predict(input_filename))
pyplot.show()
@@ -126,7 +134,7 @@ if __name__ == "__main__":
parser.add_argument(
"--input_filename",
type=str,
- required=True,
- help="Input csv file.")
+ required=False,
+ help="Input csv file (omit to use the data/period_trend.csv).")
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
diff --git a/tensorflow/contrib/timeseries/python/timeseries/BUILD b/tensorflow/contrib/timeseries/python/timeseries/BUILD
index 0e96c1fbd4..c230919168 100644
--- a/tensorflow/contrib/timeseries/python/timeseries/BUILD
+++ b/tensorflow/contrib/timeseries/python/timeseries/BUILD
@@ -94,7 +94,6 @@ py_library(
"//tensorflow/python:training",
"//tensorflow/python:util",
"//tensorflow/python/estimator:estimator_py",
- "//tensorflow/python/estimator:export",
"//tensorflow/python/feature_column",
],
)
@@ -149,9 +148,6 @@ py_library(
"//tensorflow/python:util",
"//tensorflow/python:variable_scope",
"//tensorflow/python/estimator:estimator_py",
- "//tensorflow/python/estimator:export",
- "//tensorflow/python/estimator:head",
- "//tensorflow/python/estimator:metric_keys",
],
)
diff --git a/tensorflow/contrib/timeseries/python/timeseries/ar_model_test.py b/tensorflow/contrib/timeseries/python/timeseries/ar_model_test.py
index 63f5d3568b..de547f835d 100644
--- a/tensorflow/contrib/timeseries/python/timeseries/ar_model_test.py
+++ b/tensorflow/contrib/timeseries/python/timeseries/ar_model_test.py
@@ -195,7 +195,7 @@ class ARModelTest(test.TestCase):
self.train_helper(input_window_size=10,
loss=ar_model.ARModel.NORMAL_LIKELIHOOD_LOSS,
train_steps=300,
- max_loss=1.5,
+ max_loss=50., # Just make sure there are no exceptions.
anomaly_distribution=None)
def test_autoregression_normal_multiple_periods(self):
diff --git a/tensorflow/contrib/timeseries/python/timeseries/estimators_test.py b/tensorflow/contrib/timeseries/python/timeseries/estimators_test.py
index 983455f63d..461fe22210 100644
--- a/tensorflow/contrib/timeseries/python/timeseries/estimators_test.py
+++ b/tensorflow/contrib/timeseries/python/timeseries/estimators_test.py
@@ -69,8 +69,10 @@ class TimeSeriesRegressorTest(test.TestCase):
input_pipeline.NumpyReader(features), shuffle_seed=3, num_threads=1,
batch_size=16, window_size=16)
first_estimator.train(input_fn=train_input_fn, steps=1)
- first_loss_before_fit = first_estimator.evaluate(
- input_fn=eval_input_fn, steps=1)["loss"]
+ first_evaluation = first_estimator.evaluate(
+ input_fn=eval_input_fn, steps=1)
+ first_loss_before_fit = first_evaluation["loss"]
+ self.assertAllEqual(first_loss_before_fit, first_evaluation["average_loss"])
self.assertAllEqual([], first_loss_before_fit.shape)
first_estimator.train(input_fn=train_input_fn, steps=1)
first_loss_after_fit = first_estimator.evaluate(
diff --git a/tensorflow/contrib/timeseries/python/timeseries/head.py b/tensorflow/contrib/timeseries/python/timeseries/head.py
index 32194e400e..1f9f9b7aa6 100644
--- a/tensorflow/contrib/timeseries/python/timeseries/head.py
+++ b/tensorflow/contrib/timeseries/python/timeseries/head.py
@@ -30,6 +30,7 @@ from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import metrics_impl
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.summary import summary
@@ -123,6 +124,8 @@ class TimeSeriesRegressionHead(head_lib._Head): # pylint:disable=protected-acce
metrics[feature_keys.FilteringResults.STATE_TUPLE] = (
_identity_metric_nested(feature_keys.FilteringResults.STATE_TUPLE,
model_outputs.end_state))
+ metrics[metric_keys.MetricKeys.LOSS_MEAN] = metrics_impl.mean(
+ model_outputs.loss, name="average_loss")
return estimator_lib.EstimatorSpec(
loss=model_outputs.loss,
mode=mode,
diff --git a/tensorflow/contrib/timeseries/python/timeseries/head_test.py b/tensorflow/contrib/timeseries/python/timeseries/head_test.py
index bda3b53aca..e65e7b74d4 100644
--- a/tensorflow/contrib/timeseries/python/timeseries/head_test.py
+++ b/tensorflow/contrib/timeseries/python/timeseries/head_test.py
@@ -172,6 +172,7 @@ class EvaluationMetricsTests(test.TestCase):
evaluation = estimator.evaluate(input_fn, steps=1)
self.assertIn("plain_boring_metric386", evaluation)
self.assertIn("fun_metric101", evaluation)
+ self.assertIn("average_loss", evaluation)
# The values are deterministic because of fixed tf_random_seed.
# However if they become flaky, remove such exacts comparisons.
self.assertAllClose(evaluation["plain_boring_metric386"], 1.130380)
@@ -398,6 +399,7 @@ class OneShotTests(parameterized.TestCase):
num_threads=1, batch_size=16, window_size=16)
estimator.train(input_fn=train_input_fn, steps=5)
result = estimator.evaluate(input_fn=train_input_fn, steps=1)
+ self.assertIn("average_loss", result)
self.assertNotIn(feature_keys.State.STATE_TUPLE, result)
input_receiver_fn = estimator.build_raw_serving_input_receiver_fn()
export_location = estimator.export_savedmodel(_new_temp_dir(),
diff --git a/tensorflow/contrib/tpu/BUILD b/tensorflow/contrib/tpu/BUILD
index 1669f6050e..56e451e2e3 100644
--- a/tensorflow/contrib/tpu/BUILD
+++ b/tensorflow/contrib/tpu/BUILD
@@ -62,10 +62,7 @@ py_library(
"//tensorflow/python:training",
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
- "//tensorflow/python/estimator",
- "//tensorflow/python/estimator:model_fn",
- "//tensorflow/python/estimator:run_config",
- "//tensorflow/python/estimator:util",
+ "//tensorflow/python/estimator:estimator_py",
"@six_archive//:six",
],
)
@@ -195,7 +192,7 @@ py_library(
"//tensorflow/python:tensor_spec",
"//tensorflow/python:variable_scope",
"//tensorflow/python/data/ops:dataset_ops",
- "//tensorflow/python/estimator:model_fn",
+ "//tensorflow/python/estimator:estimator_py",
"//tensorflow/python/keras:backend",
"//tensorflow/python/keras:engine",
"//tensorflow/python/keras:layers",
@@ -268,7 +265,6 @@ tf_py_test(
":datasets",
],
grpc_enabled = True,
- tags = ["no_windows"],
)
tf_py_test(
diff --git a/tensorflow/contrib/tpu/profiler/pip_package/setup.py b/tensorflow/contrib/tpu/profiler/pip_package/setup.py
index 19f088f8b8..d4ccb0f246 100644
--- a/tensorflow/contrib/tpu/profiler/pip_package/setup.py
+++ b/tensorflow/contrib/tpu/profiler/pip_package/setup.py
@@ -20,7 +20,7 @@ from __future__ import print_function
from setuptools import setup
-_VERSION = '1.9.0'
+_VERSION = '1.10.0'
CONSOLE_SCRIPTS = [
'capture_tpu_profile=cloud_tpu_profiler.main:run_main',
diff --git a/tensorflow/contrib/tpu/profiler/version.h b/tensorflow/contrib/tpu/profiler/version.h
index 1bf49966d1..aee094177b 100644
--- a/tensorflow/contrib/tpu/profiler/version.h
+++ b/tensorflow/contrib/tpu/profiler/version.h
@@ -16,6 +16,6 @@ limitations under the License.
#ifndef TENSORFLOW_CONTRIB_TPU_PROFILER_VERSION_H_
#define TENSORFLOW_CONTRIB_TPU_PROFILER_VERSION_H_
-#define TPU_PROFILER_VERSION "1.9.0"
+#define TPU_PROFILER_VERSION "1.10.0"
#endif // TENSORFLOW_CONTRIB_TPU_PROFILER_VERSION_H_
diff --git a/tensorflow/contrib/tpu/python/tpu/keras_support.py b/tensorflow/contrib/tpu/python/tpu/keras_support.py
index ff893a722f..a5e8277ba5 100644
--- a/tensorflow/contrib/tpu/python/tpu/keras_support.py
+++ b/tensorflow/contrib/tpu/python/tpu/keras_support.py
@@ -54,7 +54,7 @@ import time
import numpy as np
-from tensorflow.contrib.cluster_resolver.python.training import tpu_cluster_resolver
+from tensorflow.contrib.cluster_resolver.python.training import tpu_cluster_resolver as tpu_cluster_resolver_lib
from tensorflow.contrib.framework.python.framework import experimental
from tensorflow.contrib.tpu.proto import compilation_result_pb2 as tpu_compilation_result
from tensorflow.contrib.tpu.python.ops import tpu_ops
@@ -80,12 +80,54 @@ from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
+from tensorflow.python.util import tf_inspect
+
+
+_SESSIONS = {}
+
+
+def tpu_session(cluster_resolver):
+ """Construct or return a `tf.Session` connected to the given cluster."""
+ global _SESSIONS
+ master = cluster_resolver.master()
+ if master not in _SESSIONS:
+ cluster_spec = cluster_resolver.cluster_spec()
+ config = config_pb2.ConfigProto(isolate_session_state=True)
+ if cluster_spec:
+ config.cluster_def.CopyFrom(cluster_spec.as_cluster_def())
+
+ graph = ops.Graph()
+ session = tf_session.Session(graph=graph, target=master, config=config)
+
+ with graph.as_default():
+ session.run(tpu.initialize_system())
+
+ _SESSIONS[master] = session
+ return _SESSIONS[master]
+
+
+def reset_tpu_sessions():
+ _SESSIONS.clear()
# Work-around dependency cycle between DistributionStrategy and TPU lib.
-def TPUDistributionStrategy(*args, **kw): # pylint: disable=invalid-name
+def TPUDistributionStrategy(tpu_cluster_resolver=None): # pylint: disable=invalid-name
+ """Construct a TPUDistributionStrategy."""
from tensorflow.contrib.distribute.python import tpu_strategy # pylint: disable=g-import-not-at-top
- return tpu_strategy.TPUStrategy(*args, **kw)
+ # TODO -- remove this when TPUStrategy API is consistent (b/112705069)
+ if tpu_cluster_resolver is None:
+ tpu_cluster_resolver = tpu_cluster_resolver_lib.TPUClusterResolver('')
+
+ args, _, _, _ = tf_inspect.getargspec(tpu_strategy.TPUStrategy.__init__)
+ if len(args) == 3:
+ logging.info('Detected new TPUStrategy API.')
+ return tpu_strategy.TPUStrategy(tpu_cluster_resolver, steps_per_run=1)
+ else:
+ logging.info('Detected old TPUStrategy API.')
+ strategy = tpu_strategy.TPUStrategy(num_cores_per_host=8)
+ strategy._tpu_cluster_resolver = tpu_cluster_resolver
+
+ return strategy
class TPUEmbedding(embeddings.Embedding):
@@ -666,9 +708,10 @@ class TPUFunction(object):
# Clone our CPU model, running within the TPU device context.
with TPURewriteContext(tpu_input_map):
- # TODO(power): Replicate variables.
- with ops.device('/device:TPU:0'):
- self._cloned_model = models.clone_model(self.model)
+ with variable_scope.variable_scope('tpu_model_%s' % id(self.model)):
+ # TODO(power): Replicate variables.
+ with ops.device('/device:TPU:0'):
+ self._cloned_model = models.clone_model(self.model)
# Create a copy of the optimizer for this graph.
if isinstance(self.model.optimizer, keras_optimizers.TFOptimizer):
@@ -845,7 +888,7 @@ class TPUFunction(object):
class KerasTPUModel(models.Model):
"""TPU compatible Keras model wrapper."""
- def __init__(self, cpu_model, tpu_name_or_address, strategy):
+ def __init__(self, cpu_model, strategy):
super(models.Model, self).__init__( # pylint: disable=bad-super-call
inputs=cpu_model.inputs,
outputs=cpu_model.outputs,
@@ -862,27 +905,14 @@ class KerasTPUModel(models.Model):
self.train_function = None
self._strategy = strategy
- self._tpu_name_or_address = tpu_name_or_address
+ cluster_resolver = self._strategy._tpu_cluster_resolver
+ self._tpu_name_or_address = cluster_resolver.get_master()
self._cpu_model = cpu_model
self._tpu_model = None
self._tpu_weights_initialized = False
- self._graph = ops.Graph()
-
- self._cluster_resolver = tpu_cluster_resolver.TPUClusterResolver(
- tpu_name_or_address)
- master = self._cluster_resolver.master()
- cluster_spec = self._cluster_resolver.cluster_spec()
- self._session = tf_session.Session(
- graph=self._graph,
- target=master,
- config=config_pb2.ConfigProto(isolate_session_state=True))
-
- # TODO(saeta): Confirm the lines below work in ClusterSpec propagation env.
- if cluster_spec:
- self._session.cluster_def.CopyFrom(cluster_spec.as_cluster_def())
- with self._graph.as_default():
- self._session.run(tpu.initialize_system())
+ self._session = tpu_session(cluster_resolver)
+ self._graph = self._session.graph
# If the input CPU model has already been compiled, compile our TPU model
# immediately.
@@ -1137,7 +1167,7 @@ Output shape: %(output_shape)s
@experimental
-def tpu_model(model, tpu_name_or_address=None, strategy=None):
+def tpu_model(model, strategy=None):
"""Copy `model` along with weights to the TPU. Returns a TPU model.
Usage:
@@ -1148,7 +1178,7 @@ def tpu_model(model, tpu_name_or_address=None, strategy=None):
# If `num_cores_per_host` is greater than one, batch parallelism will be used
# to run on multiple TPU cores.
- strategy = keras_support.TPUDistributionStrategy(num_cores_per_host=8)
+ strategy = keras_support.TPUDistributionStrategy(tpu_cluster_resolver)
model = keras_support.tpu_model(model, strategy)
model.compile(
optimizer=tf.train.GradientDescentOptimizer(learning_rate=1.0),
@@ -1158,10 +1188,6 @@ def tpu_model(model, tpu_name_or_address=None, strategy=None):
Args:
model: A `KerasTPUModel`.
- tpu_name_or_address: A string that is either the name of the Cloud TPU,
- the grpc address of the Cloud TPU, or (Googlers only) the BNS name of the
- Cloud TPU. If tpu_name_or_address is None, the TPUClusterResolver will
- examine the environment to determine a potential Cloud TPU to use.
strategy: `TPUDistributionStrategy`. The strategy to use for replicating
model across multiple TPU cores.
@@ -1176,9 +1202,8 @@ def tpu_model(model, tpu_name_or_address=None, strategy=None):
# TODO(xiejw): Validate TPU model. TPUModel only?
# TODO(xiejw): Validate replicas. Full or 1. Shall we allow subset?
# TODO(xiejw): Adds reduction option.
+
if strategy is None:
- strategy = TPUDistributionStrategy(num_cores_per_host=1)
- return KerasTPUModel(
- cpu_model=model,
- tpu_name_or_address=tpu_name_or_address,
- strategy=strategy)
+ strategy = TPUDistributionStrategy()
+
+ return KerasTPUModel(cpu_model=model, strategy=strategy)
diff --git a/tensorflow/contrib/tpu/python/tpu/tpu.py b/tensorflow/contrib/tpu/python/tpu/tpu.py
index 7994c2c6c7..7fa06d6d56 100644
--- a/tensorflow/contrib/tpu/python/tpu/tpu.py
+++ b/tensorflow/contrib/tpu/python/tpu/tpu.py
@@ -1015,6 +1015,19 @@ _BLACKLISTED_INFERENCE_OPS = set([
])
+def under_tpu_inference_context():
+ """Check if it is currently under `tpu.rewrite_for_inference()`."""
+ graph = ops.get_default_graph()
+
+ context = graph._get_control_flow_context() # pylint: disable=protected-access
+ while context:
+ if isinstance(context, _TPUInferenceContext):
+ return True
+ context = context.outer_context
+
+ return False
+
+
class _TPUInferenceContext(control_flow_ops.XLAControlFlowContext):
"""A `ControlFlowContext` for nodes inside a TPU inference computation.
diff --git a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
index c104b2403c..fed07f00e7 100644
--- a/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
+++ b/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py
@@ -45,6 +45,7 @@ from tensorflow.core.framework import variable_pb2
from tensorflow.core.framework.summary_pb2 import Summary
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.data.ops import dataset_ops
+from tensorflow.python.data.util import nest as data_nest
from tensorflow.python.estimator import estimator as estimator_lib
from tensorflow.python.estimator import model_fn as model_fn_lib
from tensorflow.python.estimator import util as estimator_util
@@ -204,6 +205,12 @@ def _increase_eval_step_op(iterations_per_loop):
use_locking=True)
+def _extract_key_names(tensor_or_dict):
+ if isinstance(tensor_or_dict, dict):
+ return sorted(tensor_or_dict.keys())
+ return []
+
+
class _SIGNAL(object):
"""Signal used to control the thread of infeed/outfeed.
@@ -711,8 +718,7 @@ def generate_per_host_enqueue_ops_fn_for_host(
features, labels = inputs.features_and_labels()
signals = inputs.signals()
- inputs_structure_recorder.validate_and_record_structure(
- features, labels, signals)
+ inputs_structure_recorder.validate_and_record_structure(features, labels)
unsharded_tensor_list = (
inputs_structure_recorder.flatten_features_and_labels(
features, labels, signals))
@@ -756,9 +762,13 @@ def generate_per_host_v2_enqueue_ops_fn_for_host(
if not is_dataset:
raise TypeError('`input_fn` must return a `Dataset` for the PER_HOST_V2 '
'input pipeline configuration.')
+
if ctx.mode == model_fn_lib.ModeKeys.PREDICT:
- # TODO(b/XXX): Add predict support for PER_HOST_V2
- raise TypeError('Most PREDICT not yet supported in PER_HOST_V2 mode.')
+ inputs = _InputsWithStoppingSignals(
+ dataset=inputs.dataset,
+ batch_size=ctx.batch_size_for_input_fn,
+ add_padding=True,
+ num_invocations_per_step=ctx.num_of_replicas_per_host)
hooks.append(inputs.dataset_initializer_hook())
tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id)
@@ -768,6 +778,7 @@ def generate_per_host_v2_enqueue_ops_fn_for_host(
control_deps = []
per_host_sharded_inputs = []
num_replicas_per_host = ctx.num_of_replicas_per_host
+ cached_signals = None
with ops.device(device):
if not inputs.is_dataset:
raise TypeError('`input_fn` must return a `Dataset` for this mode.')
@@ -775,12 +786,20 @@ def generate_per_host_v2_enqueue_ops_fn_for_host(
# Use control dependencies to ensure a deterministic ordering.
with ops.control_dependencies(control_deps):
features, labels = inputs.features_and_labels() # Calls get_next()
+ signals = inputs.signals()
+
+ # All the replicas share the replica 0's stopping singal.
+ # This avoids inconsistent state among different model replcias.
+ if cached_signals:
+ signals['stopping'] = cached_signals['stopping']
+ else:
+ cached_signals = signals
inputs_structure_recorder.validate_and_record_structure(
features, labels)
flattened_inputs = (
inputs_structure_recorder.flatten_features_and_labels(
- features, labels))
+ features, labels, signals))
control_deps.extend(flattened_inputs)
per_host_sharded_inputs.append(flattened_inputs)
@@ -801,7 +820,13 @@ def generate_per_host_v2_enqueue_ops_fn_for_host(
tpu_ordinal_function=tpu_ordinal_function_impl)
captured_infeed_queue.capture(infeed_queue)
- return per_host_enqueue_ops
+ if signals is None:
+ return per_host_enqueue_ops
+ else:
+ return {
+ 'ops': per_host_enqueue_ops,
+ 'signals': signals,
+ }
return enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset
@@ -859,7 +884,7 @@ def generate_broadcast_enqueue_ops_fn(ctx, input_fn, inputs_structure_recorder,
signals = inputs.signals()
inputs_structure_recorder.validate_and_record_structure(
- features, labels, signals)
+ features, labels)
flattened_inputs = (
inputs_structure_recorder.flatten_features_and_labels(
features, labels, signals))
@@ -901,17 +926,19 @@ class _InputPipeline(object):
inputs returned by the `input_fn` can have one of the following forms:
1. features
2. (features, labels)
+ 3. ((arbitrarily nested structure of features), labels)
Internally, form 1 is reformed to `(features, None)` as features and labels
are passed separately to underlying methods. For TPU training, TPUEstimator
may expect multiple `features` and `labels` tuples one for each core.
TPUEstimator allows various different structures for inputs (namely `features`
- and `labels`). `features` can be `Tensor` or dict of string name to `Tensor`,
- and `labels` could be `None`, `Tensor`, or dict of string name to `Tensor`.
- TPU infeed/outfeed library expects flattened tensor list. So, `features` and
- `labels` need to be flattened, before infeed enqueue, and the structure of
- them needs to be recorded, in order to restore them after infeed dequeue.
+ and `labels`). `features` can be `Tensor`, dict of string name to `Tensor`,
+ or nested tuples and `labels` could be `None`, `Tensor`, or dict of string
+ name to `Tensor`. TPU infeed/outfeed library expects flattened tensor list.
+ So, `features` and `labels` need to be flattened, before infeed enqueue, and
+ the structure of them needs to be recorded, in order to restore them after
+ infeed dequeue.
"""
class InputsStructureRecorder(object):
@@ -919,10 +946,7 @@ class _InputPipeline(object):
def __init__(self, input_partition_dims=None):
# Holds the structure of inputs
- self._feature_names = []
- self._label_names = []
- self._has_labels = False
- self._signals_helper = None
+ self._feature_structure = {}
self._flattened_input_dims = None
if input_partition_dims:
@@ -949,7 +973,7 @@ class _InputPipeline(object):
return self._flattened_input_dims
def has_labels(self):
- return self._has_labels
+ return 'labels' in self._feature_structure
def _flatten_input_dims(self, feature_dims, feature_dims_names, label_dims,
label_dims_names, label_names, has_labels):
@@ -977,35 +1001,16 @@ class _InputPipeline(object):
return flattened_input_dims
- def validate_and_record_structure(self, features, labels, signals=None):
+ def validate_and_record_structure(self, features, labels):
"""Validates and records the structure of `features` and `labels`."""
-
- def _extract_key_names(tensor_or_dict):
- if tensor_or_dict is None:
- return []
- return sorted(tensor_or_dict.keys()) if isinstance(
- tensor_or_dict, dict) else []
-
# Extract structure.
has_labels = labels is not None
feature_names = _extract_key_names(features)
label_names = _extract_key_names(labels)
- if signals is not None and self._signals_helper is None:
- # Record signals helper.
- self._signals_helper = _SignalsHelper(signals)
-
- if self._initialized:
- # Verify the structure is same. The following should never happen.
- assert feature_names == self._feature_names, 'feature keys mismatched'
- assert label_names == self._label_names, 'label keys mismatched'
- assert has_labels == self._has_labels, 'label presence mismatched'
- else:
+ if not self._initialized:
# Record structure.
self._initialized = True
- self._feature_names = feature_names
- self._label_names = label_names
- self._has_labels = has_labels
if self._feature_dims is not None:
feature_dims_names = _extract_key_names(self._feature_dims)
if feature_dims_names != feature_names:
@@ -1027,24 +1032,12 @@ class _InputPipeline(object):
def flatten_features_and_labels(self, features, labels, signals=None):
"""Flattens the `features` and `labels` to a single tensor list."""
- flattened_inputs = []
- if self._feature_names:
- # We need a fixed ordering for enqueueing and dequeueing.
- flattened_inputs.extend(
- [features[name] for name in self._feature_names])
- else:
- flattened_inputs.append(features)
-
+ self._feature_structure['features'] = features
if labels is not None:
- if self._label_names:
- # We need a fixed ordering for enqueueing and dequeueing.
- flattened_inputs.extend([labels[name] for name in self._label_names])
- else:
- flattened_inputs.append(labels)
-
+ self._feature_structure['labels'] = labels
if signals is not None:
- flattened_inputs.extend(_SignalsHelper.as_tensor_list(signals))
- return flattened_inputs
+ self._feature_structure['signals'] = signals
+ return data_nest.flatten(self._feature_structure)
def unflatten_features_and_labels(self, flattened_inputs):
"""Restores the flattened inputs to original features and labels form.
@@ -1061,49 +1054,13 @@ class _InputPipeline(object):
ValueError: If the number of expected tensors from `flattened_inputs`
mismatches the recorded structure.
"""
- expected_num_features = (
- len(self._feature_names) if self._feature_names else 1)
- if self._has_labels:
- expected_num_labels = (
- len(self._label_names) if self._label_names else 1)
- else:
- expected_num_labels = 0
-
- expected_num_signals = (
- self._signals_helper.num_signals if self._signals_helper else 0)
-
- expected_num_tensors = (
- expected_num_features + expected_num_labels + expected_num_signals)
-
- if expected_num_tensors != len(flattened_inputs):
- raise ValueError(
- 'The number of flattened tensors mismatches expected num. '
- 'Expected {}, got {}'.format(expected_num_tensors,
- len(flattened_inputs)))
- if self._feature_names:
- unflattened_features = dict(
- zip(self._feature_names, flattened_inputs[:expected_num_features]))
- else:
- # Single tensor case
- unflattened_features = flattened_inputs[0]
-
- if expected_num_labels == 0:
- unflattened_label = None
- elif self._label_names:
- label_list = flattened_inputs[
- expected_num_features:expected_num_features + expected_num_labels]
- unflattened_label = dict(zip(self._label_names, label_list))
- else:
- # Single tensor case.
- unflattened_label = flattened_inputs[expected_num_features]
-
- signals = None
- if expected_num_signals != 0:
- tensor_list_for_signals = flattened_inputs[
- expected_num_features + expected_num_labels:]
- signals = self._signals_helper.unflatten(tensor_list_for_signals)
- return _Inputs(unflattened_features, unflattened_label, signals=signals)
+ unflattened_inputs = data_nest.pack_sequence_as(self._feature_structure,
+ flattened_inputs)
+ return _Inputs(
+ unflattened_inputs['features'],
+ unflattened_inputs.get('labels'),
+ signals=unflattened_inputs.get('signals'))
def __init__(self, input_fn, batch_axis, ctx):
"""Constructor.
@@ -1505,12 +1462,14 @@ class _ModelFnWrapper(object):
'The {} to the model returned by input_fn must have static shape.'
' Tensor: {}'.format(obj_name, obj))
else:
- for (key, tensor) in obj.items():
- if not tensor.get_shape().is_fully_defined():
- raise ValueError(
- 'The {} to the model returned by input_fn must have static '
- 'shape. Key: \'{}\', Tensor: {}'.format(
- obj_name, key, tensor))
+ for (key, value) in obj.items():
+ flattened_tensors = data_nest.flatten(value)
+ for tensor in flattened_tensors:
+ if not tensor.get_shape().is_fully_defined():
+ raise ValueError(
+ 'The {} to the model returned by input_fn must have static '
+ 'shape. Key: \'{}\', Tensor: {}'.format(
+ obj_name, key, tensor))
validate(features, 'features')
if labels is not None:
@@ -3103,16 +3062,48 @@ class _Inputs(object):
class _InputsWithStoppingSignals(_Inputs):
"""Inputs with `_StopSignals` inserted into the dataset."""
- def __init__(self, dataset, batch_size, add_padding=False):
+ def __init__(self,
+ dataset,
+ batch_size,
+ add_padding=False,
+ num_invocations_per_step=1):
assert dataset is not None
-
user_provided_dataset = dataset.map(
_InputsWithStoppingSignals.insert_stopping_signal(
stop=False, batch_size=batch_size, add_padding=add_padding))
- final_batch_dataset = dataset.take(1).map(
- _InputsWithStoppingSignals.insert_stopping_signal(
- stop=True, batch_size=batch_size, add_padding=add_padding))
+ if num_invocations_per_step == 1:
+ final_batch_dataset = dataset.take(1).map(
+ _InputsWithStoppingSignals.insert_stopping_signal(
+ stop=True, batch_size=batch_size, add_padding=add_padding))
+ else:
+ # We append (2 * num_invocations_per_step - 1) batches for exhausting the
+ # user_provided_dataset and stop properly.
+ # For example, if num_invocations_per_step is 2, we append 3 additional
+ # padding batches: b1, b2, b3.
+ # If user_provided_dataset contains two batches: a1, a2
+ # Step 1: [a1, a2]
+ # Step 2: [b1, b2] -> STOP
+ # If user_provided_dataset contains three batches: a1, a2, a3.
+ # The training loops:
+ # Step 1: [a1, a2]
+ # Step 2: [a3, b1]
+ # Step 3: [b2, b3] -> STOP.
+ final_batch_dataset = dataset.take(1).map(
+ _InputsWithStoppingSignals.insert_stopping_signal(
+ stop=True, batch_size=batch_size, add_padding=add_padding))
+ final_batch_dataset = final_batch_dataset.repeat(
+ 2 * num_invocations_per_step - 1)
+
+ def _set_mask(data_dict):
+ signals = data_dict['signals']
+ signals['padding_mask'] = array_ops.ones_like(signals['padding_mask'])
+ data_dict['signals'] = signals
+ return data_dict
+
+ # Mask out the extra batch.
+ final_batch_dataset = final_batch_dataset.map(_set_mask)
+
dataset = user_provided_dataset.concatenate(final_batch_dataset).prefetch(2)
super(_InputsWithStoppingSignals, self).__init__(dataset=dataset)
@@ -3338,26 +3329,6 @@ class _PaddingSignals(object):
return padding_mask
-class _SignalsHelper(object):
- """A general helper class to handle common signals manipulation."""
-
- def __init__(self, signals):
- self._signal_keys = []
- for key in sorted(iter(signals.keys())):
- self._signal_keys.append(key)
-
- @property
- def num_signals(self):
- return len(self._signal_keys)
-
- def unflatten(self, tensor_list):
- return dict(zip(self._signal_keys, tensor_list))
-
- @staticmethod
- def as_tensor_list(signals):
- return [signals[key] for key in sorted(iter(signals.keys()))]
-
-
def _verify_cross_hosts_transfer_size(tensor_dict, message):
total_size = 0
tensor_structure = {}
diff --git a/tensorflow/contrib/tpu/python/tpu/tpu_estimator_signals_test.py b/tensorflow/contrib/tpu/python/tpu/tpu_estimator_signals_test.py
index 3e90957e6d..bd530fdc3a 100644
--- a/tensorflow/contrib/tpu/python/tpu/tpu_estimator_signals_test.py
+++ b/tensorflow/contrib/tpu/python/tpu/tpu_estimator_signals_test.py
@@ -286,6 +286,59 @@ class TPUEstimatorStoppingSignalsWithPaddingTest(test.TestCase):
with self.assertRaises(errors.OutOfRangeError):
sess.run(sliced_features)
+ def test_slice_with_multi_invocations_per_step(self):
+ num_samples = 3
+ batch_size = 2
+
+ params = {'batch_size': batch_size}
+ input_fn, (a, b) = make_input_fn(num_samples=num_samples)
+
+ with ops.Graph().as_default():
+ dataset = input_fn(params)
+ inputs = tpu_estimator._InputsWithStoppingSignals(
+ dataset, batch_size, add_padding=True, num_invocations_per_step=2)
+ hook = inputs.dataset_initializer_hook()
+ features, _ = inputs.features_and_labels()
+ signals = inputs.signals()
+
+ sliced_features = (
+ tpu_estimator._PaddingSignals.slice_tensor_or_dict(features, signals))
+
+ with session.Session() as sess:
+ hook.begin()
+ hook.after_create_session(sess, coord=None)
+
+ result, evaluated_signals = sess.run([sliced_features, signals])
+ self.assertAllEqual(a[:batch_size], result['a'])
+ self.assertAllEqual(b[:batch_size], result['b'])
+ self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping'])
+
+ # This is the final partial batch.
+ result, evaluated_signals = sess.run([sliced_features, signals])
+ self.assertEqual(1, len(result['a']))
+ self.assertAllEqual(a[batch_size:num_samples], result['a'])
+ self.assertAllEqual(b[batch_size:num_samples], result['b'])
+ self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping'])
+
+ # We should see 3 continuous batches with STOP ('1') as signals and all
+ # of them have mask 1.
+ _, evaluated_signals = sess.run([sliced_features, signals])
+ self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping'])
+ self.assertAllEqual([1.] * batch_size,
+ evaluated_signals['padding_mask'])
+
+ _, evaluated_signals = sess.run([sliced_features, signals])
+ self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping'])
+ self.assertAllEqual([1.] * batch_size,
+ evaluated_signals['padding_mask'])
+
+ _, evaluated_signals = sess.run([sliced_features, signals])
+ self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping'])
+ self.assertAllEqual([1.] * batch_size,
+ evaluated_signals['padding_mask'])
+ with self.assertRaises(errors.OutOfRangeError):
+ sess.run(sliced_features)
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/contrib/training/BUILD b/tensorflow/contrib/training/BUILD
index 76927e62e8..ddf8365d61 100644
--- a/tensorflow/contrib/training/BUILD
+++ b/tensorflow/contrib/training/BUILD
@@ -61,7 +61,7 @@ py_library(
"//tensorflow/python:variable_scope",
"//tensorflow/python:variables",
"//tensorflow/python/data",
- "//tensorflow/python/estimator:inputs_queues",
+ "//tensorflow/python/estimator:estimator_py",
"//third_party/py/numpy",
"@six_archive//:six",
],
@@ -133,7 +133,7 @@ py_test(
"//tensorflow/python:framework_ops",
"//tensorflow/python:session",
"//tensorflow/python:training",
- "//tensorflow/python/estimator:inputs_queues",
+ "//tensorflow/python/estimator:estimator_py",
"//third_party/py/numpy",
],
)
diff --git a/tensorflow/contrib/training/__init__.py b/tensorflow/contrib/training/__init__.py
index edd71fb250..3547e71184 100644
--- a/tensorflow/contrib/training/__init__.py
+++ b/tensorflow/contrib/training/__init__.py
@@ -14,7 +14,9 @@
# ==============================================================================
"""Training and input utilities.
-See @{$python/contrib.training} guide.
+See
+[Contrib Training](https://tensorflow.org/api_guides/python/contrib.training)
+guide.
@@batch_sequences_with_states
@@NextQueuedSequenceBatch
diff --git a/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py b/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
index 39d75a0806..53e4f23a7c 100644
--- a/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
+++ b/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
@@ -988,14 +988,14 @@ class SequenceQueueingStateSaver(object):
assert isinstance(sequences, dict)
assert isinstance(context, dict)
assert isinstance(states, dict)
- self._name_to_index = dict(
- (name, ix)
+ self._name_to_index = {
+ name: ix
for (ix, name) in enumerate([
"__length", "__total_length", "__next_key", "__sequence",
"__sequence_count"
] + ["__sequence__%s" % k for k in sequences.keys()] + [
"__context__%s" % k for k in context.keys()
- ] + ["__state__%s" % k for k in states.keys()]))
+ ] + ["__state__%s" % k for k in states.keys()])}
self._index_to_name = [
name
for (name, _) in sorted(
diff --git a/tensorflow/contrib/training/python/training/tensor_queue_dataset.py b/tensorflow/contrib/training/python/training/tensor_queue_dataset.py
index a2444934bc..f46d03209c 100644
--- a/tensorflow/contrib/training/python/training/tensor_queue_dataset.py
+++ b/tensorflow/contrib/training/python/training/tensor_queue_dataset.py
@@ -156,7 +156,7 @@ def prepend_from_queue_and_padded_batch_dataset(batch_size,
Returns:
A `Dataset` transformation function, which can be passed to
- @{tf.data.Dataset.apply}.
+ `tf.data.Dataset.apply`.
"""
def _apply_fn(dataset):
diff --git a/tensorflow/contrib/training/python/training/training.py b/tensorflow/contrib/training/python/training/training.py
index f72e0a3f83..c272a2ac14 100644
--- a/tensorflow/contrib/training/python/training/training.py
+++ b/tensorflow/contrib/training/python/training/training.py
@@ -484,7 +484,8 @@ def train(train_op,
save_checkpoint_secs=600,
save_summaries_steps=100,
config=None,
- max_wait_secs=7200):
+ max_wait_secs=7200,
+ run_metadata=None):
"""Runs the training loop.
Args:
@@ -511,6 +512,7 @@ def train(train_op,
become available. This should be kept relatively short to help detect
incorrect code, but sometimes may need to be increased if the chief takes
a while to start up.
+ run_metadata: A [`RunMetadata`] protocol buffer.
Returns:
the value of the loss function after training.
@@ -541,5 +543,5 @@ def train(train_op,
max_wait_secs=max_wait_secs) as session:
loss = None
while not session.should_stop():
- loss = session.run(train_op)
+ loss = session.run(train_op, run_metadata=run_metadata)
return loss
diff --git a/tensorflow/contrib/util/__init__.py b/tensorflow/contrib/util/__init__.py
index 08741cf8ca..338acef63f 100644
--- a/tensorflow/contrib/util/__init__.py
+++ b/tensorflow/contrib/util/__init__.py
@@ -15,7 +15,7 @@
"""Utilities for dealing with Tensors.
-See @{$python/contrib.util} guide.
+See [Contrib Util](https://tensorflow.org/api_guides/python/contrib.util) guide.
@@constant_value
@@make_tensor_proto
diff --git a/tensorflow/core/BUILD b/tensorflow/core/BUILD
index 1423c7fbcb..64430a1418 100644
--- a/tensorflow/core/BUILD
+++ b/tensorflow/core/BUILD
@@ -121,6 +121,7 @@ load(
"tf_additional_minimal_lib_srcs",
"tf_additional_mpi_lib_defines",
"tf_additional_proto_hdrs",
+ "tf_additional_proto_compiler_hdrs",
"tf_additional_proto_srcs",
"tf_additional_test_deps",
"tf_additional_test_srcs",
@@ -128,6 +129,7 @@ load(
"tf_jspb_proto_library",
"tf_kernel_tests_linkstatic",
"tf_lib_proto_parsing_deps",
+ "tf_lib_proto_compiler_deps",
"tf_nano_proto_library",
"tf_platform_hdrs",
"tf_platform_srcs",
@@ -149,6 +151,7 @@ load("@io_bazel_rules_closure//closure:defs.bzl", "closure_proto_library")
load(
"//third_party/mkl:build_defs.bzl",
"if_mkl",
+ "mkl_deps",
)
exports_files(["ops/ops.pbtxt"])
@@ -612,6 +615,17 @@ cc_library(
],
)
+cc_library(
+ name = "lib_proto_compiler",
+ hdrs = [
+ "platform/protobuf_compiler.h",
+ ] + tf_additional_proto_compiler_hdrs(),
+ copts = tf_copts(),
+ deps = tf_lib_proto_compiler_deps() + [
+ ":lib_proto_parsing",
+ ],
+)
+
# This build rule (along with :lib_internal, :framework, and
# :framework_internal) purposefully omits the definitions of many declared
# symbols, which are included in //tensorflow:libtensorflow_framework.so. Using
@@ -735,7 +749,10 @@ cc_library(
"util/reporter.h",
],
copts = tf_copts(),
- linkopts = ["-lm"],
+ linkopts = select({
+ "//tensorflow:windows": [],
+ "//conditions:default": ["-lm"],
+ }),
visibility = ["//visibility:public"],
deps = [
":lib",
@@ -860,7 +877,6 @@ tf_cuda_library(
"util/work_sharder.h",
] + select({
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": [
"util/memmapped_file_system.h",
"util/memmapped_file_system_writer.h",
@@ -2036,7 +2052,7 @@ cc_library(
linkopts = select({
"//tensorflow:freebsd": [],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
+ "//tensorflow:android": [],
"//conditions:default": [
"-ldl",
"-lpthread",
@@ -2125,7 +2141,6 @@ cc_library(
linkopts = select({
"//tensorflow:freebsd": [],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": ["-ldl"],
}),
deps = [
@@ -2150,7 +2165,6 @@ cc_library(
linkopts = select({
"//tensorflow:freebsd": [],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": ["-ldl"],
}),
deps = [
@@ -2182,7 +2196,6 @@ cc_library(
linkopts = select({
"//tensorflow:freebsd": [],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": ["-ldl"],
}),
deps = [
@@ -2486,7 +2499,6 @@ tf_cuda_library(
],
) + select({
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": [
"util/memmapped_file_system.cc",
"util/memmapped_file_system_writer.cc",
@@ -2495,13 +2507,13 @@ tf_cuda_library(
hdrs = FRAMEWORK_INTERNAL_PUBLIC_HEADERS,
copts = tf_copts(),
linkopts = select({
- "//tensorflow:freebsd": [],
+ "//tensorflow:freebsd": ["-lm"],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
- "//conditions:default": ["-ldl"],
- }) + [
- "-lm",
- ],
+ "//conditions:default": [
+ "-ldl",
+ "-lm",
+ ],
+ }),
deps = [
":lib",
":lib_internal",
@@ -2516,12 +2528,7 @@ tf_cuda_library(
] + if_static(
extra_deps = ["@protobuf_archive//:protobuf"],
otherwise = ["@protobuf_archive//:protobuf_headers"],
- ) + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- "@mkl_dnn",
- ],
- ),
+ ) + mkl_deps(),
alwayslink = 1,
)
@@ -2802,12 +2809,7 @@ tf_cuda_library(
":protos_all_cc",
"//third_party/eigen3",
"//tensorflow/core/grappler:grappler_item",
- ] + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- "@mkl_dnn",
- ],
- ),
+ ] + mkl_deps(),
alwayslink = 1,
)
@@ -2847,12 +2849,7 @@ tf_cuda_library(
"//tensorflow/core/grappler/optimizers:meta_optimizer",
"//third_party/eigen3",
"//tensorflow/core/kernels:required",
- ] + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- "@mkl_dnn",
- ],
- ) + tf_additional_core_deps() + if_static([":core_cpu_impl"]),
+ ] + mkl_deps() + tf_additional_core_deps() + if_static([":core_cpu_impl"]),
alwayslink = 1,
)
@@ -3145,7 +3142,10 @@ cc_library(
testonly = 1,
srcs = ["platform/test_main.cc"],
copts = tf_copts(),
- linkopts = ["-lm"],
+ linkopts = select({
+ "//tensorflow:windows": [],
+ "//conditions:default": ["-lm"],
+ }),
visibility = ["//tensorflow:internal"],
deps = [
":lib",
@@ -3856,11 +3856,7 @@ tf_cuda_only_cc_test(
":test",
":test_main",
"//third_party/eigen3",
- ] + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- ],
- ),
+ ] + mkl_deps(),
)
tf_cc_test_gpu(
@@ -4581,6 +4577,8 @@ filegroup(
# PNG data
"lib/png/testdata/lena_gray.png",
"lib/png/testdata/lena_rgba.png",
+ "lib/png/testdata/lena_palette.png",
+ "lib/png/testdata/lena_palette_trns.png",
# JPEG data
"lib/jpeg/testdata/jpeg_merge_test1.jpg",
"lib/jpeg/testdata/jpeg_merge_test1_cmyk.jpg",
diff --git a/tensorflow/core/api_def/api_test.cc b/tensorflow/core/api_def/api_test.cc
index ae03a61ae6..51812caeb2 100644
--- a/tensorflow/core/api_def/api_test.cc
+++ b/tensorflow/core/api_def/api_test.cc
@@ -59,8 +59,8 @@ void GetGoldenApiDefs(Env* env, const string& api_files_dir,
file_contents = PBTxtFromMultiline(file_contents);
ApiDefs api_defs;
- CHECK(tensorflow::protobuf::TextFormat::ParseFromString(file_contents,
- &api_defs))
+ QCHECK(tensorflow::protobuf::TextFormat::ParseFromString(file_contents,
+ &api_defs))
<< "Failed to load " << file_path;
CHECK_EQ(api_defs.op_size(), 1);
(*name_to_api_def)[api_defs.op(0).graph_op_name()] = api_defs.op(0);
diff --git a/tensorflow/core/api_def/base_api/api_def_DivNoNan.pbtxt b/tensorflow/core/api_def/base_api/api_def_DivNoNan.pbtxt
new file mode 100644
index 0000000000..5604a1a89e
--- /dev/null
+++ b/tensorflow/core/api_def/base_api/api_def_DivNoNan.pbtxt
@@ -0,0 +1,9 @@
+op {
+ graph_op_name: "DivNoNan"
+ summary: "Returns 0 if the denominator is zero."
+ description: <<END
+
+*NOTE*: `DivNoNan` supports broadcasting. More about broadcasting
+[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
+END
+}
diff --git a/tensorflow/core/api_def/base_api/api_def_Fill.pbtxt b/tensorflow/core/api_def/base_api/api_def_Fill.pbtxt
index 58262a385c..37d1a9dcbf 100644
--- a/tensorflow/core/api_def/base_api/api_def_Fill.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_Fill.pbtxt
@@ -27,5 +27,15 @@ For example:
fill([2, 3], 9) ==> [[9, 9, 9]
[9, 9, 9]]
```
+
+`tf.fill` differs from `tf.constant` in a few ways:
+
+* `tf.fill` only supports scalar contents, whereas `tf.constant` supports
+ Tensor values.
+* `tf.fill` creates an Op in the computation graph that constructs the actual
+ Tensor value at runtime. This is in contrast to `tf.constant` which embeds
+ the entire Tensor into the graph with a `Const` node.
+* Because `tf.fill` evaluates at graph runtime, it supports dynamic shapes
+ based on other runtime Tensors, unlike `tf.constant`.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_GatherNd.pbtxt b/tensorflow/core/api_def/base_api/api_def_GatherNd.pbtxt
index 342a1f6b05..9f3f9b276b 100644
--- a/tensorflow/core/api_def/base_api/api_def_GatherNd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_GatherNd.pbtxt
@@ -27,7 +27,7 @@ slice of `params`:
output[\\(i_0, ..., i_{K-2}\\)] = params[indices[\\(i_0, ..., i_{K-2}\\)]]
-Whereas in @{tf.gather} `indices` defines slices into the first
+Whereas in `tf.gather` `indices` defines slices into the first
dimension of `params`, in `tf.gather_nd`, `indices` defines slices into the
first `N` dimensions of `params`, where `N = indices.shape[-1]`.
@@ -123,5 +123,7 @@ Batched indexing into a 3-tensor:
[['a1', 'b1'], ['c1', 'd1']]]
output = [['b0', 'b1'], ['d0', 'c1']]
```
+
+See also `tf.gather` and `tf.batch_gather`.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_GatherV2.pbtxt b/tensorflow/core/api_def/base_api/api_def_GatherV2.pbtxt
index 162ef2b033..c6104da4a6 100644
--- a/tensorflow/core/api_def/base_api/api_def_GatherV2.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_GatherV2.pbtxt
@@ -54,5 +54,7 @@ params.shape[axis + 1:]` where:
Note that on CPU, if an out of bound index is found, an error is returned.
On GPU, if an out of bound index is found, a 0 is stored in the
corresponding output value.
+
+See also `tf.batch_gather` and `tf.gather_nd`.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_HostConst.pbtxt b/tensorflow/core/api_def/base_api/api_def_HostConst.pbtxt
new file mode 100644
index 0000000000..9d04a01f6f
--- /dev/null
+++ b/tensorflow/core/api_def/base_api/api_def_HostConst.pbtxt
@@ -0,0 +1,11 @@
+op {
+ graph_op_name: "HostConst"
+ attr {
+ name: "value"
+ description: <<END
+Attr `value` is the tensor to return.
+END
+ }
+ visibility: SKIP
+ summary: "Returns a constant tensor on the host. Only for writing C++ tests."
+}
diff --git a/tensorflow/core/api_def/base_api/api_def_Igamma.pbtxt b/tensorflow/core/api_def/base_api/api_def_Igamma.pbtxt
index e7bc5ddae2..40d7d371ca 100644
--- a/tensorflow/core/api_def/base_api/api_def_Igamma.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_Igamma.pbtxt
@@ -1,6 +1,6 @@
op {
graph_op_name: "Igamma"
- summary: "Compute the lower regularized incomplete Gamma function `Q(a, x)`."
+ summary: "Compute the lower regularized incomplete Gamma function `P(a, x)`."
description: <<END
The lower regularized incomplete Gamma function is defined as:
diff --git a/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdAdd.pbtxt b/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdAdd.pbtxt
index 2b58969da2..d9c4d5a4a4 100644
--- a/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdAdd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdAdd.pbtxt
@@ -63,7 +63,7 @@ The resulting update to ref would look like this:
[1, 12, 3, 14, 14, 6, 7, 20]
-See @{tf.scatter_nd} for more details about how to make updates to
+See `tf.scatter_nd` for more details about how to make updates to
slices.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdUpdate.pbtxt b/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdUpdate.pbtxt
index 17b79ee30c..d724cfccec 100644
--- a/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdUpdate.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ResourceScatterNdUpdate.pbtxt
@@ -63,7 +63,7 @@ The resulting update to ref would look like this:
[1, 11, 3, 10, 9, 6, 7, 12]
-See @{tf.scatter_nd} for more details about how to make updates to
+See `tf.scatter_nd` for more details about how to make updates to
slices.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_ScatterNd.pbtxt b/tensorflow/core/api_def/base_api/api_def_ScatterNd.pbtxt
index ad1c527b01..0b5917d428 100644
--- a/tensorflow/core/api_def/base_api/api_def_ScatterNd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ScatterNd.pbtxt
@@ -30,7 +30,7 @@ END
Creates a new tensor by applying sparse `updates` to individual values or
slices within a tensor (initially zero for numeric, empty for string) of
the given `shape` according to indices. This operator is the inverse of the
-@{tf.gather_nd} operator which extracts values or slices from a given tensor.
+`tf.gather_nd` operator which extracts values or slices from a given tensor.
If `indices` contains duplicates, then their updates are accumulated (summed).
diff --git a/tensorflow/core/api_def/base_api/api_def_ScatterNdAdd.pbtxt b/tensorflow/core/api_def/base_api/api_def_ScatterNdAdd.pbtxt
index a9a7646314..5929425bc8 100644
--- a/tensorflow/core/api_def/base_api/api_def_ScatterNdAdd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ScatterNdAdd.pbtxt
@@ -66,7 +66,7 @@ The resulting update to ref would look like this:
[1, 13, 3, 14, 14, 6, 7, 20]
-See @{tf.scatter_nd} for more details about how to make updates to
+See `tf.scatter_nd` for more details about how to make updates to
slices.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_ScatterNdNonAliasingAdd.pbtxt b/tensorflow/core/api_def/base_api/api_def_ScatterNdNonAliasingAdd.pbtxt
index 35116e5f6a..fa15538f8c 100644
--- a/tensorflow/core/api_def/base_api/api_def_ScatterNdNonAliasingAdd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ScatterNdNonAliasingAdd.pbtxt
@@ -61,6 +61,6 @@ The resulting value `output` would look like this:
[1, 13, 3, 14, 14, 6, 7, 20]
-See @{tf.scatter_nd} for more details about how to make updates to slices.
+See `tf.scatter_nd` for more details about how to make updates to slices.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_ScatterNdSub.pbtxt b/tensorflow/core/api_def/base_api/api_def_ScatterNdSub.pbtxt
index 99e5c4908b..67346f051e 100644
--- a/tensorflow/core/api_def/base_api/api_def_ScatterNdSub.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ScatterNdSub.pbtxt
@@ -66,7 +66,7 @@ The resulting update to ref would look like this:
[1, -9, 3, -6, -4, 6, 7, -4]
-See @{tf.scatter_nd} for more details about how to make updates to
+See `tf.scatter_nd` for more details about how to make updates to
slices.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_ScatterNdUpdate.pbtxt b/tensorflow/core/api_def/base_api/api_def_ScatterNdUpdate.pbtxt
index cb57c171b9..1a75e67c0c 100644
--- a/tensorflow/core/api_def/base_api/api_def_ScatterNdUpdate.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_ScatterNdUpdate.pbtxt
@@ -68,7 +68,7 @@ The resulting update to ref would look like this:
[1, 11, 3, 10, 9, 6, 7, 12]
-See @{tf.scatter_nd} for more details about how to make updates to
+See `tf.scatter_nd` for more details about how to make updates to
slices.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_SegmentMax.pbtxt b/tensorflow/core/api_def/base_api/api_def_SegmentMax.pbtxt
index 5e2912fcdd..35f55fe106 100644
--- a/tensorflow/core/api_def/base_api/api_def_SegmentMax.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SegmentMax.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the maximum along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Computes a tensor such that
\\(output_i = \max_j(data_j)\\) where `max` is over `j` such
diff --git a/tensorflow/core/api_def/base_api/api_def_SegmentMean.pbtxt b/tensorflow/core/api_def/base_api/api_def_SegmentMean.pbtxt
index a7d85b3f4e..70a07d9b4c 100644
--- a/tensorflow/core/api_def/base_api/api_def_SegmentMean.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SegmentMean.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the mean along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Computes a tensor such that
\\(output_i = \frac{\sum_j data_j}{N}\\) where `mean` is
diff --git a/tensorflow/core/api_def/base_api/api_def_SegmentMin.pbtxt b/tensorflow/core/api_def/base_api/api_def_SegmentMin.pbtxt
index 74fc598218..b2e3eece38 100644
--- a/tensorflow/core/api_def/base_api/api_def_SegmentMin.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SegmentMin.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the minimum along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Computes a tensor such that
\\(output_i = \min_j(data_j)\\) where `min` is over `j` such
diff --git a/tensorflow/core/api_def/base_api/api_def_SegmentProd.pbtxt b/tensorflow/core/api_def/base_api/api_def_SegmentProd.pbtxt
index 4c4363e524..7bac02e23d 100644
--- a/tensorflow/core/api_def/base_api/api_def_SegmentProd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SegmentProd.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the product along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Computes a tensor such that
\\(output_i = \prod_j data_j\\) where the product is over `j` such
diff --git a/tensorflow/core/api_def/base_api/api_def_SegmentSum.pbtxt b/tensorflow/core/api_def/base_api/api_def_SegmentSum.pbtxt
index 583ab3904f..a73306a892 100644
--- a/tensorflow/core/api_def/base_api/api_def_SegmentSum.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SegmentSum.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the sum along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Computes a tensor such that
\\(output_i = \sum_j data_j\\) where sum is over `j` such
diff --git a/tensorflow/core/api_def/base_api/api_def_SparseSegmentMean.pbtxt b/tensorflow/core/api_def/base_api/api_def_SparseSegmentMean.pbtxt
index 866e04e97b..138a6366c8 100644
--- a/tensorflow/core/api_def/base_api/api_def_SparseSegmentMean.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SparseSegmentMean.pbtxt
@@ -21,8 +21,9 @@ END
}
summary: "Computes the mean along sparse segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
diff --git a/tensorflow/core/api_def/base_api/api_def_SparseSegmentMeanWithNumSegments.pbtxt b/tensorflow/core/api_def/base_api/api_def_SparseSegmentMeanWithNumSegments.pbtxt
index af4bc75fa0..b8073d88ac 100644
--- a/tensorflow/core/api_def/base_api/api_def_SparseSegmentMeanWithNumSegments.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SparseSegmentMeanWithNumSegments.pbtxt
@@ -30,7 +30,8 @@ END
Like `SparseSegmentMean`, but allows missing ids in `segment_ids`. If an id is
misisng, the `output` tensor at that position will be zeroed.
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtN.pbtxt b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtN.pbtxt
index 194bcea726..945bbdcf62 100644
--- a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtN.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtN.pbtxt
@@ -23,7 +23,8 @@ END
description: <<END
N is the size of the segment being reduced.
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtNWithNumSegments.pbtxt b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtNWithNumSegments.pbtxt
index 8b502928a5..ff328c8a61 100644
--- a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtNWithNumSegments.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSqrtNWithNumSegments.pbtxt
@@ -32,7 +32,8 @@ N is the size of the segment being reduced.
Like `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is
misisng, the `output` tensor at that position will be zeroed.
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
END
}
diff --git a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSum.pbtxt b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSum.pbtxt
index dfd50bf273..a68e14607f 100644
--- a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSum.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSum.pbtxt
@@ -21,8 +21,9 @@ END
}
summary: "Computes the sum along sparse segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
diff --git a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSumWithNumSegments.pbtxt b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSumWithNumSegments.pbtxt
index 3bc16577ff..aa5c1fc8d0 100644
--- a/tensorflow/core/api_def/base_api/api_def_SparseSegmentSumWithNumSegments.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_SparseSegmentSumWithNumSegments.pbtxt
@@ -30,8 +30,9 @@ END
Like `SparseSegmentSum`, but allows missing ids in `segment_ids`. If an id is
misisng, the `output` tensor at that position will be zeroed.
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
For example:
diff --git a/tensorflow/core/api_def/base_api/api_def_StaticRegexReplace.pbtxt b/tensorflow/core/api_def/base_api/api_def_StaticRegexReplace.pbtxt
new file mode 100644
index 0000000000..e382bcec81
--- /dev/null
+++ b/tensorflow/core/api_def/base_api/api_def_StaticRegexReplace.pbtxt
@@ -0,0 +1,26 @@
+op {
+ graph_op_name: "StaticRegexReplace"
+ in_arg {
+ name: "input"
+ description: "The text to be processed."
+ }
+ out_arg {
+ name: "output"
+ description: "The text after applying pattern and rewrite."
+ }
+ attr {
+ name: "pattern"
+ description: "The regular expression to match the input."
+ }
+ attr {
+ name: "rewrite"
+ description: "The rewrite to be applied to the matched expresion."
+ }
+ attr {
+ name: "replace_global"
+ description: "If True, the replacement is global, otherwise the replacement\nis done only on the first match."
+ }
+ summary: "Replaces the match of pattern in input with rewrite."
+ description: "It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)"
+ visibility: HIDDEN
+}
diff --git a/tensorflow/core/api_def/base_api/api_def_StringLength.pbtxt b/tensorflow/core/api_def/base_api/api_def_StringLength.pbtxt
new file mode 100644
index 0000000000..cc21ddc815
--- /dev/null
+++ b/tensorflow/core/api_def/base_api/api_def_StringLength.pbtxt
@@ -0,0 +1,20 @@
+op {
+ graph_op_name: "StringLength"
+ in_arg {
+ name: "input"
+ description: <<END
+The string for which to compute the length.
+END
+ }
+ out_arg {
+ name: "output"
+ description: <<END
+Integer tensor that has the same shape as `input`. The output contains the
+element-wise string lengths of `input`.
+END
+ }
+ summary: "String lengths of `input`."
+ description: <<END
+Computes the length of each string given in the input tensor.
+END
+}
diff --git a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMax.pbtxt b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMax.pbtxt
index 4ca6780c95..907c6d2022 100644
--- a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMax.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMax.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the maximum along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
diff --git a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMin.pbtxt b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMin.pbtxt
index 55ea69b5dd..37dd973b23 100644
--- a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMin.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentMin.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the minimum along segments of a tensor."
description: <<END
-Read @{$math_ops#segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)
+for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
diff --git a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentProd.pbtxt b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentProd.pbtxt
index 577ff53d60..efbc023705 100644
--- a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentProd.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentProd.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the product along segments of a tensor."
description: <<END
-Read @{$math_ops#segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)
+for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
diff --git a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentSum.pbtxt b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentSum.pbtxt
index 9aeabd030d..a8874950eb 100644
--- a/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentSum.pbtxt
+++ b/tensorflow/core/api_def/base_api/api_def_UnsortedSegmentSum.pbtxt
@@ -16,8 +16,9 @@ END
}
summary: "Computes the sum along segments of a tensor."
description: <<END
-Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-segments.
+Read
+[the section on segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+for an explanation of segments.
Computes a tensor such that
\\(output[i] = sum_{j...} data[j...]\\) where the sum is over tuples `j...` such
diff --git a/tensorflow/core/api_def/python_api/api_def_DivNoNan.pbtxt b/tensorflow/core/api_def/python_api/api_def_DivNoNan.pbtxt
new file mode 100644
index 0000000000..1bf3fba3c6
--- /dev/null
+++ b/tensorflow/core/api_def/python_api/api_def_DivNoNan.pbtxt
@@ -0,0 +1,4 @@
+op {
+ graph_op_name: "DivNoNan"
+ visibility: HIDDEN
+}
diff --git a/tensorflow/core/api_def/python_api/api_def_ScatterSub.pbtxt b/tensorflow/core/api_def/python_api/api_def_ScatterSub.pbtxt
new file mode 100644
index 0000000000..f1a4cccbc3
--- /dev/null
+++ b/tensorflow/core/api_def/python_api/api_def_ScatterSub.pbtxt
@@ -0,0 +1,4 @@
+op {
+ graph_op_name: "ScatterSub"
+ visibility: HIDDEN
+}
diff --git a/tensorflow/core/api_def/python_api/api_def_StringLength.pbtxt b/tensorflow/core/api_def/python_api/api_def_StringLength.pbtxt
new file mode 100644
index 0000000000..01c02e1f70
--- /dev/null
+++ b/tensorflow/core/api_def/python_api/api_def_StringLength.pbtxt
@@ -0,0 +1,6 @@
+op {
+ graph_op_name: "StringLength"
+ endpoint {
+ name: "strings.length"
+ }
+}
diff --git a/tensorflow/core/common_runtime/collective_rma_local.h b/tensorflow/core/common_runtime/collective_rma_local.h
index dbb2e67c7d..44408438b9 100644
--- a/tensorflow/core/common_runtime/collective_rma_local.h
+++ b/tensorflow/core/common_runtime/collective_rma_local.h
@@ -34,7 +34,7 @@ class CollectiveRemoteAccessLocal : public PerStepCollectiveRemoteAccess {
virtual ~CollectiveRemoteAccessLocal() {}
- void StartAbort(const Status& s);
+ void StartAbort(const Status& s) override;
void RecvFromPeer(const string& peer_device, const string& peer_task,
bool peer_is_local, const string& key, Device* to_device,
diff --git a/tensorflow/core/common_runtime/direct_session.cc b/tensorflow/core/common_runtime/direct_session.cc
index 0695278c0d..bf1d78ec65 100644
--- a/tensorflow/core/common_runtime/direct_session.cc
+++ b/tensorflow/core/common_runtime/direct_session.cc
@@ -602,7 +602,7 @@ Status DirectSession::RunInternal(int64 step_id, const RunOptions& run_options,
if (tracer) {
TF_RETURN_IF_ERROR(tracer->Stop());
- TF_RETURN_IF_ERROR(tracer->Collect(args.stats_collector));
+ TF_RETURN_IF_ERROR(tracer->Collect(run_state.collector.get()));
}
{
@@ -618,8 +618,8 @@ Status DirectSession::RunInternal(int64 step_id, const RunOptions& run_options,
&session_state_));
}
- if (args.stats_collector) {
- args.stats_collector->Finalize();
+ if (run_state.collector) {
+ run_state.collector->Finalize();
}
// Build and return the cost model as instructed.
@@ -634,7 +634,7 @@ Status DirectSession::RunInternal(int64 step_id, const RunOptions& run_options,
}
mutex_lock l(executor_lock_);
- args.stats_collector->BuildCostModel(&cost_model_manager_, device_to_graph);
+ run_state.collector->BuildCostModel(&cost_model_manager_, device_to_graph);
// annotate stats onto cost graph.
CostGraphDef* cost_graph = run_metadata->mutable_cost_graph();
diff --git a/tensorflow/core/common_runtime/eager/attr_builder.cc b/tensorflow/core/common_runtime/eager/attr_builder.cc
index 92307d78f2..cf1cd4134e 100644
--- a/tensorflow/core/common_runtime/eager/attr_builder.cc
+++ b/tensorflow/core/common_runtime/eager/attr_builder.cc
@@ -103,7 +103,6 @@ Status AttrTypeMapForOp(const char* op_name, const AttrTypeMap** out) {
return *this; \
}
-DEFINE_SET_ATTR(StringPiece, string_attrs_);
DEFINE_SET_ATTR(float, float_attrs_);
DEFINE_SET_ATTR(int, int_attrs_);
DEFINE_SET_ATTR(bool, bool_attrs_);
@@ -119,9 +118,6 @@ AttrBuilder& AttrBuilder::NumInputs(int n) {
void AttrBuilder::FillAttrValueMap(AttrValueMap* m,
bool include_those_in_node_def) const {
- for (const auto& p : string_attrs_) {
- SetInAttrValueMap(m, p.first, p.second);
- }
for (const auto& p : int_attrs_) {
SetInAttrValueMap(m, p.first, p.second);
}
@@ -211,10 +207,6 @@ tensorflow::Fprint128 AttrBuilder::CacheKey(const string& device) const {
// not been called.
if (node_def_finalized_) return f;
}
- for (const auto& p : string_attrs_) {
- CombineUnordered(
- CacheKeyHelper(p.first, tensorflow::Fingerprint128(p.second)), &f);
- }
for (const auto& p : int_attrs_) {
CombineUnordered(CacheKeyHelper(p.first, static_cast<uint64>(p.second)),
&f);
diff --git a/tensorflow/core/common_runtime/eager/attr_builder.h b/tensorflow/core/common_runtime/eager/attr_builder.h
index 929b1b8296..fc50bed3c0 100644
--- a/tensorflow/core/common_runtime/eager/attr_builder.h
+++ b/tensorflow/core/common_runtime/eager/attr_builder.h
@@ -131,7 +131,6 @@ class AttrBuilder {
}
}
- AttrVec<StringPiece> string_attrs_;
AttrVec<int> int_attrs_;
AttrVec<float> float_attrs_;
AttrVec<bool> bool_attrs_;
@@ -143,8 +142,6 @@ class AttrBuilder {
}; // namespace tensorflow
template <>
-AttrBuilder& AttrBuilder::Set(StringPiece attr_name, StringPiece&& value);
-template <>
AttrBuilder& AttrBuilder::Set(StringPiece attr_name, int&& value);
template <>
AttrBuilder& AttrBuilder::Set(StringPiece attr_name, float&& value);
diff --git a/tensorflow/core/common_runtime/eager/context.h b/tensorflow/core/common_runtime/eager/context.h
index ebaf500bb3..9835b19511 100644
--- a/tensorflow/core/common_runtime/eager/context.h
+++ b/tensorflow/core/common_runtime/eager/context.h
@@ -134,8 +134,6 @@ class EagerContext {
Rendezvous* GetRendezvous() { return rendezvous_; }
- mutex* FunctionsMu() { return &functions_mu_; }
-
const tensorflow::DeviceMgr* local_device_mgr() const {
return (local_device_manager_ != nullptr) ? local_device_manager_.get()
: local_unowned_device_manager_;
@@ -208,6 +206,7 @@ class EagerContext {
// Only one of the below is set.
std::unique_ptr<DeviceMgr> local_device_manager_;
DeviceMgr* local_unowned_device_manager_;
+ std::unique_ptr<DeviceMgr> remote_device_manager_;
// Devices owned by device_manager
std::vector<Device*> devices_;
@@ -255,7 +254,6 @@ class EagerContext {
#ifndef __ANDROID__
void CloseRemoteContexts();
- std::unique_ptr<DeviceMgr> remote_device_manager_;
// The server_ is not const since we release it when the context is destroyed.
// Therefore the server_ object is not marked as const (even though it should
diff --git a/tensorflow/core/common_runtime/eager/execute.cc b/tensorflow/core/common_runtime/eager/execute.cc
index 8eaa6e4429..46065f399c 100644
--- a/tensorflow/core/common_runtime/eager/execute.cc
+++ b/tensorflow/core/common_runtime/eager/execute.cc
@@ -300,12 +300,6 @@ Status EagerLocalExecute(EagerOperation* op,
<< device->name();
}
kernel = new KernelAndDevice(ctx->GetRendezvous());
- // Knowledge of the implementation of Init (and in-turn
- // FunctionLibraryRuntime::CreateKernel) tells us that ctx->func_lib_def
- // will be accessed, so grab on to the lock.
- // See WARNING comment in Execute (before kernel->Run) - would be nice to
- // rework to avoid this subtlety.
- tf_shared_lock l(*ctx->FunctionsMu());
auto* flr = ctx->func_lib(device);
if (flr == nullptr) {
@@ -646,15 +640,8 @@ Status EagerExecute(EagerContext* ctx, Device* device,
TF_RETURN_IF_ERROR(op_inputs[i]->Tensor(&input_tensor));
inputs[i] = *input_tensor;
}
- // WARNING: kernel->Run utilizes the FunctionLibraryRuntime
- // (ctx->func_lib(device)), which in turn holds a pointer to func_lib_def.
- // But knowledge of the implementation
- // of FunctionLibraryRuntime tells us that func_lib_def is not accessed by
- // FunctionLibraryRuntime::Run(), so there is no thread-safety concern here.
- // This is quite subtle. Re-work things to make this better? (Would it make
- // sense for FunctionLibraryRuntime to ensure thread-safe access to
- // FunctionLibraryDefinition?). TODO(apassos) figure out how to record stats
- // for ops which are a part of functions.
+ // TODO(apassos) figure out how to record stats for ops which are a part of
+ // functions.
// TODO(agarwal): change Run to take vector of handles ?
ScopedStepContainer* container = ctx->StepContainer();
if (container == nullptr) {
diff --git a/tensorflow/core/common_runtime/eager/kernel_and_device.h b/tensorflow/core/common_runtime/eager/kernel_and_device.h
index 751cf687b2..0ef419cbaa 100644
--- a/tensorflow/core/common_runtime/eager/kernel_and_device.h
+++ b/tensorflow/core/common_runtime/eager/kernel_and_device.h
@@ -49,13 +49,6 @@ class KernelAndDevice {
//
// The provided FunctionLibraryRuntime MUST outlive all calls to
// Run() on the returned KernelAndDevice.
- //
- // TODO(ashankar): Figure out thread-safety concerns around
- // FunctionLibraryRuntime (in particular, how the underlying
- // FunctionLibraryDefinition might be mutated by another thread as new
- // functions are registered with it). Conservatively, thread-safe usage of
- // the FunctionLibraryRuntime is pushed on to the caller (see locking in
- // c_api.cc).
static Status Init(const NodeDef& ndef, FunctionLibraryRuntime* flib,
std::function<void(std::function<void()>)>* runner,
KernelAndDevice* out);
diff --git a/tensorflow/core/common_runtime/executor.cc b/tensorflow/core/common_runtime/executor.cc
index c2fac4c2c8..63ed860b9f 100644
--- a/tensorflow/core/common_runtime/executor.cc
+++ b/tensorflow/core/common_runtime/executor.cc
@@ -72,141 +72,58 @@ bool IsInitializationOp(const Node* node) {
return node->op_def().allows_uninitialized_input();
}
-// Sets the timeline_label field of *node_stats, using data from *node.
-// Returns true iff the node is a transfer node.
-// TODO(tucker): merge with the DetailText function in session.cc
-// in a common location.
-bool SetTimelineLabel(const Node* node, NodeExecStatsWrapper* stats) {
- bool is_transfer_node = false;
- if (!stats) {
- return is_transfer_node;
- }
- string memory;
- for (auto& all : stats->stats()->memory()) {
- int64 tot = all.total_bytes();
- if (tot >= 0.1 * 1048576.0) {
- int64 peak = all.peak_bytes();
- if (peak > 0) {
- memory =
- strings::StrCat(memory, "[", all.allocator_name(),
- strings::Printf(" %.1fMB %.1fMB] ", tot / 1048576.0,
- peak / 1048576.0));
- } else {
- memory = strings::StrCat(memory, "[", all.allocator_name(),
- strings::Printf(" %.1fMB] ", tot / 1048576.0));
- }
- }
- }
- const AttrSlice attrs = node->attrs();
- string text;
- if (IsSend(node)) {
- string tensor_name;
- TF_CHECK_OK(GetNodeAttr(attrs, "tensor_name", &tensor_name));
- string recv_device;
- TF_CHECK_OK(GetNodeAttr(attrs, "recv_device", &recv_device));
- text = strings::StrCat(memory, node->name(), " = ", node->type_string(),
- "(", tensor_name, " @", recv_device);
- is_transfer_node = true;
- } else if (IsRecv(node)) {
- string tensor_name;
- TF_CHECK_OK(GetNodeAttr(attrs, "tensor_name", &tensor_name));
- string send_device;
- TF_CHECK_OK(GetNodeAttr(attrs, "send_device", &send_device));
- text = strings::StrCat(memory, node->name(), " = ", node->type_string(),
- "(", tensor_name, " @", send_device);
- is_transfer_node = true;
- } else {
- text =
- strings::StrCat(memory, node->name(), " = ", node->type_string(), "(",
- str_util::Join(node->requested_inputs(), ", "), ")");
- }
- stats->stats()->set_timeline_label(text);
- return is_transfer_node;
-}
-
// Helper routines for collecting step stats.
namespace nodestats {
-inline int64 NowInUsec() { return Env::Default()->NowMicros(); }
inline int64 NowInNsec() { return Env::Default()->NowNanos(); }
-void SetScheduled(NodeExecStatsWrapper* stats, int64 nanos) {
+void SetScheduled(NodeExecStatsWrapper* stats, int64 micros) {
if (!stats) return;
- stats->stats()->set_scheduled_micros(nanos / EnvTime::kMicrosToNanos);
- stats->stats()->set_scheduled_nanos(nanos);
+ stats->SetScheduled(micros * EnvTime::kMicrosToNanos);
}
void SetAllStart(NodeExecStatsWrapper* stats) {
if (!stats) return;
- int64 now_nanos = NowInNsec();
- stats->stats()->set_all_start_micros(now_nanos / EnvTime::kMicrosToNanos);
- stats->stats()->set_all_start_nanos(now_nanos);
+ stats->RecordExecutorStarted();
}
void SetOpStart(NodeExecStatsWrapper* stats) {
if (!stats) return;
- NodeExecStats* nt = stats->stats();
- DCHECK_NE(nt->all_start_micros(), 0);
- DCHECK_NE(nt->all_start_nanos(), 0);
- int64 now_nanos = NowInNsec();
- nt->set_op_start_rel_micros(now_nanos / EnvTime::kMicrosToNanos -
- nt->all_start_micros());
- nt->set_op_start_rel_nanos(now_nanos - nt->all_start_nanos());
+ stats->RecordComputeStarted();
}
void SetOpEnd(NodeExecStatsWrapper* stats) {
if (!stats) return;
- NodeExecStats* nt = stats->stats();
- DCHECK_NE(nt->all_start_micros(), 0);
- DCHECK_NE(nt->all_start_nanos(), 0);
- int64 now_nanos = NowInNsec();
- nt->set_op_end_rel_micros(now_nanos / EnvTime::kMicrosToNanos -
- nt->all_start_micros());
- nt->set_op_end_rel_nanos(now_nanos - nt->all_start_nanos());
+ stats->RecordComputeEnded();
}
void SetAllEnd(NodeExecStatsWrapper* stats) {
if (!stats) return;
- NodeExecStats* nt = stats->stats();
- DCHECK_NE(nt->all_start_micros(), 0);
- DCHECK_NE(nt->all_start_nanos(), 0);
- int64 now_nanos = NowInNsec();
- nt->set_all_end_rel_micros(now_nanos / EnvTime::kMicrosToNanos -
- nt->all_start_micros());
- nt->set_all_end_rel_nanos(now_nanos - nt->all_start_nanos());
+ stats->RecordExecutorEnded();
}
void SetOutput(NodeExecStatsWrapper* stats, int slot, const Tensor* v) {
if (!stats) return;
- DCHECK(v);
- NodeOutput* no = stats->stats()->add_output();
- no->set_slot(slot);
- v->FillDescription(no->mutable_tensor_description());
+ stats->SetOutput(slot, v);
}
void SetMemory(NodeExecStatsWrapper* stats, OpKernelContext* ctx) {
if (!stats) return;
-
- for (const auto& allocator_pair : ctx->wrapped_allocators()) {
- stats->AddAllocation(allocator_pair.first, allocator_pair.second);
- }
- auto* ms = stats->stats()->mutable_memory_stats();
- ms->set_temp_memory_size(ctx->temp_memory_allocated());
- for (const auto& alloc_id : ctx->persistent_alloc_ids()) {
- ms->mutable_persistent_tensor_alloc_ids()->Add(alloc_id);
- }
- ms->set_persistent_memory_size(ctx->persistent_memory_allocated());
+ stats->SetMemory(ctx);
}
void SetReferencedTensors(NodeExecStatsWrapper* stats,
const TensorReferenceVector& tensors) {
if (!stats) return;
- // be careful not to increment the reference count on any tensor
- // while recording the information
- for (size_t i = 0; i < tensors.size(); ++i) {
- AllocationDescription* description =
- stats->stats()->add_referenced_tensor();
- tensors.at(i).FillDescription(description);
+ stats->SetReferencedTensors(tensors);
+}
+
+// Sets the timeline_label field of *stats, using data from *node.
+// Returns true iff the node is a transfer node.
+bool SetTimelineLabel(const Node* node, NodeExecStatsWrapper* stats) {
+ if (!stats) {
+ return false;
}
+ return stats->SetTimelineLabel(node);
}
} // namespace nodestats
@@ -1319,7 +1236,7 @@ class ExecutorState {
TensorStore* tensor_store_;
// Step-local container.
ScopedStepContainer* step_container_;
- StepStatsCollector* stats_collector_;
+ StepStatsCollectorInterface* const stats_collector_;
// QUESTION: Make it a checkpoint::TensorSliceReaderCacheWrapper
// instead of a pointer? (avoids having to delete).
checkpoint::TensorSliceReaderCacheWrapper* slice_reader_cache_;
@@ -1694,8 +1611,7 @@ void ExecutorState::Process(TaggedNode tagged_node, int64 scheduled_nsec) {
if (stats_collector_ && !tagged_node.is_dead) {
// track allocations if and only if we are collecting statistics
params.track_allocations = true;
- stats = new NodeExecStatsWrapper;
- stats->stats()->set_node_name(node->name());
+ stats = new NodeExecStatsWrapper(node->name());
nodestats::SetScheduled(stats, scheduled_nsec);
nodestats::SetAllStart(stats);
}
@@ -2165,7 +2081,8 @@ bool ExecutorState::NodeDone(const Status& s, const Node* node,
NodeExecStatsWrapper* stats,
TaggedNodeReadyQueue* inline_ready) {
nodestats::SetAllEnd(stats);
- if (stats_collector_ != nullptr && !SetTimelineLabel(node, stats)) {
+ if (stats_collector_ != nullptr &&
+ !nodestats::SetTimelineLabel(node, stats)) {
// Only record non-transfer nodes.
// Transfers 'stats' ownership to 'stats_collector_'.
stats_collector_->Save(impl_->params_.device->name(), stats);
diff --git a/tensorflow/core/common_runtime/executor.h b/tensorflow/core/common_runtime/executor.h
index cd01b43aea..a238a6763a 100644
--- a/tensorflow/core/common_runtime/executor.h
+++ b/tensorflow/core/common_runtime/executor.h
@@ -83,7 +83,7 @@ class Executor {
struct Args {
int64 step_id = 0;
Rendezvous* rendezvous = nullptr;
- StepStatsCollector* stats_collector = nullptr;
+ StepStatsCollectorInterface* stats_collector = nullptr;
CallFrameInterface* call_frame = nullptr;
CancellationManager* cancellation_manager = nullptr;
SessionState* session_state = nullptr;
diff --git a/tensorflow/core/common_runtime/graph_execution_state.cc b/tensorflow/core/common_runtime/graph_execution_state.cc
index 9c9eacb5b5..c23b7d3699 100644
--- a/tensorflow/core/common_runtime/graph_execution_state.cc
+++ b/tensorflow/core/common_runtime/graph_execution_state.cc
@@ -643,10 +643,9 @@ Status GraphExecutionState::OptimizeGraph(
for (const FunctionDef& fdef : new_graph.library().function()) {
const string& func_name = fdef.signature().name();
- if ((*optimized_flib)->Find(func_name)) {
+ if ((*optimized_flib)->Contains(func_name)) {
VLOG(3) << "Replace function: name=" << func_name;
- TF_RETURN_IF_ERROR((*optimized_flib)->RemoveFunction(func_name));
- TF_RETURN_IF_ERROR((*optimized_flib)->AddFunctionDef(fdef));
+ TF_RETURN_IF_ERROR((*optimized_flib)->ReplaceFunction(func_name, fdef));
} else {
VLOG(3) << "Add new function: name=" << func_name;
TF_RETURN_IF_ERROR((*optimized_flib)->AddFunctionDef(fdef));
diff --git a/tensorflow/core/common_runtime/mkl_cpu_allocator.h b/tensorflow/core/common_runtime/mkl_cpu_allocator.h
index 94e10dbfa2..99bd43e090 100644
--- a/tensorflow/core/common_runtime/mkl_cpu_allocator.h
+++ b/tensorflow/core/common_runtime/mkl_cpu_allocator.h
@@ -28,7 +28,7 @@ limitations under the License.
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/mem.h"
-#ifndef DO_NOT_USE_ML
+#ifndef INTEL_MKL_DNN_ONLY
#include "i_malloc.h"
#endif
@@ -98,7 +98,7 @@ class MklCPUAllocator : public VisitableAllocator {
VLOG(1) << "MklCPUAllocator: Setting max_mem_bytes: " << max_mem_bytes;
allocator_ = new BFCAllocator(new MklSubAllocator, max_mem_bytes,
kAllowGrowth, kName);
-#ifndef DO_NOT_USE_ML
+#ifndef INTEL_MKL_DNN_ONLY
// For redirecting all allocations from MKL to this allocator
// From: http://software.intel.com/en-us/node/528565
i_malloc = MallocHook;
diff --git a/tensorflow/core/common_runtime/step_stats_collector.cc b/tensorflow/core/common_runtime/step_stats_collector.cc
index af6880c6b3..9c2510e6a9 100644
--- a/tensorflow/core/common_runtime/step_stats_collector.cc
+++ b/tensorflow/core/common_runtime/step_stats_collector.cc
@@ -16,12 +16,16 @@ limitations under the License.
#include "tensorflow/core/common_runtime/step_stats_collector.h"
#include "tensorflow/core/common_runtime/costmodel_manager.h"
#include "tensorflow/core/framework/allocation_description.pb.h"
+#include "tensorflow/core/framework/op_kernel.h"
+#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_description.pb.h"
#include "tensorflow/core/framework/tracking_allocator.h"
#include "tensorflow/core/graph/costmodel.h"
+#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/scanner.h"
+#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
@@ -36,11 +40,89 @@ struct AllocStats {
};
} // namespace
-NodeExecStatsWrapper::NodeExecStatsWrapper()
- : NodeExecStatsWrapper(new NodeExecStats) {}
+NodeExecStatsWrapper::NodeExecStatsWrapper(const string& node_name)
+ : NodeExecStatsWrapper(new NodeExecStats) {
+ stats_->set_node_name(node_name);
+}
NodeExecStatsWrapper::NodeExecStatsWrapper(NodeExecStats* stats)
: stats_(stats) {}
+void NodeExecStatsWrapper::SetOutput(int slot, const Tensor* v) {
+ DCHECK(v);
+ NodeOutput* no = stats_->add_output();
+ no->set_slot(slot);
+ v->FillDescription(no->mutable_tensor_description());
+}
+
+void NodeExecStatsWrapper::SetMemory(OpKernelContext* ctx) {
+ for (const auto& allocator_pair : ctx->wrapped_allocators()) {
+ AddAllocation(allocator_pair.first, allocator_pair.second);
+ }
+ auto* ms = stats_->mutable_memory_stats();
+ ms->set_temp_memory_size(ctx->temp_memory_allocated());
+ for (const auto& alloc_id : ctx->persistent_alloc_ids()) {
+ ms->mutable_persistent_tensor_alloc_ids()->Add(alloc_id);
+ }
+ ms->set_persistent_memory_size(ctx->persistent_memory_allocated());
+}
+
+void NodeExecStatsWrapper::SetReferencedTensors(
+ const TensorReferenceVector& tensors) {
+ // be careful not to increment the reference count on any tensor
+ // while recording the information
+ for (size_t i = 0; i < tensors.size(); ++i) {
+ AllocationDescription* description = stats_->add_referenced_tensor();
+ tensors.at(i).FillDescription(description);
+ }
+}
+
+// TODO(tucker): merge with the DetailText function in session.cc
+// in a common location.
+bool NodeExecStatsWrapper::SetTimelineLabel(const Node* node) {
+ bool is_transfer_node = false;
+ string memory;
+ for (auto& all : stats_->memory()) {
+ int64 tot = all.total_bytes();
+ if (tot >= 0.1 * 1048576.0) {
+ int64 peak = all.peak_bytes();
+ if (peak > 0) {
+ memory =
+ strings::StrCat(memory, "[", all.allocator_name(),
+ strings::Printf(" %.1fMB %.1fMB] ", tot / 1048576.0,
+ peak / 1048576.0));
+ } else {
+ memory = strings::StrCat(memory, "[", all.allocator_name(),
+ strings::Printf(" %.1fMB] ", tot / 1048576.0));
+ }
+ }
+ }
+ const AttrSlice attrs = node->attrs();
+ string text;
+ if (IsSend(node)) {
+ string tensor_name;
+ TF_CHECK_OK(GetNodeAttr(attrs, "tensor_name", &tensor_name));
+ string recv_device;
+ TF_CHECK_OK(GetNodeAttr(attrs, "recv_device", &recv_device));
+ text = strings::StrCat(memory, node->name(), " = ", node->type_string(),
+ "(", tensor_name, " @", recv_device);
+ is_transfer_node = true;
+ } else if (IsRecv(node)) {
+ string tensor_name;
+ TF_CHECK_OK(GetNodeAttr(attrs, "tensor_name", &tensor_name));
+ string send_device;
+ TF_CHECK_OK(GetNodeAttr(attrs, "send_device", &send_device));
+ text = strings::StrCat(memory, node->name(), " = ", node->type_string(),
+ "(", tensor_name, " @", send_device);
+ is_transfer_node = true;
+ } else {
+ text =
+ strings::StrCat(memory, node->name(), " = ", node->type_string(), "(",
+ str_util::Join(node->requested_inputs(), ", "), ")");
+ }
+ stats_->set_timeline_label(text);
+ return is_transfer_node;
+}
+
void NodeExecStatsWrapper::AddAllocation(
Allocator* allocator, TrackingAllocator* tracking_allocator) {
AllocatorMemoryUsed* memory = stats_->add_memory();
diff --git a/tensorflow/core/common_runtime/step_stats_collector.h b/tensorflow/core/common_runtime/step_stats_collector.h
index 996dbb59bc..7206fbf427 100644
--- a/tensorflow/core/common_runtime/step_stats_collector.h
+++ b/tensorflow/core/common_runtime/step_stats_collector.h
@@ -12,14 +12,16 @@ 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.
==============================================================================*/
-#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_STEP_STATS_COLLECTOR_H_
-#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_STEP_STATS_COLLECTOR_H_
+#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_STEP_STATS_COLLECTOR_H_
+#define TENSORFLOW_CORE_COMMON_RUNTIME_STEP_STATS_COLLECTOR_H_
#include <memory>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/framework/step_stats.pb.h"
+#include "tensorflow/core/framework/tensor_reference.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
+#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
@@ -30,42 +32,127 @@ class Allocator;
class AllocatorMemoryUsed;
class CostModelManager;
class Graph;
+class Node;
class NodeExecStats;
+class OpKernelContext;
class StepStats;
+class Tensor;
class TrackingAllocator;
// Wraps NodeExecStats and adds allocation to it.
class NodeExecStatsWrapper {
public:
- NodeExecStatsWrapper();
+ NodeExecStatsWrapper(const string& node_name);
// Owns 'stats'.
NodeExecStatsWrapper(NodeExecStats* stats);
// Destructor calls Finalize() to release the TrackingAllocators.
~NodeExecStatsWrapper() { Finalize(); }
- NodeExecStats* stats() { return stats_.get(); }
-
- // "Does not take ownership of the 'allocator'.
- // Transfers ownership of the 'tracking_allocator' to *this."
- void AddAllocation(Allocator* allocator,
- TrackingAllocator* tracking_allocator);
+ // Records the absolute time in nanoseconds at which this node became
+ // runnable (i.e. was scheduled for execution).
+ void SetScheduled(int64 nanos) {
+ stats_->set_scheduled_micros(nanos / EnvTime::kMicrosToNanos);
+ stats_->set_scheduled_nanos(nanos);
+ }
+
+ // Called immediately after this node starts being processed by the executor.
+ void RecordExecutorStarted() {
+ int64 now_nanos = Env::Default()->NowNanos();
+ stats_->set_all_start_micros(now_nanos / EnvTime::kMicrosToNanos);
+ stats_->set_all_start_nanos(now_nanos);
+ }
+
+ // Called immediately before this node's `Compute()` or `ComputeAsync()`
+ // method is called.
+ void RecordComputeStarted() {
+ int64 now_nanos = Env::Default()->NowNanos();
+ DCHECK_NE(stats_->all_start_micros(), 0);
+ DCHECK_NE(stats_->all_start_nanos(), 0);
+ stats_->set_op_start_rel_micros(now_nanos / EnvTime::kMicrosToNanos -
+ stats_->all_start_micros());
+ stats_->set_op_start_rel_nanos(now_nanos - stats_->all_start_nanos());
+ }
+
+ // Called immediately after this node's `Compute()` method returned (or, for
+ // asynchronous operations, the callback passed to its `ComputeAsync()` method
+ // was called).
+ void RecordComputeEnded() {
+ int64 now_nanos = Env::Default()->NowNanos();
+ DCHECK_NE(stats_->all_start_micros(), 0);
+ DCHECK_NE(stats_->all_start_nanos(), 0);
+ stats_->set_op_end_rel_micros(now_nanos / EnvTime::kMicrosToNanos -
+ stats_->all_start_micros());
+ stats_->set_op_end_rel_nanos(now_nanos - stats_->all_start_nanos());
+ }
+
+ // Called immediately after this executor finishes processing this node.
+ void RecordExecutorEnded() {
+ int64 now_nanos = Env::Default()->NowNanos();
+ DCHECK_NE(stats_->all_start_micros(), 0);
+ DCHECK_NE(stats_->all_start_nanos(), 0);
+ stats_->set_all_end_rel_micros(now_nanos / EnvTime::kMicrosToNanos -
+ stats_->all_start_micros());
+ stats_->set_all_end_rel_nanos(now_nanos - stats_->all_start_nanos());
+ }
+
+ // Records information about the tensor produced by this node at the given
+ // output slot.
+ void SetOutput(int slot, const Tensor* v);
+
+ // Records information about the memory allocated during the execution of this
+ // node.
+ void SetMemory(OpKernelContext* ctx);
+
+ // Records information about the tensors that were accessed during the
+ // execution of this node.
+ void SetReferencedTensors(const TensorReferenceVector& tensors);
+
+ // Sets the timeline_label field of the wrapped NodeExecStats, using data
+ // from *node. Returns true iff the node is a transfer node.
+ bool SetTimelineLabel(const Node* node);
private:
friend class StepStatsCollector;
+ NodeExecStats* stats() { return stats_.get(); }
+
// Populates stats_ and releases TrackingAllocator.
void Finalize();
+ // Does not take ownership of the `allocator`.
+ // Takes ownership of `tracking_allocator`.
+ void AddAllocation(Allocator* allocator,
+ TrackingAllocator* tracking_allocator);
+
gtl::InlinedVector<std::pair<AllocatorMemoryUsed*, TrackingAllocator*>, 2>
allocations_;
std::unique_ptr<NodeExecStats> stats_;
};
+// Statistics collection interface for individual node execution.
+//
+// See `StepStatsCollector` for a concrete implementation of this interface
+// that interfaces with the `Session` layer.
+class StepStatsCollectorInterface {
+ public:
+ virtual ~StepStatsCollectorInterface() {}
+
+ // Saves `stats` to the collector.
+ virtual void Save(const string& device, NodeExecStatsWrapper* stats) = 0;
+
+ // Generates a string reporting the currently used memory based
+ // on ResourceExhausted OOM `err` message.
+ // `err` message needs to contain device name and allocator name, e.g.:
+ // "ResourceExhaustedError: OOM when allocating tensor ...
+ // on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc"
+ virtual string ReportAllocsOnResourceExhausted(const string& err) = 0;
+};
+
// StepStatsCollector manages the collection of a StepStats object.
// The StepStats object holds multiple DeviceStats.
// Each DeviceStats object holds multiple NodeExecStats.
-class StepStatsCollector {
+class StepStatsCollector : public StepStatsCollectorInterface {
public:
// Does not take ownership of `ss`.
explicit StepStatsCollector(StepStats* ss);
@@ -80,14 +167,9 @@ class StepStatsCollector {
// Save saves nt to the DeviceStats object associated with device.
// Should be called before Finalize.
void Save(const string& device, NodeExecStats* nt);
- void Save(const string& device, NodeExecStatsWrapper* stats);
+ void Save(const string& device, NodeExecStatsWrapper* stats) override;
- // Generates a string reporting the currently used memory based
- // on ResourceExhausted OOM `err` message.
- // `err` message needs to contain device name and allocator name, E.g.:
- // "ResourceExhaustedError: OOM when allocating tensor ...
- // on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc"
- string ReportAllocsOnResourceExhausted(const string& err);
+ string ReportAllocsOnResourceExhausted(const string& err) override;
// The following 2 Finalize methods populate the StepStats passed
// from the constructor. Calling it more than once won't have any effect.
@@ -112,4 +194,4 @@ class StepStatsCollector {
} // namespace tensorflow
-#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_STEP_STATS_COLLECTOR_H_
+#endif // TENSORFLOW_CORE_COMMON_RUNTIME_STEP_STATS_COLLECTOR_H_
diff --git a/tensorflow/core/common_runtime/sycl/sycl_allocator.h b/tensorflow/core/common_runtime/sycl/sycl_allocator.h
index 550f193332..cc5909de17 100644
--- a/tensorflow/core/common_runtime/sycl/sycl_allocator.h
+++ b/tensorflow/core/common_runtime/sycl/sycl_allocator.h
@@ -17,8 +17,8 @@ limitations under the License.
#error This file must only be included when building TensorFlow with SYCL support
#endif
-#ifndef TENSORFLOW_COMMON_RUNTIME_SYCL_SYCL_ALLOCATOR_H_
-#define TENSORFLOW_COMMON_RUNTIME_SYCL_SYCL_ALLOCATOR_H_
+#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_SYCL_SYCL_ALLOCATOR_H_
+#define TENSORFLOW_CORE_COMMON_RUNTIME_SYCL_SYCL_ALLOCATOR_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/allocator.h"
@@ -72,4 +72,4 @@ class SYCLAllocator : public Allocator {
} // namespace tensorflow
-#endif // TENSORFLOW_COMMON_RUNTIME_SYCL_SYCL_ALLOCATOR_H_
+#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SYCL_SYCL_ALLOCATOR_H_
diff --git a/tensorflow/core/distributed_runtime/eager/eager_service_impl.h b/tensorflow/core/distributed_runtime/eager/eager_service_impl.h
index 5723106aa6..2784c5d26e 100644
--- a/tensorflow/core/distributed_runtime/eager/eager_service_impl.h
+++ b/tensorflow/core/distributed_runtime/eager/eager_service_impl.h
@@ -167,7 +167,7 @@ class EagerServiceImpl {
bool IsStale() {
mutex_lock l(last_accessed_mu_);
- return (destroy_after_micros_ <= 0 ||
+ return (destroy_after_micros_ > 0 &&
(env_->env->NowMicros() - last_accessed_micros_) >
destroy_after_micros_);
}
diff --git a/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc b/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc
index 8a6903be9e..bcd46a4c06 100644
--- a/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc
+++ b/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc
@@ -120,27 +120,8 @@ Status GrpcServer::Init(
master_env_.env = env_;
worker_env_.env = env_;
- SessionOptions sess_opts;
- ConfigProto config = server_def_.default_session_config();
- sess_opts.config = config;
-
- // Configure shared devices between master and worker.
- string name_prefix =
- strings::StrCat("/job:", server_def_.job_name(), "/replica:0",
- "/task:", server_def_.task_index());
- TF_RETURN_IF_ERROR(DeviceFactory::AddDevices(sess_opts, name_prefix,
- &master_env_.local_devices));
- worker_env_.local_devices = master_env_.local_devices;
- worker_env_.device_mgr = new DeviceMgr(worker_env_.local_devices);
- worker_env_.rendezvous_mgr = rendezvous_mgr_func == nullptr
- ? new RpcRendezvousMgr(&worker_env_)
- : rendezvous_mgr_func(&worker_env_);
- string unused;
- string default_worker_name;
- if (!DeviceNameUtils::SplitDeviceName(master_env_.local_devices[0]->name(),
- &default_worker_name, &unused)) {
- return errors::Internal("Could not parse worker name.");
- }
+ // Check parameters before DeviceFactory::AddDevices,
+ // otherwise if 'task_index=-1' the program will abort.
// Look up the port that has been requested for this task in `server_def_`.
int requested_port = -1;
@@ -167,6 +148,28 @@ Status GrpcServer::Init(
"\" was not defined in cluster");
}
+ SessionOptions sess_opts;
+ ConfigProto config = server_def_.default_session_config();
+ sess_opts.config = config;
+
+ // Configure shared devices between master and worker.
+ string name_prefix =
+ strings::StrCat("/job:", server_def_.job_name(), "/replica:0",
+ "/task:", server_def_.task_index());
+ TF_RETURN_IF_ERROR(DeviceFactory::AddDevices(sess_opts, name_prefix,
+ &master_env_.local_devices));
+ worker_env_.local_devices = master_env_.local_devices;
+ worker_env_.device_mgr = new DeviceMgr(worker_env_.local_devices);
+ worker_env_.rendezvous_mgr = rendezvous_mgr_func == nullptr
+ ? new RpcRendezvousMgr(&worker_env_)
+ : rendezvous_mgr_func(&worker_env_);
+ string unused;
+ string default_worker_name;
+ if (!DeviceNameUtils::SplitDeviceName(master_env_.local_devices[0]->name(),
+ &default_worker_name, &unused)) {
+ return errors::Internal("Could not parse worker name.");
+ }
+
// N.B. The order of initialization here is intricate, because we
// wish to allow `requested_port == 0` (for choosing any port,
// mostly for testing). Therefore, the construction of the channel
diff --git a/tensorflow/core/framework/dataset.cc b/tensorflow/core/framework/dataset.cc
index 6510f81ab7..f3c7189292 100644
--- a/tensorflow/core/framework/dataset.cc
+++ b/tensorflow/core/framework/dataset.cc
@@ -74,18 +74,18 @@ class DatasetVariantWrapper {
} // namespace
Status GraphDefBuilderWrapper::AddDataset(
- const GraphDatasetBase* dataset,
+ const DatasetBase* dataset,
const std::vector<std::pair<size_t, Node*>>& inputs,
const std::vector<std::pair<size_t, gtl::ArraySlice<Node*>>>& list_inputs,
const std::vector<std::pair<StringPiece, AttrValue>>& attrs,
Node** output) {
- const string& op_type_name = dataset->op_name();
+ const string& name = dataset->name();
std::unique_ptr<const GraphDefBuilder::Options> opts(
new GraphDefBuilder::Options(b_->opts()));
// TODO(srbs|mrry): Not all datasets have output_types and output_shapes
// attributes defined. It will be nice to have a consistent pattern.
- bool has_output_types_attr = HasAttr(op_type_name, "output_types");
- bool has_output_shapes_attr = HasAttr(op_type_name, "output_shapes");
+ bool has_output_types_attr = HasAttr(name, "output_types");
+ bool has_output_shapes_attr = HasAttr(name, "output_shapes");
if (has_output_shapes_attr) {
opts.reset(new GraphDefBuilder::Options(
opts->WithAttr("output_shapes", dataset->output_shapes())));
@@ -102,8 +102,7 @@ Status GraphDefBuilderWrapper::AddDataset(
return errors::Internal("AddDataset: Failed to build Options with error ",
opts->StatusToString());
}
- NodeBuilder node_builder(opts->GetNameForOp(op_type_name), op_type_name,
- opts->op_registry());
+ NodeBuilder node_builder(opts->GetNameForOp(name), name, opts->op_registry());
{
size_t total_size = inputs.size() + list_inputs.size();
auto inputs_iter = inputs.begin();
@@ -128,30 +127,28 @@ Status GraphDefBuilderWrapper::AddDataset(
}
*output = opts->FinalizeBuilder(&node_builder);
if (*output == nullptr) {
- return errors::Internal("AddDataset: Failed to build ", op_type_name,
+ return errors::Internal("AddDataset: Failed to build ", name,
" op with error ", opts->StatusToString());
}
return Status::OK();
}
-Status GraphDefBuilderWrapper::AddFunction(OpKernelContext* ctx,
- const string& function_name) {
+Status GraphDefBuilderWrapper::AddFunction(
+ const FunctionLibraryDefinition& flib_def, const string& function_name) {
if (b_->HasFunction(function_name)) {
- LOG(INFO) << "Function with name " << function_name << "already exists in"
- << " the graph. It will not be added again.";
+ VLOG(1) << "Function with name " << function_name << "already exists in"
+ << " the graph. It will not be added again.";
return Status::OK();
}
- TF_RETURN_IF_ERROR(EnsureFunctionIsStateless(ctx, function_name));
- const FunctionLibraryDefinition* flib_def =
- ctx->function_library()->GetFunctionLibraryDefinition();
- const FunctionDef* f_def = flib_def->Find(function_name);
+ TF_RETURN_IF_ERROR(EnsureFunctionIsStateless(flib_def, function_name));
+ const FunctionDef* f_def = flib_def.Find(function_name);
if (f_def == nullptr) {
return errors::InvalidArgument("Unable to find FunctionDef for ",
function_name, " in the registry.");
}
FunctionDefLibrary def;
*def.add_function() = *f_def;
- const string gradient_func = flib_def->FindGradient(function_name);
+ const string gradient_func = flib_def.FindGradient(function_name);
if (!gradient_func.empty()) {
GradientDef* g_def = def.add_gradient();
g_def->set_function_name(function_name);
@@ -162,19 +159,19 @@ Status GraphDefBuilderWrapper::AddFunction(OpKernelContext* ctx,
// Recursively add functions in inputs of function_name.
for (const NodeDef& node_def : f_def->node_def()) {
const OpRegistrationData* op_reg_data = nullptr;
- TF_RETURN_IF_ERROR(flib_def->LookUp(node_def.op(), &op_reg_data));
+ TF_RETURN_IF_ERROR(flib_def.LookUp(node_def.op(), &op_reg_data));
if (op_reg_data->is_function_op) {
- TF_RETURN_IF_ERROR(AddFunction(ctx, op_reg_data->op_def.name()));
+ TF_RETURN_IF_ERROR(AddFunction(flib_def, op_reg_data->op_def.name()));
}
// Recursively add functions in attrs of this NodeDef.
for (const auto& pair : node_def.attr()) {
- TF_RETURN_IF_ERROR(AddAttrFunctions(pair.second, ctx));
+ TF_RETURN_IF_ERROR(AddAttrFunctions(pair.second, flib_def));
}
}
// Recursively add functions in attrs of function_name.
for (auto iter = f_def->attr().begin(); iter != f_def->attr().end(); iter++) {
- TF_RETURN_IF_ERROR(AddAttrFunctions(iter->second, ctx));
+ TF_RETURN_IF_ERROR(AddAttrFunctions(iter->second, flib_def));
}
return Status::OK();
}
@@ -186,27 +183,32 @@ void GraphDefBuilderWrapper::AddTensorInternal(const Tensor& val,
b_->opts().WithAttr("dtype", val.dtype()).WithAttr("value", val));
}
-bool GraphDefBuilderWrapper::HasAttr(const string& op_type_name,
+bool GraphDefBuilderWrapper::HasAttr(const string& name,
const string& attr_name) const {
const OpDef* op_def = nullptr;
- Status s = b_->opts().op_registry()->LookUpOpDef(op_type_name, &op_def);
+ Status s = b_->opts().op_registry()->LookUpOpDef(name, &op_def);
if (!s.ok() || op_def == nullptr) {
return false;
}
return HasAttr(op_def, attr_name);
}
-Status GraphDatasetBase::Serialize(OpKernelContext* ctx,
- string* serialized_graph_def,
- string* output_node) const {
+Status DatasetBase::Save(SerializationContext* ctx,
+ IteratorStateWriter* writer) const {
+ string serialized_graph_def;
+ string output_node;
GraphDefBuilder b;
DatasetGraphDefBuilder db(&b);
Node* node = nullptr;
TF_RETURN_IF_ERROR(AsGraphDefInternal(ctx, &db, &node));
- *output_node = node->name();
+ output_node = node->name();
GraphDef graph_def;
TF_RETURN_IF_ERROR(b.ToGraphDef(&graph_def));
- graph_def.SerializeToString(serialized_graph_def);
+ graph_def.SerializeToString(&serialized_graph_def);
+ TF_RETURN_IF_ERROR(
+ writer->WriteScalar(kDatasetGraphKey, serialized_graph_def));
+ TF_RETURN_IF_ERROR(
+ writer->WriteScalar(kDatasetGraphOutputNodeKey, output_node));
return Status::OK();
}
@@ -266,8 +268,8 @@ void BinaryDatasetOpKernel::MakeDataset(OpKernelContext* ctx,
MakeDataset(ctx, input, another_input, output);
}
-const char GraphDatasetBase::kDatasetGraphKey[] = "_DATASET_GRAPH";
-const char GraphDatasetBase::kDatasetGraphOutputNodeKey[] =
+const char DatasetBase::kDatasetGraphKey[] = "_DATASET_GRAPH";
+const char DatasetBase::kDatasetGraphOutputNodeKey[] =
"_DATASET_GRAPH_OUTPUT_NODE";
BackgroundWorker::BackgroundWorker(Env* env, const string& name) {
@@ -317,22 +319,4 @@ void BackgroundWorker::WorkerLoop() {
}
}
-namespace dataset {
-
-IteratorContext MakeIteratorContext(OpKernelContext* ctx) {
- IteratorContext::Params params;
- params.env = ctx->env();
- params.runner = *(ctx->runner());
- params.lib = ctx->function_library();
- // Note: must use reinterpret_cast because function.h forward-declares Device.
- DeviceBase* device =
- reinterpret_cast<DeviceBase*>(ctx->function_library()->device());
- params.allocator_getter = [device](AllocatorAttributes attrs) {
- return device->GetAllocator(attrs);
- };
- return IteratorContext(params);
-}
-
-} // namespace dataset
-
} // namespace tensorflow
diff --git a/tensorflow/core/framework/dataset.h b/tensorflow/core/framework/dataset.h
index ad73a3d0c7..e0c26d9286 100644
--- a/tensorflow/core/framework/dataset.h
+++ b/tensorflow/core/framework/dataset.h
@@ -40,6 +40,8 @@ limitations under the License.
namespace tensorflow {
+class DatasetBase;
+
// Interface for reading values from a key-value store.
// Used for restoring iterator state.
class IteratorStateReader {
@@ -66,7 +68,6 @@ class IteratorStateWriter {
// Forward declarations to avoid introducing a dependency on headers in
// "tensorflow/core/graph/...".
class GraphDefBuilder;
-class GraphDatasetBase;
class Node;
// Wrapper around GraphDefBuilder. Used to serialize Dataset graph.
@@ -120,7 +121,7 @@ class GraphDefBuilderWrapper {
return Status::OK();
}
- Status AddDataset(const GraphDatasetBase* dataset,
+ Status AddDataset(const DatasetBase* dataset,
const std::vector<Node*>& inputs, Node** output) {
return AddDataset(dataset, inputs, {}, output);
}
@@ -133,7 +134,7 @@ class GraphDefBuilderWrapper {
// `*output` contains a pointer to the output `Node`. It is guaranteed to be
// non-null if the method returns with an OK status.
// The returned Node pointer is owned by the backing Graph of GraphDefBuilder.
- Status AddDataset(const GraphDatasetBase* dataset,
+ Status AddDataset(const DatasetBase* dataset,
const std::vector<Node*>& inputs,
const std::vector<std::pair<StringPiece, AttrValue>>& attrs,
Node** output) {
@@ -145,7 +146,7 @@ class GraphDefBuilderWrapper {
}
Status AddDataset(
- const GraphDatasetBase* dataset,
+ const DatasetBase* dataset,
const std::vector<std::pair<size_t, Node*>>& inputs,
const std::vector<std::pair<size_t, gtl::ArraySlice<Node*>>>& list_inputs,
const std::vector<std::pair<StringPiece, AttrValue>>& attrs,
@@ -157,7 +158,8 @@ class GraphDefBuilderWrapper {
// name `function_name` is not found in the FunctionLibraryDefinition, returns
// an InvalidArgumentError. If the function with name `function_name` or any
// of its dependent functions are stateful, returns an InvalidArgument error.
- Status AddFunction(OpKernelContext* ctx, const string& function_name);
+ Status AddFunction(const FunctionLibraryDefinition& flib_def,
+ const string& function_name);
template <typename T>
void BuildAttrValue(const T& value, AttrValue* attr) {
@@ -167,18 +169,16 @@ class GraphDefBuilderWrapper {
private:
void AddTensorInternal(const Tensor& val, Node** output);
- Status EnsureFunctionIsStateless(OpKernelContext* ctx,
+ Status EnsureFunctionIsStateless(const FunctionLibraryDefinition& flib_def,
const string& function_name) const {
- const FunctionLibraryDefinition* lib_def =
- ctx->function_library()->GetFunctionLibraryDefinition();
- const FunctionDef* function_def = lib_def->Find(function_name);
+ const FunctionDef* function_def = flib_def.Find(function_name);
if (!function_def) {
return errors::InvalidArgument("Unable to find FunctionDef for ",
function_name, " in registry.");
}
for (const NodeDef& node_def : function_def->node_def()) {
const OpDef* op_def;
- TF_RETURN_IF_ERROR(lib_def->LookUpOpDef(node_def.op(), &op_def));
+ TF_RETURN_IF_ERROR(flib_def.LookUpOpDef(node_def.op(), &op_def));
// TODO(b/65524810): Hack to allow functions to capture Dataset op
// nodes needed for FlatMap. Currently, source datasets nodes have been
// marked stateful to avoid constant folding since we do not have a
@@ -220,12 +220,13 @@ class GraphDefBuilderWrapper {
return false;
}
- Status AddAttrFunctions(const AttrValue& attr_value, OpKernelContext* ctx) {
+ Status AddAttrFunctions(const AttrValue& attr_value,
+ const FunctionLibraryDefinition& flib_def) {
if (attr_value.has_func()) {
- TF_RETURN_IF_ERROR(AddFunction(ctx, attr_value.func().name()));
+ TF_RETURN_IF_ERROR(AddFunction(flib_def, attr_value.func().name()));
} else if (attr_value.has_list()) {
for (const NameAttrList& name_attr_list : attr_value.list().func()) {
- TF_RETURN_IF_ERROR(AddFunction(ctx, name_attr_list.name()));
+ TF_RETURN_IF_ERROR(AddFunction(flib_def, name_attr_list.name()));
}
}
return Status::OK();
@@ -236,21 +237,17 @@ class GraphDefBuilderWrapper {
class StatsAggregator;
-// A cut-down version of OpKernelContext for running computations in
-// iterators. Note that we cannot simply use OpKernelContext here
-// because we might run computation in an iterator whose lifetime is
-// not nested within the lifetime of a single OpKernelContext
-// (e.g. asynchronous prefetching).
+// A cut-down version of `OpKernelContext` for running computations in
+// iterators. Note that we cannot simply use `OpKernelContext` here because we
+// might run computation in an iterator whose lifetime is not nested within the
+// lifetime of a single `OpKernelContext` (e.g. asynchronous prefetching).
//
-// TODO(mrry): We will probably need to support more of
-// OpKernelContext here. For example, should allocation be handled by
-// the IteratorContext?
-// TODO(mrry): We're making some daring assumptions about the lifetime
-// of the runner passed in here. A runner will be deleted when the original
-// step ends, but all existing runners only close over session-lifetime (or
-// longer-lived) state, so we can make a copy of the function. There's nothing
-// in the definition of the API from which we took the runner to guarantee that
-// what we are doing is safe. We should formalize the properties here.
+// TODO(mrry): We're making some daring assumptions about the lifetime of the
+// runner passed in here. A runner will be deleted when the original step ends,
+// but all existing runners only close over session-lifetime (or longer-lived)
+// state, so we can make a copy of the function. There's nothing in the
+// definition of the API from which we took the runner to guarantee that what we
+// are doing is safe. We should formalize the properties here.
class IteratorContext {
public:
struct Params {
@@ -280,6 +277,19 @@ class IteratorContext {
explicit IteratorContext(Params params) : params_(std::move(params)) {}
+ explicit IteratorContext(OpKernelContext* ctx) {
+ params_.env = ctx->env();
+ params_.runner = *(ctx->runner());
+ params_.lib = ctx->function_library();
+ // NOTE: must use reinterpret_cast because function.h forward-declares
+ // Device.
+ DeviceBase* device =
+ reinterpret_cast<DeviceBase*>(ctx->function_library()->device());
+ params_.allocator_getter = [device](AllocatorAttributes attrs) {
+ return device->GetAllocator(attrs);
+ };
+ }
+
Env* env() const { return params_.env; }
std::function<void(std::function<void()>)>* runner() {
@@ -318,6 +328,23 @@ class IteratorContext {
Params params_;
};
+// Aggregates runtime support needed for dataset and iterator serialization.
+class SerializationContext {
+ public:
+ struct Params {
+ const FunctionLibraryDefinition* flib_def; // Not owned.
+ };
+
+ explicit SerializationContext(Params params) : params_(std::move(params)) {}
+
+ const FunctionLibraryDefinition& flib_def() { return *params_.flib_def; }
+
+ private:
+ Params params_;
+
+ TF_DISALLOW_COPY_AND_ASSIGN(SerializationContext);
+};
+
// Represents the current position in a range of outputs, where the
// range of outputs is typically represented by an `DatasetBase`,
// defined below.
@@ -342,6 +369,11 @@ class IteratorBase {
virtual Status GetNext(IteratorContext* ctx, std::vector<Tensor>* out_tensors,
bool* end_of_sequence) = 0;
+ Status GetNext(IteratorContext&& ctx, std::vector<Tensor>* out_tensors,
+ bool* end_of_sequence) {
+ return GetNext(&ctx, out_tensors, end_of_sequence);
+ }
+
// Returns a vector of DataType values, representing the respective
// element types of each tuple component in the outputs of this
// iterator.
@@ -357,7 +389,7 @@ class IteratorBase {
virtual Status Initialize(IteratorContext* ctx) { return Status::OK(); }
// Saves the state of this iterator.
- virtual Status Save(OpKernelContext* ctx, IteratorStateWriter* writer) {
+ virtual Status Save(SerializationContext* ctx, IteratorStateWriter* writer) {
return SaveInternal(writer);
}
@@ -368,19 +400,17 @@ class IteratorBase {
protected:
// This is needed so that sub-classes of IteratorBase can call
- // `SaveInternal` on their parent iterators, e.g., in
- // `RepeatDatasetOp::Dataset`.
- Status SaveParent(IteratorStateWriter* writer,
- const std::unique_ptr<IteratorBase>& parent) {
- return parent->SaveInternal(writer);
+ // `SaveInternal` on their input iterators.
+ Status SaveInput(IteratorStateWriter* writer,
+ const std::unique_ptr<IteratorBase>& input) {
+ return input->SaveInternal(writer);
}
// This is needed so that sub-classes of IteratorBase can call
- // `RestoreInternal` on their parent iterators, e.g., in
- // `RepeatDatasetOp::Dataset`.
- Status RestoreParent(IteratorContext* ctx, IteratorStateReader* reader,
- const std::unique_ptr<IteratorBase>& parent) {
- return parent->RestoreInternal(ctx, reader);
+ // `RestoreInternal` on their input iterators.
+ Status RestoreInput(IteratorContext* ctx, IteratorStateReader* reader,
+ const std::unique_ptr<IteratorBase>& input) {
+ return input->RestoreInternal(ctx, reader);
}
// Saves the state of this iterator recursively.
@@ -395,10 +425,40 @@ class IteratorBase {
}
};
+// Represents runtime information needed to construct a dataset.
+class DatasetContext {
+ public:
+ struct Params {
+ string name;
+ };
+
+ explicit DatasetContext(Params params) : params_(std::move(params)) {}
+
+ explicit DatasetContext(OpKernelContext* ctx) {
+ params_.name = ctx->op_kernel().type_string();
+ }
+
+ const string& name() const { return params_.name; }
+
+ private:
+ Params params_;
+};
+
// Represents a (potentially infinite) range of outputs, where each
// output is a tuple of tensors.
class DatasetBase : public core::RefCounted {
public:
+ // Key for storing the Dataset graph in the serialized format.
+ TF_EXPORT static const char kDatasetGraphKey[];
+
+ // Key for storing the output node of the Dataset graph in the serialized
+ // format.
+ TF_EXPORT static const char kDatasetGraphOutputNodeKey[];
+
+ explicit DatasetBase(DatasetContext&& ctx) : name_(ctx.name()) {}
+
+ const string& name() const { return name_; }
+
// Returns a new iterator for iterating over the range of elements in
// this dataset.
//
@@ -415,6 +475,11 @@ class DatasetBase : public core::RefCounted {
return (*iterator)->Initialize(ctx);
}
+ Status MakeIterator(IteratorContext&& ctx, const string& prefix,
+ std::unique_ptr<IteratorBase>* iterator) const {
+ return MakeIterator(&ctx, prefix, iterator);
+ }
+
// Returns a vector of DataType values, representing the respective
// element types of each tuple component in the outputs of this
// dataset.
@@ -429,76 +494,34 @@ class DatasetBase : public core::RefCounted {
virtual string DebugString() const = 0;
// Serializes the dataset and writes it to the `writer`.
- virtual Status Save(OpKernelContext* ctx, IteratorStateWriter* writer) const {
- return errors::Unimplemented("DatasetBase::Save");
- }
+ virtual Status Save(SerializationContext* ctx,
+ IteratorStateWriter* writer) const;
protected:
- // TODO(srbs): Ideally all graph related logic should reside in
- // GraphDatasetBase. However, that would require Datasets defined in all ops
- // to derive from GraphDatasetBase. Once that is done we can move
- // DatasetGraphDefBuilder and AsGraphDefInternal to GraphDatasetBase.
class DatasetGraphDefBuilder : public GraphDefBuilderWrapper {
public:
DatasetGraphDefBuilder(GraphDefBuilder* b) : GraphDefBuilderWrapper(b) {}
- Status AddParentDataset(OpKernelContext* ctx, const DatasetBase* dataset,
- Node** output) {
+ Status AddInputDataset(SerializationContext* ctx,
+ const DatasetBase* dataset, Node** output) {
return dataset->AsGraphDefInternal(ctx, this, output);
}
};
- virtual Status AsGraphDefInternal(OpKernelContext* ctx,
+ // TODO(jsimsa): Consolidate overloading into a single method.
+ virtual Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
- Node** node) const {
- return AsGraphDefInternal(b, node);
- }
-
- virtual Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
- Node** node) const {
- return errors::Unimplemented("AsGraphDefInternal");
- }
+ Node** node) const = 0;
virtual std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const = 0;
friend class DatasetToGraphOp; // For access to graph related members.
-};
-
-// Base-class for datasets that are built by ops.
-class GraphDatasetBase : public DatasetBase {
- public:
- GraphDatasetBase(OpKernelContext* ctx)
- : op_name_(ctx->op_kernel().type_string()) {}
-
- const string op_name() const { return op_name_; }
-
- Status Save(OpKernelContext* ctx,
- IteratorStateWriter* writer) const override {
- string serialized_graph_def;
- string output_node;
- TF_RETURN_IF_ERROR(Serialize(ctx, &serialized_graph_def, &output_node));
- TF_RETURN_IF_ERROR(
- writer->WriteScalar(kDatasetGraphKey, serialized_graph_def));
- TF_RETURN_IF_ERROR(
- writer->WriteScalar(kDatasetGraphOutputNodeKey, output_node));
- return Status::OK();
- }
-
- // Key for storing the Dataset graph in the serialized format.
- TF_EXPORT static const char kDatasetGraphKey[];
-
- // Key for storing the output node of the Dataset graph in the serialized
- // format.
- TF_EXPORT static const char kDatasetGraphOutputNodeKey[];
private:
- Status Serialize(OpKernelContext* ctx, string* serialized_graph_def,
- string* output_node) const;
-
- const string op_name_;
+ const string name_;
};
-// Represents an iterator that is associated with a particular parent dataset.
+// Represents an iterator that is associated with a particular dataset.
class DatasetBaseIterator : public IteratorBase {
public:
struct BaseParams {
@@ -541,7 +564,7 @@ class DatasetBaseIterator : public IteratorBase {
return s;
}
- Status Save(OpKernelContext* ctx, IteratorStateWriter* writer) final {
+ Status Save(SerializationContext* ctx, IteratorStateWriter* writer) final {
TF_RETURN_IF_ERROR(params_.dataset->Save(ctx, writer));
return IteratorBase::Save(ctx, writer);
}
@@ -560,13 +583,13 @@ class DatasetBaseIterator : public IteratorBase {
BaseParams params_;
};
-// Represents an iterator that is associated with a particular parent dataset
+// Represents an iterator that is associated with a particular dataset
// with a particular type.
template <class DatasetType>
class DatasetIterator : public DatasetBaseIterator {
public:
struct Params {
- // Borrowed pointer to the parent dataset.
+ // Borrowed pointer to the dataset.
const DatasetType* dataset;
// Identifies the sequence of iterators leading up to this iterator.
@@ -703,12 +726,6 @@ class BackgroundWorker {
std::deque<std::function<void()>> work_queue_ GUARDED_BY(mu_);
};
-namespace dataset {
-
-IteratorContext MakeIteratorContext(OpKernelContext* ctx);
-
-} // namespace dataset
-
} // namespace tensorflow
#endif // TENSORFLOW_CORE_FRAMEWORK_DATASET_H_
diff --git a/tensorflow/core/framework/function.cc b/tensorflow/core/framework/function.cc
index 57bcc0f513..6b92e10d76 100644
--- a/tensorflow/core/framework/function.cc
+++ b/tensorflow/core/framework/function.cc
@@ -920,10 +920,12 @@ FunctionLibraryDefinition::FunctionDefAndOpRegistration::
FunctionLibraryDefinition::FunctionLibraryDefinition(
const FunctionLibraryDefinition& other)
- : default_registry_(other.default_registry_), func_grad_(other.func_grad_) {
+ : default_registry_(other.default_registry_) {
+ tf_shared_lock l(other.mu_);
for (const auto& it : other.function_defs_) {
TF_CHECK_OK(AddFunctionDef(it.second->fdef));
}
+ func_grad_ = other.func_grad_;
}
FunctionLibraryDefinition::FunctionLibraryDefinition(
@@ -943,8 +945,19 @@ FunctionLibraryDefinition::FunctionLibraryDefinition(
FunctionLibraryDefinition::~FunctionLibraryDefinition() {}
-const FunctionDef* FunctionLibraryDefinition::Find(const string& name) const {
- auto iter = function_defs_.find(name);
+bool FunctionLibraryDefinition::Contains(const string& func) const {
+ tf_shared_lock l(mu_);
+ return function_defs_.find(func) != function_defs_.end();
+}
+
+const FunctionDef* FunctionLibraryDefinition::Find(const string& func) const {
+ tf_shared_lock l(mu_);
+ return FindHelper(func);
+}
+
+const FunctionDef* FunctionLibraryDefinition::FindHelper(
+ const string& func) const {
+ auto iter = function_defs_.find(func);
if (iter == function_defs_.end()) {
return nullptr;
} else {
@@ -953,6 +966,7 @@ const FunctionDef* FunctionLibraryDefinition::Find(const string& name) const {
}
Status FunctionLibraryDefinition::AddFunctionDef(const FunctionDef& fdef) {
+ mutex_lock l(mu_);
bool added;
return AddFunctionDefHelper(fdef, &added);
}
@@ -984,6 +998,7 @@ Status FunctionLibraryDefinition::AddFunctionDefHelper(const FunctionDef& fdef,
}
Status FunctionLibraryDefinition::AddGradientDef(const GradientDef& grad) {
+ mutex_lock l(mu_);
bool added;
return AddGradientDefHelper(grad, &added);
}
@@ -1009,13 +1024,17 @@ Status FunctionLibraryDefinition::AddGradientDefHelper(const GradientDef& grad,
Status FunctionLibraryDefinition::AddLibrary(
const FunctionLibraryDefinition& other) {
+ // Clone `other` to ensure thread-safety (grabbing `other`'s lock for
+ // the duration of the function could lead to deadlock).
+ FunctionLibraryDefinition clone(other);
+ mutex_lock l(mu_);
// Remember the funcs and grads that we added successfully so that
// we can roll them back on error.
std::vector<string> funcs;
std::vector<string> funcs_with_grads;
Status s;
bool added;
- for (auto iter : other.function_defs_) {
+ for (auto iter : clone.function_defs_) {
s = AddFunctionDefHelper(iter.second->fdef, &added);
if (!s.ok()) {
Remove(funcs, funcs_with_grads);
@@ -1025,7 +1044,7 @@ Status FunctionLibraryDefinition::AddLibrary(
funcs.push_back(iter.second->fdef.signature().name());
}
}
- for (auto iter : other.func_grad_) {
+ for (auto iter : clone.func_grad_) {
GradientDef grad;
grad.set_function_name(iter.first);
grad.set_gradient_func(iter.second);
@@ -1045,6 +1064,7 @@ Status FunctionLibraryDefinition::AddLibrary(
const FunctionDefLibrary& lib_def) {
// Remember the funcs and grads that we added successfully so that
// we can roll them back on error.
+ mutex_lock l(mu_);
std::vector<string> funcs;
std::vector<string> funcs_with_grads;
Status s;
@@ -1072,6 +1092,15 @@ Status FunctionLibraryDefinition::AddLibrary(
return Status::OK();
}
+Status FunctionLibraryDefinition::ReplaceFunction(const string& func,
+ const FunctionDef& fdef) {
+ mutex_lock l(mu_);
+ bool added;
+ TF_RETURN_IF_ERROR(RemoveFunction(func));
+ TF_RETURN_IF_ERROR(AddFunctionDefHelper(fdef, &added));
+ return Status::OK();
+}
+
Status FunctionLibraryDefinition::RemoveFunction(const string& func) {
const auto& i = function_defs_.find(func);
if (i == function_defs_.end()) {
@@ -1106,11 +1135,17 @@ void FunctionLibraryDefinition::Remove(
}
string FunctionLibraryDefinition::FindGradient(const string& func) const {
+ tf_shared_lock l(mu_);
+ return gtl::FindWithDefault(func_grad_, func, "");
+}
+
+string FunctionLibraryDefinition::FindGradientHelper(const string& func) const {
return gtl::FindWithDefault(func_grad_, func, "");
}
Status FunctionLibraryDefinition::LookUp(
const string& op, const OpRegistrationData** op_reg_data) const {
+ tf_shared_lock l(mu_);
auto iter = function_defs_.find(op);
if (iter != function_defs_.end()) {
*op_reg_data = &iter->second->op_registration_data;
@@ -1134,18 +1169,22 @@ const FunctionDef* FunctionLibraryDefinition::GetAttrImpl(
return nullptr;
}
const string& func_name = forward_func_attrs->name();
- const string& grad_name = FindGradient(func_name);
- // If 'func' has a user-defined gradient function, uses the grad
- // function's attrs to see if noinline is specified. Otherwise,
- // uses func's attrs.
- if (!grad_name.empty()) {
- return Find(grad_name);
- }
- return Find(func_name);
+ {
+ tf_shared_lock l(mu_);
+ const string& grad_name = FindGradientHelper(func_name);
+ // If 'func' has a user-defined gradient function, uses the grad
+ // function's attrs to see if noinline is specified. Otherwise,
+ // uses func's attrs.
+ if (!grad_name.empty()) {
+ return FindHelper(grad_name);
+ }
+ return FindHelper(func_name);
+ }
}
FunctionDefLibrary FunctionLibraryDefinition::ToProto() const {
FunctionDefLibrary lib;
+ tf_shared_lock l(mu_);
for (const auto& f : function_defs_) {
*lib.add_function() = f.second->fdef;
}
diff --git a/tensorflow/core/framework/function.h b/tensorflow/core/framework/function.h
index 5da9af7db3..edb7ed01e9 100644
--- a/tensorflow/core/framework/function.h
+++ b/tensorflow/core/framework/function.h
@@ -28,6 +28,7 @@ limitations under the License.
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/macros.h"
+#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
@@ -40,7 +41,7 @@ class ProcessFunctionLibraryRuntime;
class ResourceMgr;
class Rendezvous;
class ScopedStepContainer;
-class StepStatsCollector;
+class StepStatsCollectorInterface;
class Node;
// FunctionDefHelper::Create is a convenient helper to construct a
@@ -288,8 +289,11 @@ class FunctionCallFrame : public CallFrameInterface {
// Helper to maintain a map between function names in a given
// FunctionDefLibrary and function definitions.
+//
+// This class is thread-safe.
class FunctionLibraryDefinition : public OpRegistryInterface {
public:
+ // Note: This constructor grabs `lib_def`'s lock in shared mode.
explicit FunctionLibraryDefinition(const FunctionLibraryDefinition& lib_def);
FunctionLibraryDefinition(const OpRegistryInterface* default_registry,
const FunctionDefLibrary& lib_def);
@@ -298,9 +302,15 @@ class FunctionLibraryDefinition : public OpRegistryInterface {
FunctionLibraryDefinition& operator=(const FunctionLibraryDefinition&) =
delete;
+ // Returns True if the library contains `func`, False otherwise.
+ bool Contains(const string& func) const;
+
// Returns nullptr if "func" is not defined in "lib_def". Otherwise,
// returns its definition proto.
- const FunctionDef* Find(const string& func) const;
+ //
+ // NB: This function returns a borrowed pointer, which can be invalidated by a
+ // subsequent call to `ReplaceFunction()` with the given name.
+ const FunctionDef* Find(const string& func) const LOCKS_EXCLUDED(mu_);
// Adds function definition 'fdef' to this function library.
// Returns status 'ok' on success, or error otherwise. This is a no-op if
@@ -308,45 +318,45 @@ class FunctionLibraryDefinition : public OpRegistryInterface {
// If 'fdef' is successfully added to the library, it will be accessible
// from 'LookUp' and included in the proto returned by 'ToProto'.
// This operation is atomic.
- Status AddFunctionDef(const FunctionDef& fdef);
+ Status AddFunctionDef(const FunctionDef& fdef) LOCKS_EXCLUDED(mu_);
// Adds gradient definition 'grad' to this function library.
// This is a no-op if 'grad' already exists in this function library.
// If 'grad' is successfully added, it will be accessible via 'FindGradient'
// and included in the proto returned by 'ToProto'.
// This operation is atomic.
- Status AddGradientDef(const GradientDef& grad);
+ Status AddGradientDef(const GradientDef& grad) LOCKS_EXCLUDED(mu_);
- // Remove function `func` from the library. Returns non-OK Status unless
- // `func` is in the library.
- Status RemoveFunction(const string& func);
-
- // Remove gradient of function `func` from the library. Returns non-OK Status
- // unless `func` has a gradient.
- Status RemoveGradient(const string& func);
+ // Replaces the function corresponding to `func` with `fdef`. Returns
+ // a non-OK status if "func" was not found in the library, OK otherwise.
+ Status ReplaceFunction(const string& func, const FunctionDef& fdef);
// Adds the functions and gradients in 'other' to this function library.
// Duplicate functions and gradients are ignored.
// This operation is atomic.
- Status AddLibrary(const FunctionLibraryDefinition& other);
+ Status AddLibrary(const FunctionLibraryDefinition& other) LOCKS_EXCLUDED(mu_);
// Adds the functions and gradients in 'lib_def' to this function library.
// Duplicate functions and gradients are ignored.
// This operation is atomic.
- Status AddLibrary(const FunctionDefLibrary& lib_def);
+ Status AddLibrary(const FunctionDefLibrary& lib_def) LOCKS_EXCLUDED(mu_);
// If the gradient function for 'func' is specified explicitly in
// the library, returns the gradient function name. Otherwise,
// returns an empty string.
- string FindGradient(const string& func) const;
+ string FindGradient(const string& func) const LOCKS_EXCLUDED(mu_);
// OpRegistryInterface method. Useful for constructing a Graph.
//
// If "op" is defined in the library, returns its signature.
// Otherwise, assume "op" is a primitive op and returns its op
// signature and shape inference function.
+ //
+ // NB: This function outputs a borrowed pointer, which can be invalidated by a
+ // subsequent call to `ReplaceFunction()` with the given name.
Status LookUp(const string& op_type_name,
- const OpRegistrationData** op_reg_data) const override;
+ const OpRegistrationData** op_reg_data) const override
+ LOCKS_EXCLUDED(mu_);
// Ops created for function arguments bear the name given by `kArgOp`; those
// created for return values bear the name given by `kRetOp`.
@@ -370,9 +380,12 @@ class FunctionLibraryDefinition : public OpRegistryInterface {
Status GetAttr(const Node& node, const string& attr, T* value) const;
// Returns a proto representation of the state of this function library.
- FunctionDefLibrary ToProto() const;
+ FunctionDefLibrary ToProto() const LOCKS_EXCLUDED(mu_);
- size_t num_functions() const { return function_defs_.size(); }
+ size_t num_functions() const {
+ tf_shared_lock l(mu_);
+ return function_defs_.size();
+ }
const OpRegistryInterface* default_registry() const {
return default_registry_;
@@ -388,24 +401,42 @@ class FunctionLibraryDefinition : public OpRegistryInterface {
OpRegistrationData op_registration_data;
};
+ const FunctionDef* FindHelper(const string& func) const
+ SHARED_LOCKS_REQUIRED(mu_);
+ string FindGradientHelper(const string& func) const
+ SHARED_LOCKS_REQUIRED(mu_);
+
// Same as AddFunctionDef/AddGradientDef except these methods set
// `added` to true if the `fdef`/`grad` were actually added to this.
- Status AddFunctionDefHelper(const FunctionDef& fdef, bool* added);
- Status AddGradientDefHelper(const GradientDef& grad, bool* added);
+ Status AddFunctionDefHelper(const FunctionDef& fdef, bool* added)
+ EXCLUSIVE_LOCKS_REQUIRED(mu_);
+ Status AddGradientDefHelper(const GradientDef& grad, bool* added)
+ EXCLUSIVE_LOCKS_REQUIRED(mu_);
+ mutable mutex mu_;
const OpRegistryInterface* const default_registry_;
gtl::FlatMap<string, std::unique_ptr<FunctionDefAndOpRegistration>>
- function_defs_;
- gtl::FlatMap<string, string> func_grad_;
+ function_defs_ GUARDED_BY(mu_);
+ gtl::FlatMap<string, string> func_grad_ GUARDED_BY(mu_);
// Helper function for GetAttr. Returns the FunctionDef* to get the
// attr from.
- const FunctionDef* GetAttrImpl(const NodeDef& ndef) const;
+ const FunctionDef* GetAttrImpl(const NodeDef& ndef) const LOCKS_EXCLUDED(mu_);
- // Remove all functions in `funcs` and all gradients of
- // functions in `funcs_with_grads` from this library.
+ // Remove all functions in `funcs` and all gradients of functions in
+ // `funcs_with_grads` from this library.
void Remove(const std::vector<string>& funcs,
- const std::vector<string>& funcs_with_grads);
+ const std::vector<string>& funcs_with_grads)
+ EXCLUSIVE_LOCKS_REQUIRED(mu_);
+
+ // Remove `func` from the library. Returns non-OK Status unless `func` is in
+ // the library. This should only be called when there is a guarantee that the
+ // function being removed hasn't been retrieved with `Find`.
+ Status RemoveFunction(const string& func) EXCLUSIVE_LOCKS_REQUIRED(mu_);
+
+ // Remove gradient of function `func` from the library. Returns non-OK Status
+ // unless `func` has a gradient.
+ Status RemoveGradient(const string& func) EXCLUSIVE_LOCKS_REQUIRED(mu_);
};
// Forward declare. Defined in common_runtime/function.h
@@ -456,7 +487,7 @@ class FunctionLibraryRuntime {
// This interface is EXPERIMENTAL and subject to change.
//
- // Instatiates the function using an executor of the given type. If empty,
+ // Instantiates the function using an executor of the given type. If empty,
// the default TensorFlow executor will be used.
string executor_type;
};
@@ -496,7 +527,7 @@ class FunctionLibraryRuntime {
CancellationManager* cancellation_manager = nullptr;
CollectiveExecutor* collective_executor = nullptr;
ScopedStepContainer* step_container = nullptr;
- StepStatsCollector* stats_collector = nullptr;
+ StepStatsCollectorInterface* stats_collector = nullptr;
std::function<void(std::function<void()>)>* runner = nullptr;
diff --git a/tensorflow/core/framework/op_def_util.cc b/tensorflow/core/framework/op_def_util.cc
index 9be0dc69d2..3597f43d51 100644
--- a/tensorflow/core/framework/op_def_util.cc
+++ b/tensorflow/core/framework/op_def_util.cc
@@ -172,6 +172,15 @@ const OpDef::ArgDef* FindInputArg(StringPiece name, const OpDef& op_def) {
return nullptr;
}
+const ApiDef::Arg* FindInputArg(StringPiece name, const ApiDef& api_def) {
+ for (int i = 0; i < api_def.in_arg_size(); ++i) {
+ if (api_def.in_arg(i).name() == name) {
+ return &api_def.in_arg(i);
+ }
+ }
+ return nullptr;
+}
+
#define VALIDATE(EXPR, ...) \
do { \
if (!(EXPR)) { \
diff --git a/tensorflow/core/framework/op_def_util.h b/tensorflow/core/framework/op_def_util.h
index 0ba1325a03..4f67a258d3 100644
--- a/tensorflow/core/framework/op_def_util.h
+++ b/tensorflow/core/framework/op_def_util.h
@@ -20,6 +20,7 @@ limitations under the License.
#define TENSORFLOW_FRAMEWORK_OP_DEF_UTIL_H_
#include <string>
+#include "tensorflow/core/framework/api_def.pb.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/protobuf.h"
@@ -47,6 +48,10 @@ OpDef::AttrDef* FindAttrMutable(StringPiece name, OpDef* op_def);
// Returns nullptr if no such attr is found.
const OpDef::ArgDef* FindInputArg(StringPiece name, const OpDef& op_def);
+// Searches api_def for input argument with the indicated name.
+// Returns nullptr if no such attr is found.
+const ApiDef::Arg* FindInputArg(StringPiece name, const ApiDef& api_def);
+
// Produce a human-readable version of an op_def that is more concise
// than a text-format proto. Excludes descriptions.
string SummarizeOpDef(const OpDef& op_def);
diff --git a/tensorflow/core/framework/op_kernel.h b/tensorflow/core/framework/op_kernel.h
index aab95b785b..e752599de1 100644
--- a/tensorflow/core/framework/op_kernel.h
+++ b/tensorflow/core/framework/op_kernel.h
@@ -70,7 +70,7 @@ class OpRegistryInterface;
class ResourceMgr;
class ScopedStepContainer;
class CollectiveExecutor;
-class StepStatsCollector;
+class StepStatsCollectorInterface;
class OpKernel {
public:
@@ -569,7 +569,7 @@ class OpKernelContext {
CallFrameInterface* call_frame = nullptr;
FunctionLibraryRuntime* function_library = nullptr;
std::function<void(std::function<void()>)>* runner = nullptr;
- StepStatsCollector* stats_collector = nullptr;
+ StepStatsCollectorInterface* stats_collector = nullptr;
// TensorSliceReaderCache support.
checkpoint::TensorSliceReaderCacheWrapper* slice_reader_cache = nullptr;
@@ -984,7 +984,7 @@ class OpKernelContext {
std::function<void(std::function<void()>)>* runner() const {
return params_->runner;
}
- StepStatsCollector* stats_collector() const {
+ StepStatsCollectorInterface* stats_collector() const {
return params_->stats_collector;
}
diff --git a/tensorflow/core/framework/resource_mgr.h b/tensorflow/core/framework/resource_mgr.h
index 33d4cb77ff..976fede148 100644
--- a/tensorflow/core/framework/resource_mgr.h
+++ b/tensorflow/core/framework/resource_mgr.h
@@ -61,8 +61,8 @@ namespace tensorflow {
//
// // Create a var.
// MyVar* my_var = new MyVar;
-// my_var.val = Tensor(DT_FLOAT, my_shape);
-// my_var.val.flat<float>().setZeros(); // 0 initialized.
+// my_var->val = Tensor(DT_FLOAT, my_shape);
+// my_var->val.flat<float>().setZeros(); // 0 initialized.
// ctx->SetStatus(rm.Create("my_container", "my_name", my_var));
//
// // += a variable.
diff --git a/tensorflow/core/framework/shape_inference.cc b/tensorflow/core/framework/shape_inference.cc
index 8d597e198d..3e77028a5f 100644
--- a/tensorflow/core/framework/shape_inference.cc
+++ b/tensorflow/core/framework/shape_inference.cc
@@ -950,8 +950,7 @@ Status InferenceContext::GetScalarFromTensor(const Tensor* t, int64* val) {
*val = t->scalar<int64>()();
return Status::OK();
} else {
- return errors::InvalidArgument(
- "Scalar input for dim size must be int32 or int64");
+ return errors::InvalidArgument("Scalar input must be int32 or int64.");
}
}
diff --git a/tensorflow/core/framework/tensor.cc b/tensorflow/core/framework/tensor.cc
index 5f805f6594..a82beb7e8f 100644
--- a/tensorflow/core/framework/tensor.cc
+++ b/tensorflow/core/framework/tensor.cc
@@ -919,7 +919,13 @@ void PrintOneDim(int dim_index, const gtl::InlinedVector<int64, 4>& shape,
// We have reached the right-most dimension of the tensor.
if (dim_index == shape_size - 1) {
for (int64 i = 0; i < element_count; i++) {
- if (*data_index >= limit) return;
+ if (*data_index >= limit) {
+ // If not enough elements has been printed, append "...".
+ if (dim_index != 0 && i < element_count) {
+ strings::StrAppend(result, "...");
+ }
+ return;
+ }
if (i > 0) strings::StrAppend(result, " ");
strings::StrAppend(result, PrintOneElement(data[(*data_index)++]));
}
diff --git a/tensorflow/core/framework/tensor_test.cc b/tensorflow/core/framework/tensor_test.cc
index 80e168df97..84a373c196 100644
--- a/tensorflow/core/framework/tensor_test.cc
+++ b/tensorflow/core/framework/tensor_test.cc
@@ -1260,6 +1260,13 @@ TEST(SummarizeValue, INT32) {
EXPECT_EQ("", x.SummarizeValue(16));
}
+TEST(SummarizeValue, INT32Dims) {
+ Tensor x = MkTensor<int>(DT_INT32, TensorShape({3, 4}),
+ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
+ EXPECT_EQ("[1 2 3...]...", x.SummarizeValue(3));
+ EXPECT_EQ("[1 2 3 4][5 6 7 8][9 10...]...", x.SummarizeValue(10));
+}
+
TEST(SummarizeValue, FLOAT) {
Tensor x = MkTensor<float>(DT_FLOAT, TensorShape({5}), {1, 2, 3, 4, 0});
EXPECT_EQ("1 2 3 4 0", x.SummarizeValue(16));
diff --git a/tensorflow/core/graph/gradients.cc b/tensorflow/core/graph/gradients.cc
index c1a8a63784..bec41712b1 100644
--- a/tensorflow/core/graph/gradients.cc
+++ b/tensorflow/core/graph/gradients.cc
@@ -65,16 +65,37 @@ struct NodeOutEq {
static Node* AddZerosLike(Graph* g, NodeOut input) {
DCHECK_LT(0, input.dtype());
DCHECK_LT(input.dtype(), DT_FLOAT_REF);
- NodeDef ndef;
- ndef.set_name(g->NewName(kNodeLabel));
- ndef.set_op("ZerosLike");
- ndef.add_input(input.name());
- AddNodeAttr("T", input.dtype(), &ndef);
- Status s;
- Node* ret = g->AddNode(ndef, &s);
- TF_CHECK_OK(s);
- g->AddEdge(input.node, input.index, ret, 0);
- return ret;
+ if (input.dtype() == DT_RESOURCE) {
+ NodeDef read_def;
+ read_def.set_name(g->NewName("Read"));
+ read_def.set_op("ReadVariableOp");
+ read_def.add_input(input.name());
+ AddNodeAttr("dtype", DT_FLOAT, &read_def);
+ Status s;
+ Node* read = g->AddNode(read_def, &s);
+ TF_CHECK_OK(s);
+ g->AddEdge(input.node, input.index, read, 0);
+ NodeDef ndef;
+ ndef.set_name(g->NewName(kNodeLabel));
+ ndef.set_op("ZerosLike");
+ ndef.add_input(read_def.name());
+ AddNodeAttr("T", DT_FLOAT, &ndef);
+ Node* ret = g->AddNode(ndef, &s);
+ TF_CHECK_OK(s);
+ g->AddEdge(read, 0, ret, 0);
+ return ret;
+ } else {
+ NodeDef ndef;
+ ndef.set_name(g->NewName(kNodeLabel));
+ ndef.set_op("ZerosLike");
+ ndef.add_input(input.name());
+ AddNodeAttr("T", input.dtype(), &ndef);
+ Status s;
+ Node* ret = g->AddNode(ndef, &s);
+ TF_CHECK_OK(s);
+ g->AddEdge(input.node, input.index, ret, 0);
+ return ret;
+ }
}
static Node* AddSymGrad(Graph* g, Node* n, gtl::ArraySlice<NodeOut> grads) {
diff --git a/tensorflow/core/graph/mkl_layout_pass.cc b/tensorflow/core/graph/mkl_layout_pass.cc
index c22e0a3872..833592caab 100644
--- a/tensorflow/core/graph/mkl_layout_pass.cc
+++ b/tensorflow/core/graph/mkl_layout_pass.cc
@@ -43,7 +43,7 @@ limitations under the License.
namespace tensorflow {
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// This pass implements rewriting of graph to support following scenarios:
// (A) Merging nodes in the graph
@@ -2211,7 +2211,7 @@ Status MklLayoutRewritePass::Run(const GraphOptimizationPassOptions& options) {
return Status::OK();
}
-#else // INTEL_MKL_ML
+#else // INTEL_MKL_ML_ONLY
// This pass implements rewriting of graph to support following scenarios:
// (A) Merging nodes in the graph
@@ -2418,6 +2418,9 @@ class MklLayoutRewritePass : public GraphOptimizationPass {
csinfo_.conv2d_grad_filter = "Conv2DBackpropFilter";
csinfo_.conv2d_grad_filter_with_bias =
"__MklDummyConv2DBackpropFilterWithBias";
+ csinfo_.conv3d = "Conv3D";
+ csinfo_.conv3d_grad_input = "Conv3DBackpropInputV2";
+ csinfo_.conv3d_grad_filter = "Conv3DBackpropFilterV2";
csinfo_.fused_batch_norm = "FusedBatchNorm";
csinfo_.fused_batch_norm_grad = "FusedBatchNormGrad";
csinfo_.identity = "Identity";
@@ -2468,18 +2471,27 @@ class MklLayoutRewritePass : public GraphOptimizationPass {
CopyAttrsConcatV2, AlwaysRewrite});
rinfo_.push_back({csinfo_.conv2d,
mkl_op_registry::GetMklOpName(csinfo_.conv2d),
- CopyAttrsConv2D, AlwaysRewrite});
+ CopyAttrsConv, AlwaysRewrite});
rinfo_.push_back({csinfo_.conv2d_with_bias, csinfo_.mkl_conv2d_with_bias,
- CopyAttrsConv2D, AlwaysRewrite});
+ CopyAttrsConv, AlwaysRewrite});
rinfo_.push_back({csinfo_.conv2d_grad_filter,
mkl_op_registry::GetMklOpName(csinfo_.conv2d_grad_filter),
- CopyAttrsConv2D, AlwaysRewrite});
+ CopyAttrsConv, AlwaysRewrite});
rinfo_.push_back({csinfo_.conv2d_grad_filter_with_bias,
- csinfo_.mkl_conv2d_grad_filter_with_bias, CopyAttrsConv2D,
+ csinfo_.mkl_conv2d_grad_filter_with_bias, CopyAttrsConv,
AlwaysRewrite});
rinfo_.push_back({csinfo_.conv2d_grad_input,
mkl_op_registry::GetMklOpName(csinfo_.conv2d_grad_input),
- CopyAttrsConv2D, AlwaysRewrite});
+ CopyAttrsConv, AlwaysRewrite});
+ rinfo_.push_back({csinfo_.conv3d,
+ mkl_op_registry::GetMklOpName(csinfo_.conv3d),
+ CopyAttrsConv, AlwaysRewrite});
+ rinfo_.push_back({csinfo_.conv3d_grad_filter,
+ mkl_op_registry::GetMklOpName(csinfo_.conv3d_grad_filter),
+ CopyAttrsConv, AlwaysRewrite});
+ rinfo_.push_back({csinfo_.conv3d_grad_input,
+ mkl_op_registry::GetMklOpName(csinfo_.conv3d_grad_input),
+ CopyAttrsConv, AlwaysRewrite});
rinfo_.push_back({csinfo_.fused_batch_norm,
mkl_op_registry::GetMklOpName(csinfo_.fused_batch_norm),
CopyAttrsFusedBatchNorm, AlwaysRewrite});
@@ -2614,6 +2626,9 @@ class MklLayoutRewritePass : public GraphOptimizationPass {
string conv2d_grad_input;
string conv2d_grad_filter;
string conv2d_grad_filter_with_bias;
+ string conv3d;
+ string conv3d_grad_input;
+ string conv3d_grad_filter;
string fused_batch_norm;
string fused_batch_norm_grad;
string identity;
@@ -3086,7 +3101,7 @@ class MklLayoutRewritePass : public GraphOptimizationPass {
static void CopyAttrsBiasAddGrad(const Node* orig_node, NodeBuilder* nb);
static void CopyAttrsConcat(const Node* orig_node, NodeBuilder* nb);
static void CopyAttrsConcatV2(const Node* orig_node, NodeBuilder* nb);
- static void CopyAttrsConv2D(const Node* orig_node, NodeBuilder* nb);
+ static void CopyAttrsConv(const Node* orig_node, NodeBuilder* nb);
static void CopyAttrsDataType(const Node* orig_node, NodeBuilder* nb);
static void CopyAttrsFusedBatchNorm(const Node* orig_node, NodeBuilder* nb);
static void CopyAttrsLRN(const Node* orig_node, NodeBuilder* nb);
@@ -3571,14 +3586,13 @@ void MklLayoutRewritePass::AddWorkSpaceEdgeIfNeeded(
// Op-specific functions to copy attributes from old node to new node
//////////////////////////////////////////////////////////////////////////
-void MklLayoutRewritePass::CopyAttrsConv2D(const Node* orig_node,
- NodeBuilder* nb) {
+void MklLayoutRewritePass::CopyAttrsConv(const Node* orig_node,
+ NodeBuilder* nb) {
DataType T;
string data_format;
string padding;
std::vector<int32> strides;
std::vector<int32> dilations;
- bool use_cudnn_on_gpu;
// Get all attributes from old node.
TF_CHECK_OK(GetNodeAttr(orig_node->def(), "T", &T));
@@ -3586,8 +3600,6 @@ void MklLayoutRewritePass::CopyAttrsConv2D(const Node* orig_node,
TF_CHECK_OK(GetNodeAttr(orig_node->def(), "dilations", &dilations));
TF_CHECK_OK(GetNodeAttr(orig_node->def(), "padding", &padding));
TF_CHECK_OK(GetNodeAttr(orig_node->def(), "data_format", &data_format));
- TF_CHECK_OK(
- GetNodeAttr(orig_node->def(), "use_cudnn_on_gpu", &use_cudnn_on_gpu));
// Add attributes to new node.
nb->Attr("T", T);
@@ -3595,7 +3607,6 @@ void MklLayoutRewritePass::CopyAttrsConv2D(const Node* orig_node,
nb->Attr("dilations", dilations);
nb->Attr("padding", padding);
nb->Attr("data_format", data_format);
- nb->Attr("use_cudnn_on_gpu", use_cudnn_on_gpu);
}
void MklLayoutRewritePass::CopyAttrsAddN(const Node* orig_node,
@@ -3896,7 +3907,7 @@ Status MklLayoutRewritePass::MergeConv2DWithBiasAdd(std::unique_ptr<Graph>* g,
nb.Input(succ_in[1].first, succ_in[1].second); // In2 of BiasAdd
// Copy attributes from Conv2D to Conv2DWithBias.
- CopyAttrsConv2D(const_cast<const Node*>(pred), &nb);
+ CopyAttrsConv(const_cast<const Node*>(pred), &nb);
// Copy the device assigned to old node to new node.
nb.Device(succ->def().device());
@@ -4007,7 +4018,7 @@ Status MklLayoutRewritePass::MergeConv2DBackpropFilterWithBiasAddGrad(
}
// Copy attributes from Conv2DBackpropFilter.
- CopyAttrsConv2D(const_cast<const Node*>(fltr), &nb);
+ CopyAttrsConv(const_cast<const Node*>(fltr), &nb);
// Copy the device assigned to old node to new node.
nb.Device(fltr->def().device());
@@ -4474,7 +4485,7 @@ Status MklLayoutRewritePass::Run(const GraphOptimizationPassOptions& options) {
return Status::OK();
}
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
} // namespace tensorflow
#endif
diff --git a/tensorflow/core/graph/mkl_layout_pass_test.cc b/tensorflow/core/graph/mkl_layout_pass_test.cc
index a41f5861af..e8bac847e5 100644
--- a/tensorflow/core/graph/mkl_layout_pass_test.cc
+++ b/tensorflow/core/graph/mkl_layout_pass_test.cc
@@ -37,7 +37,7 @@ limitations under the License.
namespace tensorflow {
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
namespace {
@@ -1898,7 +1898,7 @@ BENCHMARK(BM_MklLayoutRewritePass)->Arg(1000)->Arg(10000);
} // namespace
-#else // INTEL_MKL_ML
+#else // INTEL_MKL_ML_ONLY
// NOTE: Unit tests in this file rely on a topological sorted graph for
// printing. But since sibling nodes of a node in the topologically sorted graph
@@ -3582,7 +3582,7 @@ BENCHMARK(BM_MklLayoutRewritePass)->Arg(1000)->Arg(10000);
} // namespace
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
} // namespace tensorflow
diff --git a/tensorflow/core/graph/testlib.cc b/tensorflow/core/graph/testlib.cc
index 67b252cb6c..ea7788f654 100644
--- a/tensorflow/core/graph/testlib.cc
+++ b/tensorflow/core/graph/testlib.cc
@@ -21,39 +21,14 @@ limitations under the License.
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
-#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/node_builder.h"
-#include "tensorflow/core/kernels/constant_op.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
-
-// HostConst: forced to generate output on the host.
-// Only used by testlib; no op is registered for this kernel
-// externally (i.e., in array_ops.cc)
-REGISTER_KERNEL_BUILDER(Name("HostConst").Device(DEVICE_CPU), HostConstantOp);
-REGISTER_KERNEL_BUILDER(
- Name("HostConst").Device(DEVICE_GPU).HostMemory("output"), HostConstantOp);
-#ifdef TENSORFLOW_USE_SYCL
-REGISTER_KERNEL_BUILDER(
- Name("HostConst").Device(DEVICE_SYCL).HostMemory("output"), HostConstantOp);
-#endif // TENSORFLOW_USE_SYCL
-
-// Register the HostConst Op
-// Returns a constant tensor on the host. Useful for writing C++ tests
-// and benchmarks which run on GPU but require arguments pinned to the host.
-// Used by test::graph::HostConstant.
-// value: Attr `value` is the tensor to return.
-REGISTER_OP("HostConst")
- .Output("output: dtype")
- .Attr("value: tensor")
- .Attr("dtype: type")
- .SetShapeFn(shape_inference::UnknownShape);
-
namespace test {
namespace graph {
diff --git a/tensorflow/core/grappler/costs/analytical_cost_estimator_test.cc b/tensorflow/core/grappler/costs/analytical_cost_estimator_test.cc
index f241922471..a9a1abfa98 100644
--- a/tensorflow/core/grappler/costs/analytical_cost_estimator_test.cc
+++ b/tensorflow/core/grappler/costs/analytical_cost_estimator_test.cc
@@ -103,6 +103,9 @@ TEST_F(AnalyticalCostEstimatorTest, SimpleTest) {
TF_ASSERT_OK(estimator.PredictCosts(item.graph, &cost_graph, &summary));
EXPECT_EQ(Costs::NanoSeconds(9151), summary.execution_time);
+ // Note there are totally 17 nodes (RandomUniform creates 2 nodes), but
+ // grappler will not process "label", therefore we have 15 here instead
+ EXPECT_EQ(15, summary.num_ops_total);
// Make this estimate accurate:
// TODO(http://b/70031255): Accurate estimator for RandomUniform op needed
@@ -110,6 +113,7 @@ TEST_F(AnalyticalCostEstimatorTest, SimpleTest) {
//
// Change to EXPECT_FALSE when the above TODOs are done:
EXPECT_TRUE(summary.inaccurate);
+ EXPECT_EQ(0, summary.num_ops_with_unknown_shapes);
}
} // end namespace grappler
diff --git a/tensorflow/core/grappler/costs/cost_estimator.h b/tensorflow/core/grappler/costs/cost_estimator.h
index fe8a876f8a..e91f0cc9da 100644
--- a/tensorflow/core/grappler/costs/cost_estimator.h
+++ b/tensorflow/core/grappler/costs/cost_estimator.h
@@ -109,8 +109,16 @@ struct Costs {
int64 max_per_op_buffers; // Sum of all buffers used by the ops.
int64 max_per_op_streaming; // Ignore largest input buffer, assuming it
// streams from main memory.
+
+ // Number of ops included in this Costs in total.
+ // Default initialized to be one.
+ int64 num_ops_total = 1;
// If the time estimation is inaccurate.
bool inaccurate = false;
+ // Number of ops that are estimated with unknown shapes.
+ int64 num_ops_with_unknown_shapes = 0;
+ // TODO(pcma): include a counter for total inaccurate ops and counters for
+ // other reasons causing the inaccuracy
// Max possible memory usage per device.
std::unordered_map<string, uint64> estimated_max_memory_per_device;
diff --git a/tensorflow/core/grappler/costs/op_level_cost_estimator.cc b/tensorflow/core/grappler/costs/op_level_cost_estimator.cc
index 5b303f6ccb..0341d7f8e1 100644
--- a/tensorflow/core/grappler/costs/op_level_cost_estimator.cc
+++ b/tensorflow/core/grappler/costs/op_level_cost_estimator.cc
@@ -175,14 +175,24 @@ int64 CwiseOutputElementCount(const TensorShapeProto& input_shape_1,
TensorShapeProto MaybeGetMinimumShape(const TensorShapeProto& original_shape,
int rank, bool* found_unknown_shapes) {
auto shape = original_shape;
- if (shape.unknown_rank() || shape.dim_size() < rank) {
+ bool is_scalar = !shape.unknown_rank() && shape.dim_size() == 0;
+
+ if (shape.unknown_rank() || (!is_scalar && shape.dim_size() < rank)) {
*found_unknown_shapes = true;
- TensorShapeProto::Dim dim;
VLOG(2) << "Use minimum shape because the rank is unknown.";
// The size of each dimension is at least 1, if unknown.
- dim.set_size(1);
+ for (int i = shape.dim_size(); i < rank; i++) {
+ shape.add_dim()->set_size(1);
+ }
+ } else if (is_scalar) {
+ for (int i = 0; i < rank; i++) {
+ shape.add_dim()->set_size(1);
+ }
+ } else if (shape.dim_size() > rank) {
+ *found_unknown_shapes = true;
+ shape.clear_dim();
for (int i = 0; i < rank; i++) {
- *shape.add_dim() = dim;
+ shape.add_dim()->set_size(original_shape.dim(i).size());
}
} else {
for (int i = 0; i < shape.dim_size(); i++) {
@@ -449,6 +459,7 @@ Costs OpLevelCostEstimator::PredictCwiseOp(const OpContext& op_context) const {
if (found_unknown_shapes || !is_known_elementwise_op) {
costs.inaccurate = true;
}
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
return costs;
}
@@ -469,6 +480,7 @@ Costs OpLevelCostEstimator::PredictOpCountBasedCost(
const double total_io_bytes = input_size + output_size;
Costs costs = PredictOpCountBasedCost(operations, total_io_bytes, op_info);
costs.inaccurate = unknown_shapes;
+ costs.num_ops_with_unknown_shapes = unknown_shapes;
costs.max_memory = output_size;
return costs;
}
@@ -627,6 +639,7 @@ int64 OpLevelCostEstimator::CountMatMulOperations(
if (op_features.inputs_size() < 2) {
LOG(ERROR) << "Need 2 inputs but got " << op_features.inputs_size();
+ // TODO(pcma): Try to separate invalid inputs from unknown shapes
*found_unknown_shapes = true;
return 0;
}
@@ -694,11 +707,13 @@ int64 OpLevelCostEstimator::CountBatchMatMulOperations(
const OpInfo& op_features, bool* found_unknown_shapes) const {
if (op_features.op() != kBatchMatMul) {
LOG(ERROR) << "Invalid Operation: " << op_features.op();
+ // TODO(pcma): Try to separate invalid inputs from unknown shapes
*found_unknown_shapes = true;
return 0;
}
if (op_features.inputs_size() != 2) {
LOG(ERROR) << "Expected 2 inputs but got " << op_features.inputs_size();
+ // TODO(pcma): Try to separate invalid inputs from unknown shapes
*found_unknown_shapes = true;
return 0;
}
@@ -858,6 +873,7 @@ int64 OpLevelCostEstimator::CountConv2DBackpropInputOperations(
"kDepthwiseConv2dNativeBackpropInput";
if (op_features.inputs_size() < 2) {
+ // TODO(pcma): Try to separate invalid inputs from unknown shapes
*found_unknown_shapes = true;
return ops;
}
@@ -935,6 +951,7 @@ int64 OpLevelCostEstimator::CountConv2DBackpropFilterOperations(
}
if (op_features.inputs_size() < 1) {
+ // TODO(pcma): Try to separate invalid inputs from unknown shapes
*found_unknown_shapes = true;
return ops;
}
@@ -1037,6 +1054,7 @@ Costs OpLevelCostEstimator::PredictConv2D(const OpContext& op_context) const {
auto costs = PredictOpCountBasedCost(
CountConv2DOperations(op_features, &found_unknown_shapes), op_features);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
return costs;
}
@@ -1049,6 +1067,7 @@ Costs OpLevelCostEstimator::PredictConv2DBackpropInput(
op_features, nullptr, &found_unknown_shapes),
op_features);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
return costs;
}
@@ -1061,6 +1080,7 @@ Costs OpLevelCostEstimator::PredictConv2DBackpropFilter(
op_features, nullptr, &found_unknown_shapes),
op_features);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
return costs;
}
@@ -1148,6 +1168,7 @@ Costs OpLevelCostEstimator::PredictFusedConv2DBiasActivation(
// Construct component operations and run the cost computation.
auto costs = PredictFusedOp(op_context_with_output, component_ops);
costs.inaccurate |= found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = costs.inaccurate;
return costs;
}
@@ -1157,6 +1178,7 @@ Costs OpLevelCostEstimator::PredictMatMul(const OpContext& op_context) const {
auto costs = PredictOpCountBasedCost(
CountMatMulOperations(op_features, &found_unknown_shapes), op_features);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
return costs;
}
@@ -1171,6 +1193,7 @@ Costs OpLevelCostEstimator::PredictIdentity(const OpContext& op_context) const {
VLOG(1) << "Op:" << op_features.op() << " Execution Time 0 (ns)";
Costs result = Costs::ZeroCosts();
result.max_memory = CalculateOutputSize(op_features, &result.inaccurate);
+ result.num_ops_with_unknown_shapes = result.inaccurate;
// Assign the minimum amount of time we can represent to the identity op since
// it tends to be really cheap.
result.compute_time = kMinComputeTime;
@@ -1184,6 +1207,7 @@ Costs OpLevelCostEstimator::PredictVariable(const OpContext& op_context) const {
Costs result = Costs::ZeroCosts();
result.persistent_memory =
CalculateOutputSize(op_features, &result.inaccurate);
+ result.num_ops_with_unknown_shapes = result.inaccurate;
result.compute_time = kMinComputeTime;
result.execution_time = result.execution_time;
@@ -1198,6 +1222,7 @@ Costs OpLevelCostEstimator::PredictBatchMatMul(
CountBatchMatMulOperations(op_features, &found_unknown_shapes),
op_features);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
return costs;
}
@@ -1205,6 +1230,7 @@ Costs OpLevelCostEstimator::PredictMetadata(const OpContext& op_context) const {
const auto& op_features = op_context.op_info;
Costs costs = Costs::ZeroCosts();
costs.max_memory = CalculateOutputSize(op_features, &costs.inaccurate);
+ costs.num_ops_with_unknown_shapes = costs.inaccurate;
// Metadata operations are so cheap we assume they take the minimum amount of
// time we can represent (1 ns).
costs.compute_time = kMinComputeTime;
@@ -1249,6 +1275,7 @@ Costs OpLevelCostEstimator::PredictGatherOrSlice(
const double total_io = input_size + output_size;
Costs costs = PredictOpCountBasedCost(op_count, total_io, op_info);
costs.inaccurate = unknown_shapes;
+ costs.num_ops_with_unknown_shapes = unknown_shapes;
costs.max_memory = output_size;
return costs;
@@ -1390,6 +1417,7 @@ Costs OpLevelCostEstimator::PredictMaxPool(const OpContext& op_context) const {
Costs costs = PredictOpCountBasedCost(
ops, total_input_size + total_output_size, op_info);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
costs.max_memory = total_output_size;
return costs;
}
@@ -1432,6 +1460,7 @@ Costs OpLevelCostEstimator::PredictMaxPoolGrad(
Costs costs = PredictOpCountBasedCost(
ops, total_input_size + total_output_size, op_info);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
costs.max_memory = total_output_size;
return costs;
}
@@ -1464,6 +1493,7 @@ Costs OpLevelCostEstimator::PredictAvgPool(const OpContext& op_context) const {
Costs costs = PredictOpCountBasedCost(
ops, total_input_size + total_output_size, op_info);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
costs.max_memory = total_output_size;
return costs;
}
@@ -1516,6 +1546,7 @@ Costs OpLevelCostEstimator::PredictAvgPoolGrad(
Costs costs = PredictOpCountBasedCost(
ops, total_input_size + total_output_size, op_info);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
costs.max_memory = total_output_size;
return costs;
}
@@ -1562,6 +1593,7 @@ Costs OpLevelCostEstimator::PredictFusedBatchNorm(
ops, total_input_size + total_output_size + total_internal_read_size,
op_info);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
costs.max_memory = total_output_size;
return costs;
}
@@ -1595,6 +1627,7 @@ Costs OpLevelCostEstimator::PredictFusedBatchNormGrad(
ops, total_input_size + total_output_size + total_internal_read_size,
op_info);
costs.inaccurate = found_unknown_shapes;
+ costs.num_ops_with_unknown_shapes = found_unknown_shapes;
costs.max_memory = total_output_size;
return costs;
}
diff --git a/tensorflow/core/grappler/costs/op_level_cost_estimator_test.cc b/tensorflow/core/grappler/costs/op_level_cost_estimator_test.cc
index 77352f6652..9e579098ef 100644
--- a/tensorflow/core/grappler/costs/op_level_cost_estimator_test.cc
+++ b/tensorflow/core/grappler/costs/op_level_cost_estimator_test.cc
@@ -488,7 +488,9 @@ TEST_F(OpLevelCostEstimatorTest, TestGatherCosts) {
EXPECT_EQ(Costs::Duration(130), cost.memory_time);
EXPECT_EQ(Costs::Duration(16), cost.compute_time);
EXPECT_EQ(Costs::Duration(146), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, TestGatherCostsWithoutOutput) {
@@ -504,7 +506,9 @@ TEST_F(OpLevelCostEstimatorTest, TestGatherCostsWithoutOutput) {
EXPECT_EQ(Costs::Duration(0), cost.memory_time);
EXPECT_EQ(Costs::Duration(0), cost.compute_time);
EXPECT_EQ(Costs::Duration(0), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, TestSliceCosts) {
@@ -522,7 +526,9 @@ TEST_F(OpLevelCostEstimatorTest, TestSliceCosts) {
EXPECT_EQ(Costs::Duration(81), cost.memory_time);
EXPECT_EQ(Costs::Duration(10), cost.compute_time);
EXPECT_EQ(Costs::Duration(91), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, BiasAddExecutionTime) {
@@ -530,7 +536,9 @@ TEST_F(OpLevelCostEstimatorTest, BiasAddExecutionTime) {
EXPECT_EQ(Costs::Duration(8400), cost.memory_time);
EXPECT_EQ(Costs::Duration(1000), cost.compute_time);
EXPECT_EQ(Costs::Duration(9400), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, Conv2DExecutionTime) {
@@ -538,7 +546,9 @@ TEST_F(OpLevelCostEstimatorTest, Conv2DExecutionTime) {
EXPECT_EQ(Costs::Duration(233780), cost.memory_time);
EXPECT_EQ(Costs::Duration(354877440), cost.compute_time);
EXPECT_EQ(Costs::Duration(355111220), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, DepthwiseConv2dNativeExecutionTime) {
@@ -547,7 +557,9 @@ TEST_F(OpLevelCostEstimatorTest, DepthwiseConv2dNativeExecutionTime) {
EXPECT_EQ(Costs::Duration(112340), cost.memory_time);
EXPECT_EQ(Costs::Duration(4158720), cost.compute_time);
EXPECT_EQ(Costs::Duration(4271060), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, DummyExecutionTime) {
@@ -555,7 +567,9 @@ TEST_F(OpLevelCostEstimatorTest, DummyExecutionTime) {
EXPECT_EQ(Costs::Duration(2000), cost.memory_time);
EXPECT_EQ(Costs::Duration(0), cost.compute_time);
EXPECT_EQ(Costs::Duration(2000), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, ExecutionTimeSumOrMax) {
@@ -564,7 +578,9 @@ TEST_F(OpLevelCostEstimatorTest, ExecutionTimeSumOrMax) {
EXPECT_EQ(Costs::Duration(2000), cost.memory_time);
EXPECT_EQ(Costs::Duration(0), cost.compute_time);
EXPECT_EQ(Costs::Duration(2000), cost.execution_time); // max(2000, 200)
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
SetComputeMemoryOverlap(false); // Set it back to default.
}
@@ -576,7 +592,9 @@ TEST_F(OpLevelCostEstimatorTest,
EXPECT_EQ(Costs::Duration(825345), cost.memory_time);
EXPECT_EQ(Costs::Duration(355321038), cost.compute_time);
EXPECT_EQ(Costs::Duration(356146383), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNCHW_HWIO) {
@@ -586,7 +604,9 @@ TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNCHW_HWIO) {
EXPECT_EQ(Costs::Duration(1416808), cost.memory_time);
EXPECT_EQ(Costs::Duration(355616770), cost.compute_time);
EXPECT_EQ(Costs::Duration(357033578), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNCHW_OIHW) {
@@ -596,7 +616,9 @@ TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNCHW_OIHW) {
EXPECT_EQ(Costs::Duration(1416808), cost.memory_time);
EXPECT_EQ(Costs::Duration(355616770), cost.compute_time);
EXPECT_EQ(Costs::Duration(357033578), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNHWC_HWIO) {
@@ -606,7 +628,9 @@ TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNHWC_HWIO) {
EXPECT_EQ(Costs::Duration(1416808), cost.memory_time);
EXPECT_EQ(Costs::Duration(355616770), cost.compute_time);
EXPECT_EQ(Costs::Duration(357033578), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNHWC_OIHW) {
@@ -616,7 +640,9 @@ TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNHWC_OIHW) {
EXPECT_EQ(Costs::Duration(1416808), cost.memory_time);
EXPECT_EQ(Costs::Duration(355616770), cost.compute_time);
EXPECT_EQ(Costs::Duration(357033578), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
// TODO(yaozhang): Update once NCHW_VECT_C is supported.
@@ -627,7 +653,9 @@ TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNCHW_VECT_C_OIHW) {
EXPECT_EQ(Costs::Duration(0), cost.memory_time);
EXPECT_EQ(Costs::Duration(0), cost.compute_time);
EXPECT_EQ(Costs::Duration(0), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
// TODO(yaozhang): Update once OIHW_VECT_I is supported.
@@ -638,7 +666,9 @@ TEST_F(OpLevelCostEstimatorTest, FusedConv2DBiasActivationNCHW_OIHW_VECT_I) {
EXPECT_EQ(Costs::Duration(0), cost.memory_time);
EXPECT_EQ(Costs::Duration(0), cost.compute_time);
EXPECT_EQ(Costs::Duration(0), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, MulExecutionTime) {
@@ -646,7 +676,9 @@ TEST_F(OpLevelCostEstimatorTest, MulExecutionTime) {
EXPECT_EQ(Costs::Duration(2000), cost.memory_time);
EXPECT_EQ(Costs::Duration(200), cost.compute_time);
EXPECT_EQ(Costs::Duration(2200), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, MulBroadcastExecutionTime) {
@@ -654,7 +686,9 @@ TEST_F(OpLevelCostEstimatorTest, MulBroadcastExecutionTime) {
EXPECT_EQ(Costs::Duration(3600), cost.memory_time);
EXPECT_EQ(Costs::Duration(400), cost.compute_time);
EXPECT_EQ(Costs::Duration(4000), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, ModExecutionTime) {
@@ -662,7 +696,9 @@ TEST_F(OpLevelCostEstimatorTest, ModExecutionTime) {
EXPECT_EQ(Costs::Duration(2000), cost.memory_time);
EXPECT_EQ(Costs::Duration(1600), cost.compute_time);
EXPECT_EQ(Costs::Duration(3600), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, ReluExecutionTime) {
@@ -670,28 +706,77 @@ TEST_F(OpLevelCostEstimatorTest, ReluExecutionTime) {
EXPECT_EQ(Costs::Duration(800), cost.memory_time);
EXPECT_EQ(Costs::Duration(100), cost.compute_time);
EXPECT_EQ(Costs::Duration(900), cost.execution_time);
+ EXPECT_EQ(1, cost.num_ops_total);
EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
}
TEST_F(OpLevelCostEstimatorTest, UnknownOrPartialShape) {
- EXPECT_FALSE(PredictCosts(DescribeMatMul(2, 4, 7, 7)).inaccurate);
- EXPECT_TRUE(PredictCosts(DescribeMatMul(-1, 4, 7, 7)).inaccurate);
- EXPECT_TRUE(PredictCosts(DescribeMatMul(2, 4, -1, 7)).inaccurate);
-
- EXPECT_FALSE(PredictCosts(DescribeConvolution(16, 19, 19, 48, 48, 5, 5, 256))
- .inaccurate);
- EXPECT_TRUE(PredictCosts(DescribeConvolution(16, -1, 19, 48, 48, 5, 5, 256))
- .inaccurate);
+ {
+ auto cost = PredictCosts(DescribeMatMul(2, 4, 7, 7));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost = PredictCosts(DescribeMatMul(-1, 4, 7, 7));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(1, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost = PredictCosts(DescribeMatMul(2, 4, -1, 7));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(1, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost =
+ PredictCosts(DescribeConvolution(16, 19, 19, 48, 48, 5, 5, 256));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost =
+ PredictCosts(DescribeConvolution(16, -1, 19, 48, 48, 5, 5, 256));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(1, cost.num_ops_with_unknown_shapes);
+ }
}
TEST_F(OpLevelCostEstimatorTest, BatchMatMul) {
- EXPECT_TRUE(PredictCosts(DescribeBatchMatMul({}, {})).inaccurate);
- EXPECT_TRUE(PredictCosts(DescribeBatchMatMul({2, 4}, {})).inaccurate);
- EXPECT_FALSE(PredictCosts(DescribeBatchMatMul({2, 4}, {4, 2})).inaccurate);
- EXPECT_FALSE(
- PredictCosts(DescribeBatchMatMul({1, 2, 4}, {1, 4, 2})).inaccurate);
- EXPECT_FALSE(
- PredictCosts(DescribeBatchMatMul({2, 4}, {1, 3, 4, 2})).inaccurate);
+ {
+ auto cost = PredictCosts(DescribeBatchMatMul({}, {}));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(1, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost = PredictCosts(DescribeBatchMatMul({2, 4}, {}));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_TRUE(cost.inaccurate);
+ EXPECT_EQ(1, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost = PredictCosts(DescribeBatchMatMul({2, 4}, {4, 2}));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost = PredictCosts(DescribeBatchMatMul({1, 2, 4}, {1, 4, 2}));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
+ }
+ {
+ auto cost = PredictCosts(DescribeBatchMatMul({2, 4}, {1, 3, 4, 2}));
+ EXPECT_EQ(1, cost.num_ops_total);
+ EXPECT_FALSE(cost.inaccurate);
+ EXPECT_EQ(0, cost.num_ops_with_unknown_shapes);
+ }
bool matmul_inaccurate = false;
bool batch_matmul_inaccurate = false;
EXPECT_EQ(
@@ -813,7 +898,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictMaxPool) {
EXPECT_EQ(Costs::Duration(1075200), costs.execution_time);
EXPECT_EQ(Costs::Duration(307200), costs.compute_time);
EXPECT_EQ(Costs::Duration(768000), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 1x1 window with 2x2 stride: used for shortcut in resnet-50.
@@ -821,7 +908,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictMaxPool) {
EXPECT_EQ(Costs::Duration(499200), costs.execution_time);
EXPECT_EQ(Costs::Duration(38400), costs.compute_time);
EXPECT_EQ(Costs::Duration(460800), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 2x2 window with 3x3 stride.
@@ -829,7 +918,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictMaxPool) {
EXPECT_EQ(Costs::Duration(561792), costs.execution_time);
EXPECT_EQ(Costs::Duration(56448), costs.compute_time);
EXPECT_EQ(Costs::Duration(505344), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
}
@@ -849,7 +940,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictMaxPoolGrad) {
EXPECT_EQ(Costs::Duration(1996800), costs.execution_time);
EXPECT_EQ(Costs::Duration(614400), costs.compute_time);
EXPECT_EQ(Costs::Duration(1382400), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 1x1 window with 2x2 stride: used for shortcut in resnet-50.
@@ -857,7 +950,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictMaxPoolGrad) {
EXPECT_EQ(Costs::Duration(1536000), costs.execution_time);
EXPECT_EQ(Costs::Duration(153600), costs.compute_time);
EXPECT_EQ(Costs::Duration(1382400), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 2x2 window with 3x3 stride.
@@ -865,7 +960,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictMaxPoolGrad) {
EXPECT_EQ(Costs::Duration(1514112), costs.execution_time);
EXPECT_EQ(Costs::Duration(210048), costs.compute_time);
EXPECT_EQ(Costs::Duration(1304064), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
}
@@ -884,7 +981,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictAvgPool) {
EXPECT_EQ(Costs::Duration(1113600), costs.execution_time);
EXPECT_EQ(Costs::Duration(345600), costs.compute_time);
EXPECT_EQ(Costs::Duration(768000), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 1x1 window with 2x2 stride: used for shortcut in resnet-50.
@@ -892,7 +991,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictAvgPool) {
EXPECT_EQ(Costs::Duration(499200), costs.execution_time);
EXPECT_EQ(Costs::Duration(38400), costs.compute_time);
EXPECT_EQ(Costs::Duration(460800), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 2x2 window with 3x3 stride.
@@ -900,7 +1001,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictAvgPool) {
EXPECT_EQ(Costs::Duration(580608), costs.execution_time);
EXPECT_EQ(Costs::Duration(75264), costs.compute_time);
EXPECT_EQ(Costs::Duration(505344), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
}
@@ -920,7 +1023,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictAvgPoolGrad) {
EXPECT_EQ(Costs::Duration(1305602), costs.execution_time);
EXPECT_EQ(Costs::Duration(537600), costs.compute_time);
EXPECT_EQ(Costs::Duration(768002), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 1x1 window with 2x2 stride: used for shortcut in resnet-50.
@@ -928,7 +1033,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictAvgPoolGrad) {
EXPECT_EQ(Costs::Duration(960002), costs.execution_time);
EXPECT_EQ(Costs::Duration(192000), costs.compute_time);
EXPECT_EQ(Costs::Duration(768002), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
// 2x2 window with 3x3 stride.
@@ -936,7 +1043,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictAvgPoolGrad) {
EXPECT_EQ(Costs::Duration(862082), costs.execution_time);
EXPECT_EQ(Costs::Duration(172416), costs.compute_time);
EXPECT_EQ(Costs::Duration(689666), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
}
@@ -953,7 +1062,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictFusedBatchNorm) {
EXPECT_EQ(Costs::Duration(614737), costs.execution_time);
EXPECT_EQ(Costs::Duration(153706), costs.compute_time);
EXPECT_EQ(Costs::Duration(461031), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
@@ -961,7 +1072,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictFusedBatchNorm) {
EXPECT_EQ(Costs::Duration(204913), costs.execution_time);
EXPECT_EQ(Costs::Duration(51236), costs.compute_time);
EXPECT_EQ(Costs::Duration(153677), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
@@ -969,7 +1082,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictFusedBatchNorm) {
EXPECT_EQ(Costs::Duration(384154), costs.execution_time);
EXPECT_EQ(Costs::Duration(76800), costs.compute_time);
EXPECT_EQ(Costs::Duration(307354), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
@@ -978,6 +1093,8 @@ TEST_F(OpLevelCostEstimatorTest, PredictFusedBatchNorm) {
EXPECT_EQ(Costs::Duration(25600), costs.compute_time);
EXPECT_EQ(Costs::Duration(102452), costs.memory_time);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(1, costs.num_ops_total);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
}
@@ -994,7 +1111,9 @@ TEST_F(OpLevelCostEstimatorTest, PredictFusedBatchNormGrad) {
EXPECT_EQ(Costs::Duration(1037050), costs.execution_time);
EXPECT_EQ(Costs::Duration(422496), costs.compute_time);
EXPECT_EQ(Costs::Duration(614554), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
}
{
@@ -1002,7 +1121,81 @@ TEST_F(OpLevelCostEstimatorTest, PredictFusedBatchNormGrad) {
EXPECT_EQ(Costs::Duration(6503809), costs.execution_time);
EXPECT_EQ(Costs::Duration(2649677), costs.compute_time);
EXPECT_EQ(Costs::Duration(3854132), costs.memory_time);
+ EXPECT_EQ(1, costs.num_ops_total);
EXPECT_FALSE(costs.inaccurate);
+ EXPECT_EQ(0, costs.num_ops_with_unknown_shapes);
+ }
+}
+
+TEST_F(OpLevelCostEstimatorTest, MaybeGetMinimumShape) {
+ {
+ TensorShapeProto x;
+ x.set_unknown_rank(true);
+ bool unknown_shapes = false;
+ TensorShapeProto y = MaybeGetMinimumShape(x, 4, &unknown_shapes);
+ EXPECT_TRUE(unknown_shapes);
+ ExpectTensorShape({1, 1, 1, 1}, y);
+ }
+
+ {
+ TensorShapeProto x;
+ x.set_unknown_rank(false);
+ bool unknown_shapes = false;
+ TensorShapeProto y = MaybeGetMinimumShape(x, 1, &unknown_shapes);
+ EXPECT_FALSE(unknown_shapes);
+ ExpectTensorShape({1}, y);
+ }
+
+ {
+ TensorShapeProto x;
+ x.set_unknown_rank(false);
+ bool unknown_shapes = false;
+ TensorShapeProto y = MaybeGetMinimumShape(x, 2, &unknown_shapes);
+ EXPECT_FALSE(unknown_shapes);
+ ExpectTensorShape({1, 1}, y);
+ }
+
+ {
+ TensorShapeProto x;
+ x.set_unknown_rank(false);
+ x.add_dim()->set_size(10);
+ x.add_dim()->set_size(20);
+ bool unknown_shapes = false;
+ TensorShapeProto y = MaybeGetMinimumShape(x, 2, &unknown_shapes);
+ EXPECT_FALSE(unknown_shapes);
+ ExpectTensorShape({10, 20}, y);
+
+ unknown_shapes = false;
+ TensorShapeProto z = MaybeGetMinimumShape(x, 4, &unknown_shapes);
+ EXPECT_TRUE(unknown_shapes);
+ EXPECT_EQ(4, z.dim_size());
+ ExpectTensorShape({10, 20, 1, 1}, z);
+ }
+
+ {
+ TensorShapeProto x;
+ x.set_unknown_rank(false);
+ x.add_dim()->set_size(10);
+ x.add_dim()->set_size(20);
+ x.add_dim()->set_size(-1);
+ x.add_dim()->set_size(20);
+ bool unknown_shapes = false;
+ TensorShapeProto y = MaybeGetMinimumShape(x, 4, &unknown_shapes);
+ EXPECT_TRUE(unknown_shapes);
+ ExpectTensorShape({10, 20, 1, 20}, y);
+ }
+
+ {
+ TensorShapeProto x;
+ x.set_unknown_rank(false);
+ x.add_dim()->set_size(10);
+ x.add_dim()->set_size(20);
+ x.add_dim()->set_size(30);
+ x.add_dim()->set_size(20);
+ bool unknown_shapes = false;
+ TensorShapeProto y = MaybeGetMinimumShape(x, 2, &unknown_shapes);
+ EXPECT_TRUE(unknown_shapes);
+ ExpectTensorShape({10, 20}, y);
}
}
} // end namespace grappler
diff --git a/tensorflow/core/grappler/costs/virtual_scheduler.cc b/tensorflow/core/grappler/costs/virtual_scheduler.cc
index f31d22e105..6e3ebdee12 100644
--- a/tensorflow/core/grappler/costs/virtual_scheduler.cc
+++ b/tensorflow/core/grappler/costs/virtual_scheduler.cc
@@ -47,9 +47,11 @@ Costs CombineCosts(const Costs& left, const Costs& right) {
result.execution_time += right.execution_time;
result.compute_time += right.compute_time;
result.memory_time += right.memory_time;
- if (right.inaccurate) {
- result.inaccurate = true;
- }
+
+ result.num_ops_total += right.num_ops_total;
+ if (right.inaccurate) result.inaccurate = true;
+ result.num_ops_with_unknown_shapes += right.num_ops_with_unknown_shapes;
+
if (right.max_memory != kMemoryUnknown) {
result.max_memory += right.max_memory;
}
@@ -283,6 +285,7 @@ VirtualScheduler::VirtualScheduler(const GrapplerItem* grappler_item,
grappler_item_(grappler_item),
use_static_shapes_(use_static_shapes),
placer_(cluster) {
+ graph_costs_.num_ops_total = 0;
initialized_ = false;
}
@@ -845,6 +848,11 @@ bool VirtualScheduler::MarkCurrNodeExecuted(const Costs& node_costs) {
}
Costs VirtualScheduler::Summary() const {
+ // Overall statement about accuracy
+ VLOG(1) << graph_costs_.num_ops_total << " ops processed in total, with "
+ << graph_costs_.num_ops_with_unknown_shapes
+ << " having unknown shapes";
+
// Print out basic execution summary.
VLOG(1) << "Expected execution time: " << graph_costs_.execution_time.count();
VLOG(1) << "Expected compute time: " << graph_costs_.compute_time.count();
@@ -906,6 +914,12 @@ Costs VirtualScheduler::Summary() const {
<< ", at the end: "
<< strings::HumanReadableNumBytes(state.memory_usage);
+ // Overall statement about accuracy
+ VLOG(1) << state.device_costs.num_ops_total
+ << " ops processed in total, with "
+ << state.device_costs.num_ops_with_unknown_shapes
+ << " having unknown shapes";
+
VLOG(1) << "Per-op execution time / compute time / memory time "
"(and memory usage at peak memory usage):";
diff --git a/tensorflow/core/grappler/costs/virtual_scheduler.h b/tensorflow/core/grappler/costs/virtual_scheduler.h
index 353ca6f071..0e66e8a463 100644
--- a/tensorflow/core/grappler/costs/virtual_scheduler.h
+++ b/tensorflow/core/grappler/costs/virtual_scheduler.h
@@ -114,6 +114,7 @@ struct DeviceState {
DeviceState() {
device_costs = Costs::ZeroCosts();
+ device_costs.num_ops_total = 0;
memory_usage = 0;
max_memory_usage = 0;
}
diff --git a/tensorflow/core/grappler/costs/virtual_scheduler_test.cc b/tensorflow/core/grappler/costs/virtual_scheduler_test.cc
index f9154e42f9..b1373d8317 100644
--- a/tensorflow/core/grappler/costs/virtual_scheduler_test.cc
+++ b/tensorflow/core/grappler/costs/virtual_scheduler_test.cc
@@ -942,7 +942,6 @@ versions {
// target_node.
std::unordered_map<string, OpContext> RunScheduler(
const string& target_node) {
- Costs zero_costs = Costs::ZeroCosts();
std::unordered_map<string, OpContext> ops_executed;
bool more_nodes = true;
do {
@@ -1632,6 +1631,9 @@ TEST_F(VirtualSchedulerTest, SummaryCostTest) {
// Misc - 5 * 1us
// Total: 13000005
EXPECT_EQ(13000005, c.execution_time.asMicroSeconds().count());
+ EXPECT_EQ(grappler_item_->graph.node_size(), c.num_ops_total);
+ EXPECT_FALSE(c.inaccurate);
+ EXPECT_EQ(0, c.num_ops_with_unknown_shapes);
}
// Like the above SummaryCostTest, but makes sure the stepstats timeline is
@@ -1645,6 +1647,9 @@ TEST_F(VirtualSchedulerTest, SummaryCostStepStatsTest) {
Costs c = scheduler_->Summary(&metadata);
StepStats stepstats = metadata.step_stats();
EXPECT_EQ(13000005, c.execution_time.asMicroSeconds().count());
+ EXPECT_EQ(grappler_item_->graph.node_size(), c.num_ops_total);
+ EXPECT_FALSE(c.inaccurate);
+ EXPECT_EQ(0, c.num_ops_with_unknown_shapes);
// Should only be 1 device!
EXPECT_EQ(1, stepstats.dev_stats().size());
diff --git a/tensorflow/core/grappler/optimizers/meta_optimizer.cc b/tensorflow/core/grappler/optimizers/meta_optimizer.cc
index 96f6fe1e0b..e778b7879d 100644
--- a/tensorflow/core/grappler/optimizers/meta_optimizer.cc
+++ b/tensorflow/core/grappler/optimizers/meta_optimizer.cc
@@ -35,6 +35,7 @@ limitations under the License.
#include "tensorflow/core/grappler/utils/functions.h"
#include "tensorflow/core/grappler/utils/topological_sort.h"
#include "tensorflow/core/lib/core/status.h"
+#include "tensorflow/core/util/ptr_util.h"
namespace tensorflow {
namespace grappler {
@@ -102,57 +103,57 @@ std::unique_ptr<GraphOptimizer> MetaOptimizer::MakeNewOptimizer(
Status MetaOptimizer::InitializeOptimizers(
std::vector<std::unique_ptr<GraphOptimizer>>* optimizers) const {
if (!cfg_.disable_model_pruning()) {
- optimizers->emplace_back(new ModelPruner());
+ optimizers->push_back(MakeUnique<ModelPruner>());
}
if (cfg_.function_optimization() != RewriterConfig::OFF) {
- optimizers->emplace_back(
- new FunctionOptimizer(cfg_.function_optimization()));
+ optimizers->push_back(
+ MakeUnique<FunctionOptimizer>(cfg_.function_optimization()));
}
if (cfg_.debug_stripper() == RewriterConfig::ON) {
- optimizers->emplace_back(new DebugStripper());
+ optimizers->push_back(MakeUnique<DebugStripper>());
}
if (cfg_.constant_folding() != RewriterConfig::OFF) {
- optimizers->emplace_back(
- new ConstantFolding(cfg_.constant_folding(), cpu_device_));
+ optimizers->push_back(
+ MakeUnique<ConstantFolding>(cfg_.constant_folding(), cpu_device_));
}
if (cfg_.shape_optimization() != RewriterConfig::OFF) {
- optimizers->emplace_back(new ShapeOptimizer());
+ optimizers->push_back(MakeUnique<ShapeOptimizer>());
}
if (cfg_.remapping() != RewriterConfig::OFF) {
- optimizers->emplace_back(new Remapper(cfg_.remapping()));
+ optimizers->push_back(MakeUnique<Remapper>(cfg_.remapping()));
}
if (cfg_.arithmetic_optimization() != RewriterConfig::OFF) {
- optimizers->emplace_back(
- new ArithmeticOptimizer(cfg_.arithmetic_optimization()));
+ optimizers->push_back(
+ MakeUnique<ArithmeticOptimizer>(cfg_.arithmetic_optimization()));
}
if (cfg_.loop_optimization() != RewriterConfig::OFF) {
- optimizers->emplace_back(
- new LoopOptimizer(cfg_.loop_optimization(), cpu_device_));
+ optimizers->push_back(
+ MakeUnique<LoopOptimizer>(cfg_.loop_optimization(), cpu_device_));
}
if (cfg_.dependency_optimization() != RewriterConfig::OFF) {
- optimizers->emplace_back(
- new DependencyOptimizer(cfg_.dependency_optimization()));
+ optimizers->push_back(
+ MakeUnique<DependencyOptimizer>(cfg_.dependency_optimization()));
}
if (cfg_.layout_optimizer() != RewriterConfig::OFF) {
- optimizers->emplace_back(new LayoutOptimizer());
+ optimizers->push_back(MakeUnique<LayoutOptimizer>());
}
if (cfg_.memory_optimization() != RewriterConfig::NO_MEM_OPT) {
if (cfg_.memory_optimizer_target_node_name_scope().empty()) {
- optimizers->emplace_back(
+ optimizers->push_back(
// Use the default target node name prefix "gradients/"
- new MemoryOptimizer(cfg_.memory_optimization()));
+ MakeUnique<MemoryOptimizer>(cfg_.memory_optimization()));
} else {
- optimizers->emplace_back(
- new MemoryOptimizer(cfg_.memory_optimization(),
- cfg_.memory_optimizer_target_node_name_scope()));
+ optimizers->push_back(MakeUnique<MemoryOptimizer>(
+ cfg_.memory_optimization(),
+ cfg_.memory_optimizer_target_node_name_scope()));
}
}
if (cfg_.auto_parallel().enable()) {
- optimizers->emplace_back(
- new AutoParallel(cfg_.auto_parallel().num_replicas()));
+ optimizers->push_back(
+ MakeUnique<AutoParallel>(cfg_.auto_parallel().num_replicas()));
}
if (cfg_.scoped_allocator_optimization()) {
- optimizers->emplace_back(new ScopedAllocatorOptimizer(
+ optimizers->push_back(MakeUnique<ScopedAllocatorOptimizer>(
cfg_.scoped_allocator_optimization(), cfg_.scoped_allocator_opts()));
}
return Status::OK();
@@ -382,8 +383,7 @@ Status MetaOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item,
TF_RETURN_IF_ERROR(MakeFunctionDef(func_item, flib, &optimized_func));
// Replace optimized function with a new FunctionDef.
- TF_RETURN_IF_ERROR(flib.RemoveFunction(func_name));
- TF_RETURN_IF_ERROR(flib.AddFunctionDef(optimized_func));
+ TF_RETURN_IF_ERROR(flib.ReplaceFunction(func_name, optimized_func));
}
// If optimized at least one function, update the graph library.
diff --git a/tensorflow/core/grappler/utils/functions.cc b/tensorflow/core/grappler/utils/functions.cc
index fd71406d2c..462b752316 100644
--- a/tensorflow/core/grappler/utils/functions.cc
+++ b/tensorflow/core/grappler/utils/functions.cc
@@ -303,12 +303,14 @@ Status GrapplerFunctionItemInstantiation::GetArgType(
}
GrapplerFunctionItem::GrapplerFunctionItem(
- const string& func_name, const AttrValueMap& func_attr,
+ const string& func_name, const string& description,
+ const AttrValueMap& func_attr,
const std::vector<InputArgExpansion>& input_arg_expansions,
const std::vector<OutputArgExpansion>& output_arg_expansions,
const std::vector<string>& keep_nodes, bool is_stateful,
GraphDef&& function_body)
- : func_attr_(func_attr),
+ : description_(description),
+ func_attr_(func_attr),
input_arg_expansions_(input_arg_expansions),
output_arg_expansions_(output_arg_expansions),
is_stateful_(is_stateful) {
@@ -337,6 +339,8 @@ GrapplerFunctionItem::GrapplerFunctionItem(
}
}
+const string& GrapplerFunctionItem::description() const { return description_; }
+
const std::vector<InputArgExpansion>& GrapplerFunctionItem::inputs() const {
return input_arg_expansions_;
}
@@ -589,7 +593,7 @@ Status MakeGrapplerFunctionItem(const FunctionDef& func,
bool is_stateful = signature.is_stateful();
*item = GrapplerFunctionItem(
- /*func_name=*/signature.name(),
+ /*func_name=*/signature.name(), /*description=*/signature.description(),
/*func_attr=*/AttrValueMap(func.attr().begin(), func.attr().end()),
inputs, outputs, keep_nodes, is_stateful, std::move(function_body));
return Status::OK();
@@ -674,6 +678,7 @@ Status MakeFunctionDef(const GrapplerFunctionItem& item,
const FunctionLibraryDefinition& flib,
FunctionDef* func) {
func->mutable_signature()->set_name(item.id);
+ func->mutable_signature()->set_description(item.description());
func->mutable_signature()->set_is_stateful(item.is_stateful());
// Build a GrapplerFunctionConnectivity from inputs and new function body.
diff --git a/tensorflow/core/grappler/utils/functions.h b/tensorflow/core/grappler/utils/functions.h
index 6227daa71b..9f607dc2ee 100644
--- a/tensorflow/core/grappler/utils/functions.h
+++ b/tensorflow/core/grappler/utils/functions.h
@@ -137,12 +137,15 @@ class GrapplerFunctionItem : public GrapplerItem {
public:
GrapplerFunctionItem() = default;
GrapplerFunctionItem(
- const string& func_name, const AttrValueMap& func_attr,
+ const string& func_name, const string& description,
+ const AttrValueMap& func_attr,
const std::vector<InputArgExpansion>& input_arg_expansions,
const std::vector<OutputArgExpansion>& output_arg_expansions,
const std::vector<string>& keep_nodes, bool is_stateful,
GraphDef&& function_body);
+ const string& description() const;
+
bool IsInputPlaceholder(const string& node_name) const;
const std::vector<InputArgExpansion>& inputs() const;
@@ -165,6 +168,7 @@ class GrapplerFunctionItem : public GrapplerItem {
friend Status ReplaceInputWithConst(const NodeDef&, int,
GrapplerFunctionItem*);
+ string description_;
AttrValueMap func_attr_; // Attributes specific to function definition that
// produced this item (FuncDef.attr field).
diff --git a/tensorflow/core/grappler/utils/functions_test.cc b/tensorflow/core/grappler/utils/functions_test.cc
index 8c3cc70351..b2d059e0ac 100644
--- a/tensorflow/core/grappler/utils/functions_test.cc
+++ b/tensorflow/core/grappler/utils/functions_test.cc
@@ -734,6 +734,33 @@ TEST_F(FunctionsTest, SwapFunctionBodyAndMakeFunctionDef) {
EXPECT_EQ("output:output:0", (*specialized.mutable_ret())["z"]);
}
+TEST_F(FunctionsTest, FunctionDefGrapplerFunctionItemRoundTrip) {
+ FunctionDef func = FunctionDefHelper::Define(
+ // Name
+ "DoNothing",
+ // Args
+ {"i: int32"},
+ // Return values
+ {"o: int32"},
+ // Attr def
+ {},
+ // Nodes
+ {{{"o"}, "Identity", {"i"}, {{"T", DT_INT32}}}});
+
+ constexpr char description[] = "This is a helpful description.";
+ func.mutable_signature()->set_description(description);
+ FunctionLibraryDefinition flib(OpRegistry::Global(), FunctionDefLibrary());
+
+ GrapplerFunctionItem item;
+ std::unordered_map<string, AttrValue> func_attr;
+ func_attr["T"].set_type(DT_INT32);
+ TF_EXPECT_OK(MakeGrapplerFunctionItem(func, func_attr, flib, &item));
+
+ FunctionDef func2;
+ TF_EXPECT_OK(MakeFunctionDef(item, flib, &func2));
+ EXPECT_TRUE(FunctionDefsEqual(func, func2));
+}
+
} // namespace
} // namespace grappler
} // namespace tensorflow
diff --git a/tensorflow/core/kernels/BUILD b/tensorflow/core/kernels/BUILD
index e66e9a10e7..e07d292629 100644
--- a/tensorflow/core/kernels/BUILD
+++ b/tensorflow/core/kernels/BUILD
@@ -52,6 +52,8 @@ load(
load(
"//third_party/mkl:build_defs.bzl",
"if_mkl",
+ "if_mkl_ml",
+ "mkl_deps",
)
load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda")
@@ -628,6 +630,7 @@ cc_library(
":gather_nd_op",
":gather_op",
":guarantee_const_op",
+ ":host_constant_op",
":identity_n_op",
":identity_op",
":inplace_ops",
@@ -650,7 +653,14 @@ cc_library(
":split_v_op",
":strided_slice_op",
":tile_ops",
- ":transpose_op",
+ ] + if_mkl(
+ [
+ ":mkl_transpose_op",
+ ],
+ [
+ ":transpose_op",
+ ],
+ ) + [
":unique_op",
":unpack_op",
":unravel_index_op",
@@ -695,6 +705,12 @@ tf_kernel_library(
)
tf_kernel_library(
+ name = "host_constant_op",
+ prefix = "host_constant_op",
+ deps = ARRAY_DEPS,
+)
+
+tf_kernel_library(
name = "diag_op",
prefix = "diag_op",
deps = ARRAY_DEPS,
@@ -887,18 +903,24 @@ tf_kernel_library(
deps = ARRAY_DEPS,
)
-tf_kernel_library(
- name = "transpose_op",
- srcs = [
- "transpose_op.cc",
- ] + if_mkl([
- "mkl_transpose_op.cc",
- ]),
- hdrs = ["transpose_op.h"],
- deps = ARRAY_DEPS + if_mkl([
- "//third_party/mkl:intel_binary_blob",
- "@mkl_dnn",
- ]),
+if_mkl(
+ [tf_mkl_kernel_library(
+ name = "mkl_transpose_op",
+ srcs = [
+ "mkl_transpose_op.cc",
+ "transpose_op.cc",
+ ],
+ hdrs = ["transpose_op.h"],
+ deps = ARRAY_DEPS + mkl_deps(),
+ )],
+ [tf_kernel_library(
+ name = "transpose_op",
+ srcs = [
+ "transpose_op.cc",
+ ],
+ hdrs = ["transpose_op.h"],
+ deps = ARRAY_DEPS,
+ )],
)
tf_kernel_library(
@@ -1286,6 +1308,7 @@ tf_cuda_cc_test(
srcs = ["gather_nd_op_test.cc"],
deps = [
":gather_nd_op",
+ ":host_constant_op",
":ops_testutil",
":ops_util",
"//tensorflow/core:core_cpu",
@@ -2542,6 +2565,7 @@ tf_kernel_library(
# allow multiple definitions when linking this.
linkopts = select({
"//tensorflow:darwin": [],
+ "//tensorflow:windows": [],
"//conditions:default": ["-Wl,-z,muldefs"],
}),
visibility = [":friends"],
@@ -2851,14 +2875,16 @@ tf_kernel_library(
tf_kernel_library(
name = "batch_matmul_op",
- srcs = [] + if_mkl([
+ srcs = if_mkl_ml([
"mkl_batch_matmul_op.cc",
]),
+ # <prefix>*impl.h are excluded by default from the CPU build, add explicitly.
+ hdrs = ["batch_matmul_op_impl.h"],
# Override EIGEN_STRONG_INLINE to inline when --define=override_eigen_strong_inline=true,
# to avoid long compiling time. See https://github.com/tensorflow/tensorflow/issues/10521
copts = if_override_eigen_strong_inline(["/DEIGEN_STRONG_INLINE=inline"]),
prefix = "batch_matmul_op",
- deps = MATH_DEPS + if_mkl([
+ deps = MATH_DEPS + if_mkl_ml([
"//third_party/mkl:intel_binary_blob",
]),
)
@@ -2941,10 +2967,7 @@ tf_kernel_library(
"@libxsmm_archive//:xsmm_avx",
],
"//conditions:default": [],
- }) + if_mkl([
- "//third_party/mkl:intel_binary_blob",
- "@mkl_dnn",
- ]) + if_cuda([
+ }) + mkl_deps() + if_cuda([
"//tensorflow/core/platform/default/build_config:cublas_plugin",
]),
)
@@ -3154,6 +3177,7 @@ tf_cuda_cc_test(
"//conditions:default": [],
}),
deps = [
+ ":host_constant_op",
":ops_testutil",
":ops_util",
":reduction_ops",
@@ -3289,6 +3313,7 @@ tf_cuda_cc_test(
srcs = ["diag_op_test.cc"],
deps = [
":diag_op",
+ ":host_constant_op",
":ops_testutil",
":ops_util",
"//tensorflow/core:core_cpu",
@@ -3616,6 +3641,7 @@ tf_cuda_cc_test(
name = "nn_ops_test",
srcs = ["nn_ops_test.cc"],
deps = [
+ ":host_constant_op",
":nn",
":ops_testutil",
":ops_util",
@@ -3763,6 +3789,7 @@ tf_cuda_cc_test(
srcs = ["spacetobatch_benchmark_test.cc"],
deps = [
":batch_space_ops",
+ ":host_constant_op",
":ops_testutil",
":ops_util",
"//tensorflow/core:core_cpu",
@@ -3902,6 +3929,7 @@ tf_cuda_cc_test(
size = "small",
srcs = ["random_op_test.cc"],
deps = [
+ ":host_constant_op",
":random_ops",
"//tensorflow/core:core_cpu",
"//tensorflow/core:framework",
@@ -4156,6 +4184,7 @@ tf_cuda_cc_tests(
"sparse_xent_op_test.cc",
],
deps = [
+ ":host_constant_op",
":ops_testutil",
":ops_util",
":sparse",
@@ -4369,6 +4398,7 @@ cc_library(
":regex_full_match_op",
":regex_replace_op",
":string_join_op",
+ ":string_length_op",
":string_split_op",
":string_strip_op",
":string_to_hash_bucket_op",
@@ -4404,6 +4434,12 @@ tf_kernel_library(
)
tf_kernel_library(
+ name = "string_length_op",
+ prefix = "string_length_op",
+ deps = STRING_DEPS,
+)
+
+tf_kernel_library(
name = "regex_full_match_op",
prefix = "regex_full_match_op",
deps = STRING_DEPS + ["@com_googlesource_code_re2//:re2"],
@@ -4415,12 +4451,48 @@ tf_kernel_library(
deps = STRING_DEPS + ["@com_googlesource_code_re2//:re2"],
)
+tf_cc_test(
+ name = "regex_replace_op_test",
+ size = "small",
+ srcs = ["regex_replace_op_test.cc"],
+ deps = [
+ ":regex_replace_op",
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:framework",
+ "//tensorflow/core:lib",
+ "//tensorflow/core:protos_all_cc",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ "//tensorflow/core:testlib",
+ "//tensorflow/core/kernels:ops_testutil",
+ "//tensorflow/core/kernels:ops_util",
+ ],
+)
+
tf_kernel_library(
name = "string_split_op",
prefix = "string_split_op",
deps = STRING_DEPS,
)
+tf_cc_test(
+ name = "string_split_op_test",
+ size = "small",
+ srcs = ["string_split_op_test.cc"],
+ deps = [
+ ":string_split_op",
+ "//tensorflow/core:core_cpu",
+ "//tensorflow/core:framework",
+ "//tensorflow/core:lib",
+ "//tensorflow/core:protos_all_cc",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ "//tensorflow/core:testlib",
+ "//tensorflow/core/kernels:ops_testutil",
+ "//tensorflow/core/kernels:ops_util",
+ ],
+)
+
tf_kernel_library(
name = "string_strip_op",
prefix = "string_strip_op",
@@ -4494,6 +4566,7 @@ tf_cuda_cc_test(
size = "small",
srcs = ["multinomial_op_test.cc"],
deps = [
+ ":host_constant_op",
":multinomial_op",
":ops_util",
"//tensorflow/core:core_cpu",
@@ -4521,6 +4594,7 @@ tf_cuda_cc_test(
size = "small",
srcs = ["parameterized_truncated_normal_op_test.cc"],
deps = [
+ ":host_constant_op",
":ops_util",
":parameterized_truncated_normal_op",
"//tensorflow/core:core_cpu",
@@ -5379,6 +5453,18 @@ cc_library(
alwayslink = 1,
)
+cc_library(
+ name = "android_whole_file_read_ops",
+ srcs = if_android(["whole_file_read_ops.cc"]),
+ copts = tf_copts(),
+ linkopts = ["-ldl"],
+ visibility = ["//visibility:public"],
+ deps = [
+ "//tensorflow/core:android_tensorflow_lib_lite",
+ ],
+ alwayslink = 1,
+)
+
# Quantization-specific OpKernels
tf_kernel_library(
@@ -6122,8 +6208,7 @@ tf_mkl_kernel_library(
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core:nn_ops_op_lib",
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ ] + mkl_deps(),
)
tf_mkl_kernel_library(
@@ -6137,8 +6222,7 @@ tf_mkl_kernel_library(
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core:nn_ops_op_lib",
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ ] + mkl_deps(),
)
tf_mkl_kernel_library(
@@ -6153,8 +6237,7 @@ tf_mkl_kernel_library(
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core:nn_ops_op_lib",
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ ] + mkl_deps(),
)
tf_mkl_kernel_library(
@@ -6173,8 +6256,7 @@ tf_mkl_kernel_library(
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core:nn_ops_op_lib",
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ ] + mkl_deps(),
)
tf_mkl_kernel_library(
@@ -6189,8 +6271,7 @@ tf_mkl_kernel_library(
"//tensorflow/core:lib_internal",
"//tensorflow/core:nn_ops_op_lib",
"//third_party/eigen3",
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ ] + mkl_deps(),
)
tf_mkl_kernel_library(
@@ -6205,56 +6286,43 @@ tf_mkl_kernel_library(
"//tensorflow/core:lib_internal",
"//tensorflow/core:nn_ops_op_lib",
"//third_party/eigen3",
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ ] + mkl_deps(),
)
tf_mkl_kernel_library(
name = "mkl_fused_batch_norm_op",
srcs = ["mkl_fused_batch_norm_op.cc"],
- deps = NN_DEPS + [
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ deps = NN_DEPS + mkl_deps(),
)
tf_mkl_kernel_library(
name = "mkl_aggregate_ops",
prefix = "mkl_aggregate_ops",
- deps = MATH_DEPS + [
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ deps = MATH_DEPS + mkl_deps(),
)
tf_mkl_kernel_library(
name = "mkl_concat_op",
prefix = "mkl_concat_op",
- deps = ARRAY_DEPS + [
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ deps = ARRAY_DEPS + mkl_deps(),
)
tf_mkl_kernel_library(
name = "mkl_reshape_op",
prefix = "mkl_reshape_op",
- deps = ARRAY_DEPS + [
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ deps = ARRAY_DEPS + mkl_deps(),
)
tf_mkl_kernel_library(
name = "mkl_identity_op",
prefix = "mkl_identity_op",
- deps = ARRAY_DEPS + [
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ deps = ARRAY_DEPS + mkl_deps(),
)
tf_mkl_kernel_library(
name = "mkl_lrn_op",
prefix = "mkl_lrn_op",
- deps = NN_DEPS + [
- "//third_party/mkl:intel_binary_blob",
- ] + if_mkl(["@mkl_dnn"]),
+ deps = NN_DEPS + mkl_deps(),
)
tf_mkl_kernel_library(
@@ -6265,10 +6333,7 @@ tf_mkl_kernel_library(
"cwise_ops_gradients.h",
],
prefix = "mkl_cwise_ops_common",
- deps = NN_DEPS + [
- "cwise_op",
- "//third_party/mkl:intel_binary_blob",
- ],
+ deps = NN_DEPS + mkl_deps() + [":cwise_op"],
)
# NOTE(lespeholt): This rule is deprecated, please use:
diff --git a/tensorflow/core/kernels/as_string_op.cc b/tensorflow/core/kernels/as_string_op.cc
index a7757d1361..e6d6c40f76 100644
--- a/tensorflow/core/kernels/as_string_op.cc
+++ b/tensorflow/core/kernels/as_string_op.cc
@@ -47,6 +47,7 @@ class AsStringOp : public OpKernel {
case DT_FLOAT:
case DT_DOUBLE:
case DT_COMPLEX64:
+ case DT_COMPLEX128:
break;
default:
OP_REQUIRES(ctx, !(scientific || shortest),
@@ -83,6 +84,7 @@ class AsStringOp : public OpKernel {
case DT_FLOAT:
case DT_DOUBLE:
case DT_COMPLEX64:
+ case DT_COMPLEX128:
if (shortest) {
strings::Appendf(&format_, "g");
} else if (scientific) {
@@ -100,7 +102,7 @@ class AsStringOp : public OpKernel {
DataTypeString(dtype)));
}
- if (dtype == DT_COMPLEX64) {
+ if (dtype == DT_COMPLEX64 || dtype == DT_COMPLEX128) {
format_ = strings::Printf("(%s,%s)", format_.c_str(), format_.c_str());
}
}
@@ -144,6 +146,13 @@ class AsStringOp : public OpKernel {
format_.c_str(), input_flat(i).real(), input_flat(i).imag());
}
} break;
+ case (DT_COMPLEX128): {
+ const auto& input_flat = input_tensor->flat<complex128>();
+ for (int i = 0; i < input_flat.size(); ++i) {
+ output_flat(i) = strings::Printf(
+ format_.c_str(), input_flat(i).real(), input_flat(i).imag());
+ }
+ } break;
default:
bool can_encode_type = false;
OP_REQUIRES(context, can_encode_type,
diff --git a/tensorflow/core/kernels/batch_matmul_op_complex.cc b/tensorflow/core/kernels/batch_matmul_op_complex.cc
index b77c80c01f..54c45bfe63 100644
--- a/tensorflow/core/kernels/batch_matmul_op_complex.cc
+++ b/tensorflow/core/kernels/batch_matmul_op_complex.cc
@@ -17,7 +17,7 @@ limitations under the License.
namespace tensorflow {
-#if !defined(INTEL_MKL) || defined(DO_NOT_USE_ML)
+#if !defined(INTEL_MKL) || defined(INTEL_MKL_DNN_ONLY)
TF_CALL_complex64(REGISTER_BATCH_MATMUL_CPU);
TF_CALL_complex128(REGISTER_BATCH_MATMUL_CPU);
#endif
diff --git a/tensorflow/core/kernels/batch_matmul_op_impl.h b/tensorflow/core/kernels/batch_matmul_op_impl.h
index 475bda848d..766713a338 100644
--- a/tensorflow/core/kernels/batch_matmul_op_impl.h
+++ b/tensorflow/core/kernels/batch_matmul_op_impl.h
@@ -15,6 +15,9 @@ limitations under the License.
// See docs in ../ops/math_ops.cc.
+#ifndef TENSORFLOW_CORE_KERNELS_BATCH_MATMUL_OP_IMPL_H_
+#define TENSORFLOW_CORE_KERNELS_BATCH_MATMUL_OP_IMPL_H_
+
#define EIGEN_USE_THREADS
#include <vector>
@@ -613,3 +616,5 @@ class BatchMatMul : public OpKernel {
BatchMatMul<SYCLDevice, TYPE>)
#endif // TENSORFLOW_USE_SYCL
} // end namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_BATCH_MATMUL_OP_IMPL_H_
diff --git a/tensorflow/core/kernels/batch_matmul_op_real.cc b/tensorflow/core/kernels/batch_matmul_op_real.cc
index fe259c1634..584b507c70 100644
--- a/tensorflow/core/kernels/batch_matmul_op_real.cc
+++ b/tensorflow/core/kernels/batch_matmul_op_real.cc
@@ -21,7 +21,7 @@ limitations under the License.
namespace tensorflow {
-#if !defined(INTEL_MKL) || defined(DO_NOT_USE_ML)
+#if !defined(INTEL_MKL) || defined(INTEL_MKL_DNN_ONLY)
TF_CALL_float(REGISTER_BATCH_MATMUL_CPU);
TF_CALL_double(REGISTER_BATCH_MATMUL_CPU);
#endif
@@ -31,8 +31,7 @@ TF_CALL_int32(REGISTER_BATCH_MATMUL_CPU);
#if GOOGLE_CUDA
TF_CALL_float(REGISTER_BATCH_MATMUL_GPU);
TF_CALL_double(REGISTER_BATCH_MATMUL_GPU);
-// TODO(csigg): Implement Stream::ThenBlasGemv for Eigen::half and uncomment.
-// TF_CALL_half(REGISTER_BATCH_MATMUL_GPU);
+TF_CALL_half(REGISTER_BATCH_MATMUL_GPU);
#endif // GOOGLE_CUDA
#ifdef TENSORFLOW_USE_SYCL
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/BUILD b/tensorflow/core/kernels/boosted_trees/quantiles/BUILD
new file mode 100644
index 0000000000..3163c63949
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/BUILD
@@ -0,0 +1,63 @@
+# Description:
+# This directory contains common utilities used in boosted_trees.
+package(
+ default_visibility = ["//tensorflow:internal"],
+)
+
+licenses(["notice"]) # Apache 2.0
+
+exports_files(["LICENSE"])
+
+load("//tensorflow:tensorflow.bzl", "tf_cc_test")
+
+# Quantiles
+
+cc_library(
+ name = "weighted_quantiles",
+ srcs = [],
+ hdrs = [
+ "weighted_quantiles_buffer.h",
+ "weighted_quantiles_stream.h",
+ "weighted_quantiles_summary.h",
+ ],
+ visibility = ["//visibility:public"],
+ deps = [
+ "//tensorflow/core:framework_headers_lib",
+ ],
+)
+
+tf_cc_test(
+ name = "weighted_quantiles_buffer_test",
+ size = "small",
+ srcs = ["weighted_quantiles_buffer_test.cc"],
+ deps = [
+ ":weighted_quantiles",
+ "//tensorflow/core:lib",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ ],
+)
+
+tf_cc_test(
+ name = "weighted_quantiles_summary_test",
+ size = "small",
+ srcs = ["weighted_quantiles_summary_test.cc"],
+ deps = [
+ ":weighted_quantiles",
+ "//tensorflow/core:lib",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ ],
+)
+
+tf_cc_test(
+ name = "weighted_quantiles_stream_test",
+ size = "small",
+ srcs = ["weighted_quantiles_stream_test.cc"],
+ deps = [
+ ":weighted_quantiles",
+ "//tensorflow/core:lib",
+ "//tensorflow/core:test",
+ "//tensorflow/core:test_main",
+ ],
+)
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h
new file mode 100644
index 0000000000..07aa9831c4
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h
@@ -0,0 +1,132 @@
+// 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.
+// =============================================================================
+#ifndef TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_BUFFER_H_
+#define TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_BUFFER_H_
+
+#include <algorithm>
+#include <unordered_map>
+#include <vector>
+
+#include "tensorflow/core/platform/logging.h"
+#include "tensorflow/core/platform/types.h"
+
+namespace tensorflow {
+namespace boosted_trees {
+namespace quantiles {
+
+// Buffering container ideally suited for scenarios where we need
+// to sort and dedupe/compact fixed chunks of a stream of weighted elements.
+template <typename ValueType, typename WeightType,
+ typename CompareFn = std::less<ValueType>>
+class WeightedQuantilesBuffer {
+ public:
+ struct BufferEntry {
+ BufferEntry(ValueType v, WeightType w)
+ : value(std::move(v)), weight(std::move(w)) {}
+ BufferEntry() : value(), weight(0) {}
+
+ bool operator<(const BufferEntry& other) const {
+ return kCompFn(value, other.value);
+ }
+ bool operator==(const BufferEntry& other) const {
+ return value == other.value && weight == other.weight;
+ }
+ friend std::ostream& operator<<(std::ostream& strm,
+ const BufferEntry& entry) {
+ return strm << "{" << entry.value << ", " << entry.weight << "}";
+ }
+ ValueType value;
+ WeightType weight;
+ };
+
+ explicit WeightedQuantilesBuffer(int64 block_size, int64 max_elements)
+ : max_size_(std::min(block_size << 1, max_elements)) {
+ QCHECK(max_size_ > 0) << "Invalid buffer specification: (" << block_size
+ << ", " << max_elements << ")";
+ vec_.reserve(max_size_);
+ }
+
+ // Disallow copying as it's semantically non-sensical in the Squawd algorithm
+ // but enable move semantics.
+ WeightedQuantilesBuffer(const WeightedQuantilesBuffer& other) = delete;
+ WeightedQuantilesBuffer& operator=(const WeightedQuantilesBuffer&) = delete;
+ WeightedQuantilesBuffer(WeightedQuantilesBuffer&& other) = default;
+ WeightedQuantilesBuffer& operator=(WeightedQuantilesBuffer&& other) = default;
+
+ // Push entry to buffer and maintain a compact representation within
+ // pre-defined size limit.
+ void PushEntry(ValueType value, WeightType weight) {
+ // Callers are expected to act on a full compacted buffer after the
+ // PushEntry call returns.
+ QCHECK(!IsFull()) << "Buffer already full: " << max_size_;
+
+ // Ignore zero and negative weight entries.
+ if (weight <= 0) {
+ return;
+ }
+
+ // Push back the entry to the buffer.
+ vec_.push_back(BufferEntry(std::move(value), std::move(weight)));
+ }
+
+ // Returns a sorted vector view of the base buffer and clears the buffer.
+ // Callers should minimize how often this is called, ideally only right after
+ // the buffer becomes full.
+ std::vector<BufferEntry> GenerateEntryList() {
+ std::vector<BufferEntry> ret;
+ if (vec_.size() == 0) {
+ return ret;
+ }
+ ret.swap(vec_);
+ vec_.reserve(max_size_);
+ std::sort(ret.begin(), ret.end());
+ size_t num_entries = 0;
+ for (size_t i = 1; i < ret.size(); ++i) {
+ if (ret[i].value != ret[i - 1].value) {
+ BufferEntry tmp = ret[i];
+ ++num_entries;
+ ret[num_entries] = tmp;
+ } else {
+ ret[num_entries].weight += ret[i].weight;
+ }
+ }
+ ret.resize(num_entries + 1);
+ return ret;
+ }
+
+ int64 Size() const { return vec_.size(); }
+ bool IsFull() const { return vec_.size() >= max_size_; }
+ void Clear() { vec_.clear(); }
+
+ private:
+ using BufferVector = typename std::vector<BufferEntry>;
+
+ // Comparison function.
+ static constexpr decltype(CompareFn()) kCompFn = CompareFn();
+
+ // Base buffer.
+ size_t max_size_;
+ BufferVector vec_;
+};
+
+template <typename ValueType, typename WeightType, typename CompareFn>
+constexpr decltype(CompareFn())
+ WeightedQuantilesBuffer<ValueType, WeightType, CompareFn>::kCompFn;
+
+} // namespace quantiles
+} // namespace boosted_trees
+} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_BUFFER_H_
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer_test.cc b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer_test.cc
new file mode 100644
index 0000000000..75f05d64f3
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer_test.cc
@@ -0,0 +1,99 @@
+// 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.
+// =============================================================================
+#include "tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h"
+#include "tensorflow/core/lib/random/philox_random.h"
+#include "tensorflow/core/lib/random/simple_philox.h"
+#include "tensorflow/core/platform/test.h"
+#include "tensorflow/core/platform/test_benchmark.h"
+
+namespace tensorflow {
+namespace {
+
+using Buffer =
+ boosted_trees::quantiles::WeightedQuantilesBuffer<double, double>;
+using BufferEntry =
+ boosted_trees::quantiles::WeightedQuantilesBuffer<double,
+ double>::BufferEntry;
+
+class WeightedQuantilesBufferTest : public ::testing::Test {};
+
+TEST_F(WeightedQuantilesBufferTest, Invalid) {
+ EXPECT_DEATH(
+ ({
+ boosted_trees::quantiles::WeightedQuantilesBuffer<double, double>
+ buffer(2, 0);
+ }),
+ "Invalid buffer specification");
+ EXPECT_DEATH(
+ ({
+ boosted_trees::quantiles::WeightedQuantilesBuffer<double, double>
+ buffer(0, 2);
+ }),
+ "Invalid buffer specification");
+}
+
+TEST_F(WeightedQuantilesBufferTest, PushEntryNotFull) {
+ Buffer buffer(20, 100);
+ buffer.PushEntry(5, 9);
+ buffer.PushEntry(2, 3);
+ buffer.PushEntry(-1, 7);
+ buffer.PushEntry(3, 0); // This entry will be ignored.
+
+ EXPECT_FALSE(buffer.IsFull());
+ EXPECT_EQ(buffer.Size(), 3);
+}
+
+TEST_F(WeightedQuantilesBufferTest, PushEntryFull) {
+ // buffer capacity is 4.
+ Buffer buffer(2, 100);
+ buffer.PushEntry(5, 9);
+ buffer.PushEntry(2, 3);
+ buffer.PushEntry(-1, 7);
+ buffer.PushEntry(2, 1);
+
+ std::vector<BufferEntry> expected;
+ expected.emplace_back(-1, 7);
+ expected.emplace_back(2, 4);
+ expected.emplace_back(5, 9);
+
+ // At this point, we have pushed 4 entries and we expect the buffer to be
+ // full.
+ EXPECT_TRUE(buffer.IsFull());
+ EXPECT_EQ(buffer.GenerateEntryList(), expected);
+ EXPECT_FALSE(buffer.IsFull());
+}
+
+TEST_F(WeightedQuantilesBufferTest, PushEntryFullDeath) {
+ // buffer capacity is 4.
+ Buffer buffer(2, 100);
+ buffer.PushEntry(5, 9);
+ buffer.PushEntry(2, 3);
+ buffer.PushEntry(-1, 7);
+ buffer.PushEntry(2, 1);
+
+ std::vector<BufferEntry> expected;
+ expected.emplace_back(-1, 7);
+ expected.emplace_back(2, 4);
+ expected.emplace_back(5, 9);
+
+ // At this point, we have pushed 4 entries and we expect the buffer to be
+ // full.
+ EXPECT_TRUE(buffer.IsFull());
+ // Can't push any more entries before clearing.
+ EXPECT_DEATH(({ buffer.PushEntry(6, 6); }), "Buffer already full");
+}
+
+} // namespace
+} // namespace tensorflow
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream.h b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream.h
new file mode 100644
index 0000000000..525e2a6a64
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream.h
@@ -0,0 +1,330 @@
+// 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.
+// =============================================================================
+#ifndef TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_STREAM_H_
+#define TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_STREAM_H_
+
+#include <cmath>
+#include <memory>
+#include <vector>
+
+#include "tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h"
+#include "tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary.h"
+#include "tensorflow/core/platform/types.h"
+
+namespace tensorflow {
+namespace boosted_trees {
+namespace quantiles {
+
+// Class to compute approximate quantiles with error bound guarantees for
+// weighted data sets.
+// This implementation is an adaptation of techniques from the following papers:
+// * (2001) Space-efficient online computation of quantile summaries.
+// * (2004) Power-conserving computation of order-statistics over
+// sensor networks.
+// * (2007) A fast algorithm for approximate quantiles in high speed
+// data streams.
+// * (2016) XGBoost: A Scalable Tree Boosting System.
+//
+// The key ideas at play are the following:
+// - Maintain an in-memory multi-level quantile summary in a way to guarantee
+// a maximum approximation error of eps * W per bucket where W is the total
+// weight across all points in the input dataset.
+// - Two base operations are defined: MERGE and COMPRESS. MERGE combines two
+// summaries guaranteeing a epsNew = max(eps1, eps2). COMPRESS compresses
+// a summary to b + 1 elements guaranteeing epsNew = epsOld + 1/b.
+// - b * sizeof(summary entry) must ideally be small enough to fit in an
+// average CPU L2 cache.
+// - To distribute this algorithm with maintaining error bounds, we need
+// the worker-computed summaries to have no more than eps / h error
+// where h is the height of the distributed computation graph which
+// is 2 for an MR with no combiner.
+//
+// We mainly want to max out IO bw by ensuring we're not compute-bound and
+// using a reasonable amount of RAM.
+//
+// Complexity:
+// Compute: O(n * log(1/eps * log(eps * n))).
+// Memory: O(1/eps * log^2(eps * n)) <- for one worker streaming through the
+// entire dataset.
+// An epsilon value of zero would make the algorithm extremely inefficent and
+// therefore, is disallowed.
+template <typename ValueType, typename WeightType,
+ typename CompareFn = std::less<ValueType>>
+class WeightedQuantilesStream {
+ public:
+ using Buffer = WeightedQuantilesBuffer<ValueType, WeightType, CompareFn>;
+ using BufferEntry = typename Buffer::BufferEntry;
+ using Summary = WeightedQuantilesSummary<ValueType, WeightType, CompareFn>;
+ using SummaryEntry = typename Summary::SummaryEntry;
+
+ explicit WeightedQuantilesStream(double eps, int64 max_elements)
+ : eps_(eps), buffer_(1LL, 2LL), finalized_(false) {
+ // See the class documentation. An epsilon value of zero could cause
+ // perfoamance issues.
+ QCHECK(eps > 0) << "An epsilon value of zero is not allowed.";
+ std::tie(max_levels_, block_size_) = GetQuantileSpecs(eps, max_elements);
+ buffer_ = Buffer(block_size_, max_elements);
+ summary_levels_.reserve(max_levels_);
+ }
+
+ // Disallow copy and assign but enable move semantics for the stream.
+ WeightedQuantilesStream(const WeightedQuantilesStream& other) = delete;
+ WeightedQuantilesStream& operator=(const WeightedQuantilesStream&) = delete;
+ WeightedQuantilesStream(WeightedQuantilesStream&& other) = default;
+ WeightedQuantilesStream& operator=(WeightedQuantilesStream&& other) = default;
+
+ // Pushes one entry while maintaining approximation error invariants.
+ void PushEntry(const ValueType& value, const WeightType& weight) {
+ // Validate state.
+ QCHECK(!finalized_) << "Finalize() already called.";
+
+ // Push element to base buffer.
+ buffer_.PushEntry(value, weight);
+
+ // When compacted buffer is full we need to compress
+ // and push weighted quantile summary up the level chain.
+ if (buffer_.IsFull()) {
+ PushBuffer(buffer_);
+ }
+ }
+
+ // Pushes full buffer while maintaining approximation error invariants.
+ void PushBuffer(Buffer& buffer) {
+ // Validate state.
+ QCHECK(!finalized_) << "Finalize() already called.";
+
+ // Create local compressed summary and propagate.
+ local_summary_.BuildFromBufferEntries(buffer.GenerateEntryList());
+ local_summary_.Compress(block_size_, eps_);
+ PropagateLocalSummary();
+ }
+
+ // Pushes full summary while maintaining approximation error invariants.
+ void PushSummary(const std::vector<SummaryEntry>& summary) {
+ // Validate state.
+ QCHECK(!finalized_) << "Finalize() already called.";
+
+ // Create local compressed summary and propagate.
+ local_summary_.BuildFromSummaryEntries(summary);
+ local_summary_.Compress(block_size_, eps_);
+ PropagateLocalSummary();
+ }
+
+ // Flushes approximator and finalizes state.
+ void Finalize() {
+ // Validate state.
+ QCHECK(!finalized_) << "Finalize() may only be called once.";
+
+ // Flush any remaining buffer elements.
+ PushBuffer(buffer_);
+
+ // Create final merged summary.
+ local_summary_.Clear();
+ for (auto& summary : summary_levels_) {
+ local_summary_.Merge(summary);
+ summary.Clear();
+ }
+ summary_levels_.clear();
+ summary_levels_.shrink_to_fit();
+ finalized_ = true;
+ }
+
+ // Generates requested number of quantiles after finalizing stream.
+ // The returned quantiles can be queried using std::lower_bound to get
+ // the bucket for a given value.
+ std::vector<ValueType> GenerateQuantiles(int64 num_quantiles) const {
+ // Validate state.
+ QCHECK(finalized_)
+ << "Finalize() must be called before generating quantiles.";
+ return local_summary_.GenerateQuantiles(num_quantiles);
+ }
+
+ // Generates requested number of boundaries after finalizing stream.
+ // The returned boundaries can be queried using std::lower_bound to get
+ // the bucket for a given value.
+ // The boundaries, while still guaranteeing approximation bounds, don't
+ // necessarily represent the actual quantiles of the distribution.
+ // Boundaries are preferable over quantiles when the caller is less
+ // interested in the actual quantiles distribution and more interested in
+ // getting a representative sample of boundary values.
+ std::vector<ValueType> GenerateBoundaries(int64 num_boundaries) const {
+ // Validate state.
+ QCHECK(finalized_)
+ << "Finalize() must be called before generating boundaries.";
+ return local_summary_.GenerateBoundaries(num_boundaries);
+ }
+
+ // Calculates approximation error for the specified level.
+ // If the passed level is negative, the approximation error for the entire
+ // summary is returned. Note that after Finalize is called, only the overall
+ // error is available.
+ WeightType ApproximationError(int64 level = -1) const {
+ if (finalized_) {
+ QCHECK(level <= 0) << "Only overall error is available after Finalize()";
+ return local_summary_.ApproximationError();
+ }
+
+ if (summary_levels_.empty()) {
+ // No error even if base buffer isn't empty.
+ return 0;
+ }
+
+ // If level is negative, we get the approximation error
+ // for the top-most level which is the max approximation error
+ // in all summaries by construction.
+ if (level < 0) {
+ level = summary_levels_.size() - 1;
+ }
+ QCHECK(level < summary_levels_.size()) << "Invalid level.";
+ return summary_levels_[level].ApproximationError();
+ }
+
+ size_t MaxDepth() const { return summary_levels_.size(); }
+
+ // Generates requested number of quantiles after finalizing stream.
+ const Summary& GetFinalSummary() const {
+ // Validate state.
+ QCHECK(finalized_)
+ << "Finalize() must be called before requesting final summary.";
+ return local_summary_;
+ }
+
+ // Helper method which, given the desired approximation error
+ // and an upper bound on the number of elements, computes the optimal
+ // number of levels and block size and returns them in the tuple.
+ static std::tuple<int64, int64> GetQuantileSpecs(double eps,
+ int64 max_elements);
+
+ // Serializes the internal state of the stream.
+ std::vector<Summary> SerializeInternalSummaries() const {
+ // The buffer should be empty for serialize to work.
+ QCHECK_EQ(buffer_.Size(), 0);
+ std::vector<Summary> result;
+ result.reserve(summary_levels_.size() + 1);
+ for (const Summary& summary : summary_levels_) {
+ result.push_back(summary);
+ }
+ result.push_back(local_summary_);
+ return result;
+ }
+
+ // Resets the state of the stream with a serialized state.
+ void DeserializeInternalSummaries(const std::vector<Summary>& summaries) {
+ // Clear the state before deserializing.
+ buffer_.Clear();
+ summary_levels_.clear();
+ local_summary_.Clear();
+ QCHECK_GT(max_levels_, summaries.size() - 1);
+ for (int i = 0; i < summaries.size() - 1; ++i) {
+ summary_levels_.push_back(summaries[i]);
+ }
+ local_summary_ = summaries[summaries.size() - 1];
+ }
+
+ private:
+ // Propagates local summary through summary levels while maintaining
+ // approximation error invariants.
+ void PropagateLocalSummary() {
+ // Validate state.
+ QCHECK(!finalized_) << "Finalize() already called.";
+
+ // No-op if there's nothing to add.
+ if (local_summary_.Size() <= 0) {
+ return;
+ }
+
+ // Propagate summary through levels.
+ size_t level = 0;
+ for (bool settled = false; !settled; ++level) {
+ // Ensure we have enough depth.
+ if (summary_levels_.size() <= level) {
+ summary_levels_.emplace_back();
+ }
+
+ // Merge summaries.
+ Summary& current_summary = summary_levels_[level];
+ local_summary_.Merge(current_summary);
+
+ // Check if we need to compress and propagate summary higher.
+ if (current_summary.Size() == 0 ||
+ local_summary_.Size() <= block_size_ + 1) {
+ current_summary = std::move(local_summary_);
+ settled = true;
+ } else {
+ // Compress, empty current level and propagate.
+ local_summary_.Compress(block_size_, eps_);
+ current_summary.Clear();
+ }
+ }
+ }
+
+ // Desired approximation precision.
+ double eps_;
+ // Maximum number of levels.
+ int64 max_levels_;
+ // Max block size per level.
+ int64 block_size_;
+ // Base buffer.
+ Buffer buffer_;
+ // Local summary used to minimize memory allocation and cache misses.
+ // After the stream is finalized, this summary holds the final quantile
+ // estimates.
+ Summary local_summary_;
+ // Summary levels;
+ std::vector<Summary> summary_levels_;
+ // Flag indicating whether the stream is finalized.
+ bool finalized_;
+};
+
+template <typename ValueType, typename WeightType, typename CompareFn>
+inline std::tuple<int64, int64>
+WeightedQuantilesStream<ValueType, WeightType, CompareFn>::GetQuantileSpecs(
+ double eps, int64 max_elements) {
+ int64 max_level = 1LL;
+ int64 block_size = 2LL;
+ QCHECK(eps >= 0 && eps < 1);
+ QCHECK_GT(max_elements, 0);
+
+ if (eps <= std::numeric_limits<double>::epsilon()) {
+ // Exact quantile computation at the expense of RAM.
+ max_level = 1;
+ block_size = std::max(max_elements, int64{2});
+ } else {
+ // The bottom-most level will become full at most
+ // (max_elements / block_size) times, the level above will become full
+ // (max_elements / 2 * block_size) times and generally level l becomes
+ // full (max_elements / 2^l * block_size) times until the last
+ // level max_level becomes full at most once meaning when the inequality
+ // (2^max_level * block_size >= max_elements) is satisfied.
+ // In what follows, we jointly solve for max_level and block_size by
+ // gradually increasing the level until the inequality above is satisfied.
+ // We could alternatively set max_level = ceil(log2(eps * max_elements));
+ // and block_size = ceil(max_level / eps) + 1 but that tends to give more
+ // pessimistic bounds and wastes RAM needlessly.
+ for (max_level = 1, block_size = 2;
+ (1LL << max_level) * block_size < max_elements; ++max_level) {
+ // Update upper bound on block size at current level, we always
+ // increase the estimate by 2 to hold the min/max elements seen so far.
+ block_size = static_cast<size_t>(ceil(max_level / eps)) + 1;
+ }
+ }
+ return std::make_tuple(max_level, std::max(block_size, int64{2}));
+}
+
+} // namespace quantiles
+} // namespace boosted_trees
+} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_STREAM_H_
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream_test.cc b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream_test.cc
new file mode 100644
index 0000000000..6c5b9fd23b
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream_test.cc
@@ -0,0 +1,276 @@
+// 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.
+// =============================================================================
+#include "tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_stream.h"
+#include "tensorflow/core/lib/random/philox_random.h"
+#include "tensorflow/core/lib/random/simple_philox.h"
+#include "tensorflow/core/platform/test.h"
+#include "tensorflow/core/platform/test_benchmark.h"
+
+namespace tensorflow {
+namespace {
+using Tuple = std::tuple<int64, int64>;
+
+using Summary =
+ boosted_trees::quantiles::WeightedQuantilesSummary<double, double>;
+using SummaryEntry =
+ boosted_trees::quantiles::WeightedQuantilesSummary<double,
+ double>::SummaryEntry;
+using Stream =
+ boosted_trees::quantiles::WeightedQuantilesStream<double, double>;
+
+TEST(GetQuantileSpecs, InvalidEps) {
+ EXPECT_DEATH({ Stream::GetQuantileSpecs(-0.01, 0L); }, "eps >= 0");
+ EXPECT_DEATH({ Stream::GetQuantileSpecs(1.01, 0L); }, "eps < 1");
+}
+
+TEST(GetQuantileSpecs, ZeroEps) {
+ EXPECT_DEATH({ Stream::GetQuantileSpecs(0.0, 0L); }, "max_elements > 0");
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.0, 1LL), Tuple(1LL, 2LL));
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.0, 20LL), Tuple(1LL, 20LL));
+}
+
+TEST(GetQuantileSpecs, NonZeroEps) {
+ EXPECT_DEATH({ Stream::GetQuantileSpecs(0.01, 0L); }, "max_elements > 0");
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.1, 320LL), Tuple(4LL, 31LL));
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.01, 25600LL), Tuple(6LL, 501LL));
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.01, 104857600LL), Tuple(17LL, 1601LL));
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.1, 104857600LL), Tuple(20LL, 191LL));
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.01, 1LL << 40), Tuple(29LL, 2801LL));
+ EXPECT_EQ(Stream::GetQuantileSpecs(0.001, 1LL << 40), Tuple(26LL, 25001LL));
+}
+
+class WeightedQuantilesStreamTest : public ::testing::Test {};
+
+// Stream generators.
+void GenerateFixedUniformSummary(int32 worker_id, int64 max_elements,
+ double *total_weight, Stream *stream) {
+ for (int64 i = 0; i < max_elements; ++i) {
+ const double x = static_cast<double>(i) / max_elements;
+ stream->PushEntry(x, 1.0);
+ ++(*total_weight);
+ }
+ stream->Finalize();
+}
+
+void GenerateFixedNonUniformSummary(int32 worker_id, int64 max_elements,
+ double *total_weight, Stream *stream) {
+ for (int64 i = 0; i < max_elements; ++i) {
+ const double x = static_cast<double>(i) / max_elements;
+ stream->PushEntry(x, x);
+ (*total_weight) += x;
+ }
+ stream->Finalize();
+}
+
+void GenerateRandUniformFixedWeightsSummary(int32 worker_id, int64 max_elements,
+ double *total_weight,
+ Stream *stream) {
+ // Simulate uniform distribution stream.
+ random::PhiloxRandom philox(13 + worker_id);
+ random::SimplePhilox rand(&philox);
+ for (int64 i = 0; i < max_elements; ++i) {
+ const double x = rand.RandDouble();
+ stream->PushEntry(x, 1);
+ ++(*total_weight);
+ }
+ stream->Finalize();
+}
+
+void GenerateRandUniformRandWeightsSummary(int32 worker_id, int64 max_elements,
+ double *total_weight,
+ Stream *stream) {
+ // Simulate uniform distribution stream.
+ random::PhiloxRandom philox(13 + worker_id);
+ random::SimplePhilox rand(&philox);
+ for (int64 i = 0; i < max_elements; ++i) {
+ const double x = rand.RandDouble();
+ const double w = rand.RandDouble();
+ stream->PushEntry(x, w);
+ (*total_weight) += w;
+ }
+ stream->Finalize();
+}
+
+// Single worker tests.
+void TestSingleWorkerStreams(
+ double eps, int64 max_elements,
+ const std::function<void(int32, int64, double *, Stream *)>
+ &worker_summary_generator,
+ std::initializer_list<double> expected_quantiles,
+ double quantiles_matcher_epsilon) {
+ // Generate single stream.
+ double total_weight = 0;
+ Stream stream(eps, max_elements);
+ worker_summary_generator(0, max_elements, &total_weight, &stream);
+
+ // Ensure we didn't lose track of any elements and are
+ // within approximation error bound.
+ EXPECT_LE(stream.ApproximationError(), eps);
+ EXPECT_NEAR(stream.GetFinalSummary().TotalWeight(), total_weight, 1e-6);
+
+ // Verify expected quantiles.
+ int i = 0;
+ auto actuals = stream.GenerateQuantiles(expected_quantiles.size() - 1);
+ for (auto expected_quantile : expected_quantiles) {
+ EXPECT_NEAR(actuals[i], expected_quantile, quantiles_matcher_epsilon);
+ ++i;
+ }
+}
+
+// Stream generators.
+void GenerateOneValue(int32 worker_id, int64 max_elements, double *total_weight,
+ Stream *stream) {
+ stream->PushEntry(10, 1);
+ ++(*total_weight);
+ stream->Finalize();
+}
+
+void GenerateOneZeroWeightedValue(int32 worker_id, int64 max_elements,
+ double *total_weight, Stream *stream) {
+ stream->PushEntry(10, 0);
+ stream->Finalize();
+}
+
+TEST(WeightedQuantilesStreamTest, OneValue) {
+ const double eps = 0.01;
+ const int64 max_elements = 1 << 16;
+ TestSingleWorkerStreams(eps, max_elements, GenerateOneValue,
+ {10.0, 10.0, 10.0, 10.0, 10.0}, 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, OneZeroWeightValue) {
+ const double eps = 0.01;
+ const int64 max_elements = 1 << 16;
+ TestSingleWorkerStreams(eps, max_elements, GenerateOneZeroWeightedValue, {},
+ 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, FixedUniform) {
+ const double eps = 0.01;
+ const int64 max_elements = 1 << 16;
+ TestSingleWorkerStreams(eps, max_elements, GenerateFixedUniformSummary,
+ {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0},
+ 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, FixedNonUniform) {
+ const double eps = 0.01;
+ const int64 max_elements = 1 << 16;
+ TestSingleWorkerStreams(eps, max_elements, GenerateFixedNonUniformSummary,
+ {0, std::sqrt(0.1), std::sqrt(0.2), std::sqrt(0.3),
+ std::sqrt(0.4), std::sqrt(0.5), std::sqrt(0.6),
+ std::sqrt(0.7), std::sqrt(0.8), std::sqrt(0.9), 1.0},
+ 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, RandUniformFixedWeights) {
+ const double eps = 0.01;
+ const int64 max_elements = 1 << 16;
+ TestSingleWorkerStreams(
+ eps, max_elements, GenerateRandUniformFixedWeightsSummary,
+ {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, RandUniformRandWeights) {
+ const double eps = 0.01;
+ const int64 max_elements = 1 << 16;
+ TestSingleWorkerStreams(
+ eps, max_elements, GenerateRandUniformRandWeightsSummary,
+ {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, 1e-2);
+}
+
+// Distributed tests.
+void TestDistributedStreams(
+ int32 num_workers, double eps, int64 max_elements,
+ const std::function<void(int32, int64, double *, Stream *)>
+ &worker_summary_generator,
+ std::initializer_list<double> expected_quantiles,
+ double quantiles_matcher_epsilon) {
+ // Simulate streams on each worker running independently
+ double total_weight = 0;
+ std::vector<std::vector<SummaryEntry>> worker_summaries;
+ for (int32 i = 0; i < num_workers; ++i) {
+ Stream stream(eps / 2, max_elements);
+ worker_summary_generator(i, max_elements / num_workers, &total_weight,
+ &stream);
+ worker_summaries.push_back(stream.GetFinalSummary().GetEntryList());
+ }
+
+ // In the accumulation phase, we aggregate the summaries from each worker
+ // and build an overall summary while maintaining error bounds by ensuring we
+ // don't increase the error by more than eps / 2.
+ Stream reducer_stream(eps, max_elements);
+ for (const auto &summary : worker_summaries) {
+ reducer_stream.PushSummary(summary);
+ }
+ reducer_stream.Finalize();
+
+ // Ensure we didn't lose track of any elements and are
+ // within approximation error bound.
+ EXPECT_LE(reducer_stream.ApproximationError(), eps);
+ EXPECT_NEAR(reducer_stream.GetFinalSummary().TotalWeight(), total_weight,
+ total_weight);
+
+ // Verify expected quantiles.
+ int i = 0;
+ auto actuals =
+ reducer_stream.GenerateQuantiles(expected_quantiles.size() - 1);
+ for (auto expected_quantile : expected_quantiles) {
+ EXPECT_NEAR(actuals[i], expected_quantile, quantiles_matcher_epsilon);
+ ++i;
+ }
+}
+
+TEST(WeightedQuantilesStreamTest, FixedUniformDistributed) {
+ const int32 num_workers = 10;
+ const double eps = 0.01;
+ const int64 max_elements = num_workers * (1 << 16);
+ TestDistributedStreams(
+ num_workers, eps, max_elements, GenerateFixedUniformSummary,
+ {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, FixedNonUniformDistributed) {
+ const int32 num_workers = 10;
+ const double eps = 0.01;
+ const int64 max_elements = num_workers * (1 << 16);
+ TestDistributedStreams(num_workers, eps, max_elements,
+ GenerateFixedNonUniformSummary,
+ {0, std::sqrt(0.1), std::sqrt(0.2), std::sqrt(0.3),
+ std::sqrt(0.4), std::sqrt(0.5), std::sqrt(0.6),
+ std::sqrt(0.7), std::sqrt(0.8), std::sqrt(0.9), 1.0},
+ 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, RandUniformFixedWeightsDistributed) {
+ const int32 num_workers = 10;
+ const double eps = 0.01;
+ const int64 max_elements = num_workers * (1 << 16);
+ TestDistributedStreams(
+ num_workers, eps, max_elements, GenerateRandUniformFixedWeightsSummary,
+ {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, 1e-2);
+}
+
+TEST(WeightedQuantilesStreamTest, RandUniformRandWeightsDistributed) {
+ const int32 num_workers = 10;
+ const double eps = 0.01;
+ const int64 max_elements = num_workers * (1 << 16);
+ TestDistributedStreams(
+ num_workers, eps, max_elements, GenerateRandUniformRandWeightsSummary,
+ {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, 1e-2);
+}
+
+} // namespace
+} // namespace tensorflow
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary.h b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary.h
new file mode 100644
index 0000000000..31d7fe25a4
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary.h
@@ -0,0 +1,344 @@
+// 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.
+// =============================================================================
+#ifndef TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_SUMMARY_H_
+#define TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_SUMMARY_H_
+
+#include <cstring>
+#include <vector>
+
+#include "tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_buffer.h"
+
+namespace tensorflow {
+namespace boosted_trees {
+namespace quantiles {
+
+// Summary holding a sorted block of entries with upper bound guarantees
+// over the approximation error.
+template <typename ValueType, typename WeightType,
+ typename CompareFn = std::less<ValueType>>
+class WeightedQuantilesSummary {
+ public:
+ using Buffer = WeightedQuantilesBuffer<ValueType, WeightType, CompareFn>;
+ using BufferEntry = typename Buffer::BufferEntry;
+
+ struct SummaryEntry {
+ SummaryEntry(const ValueType& v, const WeightType& w, const WeightType& min,
+ const WeightType& max) {
+ // Explicitly initialize all of memory (including padding from memory
+ // alignment) to allow the struct to be msan-resistant "plain old data".
+ //
+ // POD = http://en.cppreference.com/w/cpp/concept/PODType
+ memset(this, 0, sizeof(*this));
+
+ value = v;
+ weight = w;
+ min_rank = min;
+ max_rank = max;
+ }
+
+ SummaryEntry() {
+ memset(this, 0, sizeof(*this));
+
+ value = ValueType();
+ weight = 0;
+ min_rank = 0;
+ max_rank = 0;
+ }
+
+ bool operator==(const SummaryEntry& other) const {
+ return value == other.value && weight == other.weight &&
+ min_rank == other.min_rank && max_rank == other.max_rank;
+ }
+ friend std::ostream& operator<<(std::ostream& strm,
+ const SummaryEntry& entry) {
+ return strm << "{" << entry.value << ", " << entry.weight << ", "
+ << entry.min_rank << ", " << entry.max_rank << "}";
+ }
+
+ // Max rank estimate for previous smaller value.
+ WeightType PrevMaxRank() const { return max_rank - weight; }
+
+ // Min rank estimate for next larger value.
+ WeightType NextMinRank() const { return min_rank + weight; }
+
+ ValueType value;
+ WeightType weight;
+ WeightType min_rank;
+ WeightType max_rank;
+ };
+
+ // Re-construct summary from the specified buffer.
+ void BuildFromBufferEntries(const std::vector<BufferEntry>& buffer_entries) {
+ entries_.clear();
+ entries_.reserve(buffer_entries.size());
+ WeightType cumulative_weight = 0;
+ for (const auto& entry : buffer_entries) {
+ WeightType current_weight = entry.weight;
+ entries_.emplace_back(entry.value, entry.weight, cumulative_weight,
+ cumulative_weight + current_weight);
+ cumulative_weight += current_weight;
+ }
+ }
+
+ // Re-construct summary from the specified summary entries.
+ void BuildFromSummaryEntries(
+ const std::vector<SummaryEntry>& summary_entries) {
+ entries_.clear();
+ entries_.reserve(summary_entries.size());
+ entries_.insert(entries_.begin(), summary_entries.begin(),
+ summary_entries.end());
+ }
+
+ // Merges two summaries through an algorithm that's derived from MergeSort
+ // for summary entries while guaranteeing that the max approximation error
+ // of the final merged summary is no greater than the approximation errors
+ // of each individual summary.
+ // For example consider summaries where each entry is of the form
+ // (element, weight, min rank, max rank):
+ // summary entries 1: (1, 3, 0, 3), (4, 2, 3, 5)
+ // summary entries 2: (3, 1, 0, 1), (4, 1, 1, 2)
+ // merged: (1, 3, 0, 3), (3, 1, 3, 4), (4, 3, 4, 7).
+ void Merge(const WeightedQuantilesSummary& other_summary) {
+ // Make sure we have something to merge.
+ const auto& other_entries = other_summary.entries_;
+ if (other_entries.empty()) {
+ return;
+ }
+ if (entries_.empty()) {
+ BuildFromSummaryEntries(other_summary.entries_);
+ return;
+ }
+
+ // Move current entries to make room for a new buffer.
+ std::vector<SummaryEntry> base_entries(std::move(entries_));
+ entries_.clear();
+ entries_.reserve(base_entries.size() + other_entries.size());
+
+ // Merge entries maintaining ranks. The idea is to stack values
+ // in order which we can do in linear time as the two summaries are
+ // already sorted. We keep track of the next lower rank from either
+ // summary and update it as we pop elements from the summaries.
+ // We handle the special case when the next two elements from either
+ // summary are equal, in which case we just merge the two elements
+ // and simultaneously update both ranks.
+ auto it1 = base_entries.cbegin();
+ auto it2 = other_entries.cbegin();
+ WeightType next_min_rank1 = 0;
+ WeightType next_min_rank2 = 0;
+ while (it1 != base_entries.cend() && it2 != other_entries.cend()) {
+ if (kCompFn(it1->value, it2->value)) { // value1 < value2
+ // Take value1 and use the last added value2 to compute
+ // the min rank and the current value2 to compute the max rank.
+ entries_.emplace_back(it1->value, it1->weight,
+ it1->min_rank + next_min_rank2,
+ it1->max_rank + it2->PrevMaxRank());
+ // Update next min rank 1.
+ next_min_rank1 = it1->NextMinRank();
+ ++it1;
+ } else if (kCompFn(it2->value, it1->value)) { // value1 > value2
+ // Take value2 and use the last added value1 to compute
+ // the min rank and the current value1 to compute the max rank.
+ entries_.emplace_back(it2->value, it2->weight,
+ it2->min_rank + next_min_rank1,
+ it2->max_rank + it1->PrevMaxRank());
+ // Update next min rank 2.
+ next_min_rank2 = it2->NextMinRank();
+ ++it2;
+ } else { // value1 == value2
+ // Straight additive merger of the two entries into one.
+ entries_.emplace_back(it1->value, it1->weight + it2->weight,
+ it1->min_rank + it2->min_rank,
+ it1->max_rank + it2->max_rank);
+ // Update next min ranks for both.
+ next_min_rank1 = it1->NextMinRank();
+ next_min_rank2 = it2->NextMinRank();
+ ++it1;
+ ++it2;
+ }
+ }
+
+ // Fill in any residual.
+ while (it1 != base_entries.cend()) {
+ entries_.emplace_back(it1->value, it1->weight,
+ it1->min_rank + next_min_rank2,
+ it1->max_rank + other_entries.back().max_rank);
+ ++it1;
+ }
+ while (it2 != other_entries.cend()) {
+ entries_.emplace_back(it2->value, it2->weight,
+ it2->min_rank + next_min_rank1,
+ it2->max_rank + base_entries.back().max_rank);
+ ++it2;
+ }
+ }
+
+ // Compresses buffer into desired size. The size specification is
+ // considered a hint as we always keep the first and last elements and
+ // maintain strict approximation error bounds.
+ // The approximation error delta is taken as the max of either the requested
+ // min error or 1 / size_hint.
+ // After compression, the approximation error is guaranteed to increase
+ // by no more than that error delta.
+ // This algorithm is linear in the original size of the summary and is
+ // designed to be cache-friendly.
+ void Compress(int64 size_hint, double min_eps = 0) {
+ // No-op if we're already within the size requirement.
+ size_hint = std::max(size_hint, int64{2});
+ if (entries_.size() <= size_hint) {
+ return;
+ }
+
+ // First compute the max error bound delta resulting from this compression.
+ double eps_delta = TotalWeight() * std::max(1.0 / size_hint, min_eps);
+
+ // Compress elements ensuring approximation bounds and elements diversity
+ // are both maintained.
+ int64 add_accumulator = 0, add_step = entries_.size();
+ auto write_it = entries_.begin() + 1, last_it = write_it;
+ for (auto read_it = entries_.begin(); read_it + 1 != entries_.end();) {
+ auto next_it = read_it + 1;
+ while (next_it != entries_.end() && add_accumulator < add_step &&
+ next_it->PrevMaxRank() - read_it->NextMinRank() <= eps_delta) {
+ add_accumulator += size_hint;
+ ++next_it;
+ }
+ if (read_it == next_it - 1) {
+ ++read_it;
+ } else {
+ read_it = next_it - 1;
+ }
+ (*write_it++) = (*read_it);
+ last_it = read_it;
+ add_accumulator -= add_step;
+ }
+ // Write last element and resize.
+ if (last_it + 1 != entries_.end()) {
+ (*write_it++) = entries_.back();
+ }
+ entries_.resize(write_it - entries_.begin());
+ }
+
+ // To construct the boundaries we first run a soft compress over a copy
+ // of the summary and retrieve the values.
+ // The resulting boundaries are guaranteed to both contain at least
+ // num_boundaries unique elements and maintain approximation bounds.
+ std::vector<ValueType> GenerateBoundaries(int64 num_boundaries) const {
+ std::vector<ValueType> output;
+ if (entries_.empty()) {
+ return output;
+ }
+
+ // Generate soft compressed summary.
+ WeightedQuantilesSummary<ValueType, WeightType, CompareFn>
+ compressed_summary;
+ compressed_summary.BuildFromSummaryEntries(entries_);
+ // Set an epsilon for compression that's at most 1.0 / num_boundaries
+ // more than epsilon of original our summary since the compression operation
+ // adds ~1.0/num_boundaries to final approximation error.
+ float compression_eps = ApproximationError() + (1.0 / num_boundaries);
+ compressed_summary.Compress(num_boundaries, compression_eps);
+
+ // Return boundaries.
+ output.reserve(compressed_summary.entries_.size());
+ for (const auto& entry : compressed_summary.entries_) {
+ output.push_back(entry.value);
+ }
+ return output;
+ }
+
+ // To construct the desired n-quantiles we repetitively query n ranks from the
+ // original summary. The following algorithm is an efficient cache-friendly
+ // O(n) implementation of that idea which avoids the cost of the repetitive
+ // full rank queries O(nlogn).
+ std::vector<ValueType> GenerateQuantiles(int64 num_quantiles) const {
+ std::vector<ValueType> output;
+ if (entries_.empty()) {
+ return output;
+ }
+ num_quantiles = std::max(num_quantiles, int64{2});
+ output.reserve(num_quantiles + 1);
+
+ // Make successive rank queries to get boundaries.
+ // We always keep the first (min) and last (max) entries.
+ for (size_t cur_idx = 0, rank = 0; rank <= num_quantiles; ++rank) {
+ // This step boils down to finding the next element sub-range defined by
+ // r = (rmax[i + 1] + rmin[i + 1]) / 2 where the desired rank d < r.
+ WeightType d_2 = 2 * (rank * entries_.back().max_rank / num_quantiles);
+ size_t next_idx = cur_idx + 1;
+ while (next_idx < entries_.size() &&
+ d_2 >= entries_[next_idx].min_rank + entries_[next_idx].max_rank) {
+ ++next_idx;
+ }
+ cur_idx = next_idx - 1;
+
+ // Determine insertion order.
+ if (next_idx == entries_.size() ||
+ d_2 < entries_[cur_idx].NextMinRank() +
+ entries_[next_idx].PrevMaxRank()) {
+ output.push_back(entries_[cur_idx].value);
+ } else {
+ output.push_back(entries_[next_idx].value);
+ }
+ }
+ return output;
+ }
+
+ // Calculates current approximation error which should always be <= eps.
+ double ApproximationError() const {
+ if (entries_.empty()) {
+ return 0;
+ }
+
+ WeightType max_gap = 0;
+ for (auto it = entries_.cbegin() + 1; it < entries_.end(); ++it) {
+ max_gap = std::max(max_gap,
+ std::max(it->max_rank - it->min_rank - it->weight,
+ it->PrevMaxRank() - (it - 1)->NextMinRank()));
+ }
+ return static_cast<double>(max_gap) / TotalWeight();
+ }
+
+ ValueType MinValue() const {
+ return !entries_.empty() ? entries_.front().value
+ : std::numeric_limits<ValueType>::max();
+ }
+ ValueType MaxValue() const {
+ return !entries_.empty() ? entries_.back().value
+ : std::numeric_limits<ValueType>::max();
+ }
+ WeightType TotalWeight() const {
+ return !entries_.empty() ? entries_.back().max_rank : 0;
+ }
+ int64 Size() const { return entries_.size(); }
+ void Clear() { entries_.clear(); }
+ const std::vector<SummaryEntry>& GetEntryList() const { return entries_; }
+
+ private:
+ // Comparison function.
+ static constexpr decltype(CompareFn()) kCompFn = CompareFn();
+
+ // Summary entries.
+ std::vector<SummaryEntry> entries_;
+};
+
+template <typename ValueType, typename WeightType, typename CompareFn>
+constexpr decltype(CompareFn())
+ WeightedQuantilesSummary<ValueType, WeightType, CompareFn>::kCompFn;
+
+} // namespace quantiles
+} // namespace boosted_trees
+} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_BOOSTED_TREES_QUANTILES_WEIGHTED_QUANTILES_SUMMARY_H_
diff --git a/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary_test.cc b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary_test.cc
new file mode 100644
index 0000000000..ccd1215cf4
--- /dev/null
+++ b/tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary_test.cc
@@ -0,0 +1,223 @@
+// 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.
+// =============================================================================
+#include "tensorflow/core/kernels/boosted_trees/quantiles/weighted_quantiles_summary.h"
+#include "tensorflow/core/lib/random/philox_random.h"
+#include "tensorflow/core/lib/random/simple_philox.h"
+#include "tensorflow/core/platform/test.h"
+#include "tensorflow/core/platform/test_benchmark.h"
+
+namespace tensorflow {
+namespace {
+
+using Buffer = boosted_trees::quantiles::WeightedQuantilesBuffer<float, float>;
+using BufferEntry =
+ boosted_trees::quantiles::WeightedQuantilesBuffer<float,
+ float>::BufferEntry;
+using Summary =
+ boosted_trees::quantiles::WeightedQuantilesSummary<float, float>;
+using SummaryEntry =
+ boosted_trees::quantiles::WeightedQuantilesSummary<float,
+ float>::SummaryEntry;
+
+class WeightedQuantilesSummaryTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ // Constructs a buffer of 10 weighted unique entries.
+ buffer1_.reset(new Buffer(10, 1000));
+ buffer1_->PushEntry(5, 9);
+ buffer1_->PushEntry(2, 3);
+ buffer1_->PushEntry(-1, 7);
+ buffer1_->PushEntry(-7, 1);
+ buffer1_->PushEntry(3, 2);
+ buffer1_->PushEntry(-2, 3);
+ buffer1_->PushEntry(21, 8);
+ buffer1_->PushEntry(-13, 4);
+ buffer1_->PushEntry(8, 2);
+ buffer1_->PushEntry(-5, 6);
+
+ // Constructs a buffer of 7 weighted unique entries.
+ buffer2_.reset(new Buffer(7, 1000));
+ buffer2_->PushEntry(9, 2);
+ buffer2_->PushEntry(-7, 3);
+ buffer2_->PushEntry(2, 1);
+ buffer2_->PushEntry(4, 13);
+ buffer2_->PushEntry(0, 5);
+ buffer2_->PushEntry(-5, 3);
+ buffer2_->PushEntry(11, 3);
+ }
+
+ void TearDown() override { buffer1_->Clear(); }
+
+ std::unique_ptr<Buffer> buffer1_;
+ std::unique_ptr<Buffer> buffer2_;
+ const double buffer1_min_value_ = -13;
+ const double buffer1_max_value_ = 21;
+ const double buffer1_total_weight_ = 45;
+ const double buffer2_min_value_ = -7;
+ const double buffer2_max_value_ = 11;
+ const double buffer2_total_weight_ = 30;
+};
+
+TEST_F(WeightedQuantilesSummaryTest, BuildFromBuffer) {
+ Summary summary;
+ summary.BuildFromBufferEntries(buffer1_->GenerateEntryList());
+
+ // We expect no approximation error because no compress operation occurred.
+ EXPECT_EQ(summary.ApproximationError(), 0);
+
+ // Check first and last elements in the summary.
+ const auto& entries = summary.GetEntryList();
+ // First element's rmin should be zero.
+ EXPECT_EQ(summary.MinValue(), buffer1_min_value_);
+ EXPECT_EQ(entries.front(), SummaryEntry(-13, 4, 0, 4));
+ // Last element's rmax should be cumulative weight.
+ EXPECT_EQ(summary.MaxValue(), buffer1_max_value_);
+ EXPECT_EQ(entries.back(), SummaryEntry(21, 8, 37, 45));
+ // Check total weight.
+ EXPECT_EQ(summary.TotalWeight(), buffer1_total_weight_);
+}
+
+TEST_F(WeightedQuantilesSummaryTest, CompressSeparately) {
+ const auto entry_list = buffer1_->GenerateEntryList();
+ for (int new_size = 9; new_size >= 2; --new_size) {
+ Summary summary;
+ summary.BuildFromBufferEntries(entry_list);
+ summary.Compress(new_size);
+
+ // Expect a max approximation error of 1 / n
+ // ie. eps0 + 1/n but eps0 = 0.
+ EXPECT_TRUE(summary.Size() >= new_size && summary.Size() <= new_size + 2);
+ EXPECT_LE(summary.ApproximationError(), 1.0 / new_size);
+
+ // Min/Max elements and total weight should not change.
+ EXPECT_EQ(summary.MinValue(), buffer1_min_value_);
+ EXPECT_EQ(summary.MaxValue(), buffer1_max_value_);
+ EXPECT_EQ(summary.TotalWeight(), buffer1_total_weight_);
+ }
+}
+
+TEST_F(WeightedQuantilesSummaryTest, CompressSequentially) {
+ Summary summary;
+ summary.BuildFromBufferEntries(buffer1_->GenerateEntryList());
+ for (int new_size = 9; new_size >= 2; new_size -= 2) {
+ double prev_eps = summary.ApproximationError();
+ summary.Compress(new_size);
+
+ // Expect a max approximation error of prev_eps + 1 / n.
+ EXPECT_TRUE(summary.Size() >= new_size && summary.Size() <= new_size + 2);
+ EXPECT_LE(summary.ApproximationError(), prev_eps + 1.0 / new_size);
+
+ // Min/Max elements and total weight should not change.
+ EXPECT_EQ(summary.MinValue(), buffer1_min_value_);
+ EXPECT_EQ(summary.MaxValue(), buffer1_max_value_);
+ EXPECT_EQ(summary.TotalWeight(), buffer1_total_weight_);
+ }
+}
+
+TEST_F(WeightedQuantilesSummaryTest, CompressRandomized) {
+ // Check multiple size compressions and ensure approximation bounds
+ // are always respected.
+ int prev_size = 1;
+ int size = 2;
+ float max_value = 1 << 20;
+ while (size < (1 << 16)) {
+ // Create buffer of size from uniform random elements.
+ Buffer buffer(size, size << 4);
+ random::PhiloxRandom philox(13);
+ random::SimplePhilox rand(&philox);
+ for (int i = 0; i < size; ++i) {
+ buffer.PushEntry(rand.RandFloat() * max_value,
+ rand.RandFloat() * max_value);
+ }
+
+ // Create summary and compress.
+ Summary summary;
+ summary.BuildFromBufferEntries(buffer.GenerateEntryList());
+ int new_size = std::max(rand.Uniform(size), 2u);
+ summary.Compress(new_size);
+
+ // Ensure approximation error is acceptable.
+ EXPECT_TRUE(summary.Size() >= new_size && summary.Size() <= new_size + 2);
+ EXPECT_LE(summary.ApproximationError(), 1.0 / new_size);
+
+ // Update size to next fib number.
+ size_t last_size = size;
+ size += prev_size;
+ prev_size = last_size;
+ }
+}
+
+TEST_F(WeightedQuantilesSummaryTest, MergeSymmetry) {
+ // Create two separate summaries and merge.
+ const auto list_1 = buffer1_->GenerateEntryList();
+ const auto list_2 = buffer2_->GenerateEntryList();
+ Summary summary1;
+ summary1.BuildFromBufferEntries(list_1);
+ Summary summary2;
+ summary2.BuildFromBufferEntries(list_2);
+
+ // Merge summary 2 into 1 and verify.
+ summary1.Merge(summary2);
+ EXPECT_EQ(summary1.ApproximationError(), 0.0);
+ EXPECT_EQ(summary1.MinValue(),
+ std::min(buffer1_min_value_, buffer2_min_value_));
+ EXPECT_EQ(summary1.MaxValue(),
+ std::max(buffer1_max_value_, buffer2_max_value_));
+ EXPECT_EQ(summary1.TotalWeight(),
+ buffer1_total_weight_ + buffer2_total_weight_);
+ EXPECT_EQ(summary1.Size(), 14); // 14 unique values.
+
+ // Merge summary 1 into 2 and verify same result.
+ summary1.BuildFromBufferEntries(list_1);
+ summary2.Merge(summary1);
+ EXPECT_EQ(summary2.ApproximationError(), 0.0);
+ EXPECT_EQ(summary2.MinValue(),
+ std::min(buffer1_min_value_, buffer2_min_value_));
+ EXPECT_EQ(summary2.MaxValue(),
+ std::max(buffer1_max_value_, buffer2_max_value_));
+ EXPECT_EQ(summary2.TotalWeight(),
+ buffer1_total_weight_ + buffer2_total_weight_);
+ EXPECT_EQ(summary2.Size(), 14); // 14 unique values.
+}
+
+TEST_F(WeightedQuantilesSummaryTest, CompressThenMerge) {
+ // Create two separate summaries and merge.
+ Summary summary1;
+ summary1.BuildFromBufferEntries(buffer1_->GenerateEntryList());
+ Summary summary2;
+ summary2.BuildFromBufferEntries(buffer2_->GenerateEntryList());
+
+ // Compress summaries.
+ summary1.Compress(5); // max error is 1/5.
+ const auto eps1 = 1.0 / 5;
+ EXPECT_LE(summary1.ApproximationError(), eps1);
+ summary2.Compress(3); // max error is 1/3.
+ const auto eps2 = 1.0 / 3;
+ EXPECT_LE(summary2.ApproximationError(), eps2);
+
+ // Merge guarantees an approximation error of max(eps1, eps2).
+ // Merge summary 2 into 1 and verify.
+ summary1.Merge(summary2);
+ EXPECT_LE(summary1.ApproximationError(), std::max(eps1, eps2));
+ EXPECT_EQ(summary1.MinValue(),
+ std::min(buffer1_min_value_, buffer2_min_value_));
+ EXPECT_EQ(summary1.MaxValue(),
+ std::max(buffer1_max_value_, buffer2_max_value_));
+ EXPECT_EQ(summary1.TotalWeight(),
+ buffer1_total_weight_ + buffer2_total_weight_);
+}
+
+} // namespace
+} // namespace tensorflow
diff --git a/tensorflow/core/kernels/cast_op.cc b/tensorflow/core/kernels/cast_op.cc
index 0478c93280..3a72567655 100644
--- a/tensorflow/core/kernels/cast_op.cc
+++ b/tensorflow/core/kernels/cast_op.cc
@@ -98,7 +98,13 @@ void CastOpBase::Compute(OpKernelContext* ctx) {
ctx->set_output(0, inp);
} else {
Tensor in;
- in.UnsafeCopyFromInternal(inp, src_dtype_, inp.shape());
+ if (external_src_dtype_ != src_dtype_) {
+ // If the type is a quantized type we need to do an UnsafeCopyFromInternal
+ // since the src_dtype_ is different from external_src_type_.
+ in.UnsafeCopyFromInternal(inp, src_dtype_, inp.shape());
+ } else {
+ in = inp;
+ }
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, in.shape(), &out));
out->set_dtype(dst_dtype_);
diff --git a/tensorflow/core/kernels/colorspace_op.h b/tensorflow/core/kernels/colorspace_op.h
index 90bfce1419..4de14bc339 100644
--- a/tensorflow/core/kernels/colorspace_op.h
+++ b/tensorflow/core/kernels/colorspace_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_COLORSPACE_OP_H_
-#define TENSORFLOW_KERNELS_COLORSPACE_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_COLORSPACE_OP_H_
+#define TENSORFLOW_CORE_KERNELS_COLORSPACE_OP_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor_shape.h"
@@ -91,4 +91,4 @@ struct HSVToRGB {
} // namespace functor
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_COLORSPACE_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_COLORSPACE_OP_H_
diff --git a/tensorflow/core/kernels/concat_lib_cpu.h b/tensorflow/core/kernels/concat_lib_cpu.h
index 720b506537..29f3a427fe 100644
--- a/tensorflow/core/kernels/concat_lib_cpu.h
+++ b/tensorflow/core/kernels/concat_lib_cpu.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_CONCAT_LIB_CPU_H_
+#define TENSORFLOW_CORE_KERNELS_CONCAT_LIB_CPU_H_
+
#define EIGEN_USE_THREADS
#include <vector>
@@ -162,3 +165,5 @@ void ConcatSYCLImpl(
}
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_CONCAT_LIB_CPU_H_
diff --git a/tensorflow/core/kernels/concat_op.cc b/tensorflow/core/kernels/concat_op.cc
index 902327aaea..ff62983517 100644
--- a/tensorflow/core/kernels/concat_op.cc
+++ b/tensorflow/core/kernels/concat_op.cc
@@ -66,16 +66,17 @@ class ConcatBaseOp : public OpKernel {
// In case of ConcatV2, "axis" could be int32 or int64
if (AxisArgName == NAME_IS_AXIS) {
OP_REQUIRES(
- c, (concat_dim_tensor->dtype() == DT_INT32 ||
- concat_dim_tensor->dtype() == DT_INT64),
+ c,
+ (concat_dim_tensor->dtype() == DT_INT32 ||
+ concat_dim_tensor->dtype() == DT_INT64),
errors::InvalidArgument(axis_attribute_name,
" tensor should be int32 or int64, but got ",
- concat_dim_tensor->dtype()));
+ DataTypeString(concat_dim_tensor->dtype())));
} else {
OP_REQUIRES(c, (concat_dim_tensor->dtype() == DT_INT32),
- errors::InvalidArgument(axis_attribute_name,
- " tensor should be int32, but got ",
- concat_dim_tensor->dtype()));
+ errors::InvalidArgument(
+ axis_attribute_name, " tensor should be int32, but got ",
+ DataTypeString(concat_dim_tensor->dtype())));
}
if (concat_dim_tensor->dtype() == DT_INT32) {
concat_dim =
diff --git a/tensorflow/core/kernels/constant_op.cc b/tensorflow/core/kernels/constant_op.cc
index a888422d49..426c404f43 100644
--- a/tensorflow/core/kernels/constant_op.cc
+++ b/tensorflow/core/kernels/constant_op.cc
@@ -140,44 +140,6 @@ REGISTER_SYCL_KERNEL(SYCL, bool);
#undef REGISTER_SYCL_KERNEL
#endif
-HostConstantOp::HostConstantOp(OpKernelConstruction* ctx)
- : OpKernel(ctx), tensor_(ctx->output_type(0)) {
- const TensorProto* proto = nullptr;
- AllocatorAttributes alloc_attr;
- alloc_attr.set_on_host(true);
- OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto));
- OP_REQUIRES_OK(
- ctx, ctx->device()->MakeTensorFromProto(*proto, alloc_attr, &tensor_));
- OP_REQUIRES(
- ctx, ctx->output_type(0) == tensor_.dtype(),
- errors::InvalidArgument("Type mismatch between value (",
- DataTypeString(tensor_.dtype()), ") and dtype (",
- DataTypeString(ctx->output_type(0)), ")"));
-}
-
-void HostConstantOp::Compute(OpKernelContext* ctx) {
- ctx->set_output(0, tensor_);
-}
-
-#if GOOGLE_CUDA
-// A special GPU kernel for int32.
-// TODO(b/25387198): Also enable int32 in device memory. This kernel
-// registration requires all int32 inputs and outputs to be in host memory.
-REGISTER_KERNEL_BUILDER(Name("Const")
- .Device(DEVICE_GPU)
- .HostMemory("output")
- .TypeConstraint<int32>("dtype"),
- HostConstantOp);
-#endif
-
-#ifdef TENSORFLOW_USE_SYCL
-REGISTER_KERNEL_BUILDER(Name("Const")
- .Device(DEVICE_SYCL)
- .HostMemory("output")
- .TypeConstraint<int32>("dtype"),
- HostConstantOp);
-#endif // TENSORFLOW_USE_SYCL
-
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#ifdef TENSORFLOW_USE_SYCL
@@ -297,8 +259,9 @@ class ZerosLikeOp : public OpKernel {
errors::InvalidArgument("ZerosLike non-scalar Tensor with "
"dtype=DT_VARIANT is not supported."));
const Variant& v = input.scalar<Variant>()();
- Tensor out(ctx->device()->GetAllocator(AllocatorAttributes()), DT_VARIANT,
- TensorShape({}));
+ // DT_VARIANT tensors must be allocated on CPU since they wrap C++
+ // objects which can not be efficiently represented in GPU memory.
+ Tensor out(cpu_allocator(), DT_VARIANT, TensorShape({}));
Variant* out_v = &(out.scalar<Variant>()());
OP_REQUIRES_OK(ctx, UnaryOpVariant<Device>(
ctx, ZEROS_LIKE_VARIANT_UNARY_OP, v, out_v));
diff --git a/tensorflow/core/kernels/constant_op.h b/tensorflow/core/kernels/constant_op.h
index b98153e347..77ba441863 100644
--- a/tensorflow/core/kernels/constant_op.h
+++ b/tensorflow/core/kernels/constant_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_CONSTANT_OP_H_
-#define TENSORFLOW_KERNELS_CONSTANT_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_CONSTANT_OP_H_
+#define TENSORFLOW_CORE_KERNELS_CONSTANT_OP_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
@@ -36,20 +36,6 @@ class ConstantOp : public OpKernel {
TF_DISALLOW_COPY_AND_ASSIGN(ConstantOp);
};
-// HostConstantOp differs from ConstantOp in that its output is always
-// in host memory.
-class HostConstantOp : public OpKernel {
- public:
- explicit HostConstantOp(OpKernelConstruction* ctx);
- void Compute(OpKernelContext* ctx) override;
- bool IsExpensive() override { return false; }
- ~HostConstantOp() override {}
-
- private:
- Tensor tensor_;
- TF_DISALLOW_COPY_AND_ASSIGN(HostConstantOp);
-};
-
class PlaceholderOp : public OpKernel {
public:
explicit PlaceholderOp(OpKernelConstruction* ctx);
@@ -61,4 +47,4 @@ class PlaceholderOp : public OpKernel {
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_CONSTANT_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_CONSTANT_OP_H_
diff --git a/tensorflow/core/kernels/constant_op_test.cc b/tensorflow/core/kernels/constant_op_test.cc
index a6baae73d8..0faad11e47 100644
--- a/tensorflow/core/kernels/constant_op_test.cc
+++ b/tensorflow/core/kernels/constant_op_test.cc
@@ -60,6 +60,7 @@ void ConstantOpTest::PersistentMemoryTrackingTest(bool on_gpu) {
std::unique_ptr<OpKernel> op(CreateOpKernel(device_type, device.get(),
cpu_allocator(), const_node,
TF_GRAPH_DEF_VERSION, &status));
+ TF_ASSERT_OK(status);
OpKernelContext::Params params;
params.device = device.get();
diff --git a/tensorflow/core/kernels/conv_grad_ops.cc b/tensorflow/core/kernels/conv_grad_ops.cc
index 5bf709af08..fc0a2f123f 100644
--- a/tensorflow/core/kernels/conv_grad_ops.cc
+++ b/tensorflow/core/kernels/conv_grad_ops.cc
@@ -63,7 +63,7 @@ Status ConvBackpropExtractAndVerifyDimensionV2(
return errors::InvalidArgument(
label, ": Size of out_backprop doesn't match computed: ", "actual = ",
dim->output_size, ", computed = ", out_size,
- "spatial_dim: ", spatial_dim, " input: ", dim->input_size,
+ " spatial_dim: ", spatial_dim, " input: ", dim->input_size,
" filter: ", dim->filter_size, " output: ", dim->output_size,
" stride: ", dim->stride, " dilation: ", dim->dilation);
}
diff --git a/tensorflow/core/kernels/cross_op.h b/tensorflow/core/kernels/cross_op.h
index ca6beba52b..45bc46a921 100644
--- a/tensorflow/core/kernels/cross_op.h
+++ b/tensorflow/core/kernels/cross_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_COLORSPACE_OP_H_
-#define TENSORFLOW_KERNELS_COLORSPACE_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_CROSS_OP_H_
+#define TENSORFLOW_CORE_KERNELS_CROSS_OP_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor_shape.h"
@@ -51,4 +51,4 @@ struct Cross {
} // namespace functor
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_COLORSPACE_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_CROSS_OP_H_
diff --git a/tensorflow/core/kernels/cuda_solvers.h b/tensorflow/core/kernels/cuda_solvers.h
index b2e8ee23a9..2c30d036df 100644
--- a/tensorflow/core/kernels/cuda_solvers.h
+++ b/tensorflow/core/kernels/cuda_solvers.h
@@ -14,6 +14,9 @@ limitations under the License.
==============================================================================
*/
+#ifndef TENSORFLOW_CORE_KERNELS_CUDA_SOLVERS_H_
+#define TENSORFLOW_CORE_KERNELS_CUDA_SOLVERS_H_
+
// This header declares the class CudaSolver, which contains wrappers of linear
// algebra solvers in the cuBlas and cuSolverDN libraries for use in TensorFlow
// kernels.
@@ -433,3 +436,5 @@ inline DeviceLapackInfo CudaSolver::GetDeviceLapackInfo(
} // namespace tensorflow
#endif // GOOGLE_CUDA
+
+#endif // TENSORFLOW_CORE_KERNELS_CUDA_SOLVERS_H_
diff --git a/tensorflow/core/kernels/cwise_op_div.cc b/tensorflow/core/kernels/cwise_op_div.cc
index b12652f7fb..35662e278f 100644
--- a/tensorflow/core/kernels/cwise_op_div.cc
+++ b/tensorflow/core/kernels/cwise_op_div.cc
@@ -24,6 +24,8 @@ REGISTER5(BinaryOp, CPU, "TruncateDiv", functor::safe_div, uint8, uint16, int16,
int32, int64);
REGISTER6(BinaryOp, CPU, "RealDiv", functor::div, float, Eigen::half, double,
bfloat16, complex64, complex128);
+REGISTER2(BinaryOp, CPU, "DivNoNan", functor::div_no_nan, float, double);
+
#if GOOGLE_CUDA
REGISTER9(BinaryOp, GPU, "Div", functor::div, float, Eigen::half, double, uint8,
uint16, int16, int64, complex64, complex128);
diff --git a/tensorflow/core/kernels/cwise_op_select.cc b/tensorflow/core/kernels/cwise_op_select.cc
index e259daaba4..d6988a562c 100644
--- a/tensorflow/core/kernels/cwise_op_select.cc
+++ b/tensorflow/core/kernels/cwise_op_select.cc
@@ -22,6 +22,7 @@ limitations under the License.
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/cwise_ops_common.h"
+#include "tensorflow/core/platform/prefetch.h"
namespace tensorflow {
@@ -32,6 +33,11 @@ typedef Eigen::GpuDevice GPUDevice;
typedef Eigen::SyclDevice SYCLDevice;
#endif // TENSORFLOW_USE_SYCL
+namespace functor {
+template <typename Device, typename T>
+struct SelectScalarHandler;
+} // namespace functor
+
template <typename Device, typename T>
class SelectOp : public OpKernel {
public:
@@ -130,16 +136,8 @@ class SelectOp : public OpKernel {
then->shape().DebugString(), " vs. ",
else_->shape().DebugString()));
- Tensor* output = nullptr;
- OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
- {"t", "e"}, "output", then->shape(), &output));
-
- if (output->NumElements() > 0) {
- functor::SelectScalarFunctor<Device, T> func;
- TTypes<bool>::ConstScalar cond_scalar = cond->scalar<bool>();
- func(ctx->eigen_device<Device>(), output->flat<T>(), cond_scalar,
- then->flat<T>(), else_->flat<T>());
- }
+ functor::SelectScalarHandler<Device, T> handler;
+ handler(ctx, cond, then, else_);
}
private:
@@ -208,6 +206,40 @@ struct SelectFunctor<SYCLDevice, T> : SelectFunctorBase<SYCLDevice, T> {};
#endif // TENSORFLOW_USE_SYCL
template <typename Device, typename T>
+struct SelectScalarHandler {
+ void operator()(OpKernelContext* ctx, const Tensor* cond, const Tensor* then,
+ const Tensor* else_) {
+ Tensor* output = nullptr;
+ OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
+ {"t", "e"}, "output", then->shape(), &output));
+
+ if (output->NumElements() > 0) {
+ functor::SelectScalarFunctor<Device, T> func;
+ TTypes<bool>::ConstScalar cond_scalar = cond->scalar<bool>();
+ func(ctx->eigen_device<Device>(), output->flat<T>(), cond_scalar,
+ then->flat<T>(), else_->flat<T>());
+ }
+ }
+};
+
+// Specilization for CPU device. Forward input to output depending on the `cond`
+// value.
+// TODO(sjhwang): Consider specializing for GPUDevice as well by using
+// GPUDevice::memcpyDeviceToHost() to fetch bool value.
+template <typename T>
+struct SelectScalarHandler<CPUDevice, T> {
+ void operator()(OpKernelContext* ctx, const Tensor* cond, const Tensor* then,
+ const Tensor* else_) {
+ if (cond->scalar<bool>()()) {
+ OP_REQUIRES_OK(ctx, ctx->set_output("output", *then));
+ } else {
+ OP_REQUIRES_OK(ctx, ctx->set_output("output", *else_));
+ }
+ }
+};
+
+#ifdef TENSORFLOW_USE_SYCL
+template <typename Device, typename T>
struct SelectScalarFunctorBase {
void operator()(const Device& d, typename TTypes<T>::Flat out,
TTypes<bool>::ConstScalar cond,
@@ -217,11 +249,6 @@ struct SelectScalarFunctorBase {
}
};
-// CPU Specializations of Select functors with scalar
-template <typename T>
-struct SelectScalarFunctor<CPUDevice, T>
- : SelectScalarFunctorBase<CPUDevice, T> {};
-#ifdef TENSORFLOW_USE_SYCL
template <typename T>
struct SelectScalarFunctor<SYCLDevice, T>
: SelectScalarFunctorBase<SYCLDevice, T> {};
@@ -254,9 +281,48 @@ struct BatchSelectFunctorBase {
}
};
+// A fast implementation on CPU, using loop to get rid of broadcasting.
template <typename T>
-struct BatchSelectFunctor<CPUDevice, T> : BatchSelectFunctorBase<CPUDevice, T> {
+struct BatchSelectFunctor<CPUDevice, T> {
+ void operator()(const CPUDevice& d,
+ typename TTypes<T>::Matrix output_flat_outer_dims,
+ TTypes<bool>::ConstVec cond_vec,
+ typename TTypes<T>::ConstMatrix then_flat_outer_dims,
+ typename TTypes<T>::ConstMatrix else_flat_outer_dims) {
+ const size_t batch = cond_vec.size();
+ const size_t batch_size = then_flat_outer_dims.size() / batch;
+ T* output = output_flat_outer_dims.data();
+ const bool* c = cond_vec.data();
+ const T* t = then_flat_outer_dims.data();
+ const T* e = else_flat_outer_dims.data();
+
+ auto work = [batch_size, output, c, t, e](int64 start, int64 end) {
+ for (size_t i = start; i < end; ++i) {
+ size_t offset = i * batch_size;
+ port::prefetch<port::PREFETCH_HINT_NTA>(
+ reinterpret_cast<const void*>(&t[offset + batch_size]));
+ port::prefetch<port::PREFETCH_HINT_NTA>(
+ reinterpret_cast<const void*>(&e[offset + batch_size]));
+ port::prefetch<port::PREFETCH_HINT_NTA>(
+ reinterpret_cast<const void*>(&c[i + 1]));
+ if (c[i]) {
+ for (size_t j = 0; j < batch_size; ++j) {
+ output[offset + j] = t[offset + j];
+ }
+ } else {
+ for (size_t j = 0; j < batch_size; ++j) {
+ output[offset + j] = e[offset + j];
+ }
+ }
+ }
+ };
+ auto cost = Eigen::TensorOpCost(sizeof(T) * batch_size * 2, // ld bytes
+ sizeof(T) * batch_size, // st bytes
+ batch_size); // compute cycles
+ d.parallelFor(batch, cost, work);
+ }
};
+
#ifdef TENSORFLOW_USE_SYCL
template <typename T>
struct BatchSelectFunctor<SYCLDevice, T>
diff --git a/tensorflow/core/kernels/cwise_ops.h b/tensorflow/core/kernels/cwise_ops.h
index 1b1a704d42..de164c1c09 100644
--- a/tensorflow/core/kernels/cwise_ops.h
+++ b/tensorflow/core/kernels/cwise_ops.h
@@ -153,6 +153,27 @@ struct functor_traits<safe_div_or_mod_op<T, DivOrMod>> {
};
};
+template <typename T>
+struct div_no_nan_op {
+ EIGEN_EMPTY_STRUCT_CTOR(div_no_nan_op)
+ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const T operator()(const T& a,
+ const T& b) const {
+ if (b != 0) {
+ return scalar_quotient_op<T>()(a, b);
+ } else {
+ return 0;
+ }
+ }
+};
+
+template <typename T>
+struct functor_traits<div_no_nan_op<T>> {
+ enum {
+ Cost = functor_traits<scalar_quotient_op<T>>::Cost + NumTraits<T>::AddCost,
+ PacketAccess = false,
+ };
+};
+
// scalar_left and scalar_right are template helpers to partially
// apply a binary function.
//
@@ -721,6 +742,9 @@ struct safe_div : base<T, Eigen::internal::safe_div_or_mod_op<
};
template <typename T>
+struct div_no_nan : base<T, Eigen::internal::div_no_nan_op<T>> {};
+
+template <typename T>
struct fmod : base<T, Eigen::internal::scalar_fmod_op<T>> {};
template <typename T>
diff --git a/tensorflow/core/kernels/cwise_ops_gpu_common.cu.h b/tensorflow/core/kernels/cwise_ops_gpu_common.cu.h
index 965e42dcce..cfae273bf4 100644
--- a/tensorflow/core/kernels/cwise_ops_gpu_common.cu.h
+++ b/tensorflow/core/kernels/cwise_ops_gpu_common.cu.h
@@ -17,8 +17,8 @@ limitations under the License.
#error This file must only be included when building with Cuda support
#endif
-#ifndef TENSORFLOW_KERNELS_CWISE_OPS_GPU_COMMON_CU_H_
-#define TENSORFLOW_KERNELS_CWISE_OPS_GPU_COMMON_CU_H_
+#ifndef TENSORFLOW_CORE_KERNELS_CWISE_OPS_GPU_COMMON_CU_H_
+#define TENSORFLOW_CORE_KERNELS_CWISE_OPS_GPU_COMMON_CU_H_
#define EIGEN_USE_GPU
@@ -188,4 +188,4 @@ struct ApproximateEqual<GPUDevice, T> {
} // end namespace functor
} // end namespace tensorflow
-#endif // TENSORFLOW_KERNELS_CWISE_OPS_GPU_COMMON_CU_H_
+#endif // TENSORFLOW_CORE_KERNELS_CWISE_OPS_GPU_COMMON_CU_H_
diff --git a/tensorflow/core/kernels/cwise_ops_gpu_gradients.cu.h b/tensorflow/core/kernels/cwise_ops_gpu_gradients.cu.h
index e81b840a50..15e5de0f72 100644
--- a/tensorflow/core/kernels/cwise_ops_gpu_gradients.cu.h
+++ b/tensorflow/core/kernels/cwise_ops_gpu_gradients.cu.h
@@ -17,8 +17,8 @@ limitations under the License.
#error This file must only be included when building with Cuda support
#endif
-#ifndef TENSORFLOW_KERNELS_CWISE_OPS_GPU_GRADIENTS_CU_H_
-#define TENSORFLOW_KERNELS_CWISE_OPS_GPU_GRADIENTS_CU_H_
+#ifndef TENSORFLOW_CORE_KERNELS_CWISE_OPS_GPU_GRADIENTS_CU_H_
+#define TENSORFLOW_CORE_KERNELS_CWISE_OPS_GPU_GRADIENTS_CU_H_
#define EIGEN_USE_GPU
@@ -68,4 +68,4 @@ struct SimpleBinaryFunctor<GPUDevice, Functor> {
} // end namespace functor
} // end namespace tensorflow
-#endif // TENSORFLOW_KERNELS_CWISE_OPS_GPU_GRADIENTS_CU_H_
+#endif // TENSORFLOW_CORE_KERNELS_CWISE_OPS_GPU_GRADIENTS_CU_H_
diff --git a/tensorflow/core/kernels/data/batch_dataset_op.cc b/tensorflow/core/kernels/data/batch_dataset_op.cc
index 58b86f2a08..f9b5353724 100644
--- a/tensorflow/core/kernels/data/batch_dataset_op.cc
+++ b/tensorflow/core/kernels/data/batch_dataset_op.cc
@@ -49,11 +49,11 @@ class BatchDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 batch_size, bool drop_remainder,
const DatasetBase* input)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
batch_size_(batch_size),
drop_remainder_(drop_remainder),
input_(input) {
@@ -96,10 +96,11 @@ class BatchDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* batch_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size));
Node* drop_remainder = nullptr;
@@ -203,7 +204,7 @@ class BatchDatasetOp : public UnaryDatasetOpKernel {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
} else {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
}
return Status::OK();
}
@@ -212,7 +213,7 @@ class BatchDatasetOp : public UnaryDatasetOpKernel {
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/core/kernels/data/cache_dataset_ops.cc b/tensorflow/core/kernels/data/cache_dataset_ops.cc
index 86b0840aea..6ca0bcd37d 100644
--- a/tensorflow/core/kernels/data/cache_dataset_ops.cc
+++ b/tensorflow/core/kernels/data/cache_dataset_ops.cc
@@ -46,11 +46,11 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class FileDataset : public GraphDatasetBase {
+ class FileDataset : public DatasetBase {
public:
explicit FileDataset(OpKernelContext* ctx, const DatasetBase* input,
string filename, Env* env)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
filename_(std::move(filename)),
env_(env),
@@ -85,10 +85,11 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph));
Node* filename = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(filename_, &filename));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph, filename}, output));
@@ -135,7 +136,7 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("mode"), mode_));
- return SaveParent(writer, iterator_);
+ return SaveInput(writer, iterator_);
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
@@ -162,7 +163,7 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
}
InitializeIterator();
TF_RETURN_IF_ERROR(iterator_->Initialize(ctx));
- return RestoreParent(ctx, reader, iterator_);
+ return RestoreInput(ctx, reader, iterator_);
}
private:
@@ -269,7 +270,7 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
lockfile_ = strings::StrCat(filename_, ".lockfile");
lockfile_created_ = false;
}
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("cur_index"), cur_index_));
TF_RETURN_IF_ERROR(
@@ -285,7 +286,7 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
return Status::OK();
}
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
int64 temp;
// TODO(b/78048575): Update this when saving size_t tensors directly
// is supported.
@@ -538,10 +539,12 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
const string tensor_format_string_;
}; // FileDataset
- class MemoryDataset : public GraphDatasetBase {
+ class MemoryDataset : public DatasetBase {
public:
explicit MemoryDataset(OpKernelContext* ctx, const DatasetBase* input)
- : GraphDatasetBase(ctx), input_(input), cache_(new MemoryCache()) {
+ : DatasetBase(DatasetContext(ctx)),
+ input_(input),
+ cache_(new MemoryCache()) {
input->Ref();
}
@@ -566,10 +569,11 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* filename_node = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(string(""), &filename_node));
TF_RETURN_IF_ERROR(
@@ -702,7 +706,7 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
writer->WriteScalar(full_name("cache_completed"), ""));
}
}
- return SaveParent(writer, iterator_);
+ return SaveInput(writer, iterator_);
}
Status RestoreInternal(IteratorContext* ctx,
@@ -748,7 +752,7 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
}
InitializeIterator();
TF_RETURN_IF_ERROR(iterator_->Initialize(ctx));
- return RestoreParent(ctx, reader, iterator_);
+ return RestoreInput(ctx, reader, iterator_);
}
private:
@@ -795,13 +799,13 @@ class CacheDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- return SaveParent(writer, input_impl_);
+ return SaveInput(writer, input_impl_);
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- return RestoreParent(ctx, reader, input_impl_);
+ return RestoreInput(ctx, reader, input_impl_);
}
private:
diff --git a/tensorflow/core/kernels/data/concatenate_dataset_op.cc b/tensorflow/core/kernels/data/concatenate_dataset_op.cc
index 0012a4769d..c361a9adcb 100644
--- a/tensorflow/core/kernels/data/concatenate_dataset_op.cc
+++ b/tensorflow/core/kernels/data/concatenate_dataset_op.cc
@@ -39,11 +39,11 @@ class ConcatenateDatasetOp : public BinaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input,
const DatasetBase* to_concatenate)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
to_concatenate_(to_concatenate) {
input_->Ref();
@@ -80,13 +80,14 @@ class ConcatenateDatasetOp : public BinaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph));
Node* to_concatenate_graph = nullptr;
TF_RETURN_IF_ERROR(
- b->AddParentDataset(ctx, to_concatenate_, &to_concatenate_graph));
+ b->AddInputDataset(ctx, to_concatenate_, &to_concatenate_graph));
TF_RETURN_IF_ERROR(
b->AddDataset(this, {input_graph, to_concatenate_graph}, output));
return Status::OK();
@@ -132,7 +133,7 @@ class ConcatenateDatasetOp : public BinaryDatasetOpKernel {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("i"), i_));
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_uninitialized"), ""));
@@ -157,7 +158,7 @@ class ConcatenateDatasetOp : public BinaryDatasetOpKernel {
input_impl_.reset();
}
if (input_impl_) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/dataset_ops.cc b/tensorflow/core/kernels/data/dataset_ops.cc
index 01989a3bd9..c71d027f23 100644
--- a/tensorflow/core/kernels/data/dataset_ops.cc
+++ b/tensorflow/core/kernels/data/dataset_ops.cc
@@ -32,7 +32,11 @@ class DatasetToGraphOp : public OpKernel {
GraphDefBuilder b;
DatasetBase::DatasetGraphDefBuilder db(&b);
Node* input_node = nullptr;
- OP_REQUIRES_OK(ctx, db.AddParentDataset(ctx, dataset, &input_node));
+ SerializationContext::Params params;
+ params.flib_def = ctx->function_library()->GetFunctionLibraryDefinition();
+ SerializationContext serialization_ctx(params);
+ OP_REQUIRES_OK(
+ ctx, db.AddInputDataset(&serialization_ctx, dataset, &input_node));
GraphDef graph_def;
OP_REQUIRES_OK(ctx, b.ToGraphDef(&graph_def));
Tensor* result;
diff --git a/tensorflow/core/kernels/data/dense_to_sparse_batch_dataset_op.cc b/tensorflow/core/kernels/data/dense_to_sparse_batch_dataset_op.cc
index da4b14c8b9..9770bc025d 100644
--- a/tensorflow/core/kernels/data/dense_to_sparse_batch_dataset_op.cc
+++ b/tensorflow/core/kernels/data/dense_to_sparse_batch_dataset_op.cc
@@ -76,11 +76,11 @@ class DenseToSparseBatchDatasetOp : public UnaryDatasetOpKernel {
private:
// TODO(mrry): Push the templated code down to the raw copying routine.
template <class T>
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 batch_size,
const PartialTensorShape& row_shape, const DatasetBase* input)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
batch_size_(batch_size),
row_shape_(row_shape),
input_(input) {
@@ -115,10 +115,11 @@ class DenseToSparseBatchDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* batch_size_node;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size_node));
Node* row_shape_node;
@@ -273,14 +274,14 @@ class DenseToSparseBatchDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(Iterator::SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(Iterator::SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(Iterator::RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(Iterator::RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/filter_by_component_dataset_op.cc b/tensorflow/core/kernels/data/filter_by_component_dataset_op.cc
index 8b29456354..ce577397c5 100644
--- a/tensorflow/core/kernels/data/filter_by_component_dataset_op.cc
+++ b/tensorflow/core/kernels/data/filter_by_component_dataset_op.cc
@@ -48,12 +48,12 @@ class FilterByLastComponentDatasetOp : public UnaryDatasetOpKernel {
DataTypeVector output_types_;
std::vector<PartialTensorShape> output_shapes_;
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const DataTypeVector& output_types,
std::vector<PartialTensorShape> output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
output_types_(output_types),
output_shapes_(std::move(output_shapes)) {
@@ -80,10 +80,11 @@ class FilterByLastComponentDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {std::make_pair(0, input_graph_node)}, // Single tensor inputs.
@@ -143,14 +144,14 @@ class FilterByLastComponentDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/filter_dataset_op.cc b/tensorflow/core/kernels/data/filter_dataset_op.cc
index 6d6c44552d..a80e102ccf 100644
--- a/tensorflow/core/kernels/data/filter_dataset_op.cc
+++ b/tensorflow/core/kernels/data/filter_dataset_op.cc
@@ -79,12 +79,12 @@ class FilterDatasetOp : public UnaryDatasetOpKernel {
private:
const int graph_def_version_;
- class FilterDatasetBase : public GraphDatasetBase {
+ class FilterDatasetBase : public DatasetBase {
public:
FilterDatasetBase(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func,
std::unique_ptr<CapturedFunction> captured_func)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
func_(func),
captured_func_(std::move(captured_func)) {
@@ -109,11 +109,12 @@ class FilterDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "FilterDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), func_.name()));
Node* input_graph_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
DataTypeVector other_arguments_types;
other_arguments_types.reserve(captured_func_->captured_inputs().size());
@@ -190,7 +191,7 @@ class FilterDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_)
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
else
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impls_empty"), ""));
@@ -203,7 +204,7 @@ class FilterDatasetOp : public UnaryDatasetOpKernel {
if (reader->Contains(full_name("input_impls_empty")))
input_impl_.reset();
else
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/flat_map_dataset_op.cc b/tensorflow/core/kernels/data/flat_map_dataset_op.cc
index baca022f1e..07bcb9d414 100644
--- a/tensorflow/core/kernels/data/flat_map_dataset_op.cc
+++ b/tensorflow/core/kernels/data/flat_map_dataset_op.cc
@@ -56,14 +56,14 @@ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func,
std::unique_ptr<CapturedFunction> captured_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
func_(func),
captured_func_(std::move(captured_func)),
@@ -91,11 +91,12 @@ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "FlatMapDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), func_.name()));
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
DataTypeVector other_arguments_types;
other_arguments_types.reserve(captured_func_->captured_inputs().size());
@@ -174,7 +175,7 @@ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("element_index"), element_index_));
if (current_element_iterator_) {
@@ -186,7 +187,7 @@ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
full_name(strings::StrCat("captured_func_inputs[", i, "]")),
captured_func_inputs_[i]));
}
- TF_RETURN_IF_ERROR(SaveParent(writer, current_element_iterator_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, current_element_iterator_));
} else {
TF_RETURN_IF_ERROR(writer->WriteScalar(
full_name("current_element_iterator_uninitialized"), ""));
@@ -207,7 +208,7 @@ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
if (!reader->Contains(full_name("exhausted"))) {
TF_RETURN_IF_ERROR(
dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_));
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
{
int64 temp;
TF_RETURN_IF_ERROR(
@@ -233,7 +234,7 @@ class FlatMapDatasetOp : public UnaryDatasetOpKernel {
element_index_--;
TF_RETURN_IF_ERROR(BuildCurrentElementIteratorLocked(ctx));
TF_RETURN_IF_ERROR(
- RestoreParent(ctx, reader, current_element_iterator_));
+ RestoreInput(ctx, reader, current_element_iterator_));
}
}
return Status::OK();
diff --git a/tensorflow/core/kernels/data/generator_dataset_op.cc b/tensorflow/core/kernels/data/generator_dataset_op.cc
index c4dd849b8b..3c3d78b724 100644
--- a/tensorflow/core/kernels/data/generator_dataset_op.cc
+++ b/tensorflow/core/kernels/data/generator_dataset_op.cc
@@ -26,14 +26,14 @@ namespace tensorflow {
// See documentation in ../ops/dataset_ops.cc for a high-level
// description of the following op.
-class GeneratorDatasetOp::Dataset : public GraphDatasetBase {
+class GeneratorDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::unique_ptr<CapturedFunction> init_func,
std::unique_ptr<CapturedFunction> next_func,
std::unique_ptr<CapturedFunction> finalize_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
init_func_(std::move(init_func)),
next_func_(std::move(next_func)),
finalize_func_(std::move(finalize_func)),
@@ -47,12 +47,21 @@ class GeneratorDatasetOp::Dataset : public GraphDatasetBase {
}
const DataTypeVector& output_dtypes() const override { return output_types_; }
+
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override { return "GeneratorDatasetOp::Dataset"; }
+ protected:
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
class Iterator : public DatasetIterator<Dataset> {
public:
diff --git a/tensorflow/core/kernels/data/group_by_reducer_dataset_op.cc b/tensorflow/core/kernels/data/group_by_reducer_dataset_op.cc
index 7206be8c0d..be4132a064 100644
--- a/tensorflow/core/kernels/data/group_by_reducer_dataset_op.cc
+++ b/tensorflow/core/kernels/data/group_by_reducer_dataset_op.cc
@@ -66,7 +66,7 @@ class GroupByReducerDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
std::unique_ptr<CapturedFunction> captured_key_func,
@@ -75,7 +75,7 @@ class GroupByReducerDatasetOp : public UnaryDatasetOpKernel {
std::unique_ptr<CapturedFunction> captured_finalize_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
captured_key_func_(std::move(captured_key_func)),
captured_init_func_(std::move(captured_init_func)),
@@ -106,14 +106,16 @@ class GroupByReducerDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, key_func().name()));
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, init_func().name()));
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, reduce_func().name()));
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, finalize_func().name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), key_func().name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), init_func().name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), reduce_func().name()));
+ TF_RETURN_IF_ERROR(
+ b->AddFunction(ctx->flib_def(), finalize_func().name()));
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
std::vector<Node*> key_func_other_arguments_node;
DataTypeVector key_func_other_arguments_types;
@@ -261,7 +263,7 @@ class GroupByReducerDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
if (end_of_input_) {
TF_RETURN_IF_ERROR(
@@ -311,7 +313,7 @@ class GroupByReducerDatasetOp : public UnaryDatasetOpKernel {
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
if (reader->Contains(full_name("end_of_input"))) end_of_input_ = true;
diff --git a/tensorflow/core/kernels/data/group_by_window_dataset_op.cc b/tensorflow/core/kernels/data/group_by_window_dataset_op.cc
index 23d769e1ab..288695f3cd 100644
--- a/tensorflow/core/kernels/data/group_by_window_dataset_op.cc
+++ b/tensorflow/core/kernels/data/group_by_window_dataset_op.cc
@@ -93,7 +93,7 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& key_func, const NameAttrList& reduce_func,
@@ -103,7 +103,7 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
std::unique_ptr<CapturedFunction> captured_window_size_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
key_func_(key_func),
reduce_func_(reduce_func),
@@ -136,13 +136,15 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, key_func_.name()));
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, reduce_func_.name()));
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, window_size_func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), key_func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), reduce_func_.name()));
+ TF_RETURN_IF_ERROR(
+ b->AddFunction(ctx->flib_def(), window_size_func_.name()));
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
std::vector<Node*> key_func_other_arguments_node;
DataTypeVector key_func_other_arguments_types;
@@ -307,7 +309,7 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
if (end_of_input_) {
TF_RETURN_IF_ERROR(
@@ -348,7 +350,7 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
}
if (current_group_iterator_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, current_group_iterator_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, current_group_iterator_));
// Saving current_key_
TF_RETURN_IF_ERROR(
@@ -364,7 +366,7 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
if (reader->Contains(full_name("end_of_input"))) end_of_input_ = true;
@@ -412,7 +414,7 @@ class GroupByWindowDatasetOp : public UnaryDatasetOpKernel {
TF_RETURN_IF_ERROR(StartFlushingGroup(ctx, current_key_));
// Restore current_group_iterator_ state
TF_RETURN_IF_ERROR(
- RestoreParent(ctx, reader, current_group_iterator_));
+ RestoreInput(ctx, reader, current_group_iterator_));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/interleave_dataset_op.cc b/tensorflow/core/kernels/data/interleave_dataset_op.cc
index 0765e63993..58b79d6026 100644
--- a/tensorflow/core/kernels/data/interleave_dataset_op.cc
+++ b/tensorflow/core/kernels/data/interleave_dataset_op.cc
@@ -76,14 +76,14 @@ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func,
std::unique_ptr<CapturedFunction> captured_func, int64 cycle_length,
int64 block_length, const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
func_(func),
captured_func_(std::move(captured_func)),
@@ -114,11 +114,12 @@ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), func_.name()));
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* cycle_length_node;
TF_RETURN_IF_ERROR(b->AddScalar(cycle_length_, &cycle_length_node));
Node* block_length_node;
@@ -217,7 +218,7 @@ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("cycle_index"), cycle_index_));
TF_RETURN_IF_ERROR(
@@ -235,7 +236,7 @@ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
int64 cycle_index;
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("cycle_index"), &cycle_index));
@@ -256,7 +257,7 @@ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
EXCLUSIVE_LOCKS_REQUIRED(mu_) {
for (int idx = 0; idx < current_elements_.size(); idx++) {
if (current_elements_[idx]) {
- TF_RETURN_IF_ERROR(SaveParent(writer, current_elements_[idx]));
+ TF_RETURN_IF_ERROR(SaveInput(writer, current_elements_[idx]));
TF_RETURN_IF_ERROR(writer->WriteScalar(
full_name(strings::StrCat("args_size[", idx, "]")),
args_list_[idx].size()));
@@ -290,7 +291,7 @@ class InterleaveDatasetOp : public UnaryDatasetOpKernel {
ctx, args_list_[idx], idx, dataset()->captured_func_.get(),
prefix(), &current_elements_[idx]));
TF_RETURN_IF_ERROR(
- RestoreParent(ctx, reader, current_elements_[idx]));
+ RestoreInput(ctx, reader, current_elements_[idx]));
} else {
current_elements_[idx].reset();
}
diff --git a/tensorflow/core/kernels/data/iterator_ops.cc b/tensorflow/core/kernels/data/iterator_ops.cc
index e2df14337c..61a6c06135 100644
--- a/tensorflow/core/kernels/data/iterator_ops.cc
+++ b/tensorflow/core/kernels/data/iterator_ops.cc
@@ -116,7 +116,7 @@ class IteratorResource : public ResourceBase {
}
}
- Status Save(OpKernelContext* ctx, IteratorStateWriter* writer) {
+ Status Save(SerializationContext* ctx, IteratorStateWriter* writer) {
std::shared_ptr<IteratorBase> captured_iterator(iterator_);
if (captured_iterator) {
return captured_iterator->Save(ctx, writer);
@@ -130,7 +130,7 @@ class IteratorResource : public ResourceBase {
Status Restore(OpKernelContext* ctx, IteratorStateReader* reader) {
string serialized_graph_def;
- TF_RETURN_IF_ERROR(reader->ReadScalar(GraphDatasetBase::kDatasetGraphKey,
+ TF_RETURN_IF_ERROR(reader->ReadScalar(DatasetBase::kDatasetGraphKey,
&serialized_graph_def));
GraphDef graph_def;
if (!graph_def.ParseFromString(serialized_graph_def)) {
@@ -138,7 +138,7 @@ class IteratorResource : public ResourceBase {
}
string output_node;
TF_RETURN_IF_ERROR(reader->ReadScalar(
- GraphDatasetBase::kDatasetGraphOutputNodeKey, &output_node));
+ DatasetBase::kDatasetGraphOutputNodeKey, &output_node));
DatasetBase* dataset = nullptr;
Graph graph(OpRegistry::Global());
TF_RETURN_IF_ERROR(ImportGraphDef({}, graph_def, &graph, nullptr));
@@ -161,9 +161,9 @@ class IteratorResource : public ResourceBase {
graph_runner.Run(&graph, lib, {}, {output_node}, &outputs));
TF_RETURN_IF_ERROR(GetDatasetFromVariantTensor(outputs[0], &dataset));
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iterator;
- TF_RETURN_IF_ERROR(dataset->MakeIterator(&iter_ctx, "Iterator", &iterator));
+ TF_RETURN_IF_ERROR(
+ dataset->MakeIterator(IteratorContext(ctx), "Iterator", &iterator));
TF_RETURN_IF_ERROR(set_iterator(std::move(iterator)));
std::shared_ptr<IteratorBase> captured_iterator(iterator_);
@@ -386,10 +386,13 @@ class IteratorStateVariant {
// that it can be written on the next call to Encode().
Status InitializeFromIterator(OpKernelContext* ctx,
IteratorResource* iterator_resource) {
+ SerializationContext::Params params;
+ params.flib_def = ctx->function_library()->GetFunctionLibraryDefinition();
+ SerializationContext serialization_ctx(params);
data_.reset(new VariantTensorData());
data_->set_type_name(TypeName());
VariantTensorDataWriter writer(data_.get());
- TF_RETURN_IF_ERROR(iterator_resource->Save(ctx, &writer));
+ TF_RETURN_IF_ERROR(iterator_resource->Save(&serialization_ctx, &writer));
TF_RETURN_IF_ERROR(writer.Flush());
return Status::OK();
}
@@ -608,9 +611,9 @@ void MakeIteratorOp::Compute(OpKernelContext* ctx) {
ctx, LookupResource(ctx, HandleFromInput(ctx, 1), &iterator_resource));
core::ScopedUnref unref(iterator_resource);
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iterator;
- OP_REQUIRES_OK(ctx, dataset->MakeIterator(&iter_ctx, "Iterator", &iterator));
+ OP_REQUIRES_OK(
+ ctx, dataset->MakeIterator(IteratorContext(ctx), "Iterator", &iterator));
OP_REQUIRES_OK(ctx, iterator_resource->set_iterator(std::move(iterator)));
}
@@ -630,11 +633,11 @@ class ToSingleElementOp : public AsyncOpKernel {
DatasetBase* dataset;
OP_REQUIRES_OK_ASYNC(
ctx, GetDatasetFromVariantTensor(ctx->input(0), &dataset), done);
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iterator;
OP_REQUIRES_OK_ASYNC(
ctx,
- dataset->MakeIterator(&iter_ctx, "SingleElementIterator", &iterator),
+ dataset->MakeIterator(IteratorContext(ctx), "SingleElementIterator",
+ &iterator),
done);
// NOTE(jsimsa): We must destroy the iterator before calling `done()`, to
@@ -648,8 +651,8 @@ class ToSingleElementOp : public AsyncOpKernel {
components.reserve(dataset->output_dtypes().size());
bool end_of_sequence = false;
- Status s =
- raw_iterator->GetNext(&iter_ctx, &components, &end_of_sequence);
+ Status s = raw_iterator->GetNext(IteratorContext(ctx), &components,
+ &end_of_sequence);
if (!s.ok()) {
ctx->SetStatus(s);
return;
@@ -664,8 +667,8 @@ class ToSingleElementOp : public AsyncOpKernel {
}
components.clear();
- Status s2 =
- raw_iterator->GetNext(&iter_ctx, &components, &end_of_sequence);
+ Status s2 = raw_iterator->GetNext(IteratorContext(ctx), &components,
+ &end_of_sequence);
if (!s2.ok()) {
ctx->SetStatus(s2);
return;
@@ -833,9 +836,9 @@ class OneShotIteratorOp : public AsyncOpKernel {
// factory function.
DatasetBase* dataset;
TF_RETURN_IF_ERROR(GetDatasetFromVariantTensor(return_values[0], &dataset));
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iter;
- TF_RETURN_IF_ERROR(dataset->MakeIterator(&iter_ctx, "Iterator", &iter));
+ TF_RETURN_IF_ERROR(
+ dataset->MakeIterator(IteratorContext(ctx), "Iterator", &iter));
TF_RETURN_IF_ERROR((*iterator)->set_iterator(std::move(iter)));
(*iterator)->Ref();
diff --git a/tensorflow/core/kernels/data/map_and_batch_dataset_op.cc b/tensorflow/core/kernels/data/map_and_batch_dataset_op.cc
index 004f153af6..0e17011b05 100644
--- a/tensorflow/core/kernels/data/map_and_batch_dataset_op.cc
+++ b/tensorflow/core/kernels/data/map_and_batch_dataset_op.cc
@@ -101,7 +101,7 @@ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input, int64 batch_size,
int64 num_parallel_calls, bool drop_remainder,
@@ -110,7 +110,7 @@ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
const NameAttrList& func,
std::unique_ptr<CapturedFunction> captured_func,
const Eigen::ThreadPoolDevice* device)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
batch_size_(batch_size),
num_parallel_calls_(num_parallel_calls),
@@ -144,11 +144,12 @@ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, map_fn_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), map_fn_.name()));
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* batch_size_node;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size_node));
Node* num_parallel_calls_node;
@@ -232,7 +233,7 @@ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
cond_var_.wait(l);
}
CHECK_EQ(num_calls_, 0);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("call_counter"), call_counter_));
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("batch_results_size"),
@@ -246,7 +247,7 @@ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("call_counter"), &call_counter_));
int64 batch_results_size;
@@ -383,7 +384,7 @@ class MapAndBatchDatasetOp : public UnaryDatasetOpKernel {
#undef HANDLE_TYPE
default:
return errors::InvalidArgument("Unsupported data type: ",
- value.dtype());
+ DataTypeString(value.dtype()));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/map_dataset_op.cc b/tensorflow/core/kernels/data/map_dataset_op.cc
index aa530aea19..294fb1c49a 100644
--- a/tensorflow/core/kernels/data/map_dataset_op.cc
+++ b/tensorflow/core/kernels/data/map_dataset_op.cc
@@ -55,14 +55,14 @@ class MapDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func,
std::unique_ptr<CapturedFunction> captured_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
func_(func),
captured_func_(std::move(captured_func)),
@@ -89,11 +89,12 @@ class MapDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "MapDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), func_.name()));
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
DataTypeVector other_arguments_types;
other_arguments_types.reserve(captured_func_->captured_inputs().size());
@@ -159,13 +160,13 @@ class MapDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/optimize_dataset_op.cc b/tensorflow/core/kernels/data/optimize_dataset_op.cc
index 276f5f89c8..b097598cd9 100644
--- a/tensorflow/core/kernels/data/optimize_dataset_op.cc
+++ b/tensorflow/core/kernels/data/optimize_dataset_op.cc
@@ -59,13 +59,13 @@ class OptimizeDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const std::vector<string>& optimizations,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
optimizations_(optimizations),
output_types_(output_types),
@@ -80,15 +80,22 @@ class OptimizeDatasetOp : public UnaryDatasetOpKernel {
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
- return std::unique_ptr<IteratorBase>(
- new Iterator({this, strings::StrCat(prefix, "::Optimize")}));
+ // We do not add a token for the optimization dataset to the prefix. The
+ // prefix is used to identify checkpoint elements and since the
+ // optimization dataset is excluded from the checkpoint, adding a token
+ // here would result in invalid checkpoint identifiers.
+ return std::unique_ptr<IteratorBase>(new Iterator({this, prefix}));
}
Status Optimize(OpKernelContext* ctx) {
GraphDefBuilder b;
DatasetGraphDefBuilder db(&b);
Node* input_node = nullptr;
- TF_RETURN_IF_ERROR(db.AddParentDataset(ctx, input_, &input_node));
+ SerializationContext::Params params;
+ params.flib_def = ctx->function_library()->GetFunctionLibraryDefinition();
+ SerializationContext serialization_ctx(params);
+ TF_RETURN_IF_ERROR(
+ db.AddInputDataset(&serialization_ctx, input_, &input_node));
string output_node = input_node->name();
GraphDef graph_def;
TF_RETURN_IF_ERROR(b.ToGraphDef(&graph_def));
@@ -119,14 +126,12 @@ class OptimizeDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "OptimizeDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
- Node* optimizations_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddVector(optimizations_, &optimizations_node));
- TF_RETURN_IF_ERROR(
- b->AddDataset(this, {input_graph_node, optimizations_node}, output));
+ // We only serialize the optimized dataset to avoid re-running
+ // optimizations when the input pipeline is restored from a checkpoint.
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, optimized_input_, output));
return Status::OK();
}
@@ -157,13 +162,13 @@ class OptimizeDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/padded_batch_dataset_op.cc b/tensorflow/core/kernels/data/padded_batch_dataset_op.cc
index 59cbdb655d..be45eac46e 100644
--- a/tensorflow/core/kernels/data/padded_batch_dataset_op.cc
+++ b/tensorflow/core/kernels/data/padded_batch_dataset_op.cc
@@ -98,12 +98,12 @@ class PaddedBatchDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 batch_size, bool drop_remainder,
std::vector<PartialTensorShape> padded_shapes,
std::vector<Tensor> padding_values, const DatasetBase* input)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
batch_size_(batch_size),
drop_remainder_(drop_remainder),
padded_shapes_(std::move(padded_shapes)),
@@ -153,10 +153,11 @@ class PaddedBatchDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* batch_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size));
@@ -339,7 +340,7 @@ class PaddedBatchDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_)
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
else
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("exhausted"), ""));
return Status::OK();
@@ -353,7 +354,7 @@ class PaddedBatchDatasetOp : public UnaryDatasetOpKernel {
} else {
TF_RETURN_IF_ERROR(
dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_));
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/parallel_interleave_dataset_op.cc b/tensorflow/core/kernels/data/parallel_interleave_dataset_op.cc
index 6292b4536e..cfa96d910d 100644
--- a/tensorflow/core/kernels/data/parallel_interleave_dataset_op.cc
+++ b/tensorflow/core/kernels/data/parallel_interleave_dataset_op.cc
@@ -92,7 +92,7 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func,
@@ -100,7 +100,7 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
int64 block_length, bool sloppy, int64 buffer_output_elements,
int64 prefetch_input_elements, const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
interleave_func_(func),
captured_func_(std::move(captured_func)),
@@ -134,11 +134,13 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, interleave_func_.name()));
+ TF_RETURN_IF_ERROR(
+ b->AddFunction(ctx->flib_def(), interleave_func_.name()));
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* cycle_length_node;
TF_RETURN_IF_ERROR(b->AddScalar(cycle_length_, &cycle_length_node));
Node* block_length_node;
@@ -277,7 +279,12 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
if (!current_worker->outputs.empty()) {
// We have an element!
next_index_ = index;
- if (i == 0) {
+ const bool element_acquired_sloppily =
+ dataset()->sloppy_ && i > 1;
+ if (!element_acquired_sloppily) {
+ // If the element was acquired in the regular (non-sloppy)
+ // order, then advance the current block and cycle pointers to
+ // the next element in the regular order.
block_count_++;
if (block_count_ == dataset()->block_length_) {
next_index_ = (index + 1) % interleave_indices_.size();
@@ -358,7 +365,7 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
mutex_lock ckpt_l(ckpt_mu_);
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_exhausted"), ""));
@@ -402,7 +409,7 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
mutex_lock ckpt_l(ckpt_mu_);
if (!reader->Contains(full_name("input_exhausted"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
@@ -858,7 +865,7 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
string prefix = strings::StrCat("worker_thread_", index);
if (worker_thread_states_[index].iterator != nullptr) {
TF_RETURN_IF_ERROR(
- SaveParent(writer, worker_thread_states_[index].iterator));
+ SaveInput(writer, worker_thread_states_[index].iterator));
} else {
TF_RETURN_IF_ERROR(writer->WriteScalar(
full_name(strings::StrCat(prefix, "_iterator_exhausted")), ""));
@@ -909,7 +916,7 @@ class ParallelInterleaveDatasetOp : public UnaryDatasetOpKernel {
Status s = dataset::MakeIteratorFromInputElement(
ctx, worker_thread_states_[index].input, index,
dataset()->captured_func_.get(), prefix(), &iterator);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, iterator));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, iterator));
worker_thread_states_[index].iterator.swap(iterator);
}
TF_RETURN_IF_ERROR(ReadStatusLocked(
diff --git a/tensorflow/core/kernels/data/parallel_map_dataset_op.cc b/tensorflow/core/kernels/data/parallel_map_dataset_op.cc
index b736b33c2e..a407abfce4 100644
--- a/tensorflow/core/kernels/data/parallel_map_dataset_op.cc
+++ b/tensorflow/core/kernels/data/parallel_map_dataset_op.cc
@@ -67,14 +67,14 @@ class ParallelMapDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func, int32 num_parallel_calls,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes,
std::unique_ptr<CapturedFunction> captured_func)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
func_(func),
num_parallel_calls_(num_parallel_calls),
@@ -113,11 +113,12 @@ class ParallelMapDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
// Input: input_dataset
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
// Input: other_arguments
DataTypeVector other_arguments_types;
@@ -137,7 +138,7 @@ class ParallelMapDatasetOp : public UnaryDatasetOpKernel {
b->AddScalar(num_parallel_calls_, &num_parallel_calls));
// Attr: f
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), func_.name()));
AttrValue f;
b->BuildAttrValue(func_, &f);
diff --git a/tensorflow/core/kernels/data/parallel_map_iterator.cc b/tensorflow/core/kernels/data/parallel_map_iterator.cc
index 10549df25e..4d32b719a4 100644
--- a/tensorflow/core/kernels/data/parallel_map_iterator.cc
+++ b/tensorflow/core/kernels/data/parallel_map_iterator.cc
@@ -78,7 +78,7 @@ class ParallelMapIterator : public DatasetBaseIterator {
cond_var_.wait(l);
}
CHECK_EQ(num_calls_, 0);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("invocation_results.size"),
invocation_results_.size()));
@@ -107,7 +107,7 @@ class ParallelMapIterator : public DatasetBaseIterator {
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
int64 invocation_results_size;
TF_RETURN_IF_ERROR(reader->ReadScalar(
full_name("invocation_results.size"), &invocation_results_size));
diff --git a/tensorflow/core/kernels/data/prefetch_dataset_op.cc b/tensorflow/core/kernels/data/prefetch_dataset_op.cc
index 9000842840..50efbcbe2a 100644
--- a/tensorflow/core/kernels/data/prefetch_dataset_op.cc
+++ b/tensorflow/core/kernels/data/prefetch_dataset_op.cc
@@ -25,10 +25,12 @@ namespace tensorflow {
// See documentation in ../ops/dataset_ops.cc for a high-level
// description of the following op.
-class PrefetchDatasetOp::Dataset : public GraphDatasetBase {
+class PrefetchDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input, int64 buffer_size)
- : GraphDatasetBase(ctx), input_(input), buffer_size_(buffer_size) {
+ : DatasetBase(DatasetContext(ctx)),
+ input_(input),
+ buffer_size_(buffer_size) {
input_->Ref();
}
@@ -51,10 +53,11 @@ class PrefetchDatasetOp::Dataset : public GraphDatasetBase {
string DebugString() const override { return "PrefetchDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* buffer_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(buffer_size_, &buffer_size));
TF_RETURN_IF_ERROR(
@@ -131,7 +134,7 @@ class PrefetchDatasetOp::Dataset : public GraphDatasetBase {
// all GetNext threads are blocked.
mutex_lock parent_l(parent_mu_);
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("buffer_size"), buffer_.size()));
for (size_t i = 0; i < buffer_.size(); i++) {
@@ -156,7 +159,7 @@ class PrefetchDatasetOp::Dataset : public GraphDatasetBase {
mutex_lock parent_l(parent_mu_);
mutex_lock l(mu_);
buffer_.clear();
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
size_t buffer_size;
{
int64 temp;
diff --git a/tensorflow/core/kernels/data/random_dataset_op.cc b/tensorflow/core/kernels/data/random_dataset_op.cc
index ff166c3be7..7817170e73 100644
--- a/tensorflow/core/kernels/data/random_dataset_op.cc
+++ b/tensorflow/core/kernels/data/random_dataset_op.cc
@@ -49,10 +49,10 @@ class RandomDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 seed, int64 seed2)
- : GraphDatasetBase(ctx), seed_(seed), seed2_(seed2) {}
+ : DatasetBase(DatasetContext(ctx)), seed_(seed), seed2_(seed2) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
@@ -77,7 +77,8 @@ class RandomDatasetOp : public DatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* seed = nullptr;
Node* seed2 = nullptr;
diff --git a/tensorflow/core/kernels/data/range_dataset_op.cc b/tensorflow/core/kernels/data/range_dataset_op.cc
index 0b5c814767..aa38775125 100644
--- a/tensorflow/core/kernels/data/range_dataset_op.cc
+++ b/tensorflow/core/kernels/data/range_dataset_op.cc
@@ -43,10 +43,13 @@ class RangeDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 start, int64 stop, int64 step)
- : GraphDatasetBase(ctx), start_(start), stop_(stop), step_(step) {}
+ : DatasetBase(DatasetContext(ctx)),
+ start_(start),
+ stop_(stop),
+ step_(step) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
@@ -71,7 +74,8 @@ class RangeDatasetOp : public DatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* start = nullptr;
Node* stop = nullptr;
diff --git a/tensorflow/core/kernels/data/reader_dataset_ops.cc b/tensorflow/core/kernels/data/reader_dataset_ops.cc
index 29654b9bca..086b552936 100644
--- a/tensorflow/core/kernels/data/reader_dataset_ops.cc
+++ b/tensorflow/core/kernels/data/reader_dataset_ops.cc
@@ -78,12 +78,12 @@ class TextLineDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::vector<string> filenames,
const string& compression_type,
const io::ZlibCompressionOptions& options)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
filenames_(std::move(filenames)),
compression_type_(compression_type),
use_compression_(!compression_type.empty()),
@@ -109,7 +109,8 @@ class TextLineDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "TextLineDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
Node* compression_type = nullptr;
@@ -311,12 +312,12 @@ class FixedLengthRecordDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<string> filenames,
int64 header_bytes, int64 record_bytes, int64 footer_bytes,
int64 buffer_size)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
filenames_(std::move(filenames)),
header_bytes_(header_bytes),
record_bytes_(record_bytes),
@@ -345,7 +346,8 @@ class FixedLengthRecordDatasetOp : public DatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
Node* header_bytes = nullptr;
@@ -529,11 +531,11 @@ class TFRecordDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<string> filenames,
const string& compression_type, int64 buffer_size)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
filenames_(std::move(filenames)),
compression_type_(compression_type),
options_(io::RecordReaderOptions::CreateRecordReaderOptions(
@@ -563,7 +565,8 @@ class TFRecordDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "TFRecordDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
diff --git a/tensorflow/core/kernels/data/repeat_dataset_op.cc b/tensorflow/core/kernels/data/repeat_dataset_op.cc
index 6b3f4ed27b..5e9ace3486 100644
--- a/tensorflow/core/kernels/data/repeat_dataset_op.cc
+++ b/tensorflow/core/kernels/data/repeat_dataset_op.cc
@@ -39,10 +39,10 @@ class RepeatDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 count, const DatasetBase* input)
- : GraphDatasetBase(ctx), count_(count), input_(input) {
+ : DatasetBase(DatasetContext(ctx)), count_(count), input_(input) {
input_->Ref();
}
@@ -72,10 +72,11 @@ class RepeatDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "RepeatDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* count = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(count_, &count));
TF_RETURN_IF_ERROR(
@@ -145,7 +146,7 @@ class RepeatDatasetOp : public UnaryDatasetOpKernel {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
} else {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
}
return Status::OK();
}
@@ -155,7 +156,7 @@ class RepeatDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("i"), &i_));
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
@@ -205,7 +206,7 @@ class RepeatDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_)
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
else
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("uninitialized"), ""));
@@ -220,7 +221,7 @@ class RepeatDatasetOp : public UnaryDatasetOpKernel {
} else {
TF_RETURN_IF_ERROR(
dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_));
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/scan_dataset_op.cc b/tensorflow/core/kernels/data/scan_dataset_op.cc
index a3b20016a8..e4cb31e2b2 100644
--- a/tensorflow/core/kernels/data/scan_dataset_op.cc
+++ b/tensorflow/core/kernels/data/scan_dataset_op.cc
@@ -69,7 +69,7 @@ class ScanDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const DatasetBase* input,
const NameAttrList& func, std::vector<Tensor> initial_state,
@@ -77,7 +77,7 @@ class ScanDatasetOp : public UnaryDatasetOpKernel {
const DataTypeVector& state_types,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
func_(func),
initial_state_(std::move(initial_state)),
@@ -106,11 +106,12 @@ class ScanDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "ScanDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- TF_RETURN_IF_ERROR(b->AddFunction(ctx, func_.name()));
+ TF_RETURN_IF_ERROR(b->AddFunction(ctx->flib_def(), func_.name()));
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
std::vector<Node*> initial_state_nodes;
initial_state_nodes.reserve(initial_state_.size());
for (const Tensor& t : initial_state_) {
@@ -222,7 +223,7 @@ class ScanDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
if (!state_.empty()) {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("state_size"), state_.size()));
@@ -237,7 +238,7 @@ class ScanDatasetOp : public UnaryDatasetOpKernel {
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
if (reader->Contains(full_name("state_size"))) {
int64 size;
TF_RETURN_IF_ERROR(
diff --git a/tensorflow/core/kernels/data/shuffle_dataset_op.cc b/tensorflow/core/kernels/data/shuffle_dataset_op.cc
index b859295fa4..93a4376836 100644
--- a/tensorflow/core/kernels/data/shuffle_dataset_op.cc
+++ b/tensorflow/core/kernels/data/shuffle_dataset_op.cc
@@ -22,6 +22,7 @@ limitations under the License.
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/lib/random/random_distributions.h"
+#include "tensorflow/core/util/ptr_util.h"
namespace tensorflow {
@@ -39,11 +40,11 @@ class ShuffleDatasetOpBase : public UnaryDatasetOpKernel {
protected:
// Abstract base dataset that implements a shuffling iterator.
- class ShuffleDatasetBase : public GraphDatasetBase {
+ class ShuffleDatasetBase : public DatasetBase {
public:
ShuffleDatasetBase(OpKernelContext* ctx, const DatasetBase* input,
int64 buffer_size, int64 count)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
buffer_size_(buffer_size),
count_(count) {
@@ -75,7 +76,7 @@ class ShuffleDatasetOpBase : public UnaryDatasetOpKernel {
parent_generator_(seed, seed2),
generator_(&parent_generator_) {
buffer_.reset(new std::vector<Tensor>[params.dataset->buffer_size_]);
- slices_.emplace_back(new Slice{0, 0});
+ slices_.push_back(MakeUnique<Slice>(0, 0));
}
Status GetNextInternal(IteratorContext* ctx,
@@ -118,7 +119,7 @@ class ShuffleDatasetOpBase : public UnaryDatasetOpKernel {
}
epoch_++;
int64 n = slices_.back()->end;
- slices_.emplace_back(new Slice{n, n});
+ slices_.push_back(MakeUnique<Slice>(n, n));
TF_RETURN_IF_ERROR(this->dataset()->input_->MakeIterator(
ctx, this->prefix(), &input_impl_));
}
@@ -178,7 +179,7 @@ class ShuffleDatasetOpBase : public UnaryDatasetOpKernel {
TF_RETURN_IF_ERROR(writer->WriteScalar(
this->full_name("end_of_input_sequence"), ""));
} else {
- TF_RETURN_IF_ERROR(this->SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(this->SaveInput(writer, input_impl_));
}
// Save the epoch counter, buffer, and buffer slices.
@@ -226,7 +227,7 @@ class ShuffleDatasetOpBase : public UnaryDatasetOpKernel {
if (!reader->Contains(this->full_name("end_of_input_sequence"))) {
TF_RETURN_IF_ERROR(this->dataset()->input_->MakeIterator(
ctx, this->prefix(), &input_impl_));
- TF_RETURN_IF_ERROR(this->RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(this->RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
@@ -251,7 +252,7 @@ class ShuffleDatasetOpBase : public UnaryDatasetOpKernel {
int64 end;
TF_RETURN_IF_ERROR(reader->ReadScalar(
this->full_name(strings::StrCat("slices_end_", i)), &end));
- slices_.emplace_back(new Slice{start, end});
+ slices_.push_back(MakeUnique<Slice>(start, end));
for (size_t j = start; j < end; ++j) {
size_t index = j % this->dataset()->buffer_size_;
int64 list_size;
@@ -428,11 +429,12 @@ class ShuffleDatasetOp : public ShuffleDatasetOpBase {
}
};
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
mutex_lock l(mu_);
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* buffer_size = nullptr;
Node* seed = nullptr;
Node* seed2 = nullptr;
@@ -498,10 +500,11 @@ class ShuffleDatasetOp : public ShuffleDatasetOpBase {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* buffer_size = nullptr;
Node* seed = nullptr;
Node* seed2 = nullptr;
@@ -583,10 +586,11 @@ class ShuffleAndRepeatDatasetOp : public ShuffleDatasetOpBase {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* buffer_size = nullptr;
Node* seed = nullptr;
Node* seed2 = nullptr;
diff --git a/tensorflow/core/kernels/data/skip_dataset_op.cc b/tensorflow/core/kernels/data/skip_dataset_op.cc
index b84afa3e33..fe7ef38d5f 100644
--- a/tensorflow/core/kernels/data/skip_dataset_op.cc
+++ b/tensorflow/core/kernels/data/skip_dataset_op.cc
@@ -38,10 +38,10 @@ class SkipDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 count, const DatasetBase* input)
- : GraphDatasetBase(ctx), count_(count), input_(input) {
+ : DatasetBase(DatasetContext(ctx)), count_(count), input_(input) {
input_->Ref();
}
@@ -68,10 +68,11 @@ class SkipDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "SkipDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* count = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(count_, &count));
TF_RETURN_IF_ERROR(
@@ -152,7 +153,7 @@ class SkipDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("i"), i_));
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
@@ -165,7 +166,7 @@ class SkipDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("i"), &i_));
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/core/kernels/data/slide_dataset_op.cc b/tensorflow/core/kernels/data/slide_dataset_op.cc
index 5765c61f30..14df3a6801 100644
--- a/tensorflow/core/kernels/data/slide_dataset_op.cc
+++ b/tensorflow/core/kernels/data/slide_dataset_op.cc
@@ -63,11 +63,11 @@ class SlideDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 window_size, int64 window_shift,
int64 window_stride, const DatasetBase* input)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
window_size_(window_size),
window_shift_(window_shift),
window_stride_(window_stride),
@@ -104,10 +104,11 @@ class SlideDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* window_size = nullptr;
Node* window_shift = nullptr;
Node* window_stride = nullptr;
@@ -228,7 +229,7 @@ class SlideDatasetOp : public UnaryDatasetOpKernel {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
} else {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
}
// Save buffer.
TF_RETURN_IF_ERROR(writer->WriteScalar(strings::StrCat("buffer_size"),
@@ -248,7 +249,7 @@ class SlideDatasetOp : public UnaryDatasetOpKernel {
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc b/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc
index b5dff48d2d..e526578701 100644
--- a/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc
+++ b/tensorflow/core/kernels/data/sparse_tensor_slice_dataset_op.cc
@@ -28,11 +28,11 @@ namespace {
// description of the following op.
template <typename T>
-class Dataset : public GraphDatasetBase {
+class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx,
const sparse::SparseTensor& sparse_tensor)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
sparse_tensor_(sparse_tensor),
dtypes_({DT_INT64, sparse_tensor.dtype(), DT_INT64}),
shapes_({{-1, sparse_tensor.dims() - 1},
@@ -55,7 +55,8 @@ class Dataset : public GraphDatasetBase {
}
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* indices_node;
TF_RETURN_IF_ERROR(b->AddTensor(sparse_tensor_.indices(), &indices_node));
diff --git a/tensorflow/core/kernels/data/sql_dataset_ops.cc b/tensorflow/core/kernels/data/sql_dataset_ops.cc
index 16652e792c..2aa153fcfa 100644
--- a/tensorflow/core/kernels/data/sql_dataset_ops.cc
+++ b/tensorflow/core/kernels/data/sql_dataset_ops.cc
@@ -75,13 +75,13 @@ class SqlDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, const string& driver_name,
const string& data_source_name, const string& query,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
driver_name_(driver_name),
data_source_name_(data_source_name),
query_(query),
@@ -105,7 +105,8 @@ class SqlDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "SqlDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* driver_name_node;
TF_RETURN_IF_ERROR(b->AddScalar(driver_name_, &driver_name_node));
diff --git a/tensorflow/core/kernels/data/stats_aggregator_dataset_op.cc b/tensorflow/core/kernels/data/stats_aggregator_dataset_op.cc
index 2ff90d7b10..75af73df54 100644
--- a/tensorflow/core/kernels/data/stats_aggregator_dataset_op.cc
+++ b/tensorflow/core/kernels/data/stats_aggregator_dataset_op.cc
@@ -37,11 +37,11 @@ class SetStatsAggregatorDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input,
StatsAggregatorResource* stats_aggregator_resource)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
input_(input),
stats_aggregator_resource_(stats_aggregator_resource) {
input_->Ref();
@@ -71,11 +71,11 @@ class SetStatsAggregatorDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
- return errors::Unimplemented(
- "Cannot currently serialize the `stats_aggregator` for a "
- "SetStatsAggregatorDataset.");
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
}
private:
@@ -111,14 +111,14 @@ class SetStatsAggregatorDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/stats_dataset_ops.cc b/tensorflow/core/kernels/data/stats_dataset_ops.cc
index 58ec3d4495..52753a3ccd 100644
--- a/tensorflow/core/kernels/data/stats_dataset_ops.cc
+++ b/tensorflow/core/kernels/data/stats_dataset_ops.cc
@@ -49,10 +49,12 @@ class LatencyStatsDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input, string tag)
- : GraphDatasetBase(ctx), input_(input), tag_(std::move(tag)) {
+ : DatasetBase(DatasetContext(ctx)),
+ input_(input),
+ tag_(std::move(tag)) {
input_->Ref();
}
@@ -76,10 +78,11 @@ class LatencyStatsDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* tag_node;
TF_RETURN_IF_ERROR(b->AddScalar(tag_, &tag_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_node, tag_node}, output));
@@ -114,14 +117,14 @@ class LatencyStatsDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
@@ -148,10 +151,12 @@ class BytesProducedStatsDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input, string tag)
- : GraphDatasetBase(ctx), input_(input), tag_(std::move(tag)) {
+ : DatasetBase(DatasetContext(ctx)),
+ input_(input),
+ tag_(std::move(tag)) {
input_->Ref();
}
@@ -175,10 +180,11 @@ class BytesProducedStatsDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* tag_node;
TF_RETURN_IF_ERROR(b->AddScalar(tag_, &tag_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_node, tag_node}, output));
@@ -215,14 +221,14 @@ class BytesProducedStatsDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
@@ -253,10 +259,12 @@ class FeatureStatsDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, const DatasetBase* input, string tag)
- : GraphDatasetBase(ctx), input_(input), tag_(std::move(tag)) {
+ : DatasetBase(DatasetContext(ctx)),
+ input_(input),
+ tag_(std::move(tag)) {
input_->Ref();
}
@@ -280,10 +288,11 @@ class FeatureStatsDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node));
Node* tag_node;
TF_RETURN_IF_ERROR(b->AddScalar(tag_, &tag_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_node, tag_node}, output));
@@ -406,14 +415,14 @@ class FeatureStatsDatasetOp : public UnaryDatasetOpKernel {
protected:
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
return Status::OK();
}
diff --git a/tensorflow/core/kernels/data/take_dataset_op.cc b/tensorflow/core/kernels/data/take_dataset_op.cc
index 3d29221f3e..e5c237dfaa 100644
--- a/tensorflow/core/kernels/data/take_dataset_op.cc
+++ b/tensorflow/core/kernels/data/take_dataset_op.cc
@@ -38,10 +38,10 @@ class TakeDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 count, const DatasetBase* input)
- : GraphDatasetBase(ctx), count_(count), input_(input) {
+ : DatasetBase(DatasetContext(ctx)), count_(count), input_(input) {
input_->Ref();
}
@@ -69,10 +69,11 @@ class TakeDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "TakeDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* count = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(count_, &count));
TF_RETURN_IF_ERROR(
@@ -139,7 +140,7 @@ class TakeDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("i"), i_));
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
@@ -152,7 +153,7 @@ class TakeDatasetOp : public UnaryDatasetOpKernel {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("i"), &i_));
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/core/kernels/data/tensor_dataset_op.cc b/tensorflow/core/kernels/data/tensor_dataset_op.cc
index 36fc434d8f..fc21c3235a 100644
--- a/tensorflow/core/kernels/data/tensor_dataset_op.cc
+++ b/tensorflow/core/kernels/data/tensor_dataset_op.cc
@@ -43,10 +43,10 @@ class TensorDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::vector<Tensor> tensors)
- : GraphDatasetBase(ctx), tensors_(std::move(tensors)) {
+ : DatasetBase(DatasetContext(ctx)), tensors_(std::move(tensors)) {
for (const Tensor& t : tensors_) {
dtypes_.push_back(t.dtype());
shapes_.emplace_back(t.shape().dim_sizes());
@@ -67,7 +67,8 @@ class TensorDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "TensorDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
std::vector<Node*> components;
components.reserve(tensors_.size());
diff --git a/tensorflow/core/kernels/data/tensor_queue_dataset_op.cc b/tensorflow/core/kernels/data/tensor_queue_dataset_op.cc
index 29b4c9053e..ccd5e60acc 100644
--- a/tensorflow/core/kernels/data/tensor_queue_dataset_op.cc
+++ b/tensorflow/core/kernels/data/tensor_queue_dataset_op.cc
@@ -61,14 +61,14 @@ std::vector<PartialTensorShape> PrependQueueShapeWithBatch(
class EnqueueInQueueDatasetOp;
-class PrependFromQueueAndPaddedBatchDataset : public GraphDatasetBase {
+class PrependFromQueueAndPaddedBatchDataset : public DatasetBase {
public:
PrependFromQueueAndPaddedBatchDataset(
OpKernelContext* ctx, const int64 batch_size, const DatasetBase* input,
const DataTypeVector& dtypes,
const std::vector<PartialTensorShape>& shapes,
std::vector<Tensor> padding_values)
- : GraphDatasetBase(ctx),
+ : DatasetBase(DatasetContext(ctx)),
batch_size_(batch_size),
input_(input),
dtypes_(dtypes),
@@ -99,10 +99,11 @@ class PrependFromQueueAndPaddedBatchDataset : public GraphDatasetBase {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph));
Node* batch_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(batch_size_, &batch_size));
@@ -352,7 +353,7 @@ class PrependFromQueueAndPaddedBatchDataset : public GraphDatasetBase {
Status Save(Iterator* iter, IteratorStateWriter* writer) {
mutex_lock lock(mu_);
if (input_impl_) {
- TF_RETURN_IF_ERROR(iter->SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(iter->SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(iter->full_name("input_exhausted"), ""));
@@ -378,7 +379,7 @@ class PrependFromQueueAndPaddedBatchDataset : public GraphDatasetBase {
} else {
TF_RETURN_IF_ERROR(iter->dataset_input()->MakeIterator(
ctx, iter->prefix(), &input_impl_));
- TF_RETURN_IF_ERROR(iter->RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(iter->RestoreInput(ctx, reader, input_impl_));
}
entries_.clear();
int64 entries_size = -1;
diff --git a/tensorflow/core/kernels/data/tensor_slice_dataset_op.cc b/tensorflow/core/kernels/data/tensor_slice_dataset_op.cc
index 68ce324081..5b051e0e08 100644
--- a/tensorflow/core/kernels/data/tensor_slice_dataset_op.cc
+++ b/tensorflow/core/kernels/data/tensor_slice_dataset_op.cc
@@ -54,10 +54,10 @@ class TensorSliceDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<Tensor> tensors)
- : GraphDatasetBase(ctx), tensors_(std::move(tensors)) {
+ : DatasetBase(DatasetContext(ctx)), tensors_(std::move(tensors)) {
for (const Tensor& t : tensors_) {
dtypes_.push_back(t.dtype());
gtl::InlinedVector<int64, 4> partial_dim_sizes;
@@ -86,7 +86,8 @@ class TensorSliceDatasetOp : public DatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
std::vector<Node*> components;
components.reserve(tensors_.size());
diff --git a/tensorflow/core/kernels/data/unbatch_dataset_op.cc b/tensorflow/core/kernels/data/unbatch_dataset_op.cc
index 2aec9fb090..1a79f72b28 100644
--- a/tensorflow/core/kernels/data/unbatch_dataset_op.cc
+++ b/tensorflow/core/kernels/data/unbatch_dataset_op.cc
@@ -35,10 +35,10 @@ class UnbatchDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, DatasetBase* input)
- : GraphDatasetBase(ctx), input_(input) {
+ : DatasetBase(DatasetContext(ctx)), input_(input) {
input_->Ref();
for (const PartialTensorShape& shape : input->output_shapes()) {
gtl::InlinedVector<int64, 4> partial_dim_sizes;
@@ -65,10 +65,11 @@ class UnbatchDatasetOp : public UnaryDatasetOpKernel {
string DebugString() const override { return "UnbatchDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph_node}, output));
return Status::OK();
}
@@ -142,7 +143,7 @@ class UnbatchDatasetOp : public UnaryDatasetOpKernel {
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_) {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
@@ -164,7 +165,7 @@ class UnbatchDatasetOp : public UnaryDatasetOpKernel {
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/core/kernels/data/window_dataset.cc b/tensorflow/core/kernels/data/window_dataset.cc
index 17551bccd9..0ab6beabfc 100644
--- a/tensorflow/core/kernels/data/window_dataset.cc
+++ b/tensorflow/core/kernels/data/window_dataset.cc
@@ -13,17 +13,18 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/window_dataset.h"
+#include "tensorflow/core/lib/core/errors.h"
namespace tensorflow {
namespace {
-// TODO(b/110981596): Support checkpointing.
class WindowDataset : public DatasetBase {
public:
WindowDataset(std::vector<std::vector<Tensor>> elements,
DataTypeVector output_types,
std::vector<PartialTensorShape> output_shapes)
- : elements_(std::move(elements)),
+ : DatasetBase(DatasetContext({"Window"})),
+ elements_(std::move(elements)),
output_types_(std::move(output_types)),
output_shapes_(std::move(output_shapes)) {}
@@ -41,6 +42,15 @@ class WindowDataset : public DatasetBase {
string DebugString() const override { return "WindowDataset"; }
+ protected:
+ // TODO(b/110981596): Support checkpointing.
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
+ Node** output) const override {
+ return errors::Unimplemented("%s does not support serialization",
+ DebugString());
+ }
+
private:
class Iterator : public DatasetIterator<WindowDataset> {
public:
diff --git a/tensorflow/core/kernels/data/window_dataset_op.cc b/tensorflow/core/kernels/data/window_dataset_op.cc
index 0283e5697b..41bf9d43fe 100644
--- a/tensorflow/core/kernels/data/window_dataset_op.cc
+++ b/tensorflow/core/kernels/data/window_dataset_op.cc
@@ -43,10 +43,12 @@ class WindowDatasetOp : public UnaryDatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, int64 window_size, const DatasetBase* input)
- : GraphDatasetBase(ctx), window_size_(window_size), input_(input) {
+ : DatasetBase(DatasetContext(ctx)),
+ window_size_(window_size),
+ input_(input) {
input_->Ref();
}
@@ -74,10 +76,11 @@ class WindowDatasetOp : public UnaryDatasetOpKernel {
}
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
Node* window_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(window_size_, &window_size));
TF_RETURN_IF_ERROR(
@@ -162,7 +165,7 @@ class WindowDatasetOp : public UnaryDatasetOpKernel {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
} else {
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_));
}
return Status::OK();
}
@@ -171,7 +174,7 @@ class WindowDatasetOp : public UnaryDatasetOpKernel {
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
diff --git a/tensorflow/core/kernels/data/writer_ops.cc b/tensorflow/core/kernels/data/writer_ops.cc
index 80d9a5b867..1c49874a6a 100644
--- a/tensorflow/core/kernels/data/writer_ops.cc
+++ b/tensorflow/core/kernels/data/writer_ops.cc
@@ -70,20 +70,21 @@ class ToTFRecordOp : public AsyncOpKernel {
DatasetBase* dataset;
OP_REQUIRES_OK_ASYNC(
ctx, GetDatasetFromVariantTensor(ctx->input(0), &dataset), done);
- IteratorContext iter_ctx = dataset::MakeIteratorContext(ctx);
std::unique_ptr<IteratorBase> iterator;
OP_REQUIRES_OK_ASYNC(
ctx,
- dataset->MakeIterator(&iter_ctx, "ToTFRecordOpIterator", &iterator),
+ dataset->MakeIterator(IteratorContext(ctx), "ToTFRecordOpIterator",
+ &iterator),
done);
std::vector<Tensor> components;
components.reserve(dataset->output_dtypes().size());
bool end_of_sequence;
do {
- OP_REQUIRES_OK_ASYNC(
- ctx, iterator->GetNext(&iter_ctx, &components, &end_of_sequence),
- done);
+ OP_REQUIRES_OK_ASYNC(ctx,
+ iterator->GetNext(IteratorContext(ctx),
+ &components, &end_of_sequence),
+ done);
if (!end_of_sequence) {
OP_REQUIRES_OK_ASYNC(
diff --git a/tensorflow/core/kernels/data/zip_dataset_op.cc b/tensorflow/core/kernels/data/zip_dataset_op.cc
index 00705236f9..e4306579ed 100644
--- a/tensorflow/core/kernels/data/zip_dataset_op.cc
+++ b/tensorflow/core/kernels/data/zip_dataset_op.cc
@@ -38,11 +38,11 @@ class ZipDatasetOp : public DatasetOpKernel {
}
private:
- class Dataset : public GraphDatasetBase {
+ class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx,
const std::vector<DatasetBase*>& inputs)
- : GraphDatasetBase(ctx), inputs_(inputs) {
+ : DatasetBase(DatasetContext(ctx)), inputs_(inputs) {
for (const auto& input : inputs_) {
input->Ref();
for (DataType dt : input->output_dtypes()) {
@@ -77,13 +77,14 @@ class ZipDatasetOp : public DatasetOpKernel {
string DebugString() const override { return "ZipDatasetOp::Dataset"; }
protected:
- Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
+ Status AsGraphDefInternal(SerializationContext* ctx,
+ DatasetGraphDefBuilder* b,
Node** output) const override {
std::vector<Node*> input_graph_nodes;
input_graph_nodes.reserve(inputs_.size());
for (const auto& input : inputs_) {
Node* input_node;
- TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input, &input_node));
+ TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input, &input_node));
input_graph_nodes.emplace_back(input_node);
}
TF_RETURN_IF_ERROR(b->AddDataset(
@@ -142,7 +143,7 @@ class ZipDatasetOp : public DatasetOpKernel {
writer->WriteScalar(full_name("input_impls_empty"), ""));
} else {
for (auto& input_impl : input_impls_)
- TF_RETURN_IF_ERROR(SaveParent(writer, input_impl));
+ TF_RETURN_IF_ERROR(SaveInput(writer, input_impl));
}
return Status::OK();
}
@@ -155,7 +156,7 @@ class ZipDatasetOp : public DatasetOpKernel {
} else {
DCHECK_EQ(input_impls_.size(), dataset()->inputs_.size());
for (auto& input_impl : input_impls_)
- TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl));
+ TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/gemm_functors.h b/tensorflow/core/kernels/gemm_functors.h
index 4b30c1f17f..1c80844085 100644
--- a/tensorflow/core/kernels/gemm_functors.h
+++ b/tensorflow/core/kernels/gemm_functors.h
@@ -24,6 +24,9 @@ limitations under the License.
#error "EIGEN_USE_THREADS must be enabled by all .cc files including this."
#endif // EIGEN_USE_THREADS
+#ifndef TENSORFLOW_CORE_KERNELS_GEMM_FUNCTORS_H_
+#define TENSORFLOW_CORE_KERNELS_GEMM_FUNCTORS_H_
+
#include <string.h>
#include <map>
#include <vector>
@@ -116,3 +119,5 @@ class FastGemmFunctor<float, float, float> {
}
};
#endif // USE_CBLAS_GEMM
+
+#endif // TENSORFLOW_CORE_KERNELS_GEMM_FUNCTORS_H_
diff --git a/tensorflow/core/kernels/hexagon/soc_interface.h b/tensorflow/core/kernels/hexagon/soc_interface.h
index 062103ed98..d1a41d47c8 100644
--- a/tensorflow/core/kernels/hexagon/soc_interface.h
+++ b/tensorflow/core/kernels/hexagon/soc_interface.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_PLATFORM_HEXAGON_SOC_INTERFACE_H_
-#define TENSORFLOW_PLATFORM_HEXAGON_SOC_INTERFACE_H_
+#ifndef TENSORFLOW_CORE_KERNELS_HEXAGON_SOC_INTERFACE_H_
+#define TENSORFLOW_CORE_KERNELS_HEXAGON_SOC_INTERFACE_H_
// Declaration of APIs provided by hexagon shared library. This header is shared
// with both hexagon library built with qualcomm SDK and tensorflow.
@@ -111,4 +111,4 @@ void soc_interface_SetDebugFlag(uint64_t flag);
}
#endif // __cplusplus
-#endif // TENSORFLOW_PLATFORM_HEXAGON_SOC_INTERFACE_H_
+#endif // TENSORFLOW_CORE_KERNELS_HEXAGON_SOC_INTERFACE_H_
diff --git a/tensorflow/core/kernels/host_constant_op.cc b/tensorflow/core/kernels/host_constant_op.cc
new file mode 100644
index 0000000000..d08a7c9bd2
--- /dev/null
+++ b/tensorflow/core/kernels/host_constant_op.cc
@@ -0,0 +1,78 @@
+/* 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.
+==============================================================================*/
+
+#include "tensorflow/core/kernels/host_constant_op.h"
+
+#include "tensorflow/core/framework/allocator.h"
+#include "tensorflow/core/framework/op_kernel.h"
+#include "tensorflow/core/framework/types.h"
+#include "tensorflow/core/lib/core/status.h"
+#include "tensorflow/core/platform/logging.h"
+#include "tensorflow/core/platform/macros.h"
+
+namespace tensorflow {
+
+_HostConstantOp::_HostConstantOp(OpKernelConstruction* ctx)
+ : OpKernel(ctx), tensor_(ctx->output_type(0)) {
+ const TensorProto* proto = nullptr;
+ AllocatorAttributes alloc_attr;
+ alloc_attr.set_on_host(true);
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto));
+ OP_REQUIRES_OK(
+ ctx, ctx->device()->MakeTensorFromProto(*proto, alloc_attr, &tensor_));
+ OP_REQUIRES(
+ ctx, ctx->output_type(0) == tensor_.dtype(),
+ errors::InvalidArgument("Type mismatch between value (",
+ DataTypeString(tensor_.dtype()), ") and dtype (",
+ DataTypeString(ctx->output_type(0)), ")"));
+}
+
+void _HostConstantOp::Compute(OpKernelContext* ctx) {
+ ctx->set_output(0, tensor_);
+}
+
+#if GOOGLE_CUDA
+// A special GPU kernel for int32.
+// TODO(b/25387198): Also enable int32 in device memory. This kernel
+// registration requires all int32 inputs and outputs to be in host memory.
+REGISTER_KERNEL_BUILDER(Name("Const")
+ .Device(DEVICE_GPU)
+ .HostMemory("output")
+ .TypeConstraint<int32>("dtype"),
+ _HostConstantOp);
+#endif
+
+#ifdef TENSORFLOW_USE_SYCL
+REGISTER_KERNEL_BUILDER(Name("Const")
+ .Device(DEVICE_SYCL)
+ .HostMemory("output")
+ .TypeConstraint<int32>("dtype"),
+ _HostConstantOp);
+#endif // TENSORFLOW_USE_SYCL
+
+// HostConst: forced to generate output on the host.
+// Only used in tests; no op is registered for this kernel
+// externally (i.e., in array_ops.cc)
+REGISTER_KERNEL_BUILDER(Name("HostConst").Device(DEVICE_CPU), _HostConstantOp);
+REGISTER_KERNEL_BUILDER(
+ Name("HostConst").Device(DEVICE_GPU).HostMemory("output"), _HostConstantOp);
+#ifdef TENSORFLOW_USE_SYCL
+REGISTER_KERNEL_BUILDER(
+ Name("HostConst").Device(DEVICE_SYCL).HostMemory("output"),
+ _HostConstantOp);
+#endif // TENSORFLOW_USE_SYCL
+
+} // end namespace tensorflow
+
diff --git a/tensorflow/core/kernels/host_constant_op.h b/tensorflow/core/kernels/host_constant_op.h
new file mode 100644
index 0000000000..1b887ea1aa
--- /dev/null
+++ b/tensorflow/core/kernels/host_constant_op.h
@@ -0,0 +1,42 @@
+/* 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_CORE_KERNELS_HOST_CONSTANT_OP_H_
+#define TENSORFLOW_CORE_KERNELS_HOST_CONSTANT_OP_H_
+
+#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
+#include "tensorflow/core/framework/op_kernel.h"
+#include "tensorflow/core/framework/tensor_types.h"
+#include "tensorflow/core/platform/macros.h"
+
+namespace tensorflow {
+
+// HostConstantOp differs from ConstantOp in that its output is always
+// in host memory.
+class _HostConstantOp : public OpKernel {
+ public:
+ explicit _HostConstantOp(OpKernelConstruction* ctx);
+ void Compute(OpKernelContext* ctx) override;
+ bool IsExpensive() override { return false; }
+ ~_HostConstantOp() override {}
+
+ private:
+ Tensor tensor_;
+ TF_DISALLOW_COPY_AND_ASSIGN(_HostConstantOp);
+};
+
+} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_HOST_CONSTANT_OP_H_
diff --git a/tensorflow/core/kernels/image_resizer_state.h b/tensorflow/core/kernels/image_resizer_state.h
index faf997be05..8dcb5977c6 100644
--- a/tensorflow/core/kernels/image_resizer_state.h
+++ b/tensorflow/core/kernels/image_resizer_state.h
@@ -142,7 +142,7 @@ struct ImageResizerGradientState {
// always be a float.
OP_REQUIRES(context, input.dtype() == DT_FLOAT,
errors::InvalidArgument("input_grad must be of type float",
- input.dtype()));
+ DataTypeString(input.dtype())));
OP_REQUIRES(context, original_image.dims() == 4,
errors::InvalidArgument("original_image must be 4-dimensional",
diff --git a/tensorflow/core/kernels/inplace_ops.cc b/tensorflow/core/kernels/inplace_ops.cc
index 8ddf3c38e8..2363fbc246 100644
--- a/tensorflow/core/kernels/inplace_ops.cc
+++ b/tensorflow/core/kernels/inplace_ops.cc
@@ -55,7 +55,8 @@ Status DoParallelConcat(const CPUDevice& d, const Tensor& value, int32 loc,
TF_CALL_variant(CASE);
#undef CASE
default:
- return errors::InvalidArgument("Unsupported data type: ", value.dtype());
+ return errors::InvalidArgument("Unsupported data type: ",
+ DataTypeString(value.dtype()));
}
}
@@ -71,7 +72,8 @@ Status DoParallelConcat(const SyclDevice& d, const Tensor& value, int32 loc,
TF_CALL_GPU_NUMBER_TYPES_NO_HALF(CASE);
#undef CASE
default:
- return errors::InvalidArgument("Unsupported data type: ", value.dtype());
+ return errors::InvalidArgument("Unsupported data type: ",
+ DataTypeString(value.dtype()));
}
}
#endif // TENSORFLOW_USE_SYCL
@@ -347,7 +349,8 @@ Status DoInplace(const CPUDevice& device, InplaceOpType op, const Tensor& i,
TF_CALL_NUMBER_TYPES(CASE);
#undef CASE
default:
- return errors::InvalidArgument("Unsupported data type: ", v.dtype());
+ return errors::InvalidArgument("Unsupported data type: ",
+ DataTypeString(v.dtype()));
}
return Status::OK();
}
@@ -415,7 +418,8 @@ Status DoCopy(const CPUDevice& device, const Tensor& x, Tensor* y) {
TF_CALL_bool(CASE);
#undef CASE
default:
- return errors::InvalidArgument("Unsupported data type: ", x.dtype());
+ return errors::InvalidArgument("Unsupported data type: ",
+ DataTypeString(x.dtype()));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/inplace_ops_functor_gpu.cu.cc b/tensorflow/core/kernels/inplace_ops_functor_gpu.cu.cc
index f1616b1ea8..9d20239d2d 100644
--- a/tensorflow/core/kernels/inplace_ops_functor_gpu.cu.cc
+++ b/tensorflow/core/kernels/inplace_ops_functor_gpu.cu.cc
@@ -72,7 +72,8 @@ Status DoParallelConcat(const Device& d, const Tensor& value, int32 loc,
// that CASE is not defined...hence the above construction
#undef CASE
default:
- return errors::InvalidArgument("Unsupported data type: ", value.dtype());
+ return errors::InvalidArgument("Unsupported data type: ",
+ DataTypeString(value.dtype()));
}
return Status::OK();
}
@@ -149,7 +150,8 @@ Status DoInplace(const Device& d, InplaceOpType op, const Tensor& i,
CASE(int64)
#undef CASE
default:
- return errors::InvalidArgument("Unsupported data type: ", v.dtype());
+ return errors::InvalidArgument("Unsupported data type: ",
+ DataTypeString(v.dtype()));
}
return Status::OK();
}
@@ -169,7 +171,8 @@ Status DoCopy(const Device& d, const Tensor& x, Tensor* y) {
CASE(int64)
#undef CASE
default:
- return errors::InvalidArgument("Unsupported dtype: ", x.dtype());
+ return errors::InvalidArgument("Unsupported dtype: ",
+ DataTypeString(x.dtype()));
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/list_kernels.h b/tensorflow/core/kernels/list_kernels.h
index 42871c6113..b3f74c060b 100644
--- a/tensorflow/core/kernels/list_kernels.h
+++ b/tensorflow/core/kernels/list_kernels.h
@@ -261,14 +261,15 @@ Status TensorListZerosLike(OpKernelContext* c, const TensorList& x,
out_tensor.flat<dtype>().constant(dtype(0)); \
break;
- TF_CALL_NUMBER_TYPES(DTYPE_CASE)
+ TF_CALL_POD_TYPES(DTYPE_CASE)
#undef DTYPE_CASE
default:
return errors::InvalidArgument(
- "Trying to compute zeros_like for unsupported dtype",
- out_tensor.dtype());
+ "Trying to compute zeros_like for unsupported dtype ",
+ DataTypeString(out_tensor.dtype()));
}
+ y->tensors.emplace_back(out_tensor);
}
return Status::OK();
}
diff --git a/tensorflow/core/kernels/lookup_table_op.cc b/tensorflow/core/kernels/lookup_table_op.cc
index 07e754a6ef..2e8d9c623c 100644
--- a/tensorflow/core/kernels/lookup_table_op.cc
+++ b/tensorflow/core/kernels/lookup_table_op.cc
@@ -341,7 +341,7 @@ class MutableDenseHashTable final : public LookupInterface {
Status Find(OpKernelContext* ctx, const Tensor& key, Tensor* value,
const Tensor& default_value) override LOCKS_EXCLUDED(mu_) {
- const int64 num_elements = key.dim_size(0);
+ const int64 num_elements = (key.dims() == 0) ? 1 : key.dim_size(0);
const int64 key_size = key_shape_.num_elements();
const int64 value_size = value_shape_.num_elements();
if (key.NumElements() != num_elements * key_size) {
@@ -403,8 +403,9 @@ class MutableDenseHashTable final : public LookupInterface {
Status Insert(OpKernelContext* ctx, const Tensor& key,
const Tensor& value) override LOCKS_EXCLUDED(mu_) {
- if (key.NumElements() != key.dim_size(0) * key_shape_.num_elements()) {
- TensorShape expected_shape({key.dim_size(0)});
+ const int64 batch_size = (key.dims() == 0) ? 1 : key.dim_size(0);
+ if (key.NumElements() != batch_size * key_shape_.num_elements()) {
+ TensorShape expected_shape({batch_size});
expected_shape.AppendShape(key_shape_);
return errors::InvalidArgument("Expected key shape ",
expected_shape.DebugString(), " got ",
@@ -415,7 +416,7 @@ class MutableDenseHashTable final : public LookupInterface {
// rather than updates. That means we may grow the table even though we
// don't need to. As long as the number of keys inserted in one call is
// small compared to the size of the map, the impact of this is minimal.
- const int64 pending_num_entries = num_entries_ + key.dim_size(0);
+ const int64 pending_num_entries = num_entries_ + batch_size;
if (pending_num_entries > num_buckets_ * max_load_factor_) {
int64 new_num_buckets = num_buckets_;
do {
@@ -500,7 +501,7 @@ class MutableDenseHashTable final : public LookupInterface {
private:
Status DoInsert(OpKernelContext* ctx, const Tensor& key, const Tensor& value,
bool ignore_empty_key) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
- const int64 num_elements = key.dim_size(0);
+ const int64 num_elements = (key.dims() == 0) ? 1 : key.dim_size(0);
const int64 value_size = value_shape_.num_elements();
const int64 key_size = key_shape_.num_elements();
const auto key_matrix = key.shaped<K, 2>({num_elements, key_size});
@@ -812,17 +813,21 @@ REGISTER_KERNEL_BUILDER(Name("LookupTableImportV2").Device(DEVICE_CPU),
LookupTableOp<lookup::HashTable<key_dtype, value_dtype>, key_dtype, \
value_dtype>)
+REGISTER_KERNEL(int32, double);
+REGISTER_KERNEL(int32, float);
+REGISTER_KERNEL(int32, int32);
+REGISTER_KERNEL(int32, string);
+REGISTER_KERNEL(int64, double);
+REGISTER_KERNEL(int64, float);
+REGISTER_KERNEL(int64, int32);
+REGISTER_KERNEL(int64, int64);
+REGISTER_KERNEL(int64, string);
+REGISTER_KERNEL(string, bool);
REGISTER_KERNEL(string, double);
REGISTER_KERNEL(string, float);
REGISTER_KERNEL(string, int32);
REGISTER_KERNEL(string, int64);
-REGISTER_KERNEL(int64, string);
-REGISTER_KERNEL(int64, int64);
-REGISTER_KERNEL(int64, float);
REGISTER_KERNEL(string, string);
-REGISTER_KERNEL(string, bool);
-REGISTER_KERNEL(int32, int32);
-REGISTER_KERNEL(int32, string);
#undef REGISTER_KERNEL
@@ -843,12 +848,20 @@ REGISTER_KERNEL(int32, string);
LookupTableOp<lookup::MutableHashTableOfScalars<key_dtype, value_dtype>, \
key_dtype, value_dtype>)
-REGISTER_KERNEL(string, float);
-REGISTER_KERNEL(string, int64);
-REGISTER_KERNEL(int64, string);
-REGISTER_KERNEL(string, bool);
+REGISTER_KERNEL(int32, double);
+REGISTER_KERNEL(int32, float);
+REGISTER_KERNEL(int32, int32);
+REGISTER_KERNEL(int64, double);
REGISTER_KERNEL(int64, float);
+REGISTER_KERNEL(int64, int32);
+REGISTER_KERNEL(int64, int64);
+REGISTER_KERNEL(int64, string);
REGISTER_KERNEL(int64, Variant);
+REGISTER_KERNEL(string, bool);
+REGISTER_KERNEL(string, double);
+REGISTER_KERNEL(string, float);
+REGISTER_KERNEL(string, int32);
+REGISTER_KERNEL(string, int64);
#undef REGISTER_KERNEL
@@ -869,10 +882,19 @@ REGISTER_KERNEL(int64, Variant);
LookupTableOp<lookup::MutableHashTableOfTensors<key_dtype, value_dtype>, \
key_dtype, value_dtype>)
-REGISTER_KERNEL(string, float);
-REGISTER_KERNEL(string, int64);
+REGISTER_KERNEL(int32, double);
+REGISTER_KERNEL(int32, float);
+REGISTER_KERNEL(int32, int32);
+REGISTER_KERNEL(int64, double);
+REGISTER_KERNEL(int64, float);
+REGISTER_KERNEL(int64, int32);
+REGISTER_KERNEL(int64, int64);
REGISTER_KERNEL(int64, string);
REGISTER_KERNEL(string, bool);
+REGISTER_KERNEL(string, double);
+REGISTER_KERNEL(string, float);
+REGISTER_KERNEL(string, int32);
+REGISTER_KERNEL(string, int64);
#undef REGISTER_KERNEL
@@ -893,13 +915,20 @@ REGISTER_KERNEL(string, bool);
LookupTableOp<lookup::MutableDenseHashTable<key_dtype, value_dtype>, \
key_dtype, value_dtype>)
-REGISTER_KERNEL(int64, int64);
-REGISTER_KERNEL(int64, float);
-REGISTER_KERNEL(int64, double);
-REGISTER_KERNEL(string, float);
-REGISTER_KERNEL(string, bool);
+REGISTER_KERNEL(int32, double);
+REGISTER_KERNEL(int32, float);
+REGISTER_KERNEL(int32, int32);
REGISTER_KERNEL(int64, bool);
+REGISTER_KERNEL(int64, double);
+REGISTER_KERNEL(int64, float);
+REGISTER_KERNEL(int64, int32);
+REGISTER_KERNEL(int64, int64);
REGISTER_KERNEL(int64, Variant);
+REGISTER_KERNEL(string, bool);
+REGISTER_KERNEL(string, double);
+REGISTER_KERNEL(string, float);
+REGISTER_KERNEL(string, int32);
+REGISTER_KERNEL(string, int64);
#undef REGISTER_KERNEL
diff --git a/tensorflow/core/kernels/lookup_table_op.h b/tensorflow/core/kernels/lookup_table_op.h
index 3977f16299..35ca2b9ad0 100644
--- a/tensorflow/core/kernels/lookup_table_op.h
+++ b/tensorflow/core/kernels/lookup_table_op.h
@@ -102,9 +102,12 @@ class LookupTableOp : public OpKernel {
~LookupTableOp() override {
// If the table object was not shared, delete it.
if (table_handle_set_ && cinfo_.resource_is_private_to_kernel()) {
- TF_CHECK_OK(
- cinfo_.resource_manager()->template Delete<lookup::LookupInterface>(
- cinfo_.container(), cinfo_.name()));
+ if (!cinfo_.resource_manager()
+ ->template Delete<lookup::LookupInterface>(cinfo_.container(),
+ cinfo_.name())
+ .ok()) {
+ // Do nothing; the resource can have been deleted by session resets.
+ }
}
}
diff --git a/tensorflow/core/kernels/lookup_util.cc b/tensorflow/core/kernels/lookup_util.cc
index 77386a16e0..30fe4b077a 100644
--- a/tensorflow/core/kernels/lookup_util.cc
+++ b/tensorflow/core/kernels/lookup_util.cc
@@ -242,7 +242,8 @@ class TextFileLineIterator
break;
default:
valid_ = false;
- return errors::InvalidArgument("Data type ", dtype, " not supported.");
+ return errors::InvalidArgument("Data type ", DataTypeString(dtype),
+ " not supported.");
}
return Status::OK();
}
@@ -326,8 +327,10 @@ Status CheckTableDataTypes(const LookupInterface& table, DataType key_dtype,
DataType value_dtype, const string& table_name) {
if (table.key_dtype() != key_dtype || table.value_dtype() != value_dtype) {
return errors::InvalidArgument(
- "Conflicting key/value dtypes ", key_dtype, "->", value_dtype, " with ",
- table.key_dtype(), "-", table.value_dtype(), " for table ", table_name);
+ "Conflicting key/value dtypes ", DataTypeString(key_dtype), "->",
+ DataTypeString(value_dtype), " with ",
+ DataTypeString(table.key_dtype()), "-",
+ DataTypeString(table.value_dtype()), " for table ", table_name);
}
return Status::OK();
}
@@ -340,7 +343,7 @@ Status InitializeTableFromTextFile(const string& filename, int64 vocab_size,
if (key_index == kLineNumber && table->key_dtype() != DT_INT64) {
return errors::InvalidArgument(
"Key index for line number requires table key dtype of int64, got ",
- table->key_dtype());
+ DataTypeString(table->key_dtype()));
}
const DataType& key_dtype = table->key_dtype();
const DataType& value_dtype = table->value_dtype();
@@ -348,17 +351,17 @@ Status InitializeTableFromTextFile(const string& filename, int64 vocab_size,
key_dtype != DT_STRING) {
return errors::InvalidArgument(
"Key index for whole line requires string or integer table key, got ",
- table->key_dtype());
+ DataTypeString(table->key_dtype()));
}
if (value_index == kLineNumber && value_dtype != DT_INT64) {
return errors::InvalidArgument(
"Value index for line number requires table value dtype of int64, got ",
- table->value_dtype());
+ DataTypeString(table->value_dtype()));
}
if (value_index == kWholeLine && value_dtype != DT_STRING) {
return errors::InvalidArgument(
"Value index for whole line requires table value dtype of string, got ",
- table->value_dtype());
+ DataTypeString(table->value_dtype()));
}
TextFileLineIterator iter;
diff --git a/tensorflow/core/kernels/matmul_op.cc b/tensorflow/core/kernels/matmul_op.cc
index 5d4737549b..79967aab38 100644
--- a/tensorflow/core/kernels/matmul_op.cc
+++ b/tensorflow/core/kernels/matmul_op.cc
@@ -598,11 +598,11 @@ TF_CALL_float(REGISTER_CPU_EIGEN);
// to use only opensource MKL DNN then use default implementation for these
// types otherwise use GEMM from MKL ML binary
-#if defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL_DNN_ONLY)
TF_CALL_complex64(REGISTER_CPU);
TF_CALL_complex128(REGISTER_CPU);
TF_CALL_double(REGISTER_CPU);
-#else // DO_NOT_USE_ML
+#else // INTEL_MKL_DNN_ONLY
TF_CALL_complex64(REGISTER_CPU_EIGEN);
TF_CALL_complex128(REGISTER_CPU_EIGEN);
TF_CALL_double(REGISTER_CPU_EIGEN);
diff --git a/tensorflow/core/kernels/matrix_band_part_op.h b/tensorflow/core/kernels/matrix_band_part_op.h
index 97cc950793..b04e36db8e 100644
--- a/tensorflow/core/kernels/matrix_band_part_op.h
+++ b/tensorflow/core/kernels/matrix_band_part_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_MATRIX_DIAG_OP_H_
-#define TENSORFLOW_KERNELS_MATRIX_DIAG_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_MATRIX_BAND_PART_OP_H_
+#define TENSORFLOW_CORE_KERNELS_MATRIX_BAND_PART_OP_H_
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
@@ -34,4 +34,4 @@ struct MatrixBandPartFunctor {
} // namespace functor
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_MATRIX_DIAG_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_MATRIX_BAND_PART_OP_H_
diff --git a/tensorflow/core/kernels/matrix_diag_op.h b/tensorflow/core/kernels/matrix_diag_op.h
index 14095845b8..108ba0f56b 100644
--- a/tensorflow/core/kernels/matrix_diag_op.h
+++ b/tensorflow/core/kernels/matrix_diag_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_MATRIX_DIAG_OP_H_
-#define TENSORFLOW_KERNELS_MATRIX_DIAG_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_MATRIX_DIAG_OP_H_
+#define TENSORFLOW_CORE_KERNELS_MATRIX_DIAG_OP_H_
// Generator definition for MatrixDiagOp, must be compilable by nvcc.
@@ -91,4 +91,4 @@ struct MatrixDiag {
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_MATRIX_DIAG_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_MATRIX_DIAG_OP_H_
diff --git a/tensorflow/core/kernels/matrix_solve_ls_op_impl.h b/tensorflow/core/kernels/matrix_solve_ls_op_impl.h
index 0e09078365..00a05a87a3 100644
--- a/tensorflow/core/kernels/matrix_solve_ls_op_impl.h
+++ b/tensorflow/core/kernels/matrix_solve_ls_op_impl.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_MATRIX_SOLVE_LS_OP_IMPL_H_
+#define TENSORFLOW_CORE_KERNELS_MATRIX_SOLVE_LS_OP_IMPL_H_
+
// See docs in ../ops/linalg_ops.cc.
#include "third_party/eigen3/Eigen/Cholesky"
@@ -159,3 +162,5 @@ class MatrixSolveLsOp : public LinearAlgebraOp<Scalar> {
};
} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_MATRIX_SOLVE_LS_OP_IMPL_H_
diff --git a/tensorflow/core/kernels/mkl_aggregate_ops.cc b/tensorflow/core/kernels/mkl_aggregate_ops.cc
index 3d04aeeb3e..28edf51546 100644
--- a/tensorflow/core/kernels/mkl_aggregate_ops.cc
+++ b/tensorflow/core/kernels/mkl_aggregate_ops.cc
@@ -24,8 +24,7 @@ limitations under the License.
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/platform/logging.h"
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::stream;
using mkldnn::sum;
@@ -38,7 +37,7 @@ using mkldnn::sum;
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklAddNOp : public OpKernel {
@@ -286,7 +285,7 @@ class MklAddNOp : public OpKernel {
} MklAddNOpContext;
};
-#else // INTEL_MKL_ML
+#else // INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklAddNOp : public OpKernel {
public:
diff --git a/tensorflow/core/kernels/mkl_avgpooling_op.cc b/tensorflow/core/kernels/mkl_avgpooling_op.cc
index d3566c2e37..969baecc51 100644
--- a/tensorflow/core/kernels/mkl_avgpooling_op.cc
+++ b/tensorflow/core/kernels/mkl_avgpooling_op.cc
@@ -24,7 +24,7 @@
#include "tensorflow/core/kernels/mkl_pooling_ops_common.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::algorithm;
using mkldnn::engine;
@@ -40,7 +40,7 @@ namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklAvgPoolingOp : public OpKernel {
@@ -664,7 +664,7 @@ class MklAvgPoolingGradOp : public MklPoolingBackwardOpBase<T> {
}
}; // MklAvgPoolingGradOp
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
REGISTER_KERNEL_BUILDER(Name("_MklAvgPool")
.Device(DEVICE_CPU)
diff --git a/tensorflow/core/kernels/mkl_batch_matmul_op.cc b/tensorflow/core/kernels/mkl_batch_matmul_op.cc
index 45328b03d6..0841395dc3 100644
--- a/tensorflow/core/kernels/mkl_batch_matmul_op.cc
+++ b/tensorflow/core/kernels/mkl_batch_matmul_op.cc
@@ -25,7 +25,7 @@ limitations under the License.
#define EIGEN_USE_THREADS
-#if defined(INTEL_MKL) && !defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL) && !defined(INTEL_MKL_DNN_ONLY)
#include <vector>
#include "mkl_cblas.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
diff --git a/tensorflow/core/kernels/mkl_concat_op.cc b/tensorflow/core/kernels/mkl_concat_op.cc
index d8efb1be3e..8ad7ebb51f 100644
--- a/tensorflow/core/kernels/mkl_concat_op.cc
+++ b/tensorflow/core/kernels/mkl_concat_op.cc
@@ -27,8 +27,7 @@ limitations under the License.
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/types.h"
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::concat;
@@ -64,7 +63,7 @@ class EigenConcatBaseOp : public OpKernel {
// we need to have empty Compute because Compute is pure virtual function.
void Compute(OpKernelContext* c) {}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
void Compute(OpKernelContext* c, const std::vector<Tensor>& values) {
const Tensor* concat_dim_tensor;
@@ -232,7 +231,7 @@ class EigenConcatBaseOp : public OpKernel {
#endif
};
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// --------------------------------------------------------------------------
// Mkl Concat Op
diff --git a/tensorflow/core/kernels/mkl_conv_grad_bias_ops.cc b/tensorflow/core/kernels/mkl_conv_grad_bias_ops.cc
index f857be6c32..7c687f6581 100644
--- a/tensorflow/core/kernels/mkl_conv_grad_bias_ops.cc
+++ b/tensorflow/core/kernels/mkl_conv_grad_bias_ops.cc
@@ -18,7 +18,7 @@ limitations under the License.
// bias.
#ifdef INTEL_MKL
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
#define USE_EIGEN_TENSOR
#define EIGEN_USE_THREADS
@@ -39,7 +39,7 @@ limitations under the License.
#include "tensorflow/core/util/use_cudnn.h"
#include "tensorflow/core/util/work_sharder.h"
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
#include "mkl_dnn.h"
#include "mkl_dnn_types.h"
#endif
@@ -265,5 +265,5 @@ class MklConv2DCustomBackpropBiasOp : public OpKernel {
TF_CALL_float(REGISTER_CPU_KERNELS);
#undef REGISTER_CPU_KERNELS
} /* namespace tensorflow */
-#endif /* INTEL_MKL_ML */
+#endif /* INTEL_MKL_ML_ONLY */
#endif /* INTEL_MKL */
diff --git a/tensorflow/core/kernels/mkl_conv_grad_filter_ops.cc b/tensorflow/core/kernels/mkl_conv_grad_filter_ops.cc
index b73a119a88..afbfaa83f3 100644
--- a/tensorflow/core/kernels/mkl_conv_grad_filter_ops.cc
+++ b/tensorflow/core/kernels/mkl_conv_grad_filter_ops.cc
@@ -38,8 +38,7 @@ limitations under the License.
#include "tensorflow/core/util/use_cudnn.h"
#include "tensorflow/core/util/work_sharder.h"
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::convolution_backward_weights;
@@ -56,7 +55,7 @@ using mkldnn::stream;
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
struct MklConvBwdFilterParams {
memory::dims src_dims;
@@ -83,11 +82,11 @@ struct MklConvBwdFilterParams {
};
template <typename T>
-class MklConv2DBwdFilterPrimitive : public MklPrimitive {
+class MklConvBwdFilterPrimitive : public MklPrimitive {
public:
- explicit MklConv2DBwdFilterPrimitive(
- const MklConvBwdFilterParams& convBwdFilterDims) :
- cpu_engine_(engine::cpu, 0) {
+ explicit MklConvBwdFilterPrimitive(
+ const MklConvBwdFilterParams& convBwdFilterDims)
+ : cpu_engine_(engine::cpu, 0) {
context_.bwd_filter_stream.reset(new stream(stream::kind::eager));
// create conv primitive
if (context_.conv_bwd_filter == nullptr) {
@@ -95,7 +94,7 @@ class MklConv2DBwdFilterPrimitive : public MklPrimitive {
}
}
- ~MklConv2DBwdFilterPrimitive() {}
+ ~MklConvBwdFilterPrimitive() {}
// Convolution backward weights with bias
// src_data: input data buffer of src
@@ -298,38 +297,36 @@ class MklConv2DBwdFilterPrimitive : public MklPrimitive {
};
template <typename T>
-class MklConv2DBwdFilterPrimitiveFactory : public MklPrimitiveFactory<T> {
+class MklConvBwdFilterPrimitiveFactory : public MklPrimitiveFactory<T> {
public:
- static MklConv2DBwdFilterPrimitive<T>* Get(
+ static MklConvBwdFilterPrimitive<T>* Get(
const MklConvBwdFilterParams& convBwdFilterDims) {
- MklConv2DBwdFilterPrimitive<T>* conv2d_bwd_filter = nullptr;
+ MklConvBwdFilterPrimitive<T>* conv_bwd_filter = nullptr;
// look into the pool for reusable primitive
- conv2d_bwd_filter = dynamic_cast<MklConv2DBwdFilterPrimitive<T>*> (
- MklConv2DBwdFilterPrimitiveFactory<T>::GetInstance().GetConv2dBwdFilter(
- convBwdFilterDims));
-
- if (conv2d_bwd_filter == nullptr) {
- conv2d_bwd_filter = new MklConv2DBwdFilterPrimitive<T>(
- convBwdFilterDims);
- MklConv2DBwdFilterPrimitiveFactory<T>::GetInstance().SetConv2dBwdFilter(
- convBwdFilterDims, conv2d_bwd_filter);
+ conv_bwd_filter = dynamic_cast<MklConvBwdFilterPrimitive<T>*>(
+ MklConvBwdFilterPrimitiveFactory<T>::GetInstance().GetConvBwdFilter(
+ convBwdFilterDims));
+
+ if (conv_bwd_filter == nullptr) {
+ conv_bwd_filter = new MklConvBwdFilterPrimitive<T>(convBwdFilterDims);
+ MklConvBwdFilterPrimitiveFactory<T>::GetInstance().SetConvBwdFilter(
+ convBwdFilterDims, conv_bwd_filter);
}
- return conv2d_bwd_filter;
+ return conv_bwd_filter;
}
-
private:
- MklConv2DBwdFilterPrimitiveFactory() {}
- ~MklConv2DBwdFilterPrimitiveFactory() {}
+ MklConvBwdFilterPrimitiveFactory() {}
+ ~MklConvBwdFilterPrimitiveFactory() {}
- static MklConv2DBwdFilterPrimitiveFactory& GetInstance() {
- static MklConv2DBwdFilterPrimitiveFactory instance_;
+ static MklConvBwdFilterPrimitiveFactory& GetInstance() {
+ static MklConvBwdFilterPrimitiveFactory instance_;
return instance_;
}
static string CreateKey(const MklConvBwdFilterParams& convBwdFilterDims) {
- string prefix = "conv2d_bwd_filter";
+ string prefix = "conv_bwd_filter";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(convBwdFilterDims.src_dims);
@@ -343,14 +340,14 @@ class MklConv2DBwdFilterPrimitiveFactory : public MklPrimitiveFactory<T> {
return key_creator.GetKey();
}
- MklPrimitive* GetConv2dBwdFilter(
+ MklPrimitive* GetConvBwdFilter(
const MklConvBwdFilterParams& convBwdFilterDims) {
string key = CreateKey(convBwdFilterDims);
return this->GetOp(key);
}
- void SetConv2dBwdFilter(
- const MklConvBwdFilterParams& convBwdFilterDims, MklPrimitive* op) {
+ void SetConvBwdFilter(const MklConvBwdFilterParams& convBwdFilterDims,
+ MklPrimitive* op) {
string key = CreateKey(convBwdFilterDims);
this->SetOp(key, op);
}
@@ -358,7 +355,7 @@ class MklConv2DBwdFilterPrimitiveFactory : public MklPrimitiveFactory<T> {
#endif
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, class T>
class MklConv2DCustomBackpropFilterOp : public OpKernel {
@@ -739,14 +736,13 @@ TF_CALL_float(REGISTER_MKL_FILTER_KERNELS);
#else
template <typename Device, class T, bool biasEnabled>
-class MklConv2DCustomBackpropFilterOp
- : public MklConv2DBackpropCommonOp<Device, T> {
+class MklConvCustomBackpropFilterOp
+ : public MklConvBackpropCommonOp<Device, T> {
public:
- explicit MklConv2DCustomBackpropFilterOp(OpKernelConstruction* context)
- : MklConv2DBackpropCommonOp<Device, T>(context) {
- }
+ explicit MklConvCustomBackpropFilterOp(OpKernelConstruction* context)
+ : MklConvBackpropCommonOp<Device, T>(context) {}
- ~MklConv2DCustomBackpropFilterOp() {}
+ ~MklConvCustomBackpropFilterOp() {}
void Compute(OpKernelContext* context) {
try {
@@ -754,6 +750,9 @@ class MklConv2DCustomBackpropFilterOp
MklDnnData<T> diff_dst(&cpu_engine_);
MklDnnData<T> diff_filter(&cpu_engine_); // output
+ // This flag indicates Conv2D or Conv3D
+ bool isConv2D = (this->strides_.size() == 4);
+
// Input tensors
const int kInputIdx = 0, kFilterIdx = 1, kOutbpropIdx = 2;
const Tensor& src_tensor = MklGetInput(context, kInputIdx);
@@ -814,7 +813,10 @@ class MklConv2DCustomBackpropFilterOp
&fwd_dst_dims, &padding_left, &padding_right);
if (!context->status().ok()) return;
- auto tf_fmt = TFDataFormatToMklDnnDataFormat(this->data_format_);
+ auto tf_fmt = isConv2D
+ ? TFDataFormatToMklDnnDataFormat(this->data_format_)
+ : TFDataFormatToMklDnn3DDataFormat(this->data_format_);
+
auto fwd_src_md =
src_mkl_shape.IsMklTensor()
? src_mkl_shape.GetMklLayout()
@@ -833,21 +835,19 @@ class MklConv2DCustomBackpropFilterOp
if (biasEnabled) {
TensorShape obp_tf_shape = GetTfShape(context, 2);
depth = (this->data_format_ == FORMAT_NCHW)
- ? obp_tf_shape.dim_size(1)
- : obp_tf_shape.dim_size(3);
+ ? obp_tf_shape.dim_size(1)
+ : obp_tf_shape.dim_size(isConv2D ? 3 : 4);
diff_bias_dims = {static_cast<int>(depth)};
}
+ for (int i = 0; i < dilations.size(); i++) dilations[i] -= 1;
- dilations[kDilationH] -= 1;
- dilations[kDilationW] -= 1;
-
- MklConv2DBwdFilterPrimitive<T> *conv2d_bwd_filter = nullptr;
+ MklConvBwdFilterPrimitive<T>* conv_bwd_filter = nullptr;
MklConvBwdFilterParams convBwdFilterDims(fwd_src_dims, fwd_filter_dims,
diff_bias_dims, diff_dst_dims, strides, dilations, padding_left,
padding_right, TFPaddingToMklDnnPadding(this->padding_));
- conv2d_bwd_filter = MklConv2DBwdFilterPrimitiveFactory<T>::Get(
- convBwdFilterDims);
- auto bwd_filter_pd = conv2d_bwd_filter->GetPrimitiveDesc();
+ conv_bwd_filter =
+ MklConvBwdFilterPrimitiveFactory<T>::Get(convBwdFilterDims);
+ auto bwd_filter_pd = conv_bwd_filter->GetPrimitiveDesc();
// allocate output tensors: diff_fitler and diff_bias (w bias)
auto bwd_output_dims = GetOutputDims(fwd_src_dims, fwd_filter_dims);
@@ -855,14 +855,26 @@ class MklConv2DCustomBackpropFilterOp
// diff_filter
MklDnnShape diff_filter_mkl_shape;
diff_filter_mkl_shape.SetMklTensor(false);
- // output_dims_mkl_order is in OIHW format.
- TensorShape diff_filter_tf_shape(
- {bwd_output_dims[MklDnnDims::Dim_H],
- bwd_output_dims[MklDnnDims::Dim_W],
- bwd_output_dims[MklDnnDims::Dim_I],
- bwd_output_dims[MklDnnDims::Dim_O]});
- AllocateOutputSetMklShape(context, 0, &diff_filter_tensor,
- diff_filter_tf_shape, diff_filter_mkl_shape);
+
+ if (isConv2D) {
+ // Conv2D: output_dims_mkl_order is in OIHW format.
+ TensorShape diff_filter_tf_shape({bwd_output_dims[MklDnnDims::Dim_H],
+ bwd_output_dims[MklDnnDims::Dim_W],
+ bwd_output_dims[MklDnnDims::Dim_I],
+ bwd_output_dims[MklDnnDims::Dim_O]});
+ AllocateOutputSetMklShape(context, 0, &diff_filter_tensor,
+ diff_filter_tf_shape, diff_filter_mkl_shape);
+ } else {
+ // Conv3D: output_dims_mkl_order is in OIDHW format.
+ TensorShape diff_filter_tf_shape(
+ {bwd_output_dims[MklDnnDims3D::Dim3d_D],
+ bwd_output_dims[MklDnnDims3D::Dim3d_H],
+ bwd_output_dims[MklDnnDims3D::Dim3d_W],
+ bwd_output_dims[MklDnnDims3D::Dim3d_I],
+ bwd_output_dims[MklDnnDims3D::Dim3d_O]});
+ AllocateOutputSetMklShape(context, 0, &diff_filter_tensor,
+ diff_filter_tf_shape, diff_filter_mkl_shape);
+ }
Tensor* diff_bias_tensor = nullptr;
if (biasEnabled) {
@@ -872,7 +884,7 @@ class MklConv2DCustomBackpropFilterOp
// check if src and diff_dst need reorder
T *src_data = nullptr;
- if (fwd_src_md.data.format != conv2d_bwd_filter->GetSrcMemoryFormat()) {
+ if (fwd_src_md.data.format != conv_bwd_filter->GetSrcMemoryFormat()) {
src.SetUsrMem(fwd_src_md, &src_tensor);
src.CheckReorderToOpMem(bwd_filter_pd->src_primitive_desc());
src_data = static_cast<T*>(src.GetOpMem().get_data_handle());
@@ -883,7 +895,7 @@ class MklConv2DCustomBackpropFilterOp
T *diff_dst_data = nullptr;
if (diff_dst_md.data.format !=
- conv2d_bwd_filter->GetDiffDstMemoryFormat()) {
+ conv_bwd_filter->GetDiffDstMemoryFormat()) {
diff_dst.SetUsrMem(diff_dst_md, &diff_dst_tensor);
diff_dst.CheckReorderToOpMem(bwd_filter_pd->diff_dst_primitive_desc());
diff_dst_data = static_cast<T*>(
@@ -898,7 +910,7 @@ class MklConv2DCustomBackpropFilterOp
bool diff_filter_reorder_required = false;
T *diff_filter_data = nullptr;
if (GetOutputFormat(tf_fmt) !=
- conv2d_bwd_filter->GetDiffFilterMemoryFormat()) {
+ conv_bwd_filter->GetDiffFilterMemoryFormat()) {
// Allocate diff filter tensor as Tensorflow layout
diff_filter.SetUsrMem(bwd_output_dims, GetOutputFormat(tf_fmt),
diff_filter_tensor);
@@ -916,10 +928,10 @@ class MklConv2DCustomBackpropFilterOp
if (biasEnabled) {
T* diff_bias_data = static_cast<T*>(const_cast<T*>(
diff_bias_tensor->flat<T>().data()));
- conv2d_bwd_filter->Execute(src_data, diff_filter_data,
- diff_bias_data, diff_dst_data);
+ conv_bwd_filter->Execute(src_data, diff_filter_data, diff_bias_data,
+ diff_dst_data);
} else {
- conv2d_bwd_filter->Execute(src_data, diff_filter_data, diff_dst_data);
+ conv_bwd_filter->Execute(src_data, diff_filter_data, diff_dst_data);
}
// Reorder diff_filter back to Tensorflow layout if necessary
@@ -948,7 +960,7 @@ class MklConv2DCustomBackpropFilterOp
const MklDnnShape& filter_mkl_shape,
const MklDnnShape& obp_mkl_shape) {
CHECK(!filter_mkl_shape.IsMklTensor())
- << "Conv2DBackpropFilter: filter should not be in MKL Layout";
+ << "ConvBackpropFilter: filter should not be in MKL Layout";
}
// Get TensorFlow shape of input tensor.
@@ -984,9 +996,11 @@ class MklConv2DCustomBackpropFilterOp
return fwd_filter_dims;
}
- // Output layout is Tensorflow's filter layout (HWIO).
+ // Output layout is Tensorflow's filter layout
+ // Conv2D: HWIO; Conv3D: DHWIO
memory::format GetOutputFormat(const memory::format data_format) {
- return memory::format::hwio;
+ return (this->strides_.size() == 4) ? memory::format::hwio
+ : memory::format::dhwio;
}
// Allocate output tensor.
@@ -1028,29 +1042,32 @@ class MklConv2DCustomBackpropFilterOp
}
};
-#define REGISTER_MKL_FILTER_KERNELS(T) \
- REGISTER_KERNEL_BUILDER( \
- Name("_MklConv2DBackpropFilter") \
- .Device(DEVICE_CPU) \
- .TypeConstraint<T>("T") \
- .Label(mkl_op_registry::kMklOpLabel), \
- MklConv2DCustomBackpropFilterOp<CPUDevice, T, false>); \
- REGISTER_KERNEL_BUILDER( \
- Name("_MklConv2DBackpropFilterWithBias") \
- .Device(DEVICE_CPU) \
- .TypeConstraint<T>("T") \
- .Label(mkl_op_registry::kMklOpLabel), \
- MklConv2DCustomBackpropFilterOp<CPUDevice, T, true>); \
- REGISTER_KERNEL_BUILDER(Name("__MklDummyConv2DBackpropFilterWithBias") \
- .Device(DEVICE_CPU) \
- .TypeConstraint<T>("T") \
- .Label(mkl_op_registry::kMklOpLabel), \
- MklDummyOp<CPUDevice, T>);
+#define REGISTER_MKL_FILTER_KERNELS(T) \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv2DBackpropFilter") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConvCustomBackpropFilterOp<CPUDevice, T, false>); \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv2DBackpropFilterWithBias") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConvCustomBackpropFilterOp<CPUDevice, T, true>); \
+ REGISTER_KERNEL_BUILDER(Name("__MklDummyConv2DBackpropFilterWithBias") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklDummyOp<CPUDevice, T>); \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv3DBackpropFilterV2") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConvCustomBackpropFilterOp<CPUDevice, T, false>);
TF_CALL_float(REGISTER_MKL_FILTER_KERNELS);
#undef REGISTER_MKL_FILTER_KERNELS
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
} // namespace tensorflow
diff --git a/tensorflow/core/kernels/mkl_conv_grad_input_ops.cc b/tensorflow/core/kernels/mkl_conv_grad_input_ops.cc
index 39498f1a80..b5a98301e2 100644
--- a/tensorflow/core/kernels/mkl_conv_grad_input_ops.cc
+++ b/tensorflow/core/kernels/mkl_conv_grad_input_ops.cc
@@ -23,7 +23,7 @@ limitations under the License.
#define EIGEN_USE_THREADS
#include <algorithm>
#include <vector>
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
#include "mkl_dnn.h"
#include "mkl_dnn_types.h"
#endif
@@ -46,7 +46,7 @@ limitations under the License.
#include "tensorflow/core/util/use_cudnn.h"
#include "tensorflow/core/util/work_sharder.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::convolution_backward_data;
@@ -57,9 +57,9 @@ using mkldnn::stream;
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
-/// utility classes enabling primitive reuse for backward conv2d ops.
+/// utility classes enabling primitive reuse for backward conv ops.
struct MklConvBwdInputParams {
memory::dims diff_src_dims;
memory::dims filter_dims;
@@ -83,11 +83,11 @@ struct MklConvBwdInputParams {
};
template <typename T>
-class MklConv2DBwdInputPrimitive : public MklPrimitive {
+class MklConvBwdInputPrimitive : public MklPrimitive {
public:
- explicit MklConv2DBwdInputPrimitive(
- const MklConvBwdInputParams& convBwdInputDims) :
- cpu_engine_(engine::cpu, 0) {
+ explicit MklConvBwdInputPrimitive(
+ const MklConvBwdInputParams& convBwdInputDims)
+ : cpu_engine_(engine::cpu, 0) {
context_.bwd_input_stream.reset(new stream(stream::kind::eager));
// create conv primitive
@@ -95,7 +95,7 @@ class MklConv2DBwdInputPrimitive : public MklPrimitive {
Setup(convBwdInputDims);
}
}
- ~MklConv2DBwdInputPrimitive() {}
+ ~MklConvBwdInputPrimitive() {}
// Convolution backward filter (weights)
// diff_src_data: output data buffer of diff_src
@@ -134,7 +134,7 @@ class MklConv2DBwdInputPrimitive : public MklPrimitive {
}
private:
- // Primitive reuse context for Conv2D Bwd Input op
+ // Primitive reuse context for Conv Bwd Input op
struct ConvBwdInputContext {
// expected memory format for this primitive instance
memory::format filter_fmt;
@@ -235,38 +235,37 @@ class MklConv2DBwdInputPrimitive : public MklPrimitive {
};
template <typename T>
-class MklConv2DBwdInputPrimitiveFactory : public MklPrimitiveFactory<T> {
+class MklConvBwdInputPrimitiveFactory : public MklPrimitiveFactory<T> {
private:
- MklConv2DBwdInputPrimitiveFactory() {}
- ~MklConv2DBwdInputPrimitiveFactory() {}
+ MklConvBwdInputPrimitiveFactory() {}
+ ~MklConvBwdInputPrimitiveFactory() {}
public:
- static MklConv2DBwdInputPrimitive<T>* Get(
+ static MklConvBwdInputPrimitive<T>* Get(
const MklConvBwdInputParams& convBwdInputDims) {
- MklConv2DBwdInputPrimitive<T>* conv2d_bwd_input = nullptr;
+ MklConvBwdInputPrimitive<T>* conv_bwd_input = nullptr;
// look into the pool for reusable primitive
- conv2d_bwd_input = dynamic_cast<MklConv2DBwdInputPrimitive<T>*> (
- MklConv2DBwdInputPrimitiveFactory<T>::GetInstance().GetConv2dBwdInput(
+ conv_bwd_input = dynamic_cast<MklConvBwdInputPrimitive<T>*>(
+ MklConvBwdInputPrimitiveFactory<T>::GetInstance().GetConvBwdInput(
convBwdInputDims));
- if (conv2d_bwd_input == nullptr) {
- conv2d_bwd_input = new MklConv2DBwdInputPrimitive<T>(
- convBwdInputDims);
- MklConv2DBwdInputPrimitiveFactory<T>::GetInstance().SetConv2dBwdInput(
- convBwdInputDims, conv2d_bwd_input);
+ if (conv_bwd_input == nullptr) {
+ conv_bwd_input = new MklConvBwdInputPrimitive<T>(convBwdInputDims);
+ MklConvBwdInputPrimitiveFactory<T>::GetInstance().SetConvBwdInput(
+ convBwdInputDims, conv_bwd_input);
}
- return conv2d_bwd_input;
+ return conv_bwd_input;
}
private:
- static MklConv2DBwdInputPrimitiveFactory& GetInstance() {
- static MklConv2DBwdInputPrimitiveFactory instance_;
+ static MklConvBwdInputPrimitiveFactory& GetInstance() {
+ static MklConvBwdInputPrimitiveFactory instance_;
return instance_;
}
static string CreateKey(const MklConvBwdInputParams& convBwdInputDims) {
- string prefix = "conv2d_bwd_input";
+ string prefix = "conv_bwd_input";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(convBwdInputDims.diff_src_dims);
@@ -279,14 +278,13 @@ class MklConv2DBwdInputPrimitiveFactory : public MklPrimitiveFactory<T> {
return key_creator.GetKey();
}
- MklPrimitive* GetConv2dBwdInput(
- const MklConvBwdInputParams& convBwdInputDims) {
+ MklPrimitive* GetConvBwdInput(const MklConvBwdInputParams& convBwdInputDims) {
string key = CreateKey(convBwdInputDims);
return this->GetOp(key);
}
- void SetConv2dBwdInput(
- const MklConvBwdInputParams& convBwdInputDims, MklPrimitive *op) {
+ void SetConvBwdInput(const MklConvBwdInputParams& convBwdInputDims,
+ MklPrimitive* op) {
string key = CreateKey(convBwdInputDims);
this->SetOp(key, op);
}
@@ -294,7 +292,7 @@ class MklConv2DBwdInputPrimitiveFactory : public MklPrimitiveFactory<T> {
#endif
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, class T>
class MklConv2DCustomBackpropInputOp : public OpKernel {
@@ -594,23 +592,34 @@ class MklConv2DCustomBackpropInputOp : public OpKernel {
TensorFormat data_format;
};
+#define REGISTER_MKL_CPU_KERNELS(T) \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv2DBackpropInput") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConv2DCustomBackpropInputOp<CPUDevice, T>);
+
+TF_CALL_float(REGISTER_MKL_CPU_KERNELS);
+#undef REGISTER_MKL_CPU_KERNELS
+
#else
template <typename Device, class T>
-class MklConv2DCustomBackpropInputOp
- : public MklConv2DBackpropCommonOp<Device, T> {
+class MklConvCustomBackpropInputOp : public MklConvBackpropCommonOp<Device, T> {
public:
- explicit MklConv2DCustomBackpropInputOp(OpKernelConstruction* context)
- : MklConv2DBackpropCommonOp<Device, T>(context) {
- }
+ explicit MklConvCustomBackpropInputOp(OpKernelConstruction* context)
+ : MklConvBackpropCommonOp<Device, T>(context) {}
- ~MklConv2DCustomBackpropInputOp() {}
+ ~MklConvCustomBackpropInputOp() {}
void Compute(OpKernelContext* context) {
try {
MklDnnData<T> filter(&cpu_engine);
MklDnnData<T> diff_dst(&cpu_engine);
+ // This flag indicate Conv2D or Conv3D
+ bool isConv2D = (this->strides_.size() == 4);
+
// Input tensors
const int kInputIdx = 0, kFilterIdx = 1, kOutbpropIdx = 2;
const Tensor& src_tensor = MklGetInput(context, kInputIdx);
@@ -626,7 +635,7 @@ class MklConv2DCustomBackpropInputOp
diff_dst_mkl_shape);
// Allow operator-specific generation of shapes.
- // E.g., Conv2DBackpropFilter gets filter as filter_sizes. It is a
+ // E.g., ConvBackpropFilter gets filter as filter_sizes. It is a
// tensor containing shape of filter. So filter.shape() is not
// a correct way to get filter shape. These operator-specific calls
// allow this class to handle this case.
@@ -655,6 +664,7 @@ class MklConv2DCustomBackpropInputOp
}
return;
}
+
// By default, all dims are in MKL order. Only dims in TF order
// are those with postfix tf_order.
memory::dims diff_dst_dims, fwd_src_dims, fwd_filter_dims;
@@ -673,15 +683,18 @@ class MklConv2DCustomBackpropInputOp
// Create Convolution forward descriptor since Convolution backward
// API needs it. For that, we first need to create input, filter
// and output memory descriptors.
- auto tf_fmt = TFDataFormatToMklDnnDataFormat(this->data_format_);
+ auto tf_fmt = isConv2D
+ ? TFDataFormatToMklDnnDataFormat(this->data_format_)
+ : TFDataFormatToMklDnn3DDataFormat(this->data_format_);
// If filter is in MKL layout, then simply grab filter layout;
// otherwise, construct filter in TF layout.
// For TF layout, filter is in HWIO format.
auto fwd_filter_md = filter_mkl_shape.IsMklTensor()
- ? filter_mkl_shape.GetMklLayout()
- : memory::desc(fwd_filter_dims, MklDnnType<T>(),
- memory::format::hwio);
+ ? filter_mkl_shape.GetMklLayout()
+ : memory::desc(fwd_filter_dims, MklDnnType<T>(),
+ isConv2D ? memory::format::hwio
+ : memory::format::dhwio);
conv_utl.GetInputSizeInMklOrder(diff_dst_tf_shape, &diff_dst_dims);
if (!context->status().ok()) return;
@@ -689,18 +702,15 @@ class MklConv2DCustomBackpropInputOp
? diff_dst_mkl_shape.GetMklLayout()
: memory::desc(diff_dst_dims,
MklDnnType<T>(), tf_fmt);
+ for (int i = 0; i < dilations.size(); i++) dilations[i] -= 1;
- dilations[kDilationH] -= 1;
- dilations[kDilationW] -= 1;
-
- MklConv2DBwdInputPrimitive<T> *conv2d_bwd_input = nullptr;
- conv_utl.GetInputSizeInMklOrder(diff_dst_tf_shape, &diff_dst_dims);
+ MklConvBwdInputPrimitive<T>* conv_bwd_input = nullptr;
MklConvBwdInputParams convBwdInputDims(fwd_src_dims, fwd_filter_dims,
diff_dst_dims, strides, dilations, padding_left, padding_right,
TFPaddingToMklDnnPadding(this->padding_));
- conv2d_bwd_input = MklConv2DBwdInputPrimitiveFactory<T>::Get(
- convBwdInputDims);
- auto bwd_input_pd = conv2d_bwd_input->GetPrimitiveDesc();
+ conv_bwd_input =
+ MklConvBwdInputPrimitiveFactory<T>::Get(convBwdInputDims);
+ auto bwd_input_pd = conv_bwd_input->GetPrimitiveDesc();
// allocate output tensor
auto diff_src_pd = bwd_input_pd->diff_src_primitive_desc();
@@ -723,7 +733,7 @@ class MklConv2DCustomBackpropInputOp
// check if filter and diff_dst need reorder
T* filter_data = nullptr;
if (fwd_filter_md.data.format !=
- conv2d_bwd_input->GetFilterMemoryFormat()) {
+ conv_bwd_input->GetFilterMemoryFormat()) {
filter.SetUsrMem(fwd_filter_md, &filter_tensor);
filter.CheckReorderToOpMem(bwd_input_pd->weights_primitive_desc());
filter_data = static_cast<T*>(filter.GetOpMem().get_data_handle());
@@ -733,8 +743,7 @@ class MklConv2DCustomBackpropInputOp
}
T* diff_dst_data = nullptr;
- if (diff_dst_md.data.format !=
- conv2d_bwd_input->GetDiffDstMemoryFormat()) {
+ if (diff_dst_md.data.format != conv_bwd_input->GetDiffDstMemoryFormat()) {
diff_dst.SetUsrMem(diff_dst_md, &diff_dst_tensor);
diff_dst.CheckReorderToOpMem(bwd_input_pd->diff_dst_primitive_desc());
diff_dst_data = static_cast<T*>(
@@ -745,7 +754,7 @@ class MklConv2DCustomBackpropInputOp
}
// execute convolution input bwd
- conv2d_bwd_input->Execute(diff_src_data, filter_data, diff_dst_data);
+ conv_bwd_input->Execute(diff_src_data, filter_data, diff_dst_data);
} catch (mkldnn::error& e) {
string error_msg = "Status: " + std::to_string(e.status) +
", message: " + string(e.message) + ", in file " +
@@ -770,7 +779,7 @@ class MklConv2DCustomBackpropInputOp
// of the Tensor and never an actual tensor. So it will never be in MKL
// layout.
CHECK(!input_mkl_shape.IsMklTensor())
- << "Conv2DBackpropInput: input should not be in MKL Layout";
+ << "ConvBackpropInput: input should not be in MKL Layout";
}
// Get TensorFlow shape of input tensor.
@@ -778,10 +787,10 @@ class MklConv2DCustomBackpropInputOp
const Tensor& input_tensor) {
TensorShape input_tf_shape;
CHECK_EQ(TensorShapeUtils::IsVector(input_tensor.shape()), true);
- CHECK_EQ(
- TensorShapeUtils::MakeShape(input_tensor.vec<int32>(), &input_tf_shape)
- .ok(),
- true);
+ // Conv[2D|3D]BackpropInputV2 supports both DT_INT32 and DT_INT64
+ // output_shape MakeShape is able to handle both DT_INT32 and DT_INT64 for
+ // input_tensor.
+ CHECK_EQ(this->MakeShape(input_tensor, &input_tf_shape).ok(), true);
return input_tf_shape;
}
@@ -792,7 +801,7 @@ class MklConv2DCustomBackpropInputOp
}
// Get the Tensorflow shape of Output (diff_src),
- // which is same as shape of Conv2D 'input'.
+ // which is same as shape of Conv 'input'.
TensorShape GetOutputTfShape(const TensorShape& input_shape,
const TensorShape& filter_shape,
const TensorShape& outbprop_shape) {
@@ -800,7 +809,7 @@ class MklConv2DCustomBackpropInputOp
}
// Get the Tensorflow shape of Output (diff_src),
- // which is same as shape of Conv2D 'input'.
+ // which is same as shape of Conv 'input'.
const memory::dims& GetOutputDims(const memory::dims& fwd_input_dims,
const memory::dims& fwd_filter_dims) {
return fwd_input_dims;
@@ -839,17 +848,22 @@ class MklConv2DCustomBackpropInputOp
}
};
-#endif // INTEL_MKL_ML
-
-#define REGISTER_MKL_CPU_KERNELS(T) \
- REGISTER_KERNEL_BUILDER(Name("_MklConv2DBackpropInput") \
- .Device(DEVICE_CPU) \
- .TypeConstraint<T>("T") \
- .Label(mkl_op_registry::kMklOpLabel), \
- MklConv2DCustomBackpropInputOp<CPUDevice, T>);
+#define REGISTER_MKL_CPU_KERNELS(T) \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv2DBackpropInput") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConvCustomBackpropInputOp<CPUDevice, T>); \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv3DBackpropInputV2") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConvCustomBackpropInputOp<CPUDevice, T>);
TF_CALL_float(REGISTER_MKL_CPU_KERNELS);
#undef REGISTER_MKL_CPU_KERNELS
+#endif // INTEL_MKL_ML_ONLY
+
} // namespace tensorflow
#endif // INTEL_MKL
diff --git a/tensorflow/core/kernels/mkl_conv_ops.cc b/tensorflow/core/kernels/mkl_conv_ops.cc
index 62396eeb8b..c6295c7280 100644
--- a/tensorflow/core/kernels/mkl_conv_ops.cc
+++ b/tensorflow/core/kernels/mkl_conv_ops.cc
@@ -42,7 +42,7 @@ limitations under the License.
#include "tensorflow/core/util/mkl_util.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::prop_kind;
@@ -57,7 +57,7 @@ using mkldnn::convolution_direct;
namespace tensorflow {
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
// This structure aggregates multiple inputs to Conv2DFwd* methods.
struct MklConvFwdParams {
@@ -85,9 +85,9 @@ struct MklConvFwdParams {
};
template <typename T>
-class MklConv2DFwdPrimitive : public MklPrimitive {
+class MklConvFwdPrimitive : public MklPrimitive {
public:
- explicit MklConv2DFwdPrimitive(const MklConvFwdParams& convFwdDims)
+ explicit MklConvFwdPrimitive(const MklConvFwdParams& convFwdDims)
: cpu_engine_(engine::cpu, 0) {
context_.fwd_stream.reset(new stream(stream::kind::eager));
// create conv primitive
@@ -96,7 +96,7 @@ class MklConv2DFwdPrimitive : public MklPrimitive {
}
}
- ~MklConv2DFwdPrimitive() {}
+ ~MklConvFwdPrimitive() {}
// Convolution forward execute with bias
// src_data: input data buffer of src
@@ -269,37 +269,36 @@ class MklConv2DFwdPrimitive : public MklPrimitive {
};
template <typename T>
-class MklConv2DFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
+class MklConvFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
public:
- static MklConv2DFwdPrimitive<T>* Get(const MklConvFwdParams& convFwdDims) {
- MklConv2DFwdPrimitive<T>* conv2d_fwd = nullptr;
+ static MklConvFwdPrimitive<T>* Get(const MklConvFwdParams& convFwdDims) {
+ MklConvFwdPrimitive<T>* conv_fwd = nullptr;
// try to find a suitable one in pool
- conv2d_fwd = dynamic_cast<MklConv2DFwdPrimitive<T>*>(
- MklConv2DFwdPrimitiveFactory<T>::GetInstance().GetConv2DFwd(
- convFwdDims));
-
- if (conv2d_fwd == nullptr) {
- conv2d_fwd = new MklConv2DFwdPrimitive<T>(convFwdDims);
- MklConv2DFwdPrimitiveFactory<T>::GetInstance().SetConv2DFwd(convFwdDims,
- conv2d_fwd);
+ conv_fwd = dynamic_cast<MklConvFwdPrimitive<T>*>(
+ MklConvFwdPrimitiveFactory<T>::GetInstance().GetConvFwd(convFwdDims));
+
+ if (conv_fwd == nullptr) {
+ conv_fwd = new MklConvFwdPrimitive<T>(convFwdDims);
+ MklConvFwdPrimitiveFactory<T>::GetInstance().SetConvFwd(convFwdDims,
+ conv_fwd);
}
- return conv2d_fwd;
+ return conv_fwd;
}
private:
- MklConv2DFwdPrimitiveFactory() {}
- ~MklConv2DFwdPrimitiveFactory() {}
+ MklConvFwdPrimitiveFactory() {}
+ ~MklConvFwdPrimitiveFactory() {}
static const int kDilationH = 0, kDilationW = 1;
- static MklConv2DFwdPrimitiveFactory& GetInstance() {
- static MklConv2DFwdPrimitiveFactory instance_;
+ static MklConvFwdPrimitiveFactory& GetInstance() {
+ static MklConvFwdPrimitiveFactory instance_;
return instance_;
}
static string CreateKey(const MklConvFwdParams& convFwdDims) {
- string prefix = "conv2d_fwd_";
+ string prefix = "conv_fwd_";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(convFwdDims.src_dims);
@@ -313,12 +312,12 @@ class MklConv2DFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
return key_creator.GetKey();
}
- MklPrimitive* GetConv2DFwd(const MklConvFwdParams& convFwdDims) {
+ MklPrimitive* GetConvFwd(const MklConvFwdParams& convFwdDims) {
string key = CreateKey(convFwdDims);
return this->GetOp(key);
}
- void SetConv2DFwd(const MklConvFwdParams& convFwdDims, MklPrimitive* op) {
+ void SetConvFwd(const MklConvFwdParams& convFwdDims, MklPrimitive* op) {
string key = CreateKey(convFwdDims);
this->SetOp(key, op);
}
@@ -329,13 +328,13 @@ class MklConv2DFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
typedef Eigen::ThreadPoolDevice CPUDevice;
// For now, MKL-ML is default. So making MKL-DNN not a default choice.
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T, bool biasEnabled>
-class MklConv2DOp : public OpKernel {
+class MklConvOp : public OpKernel {
public:
- ~MklConv2DOp() {}
+ ~MklConvOp() {}
- explicit MklConv2DOp(OpKernelConstruction* context) : OpKernel(context) {
+ explicit MklConvOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_));
string data_format;
OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format));
@@ -755,21 +754,22 @@ class MklConv2DOp : public OpKernel {
#else
+// Base class for convolution forward operations
template <typename Device, typename T, bool biasEnabled>
-class MklConv2DOp : public OpKernel {
+class MklConvOp : public OpKernel {
public:
- ~MklConv2DOp() {}
+ ~MklConvOp() {}
- explicit MklConv2DOp(OpKernelConstruction* context) : OpKernel(context) {
+ explicit MklConvOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("dilations", &dilations_));
OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_));
string data_format;
OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format));
OP_REQUIRES(context, FormatFromString(data_format, &data_format_),
errors::InvalidArgument("Invalid data format"));
- OP_REQUIRES(context, strides_.size() == 4,
+ OP_REQUIRES(context, (strides_.size() == 4 || strides_.size() == 5),
errors::InvalidArgument("Sliding window strides field must "
- "specify 4 dimensions"));
+ "specify 4 or 5 dimensions"));
const int64 stride_n = GetTensorDim(strides_, data_format_, 'N');
const int64 stride_c = GetTensorDim(strides_, data_format_, 'C');
@@ -778,20 +778,39 @@ class MklConv2DOp : public OpKernel {
errors::InvalidArgument("Current implementation does not yet support "
"strides in the batch and depth dimensions."));
OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
- OP_REQUIRES(context, dilations_.size() == 4,
- errors::InvalidArgument("Sliding window dilations field must "
- "specify 4 dimensions"));
- const int64 dilation_n = GetTensorDim(dilations_, data_format_, 'N');
- const int64 dilation_c = GetTensorDim(dilations_, data_format_, 'C');
- const int64 dilation_h = GetTensorDim(dilations_, data_format_, 'H');
- const int64 dilation_w = GetTensorDim(dilations_, data_format_, 'W');
- OP_REQUIRES(context, dilation_n == 1 && dilation_c == 1,
- errors::InvalidArgument(
- "Current implementation does not yet support "
- "dilations in the batch and depth dimensions."));
- OP_REQUIRES(
- context, dilation_h > 0 && dilation_w > 0,
- errors::InvalidArgument("Dilated rates should be larger than 0."));
+
+ if (strides_.size() == 4) {
+ OP_REQUIRES(context, dilations_.size() == 4,
+ errors::InvalidArgument("Sliding window dilations field must "
+ "specify 4 dimensions"));
+ const int64 dilation_n = GetTensorDim(dilations_, data_format_, 'N');
+ const int64 dilation_c = GetTensorDim(dilations_, data_format_, 'C');
+ const int64 dilation_h = GetTensorDim(dilations_, data_format_, 'H');
+ const int64 dilation_w = GetTensorDim(dilations_, data_format_, 'W');
+ OP_REQUIRES(context, dilation_n == 1 && dilation_c == 1,
+ errors::InvalidArgument(
+ "Current implementation does not yet support "
+ "dilations in the batch and depth dimensions."));
+ OP_REQUIRES(
+ context, dilation_h > 0 && dilation_w > 0,
+ errors::InvalidArgument("Dilated rates should be larger than 0."));
+ } else if (strides_.size() == 5) {
+ OP_REQUIRES(context, dilations_.size() == 5,
+ errors::InvalidArgument("Dilation rates field must "
+ "specify 5 dimensions"));
+ OP_REQUIRES(context,
+ (GetTensorDim(dilations_, data_format_, 'N') == 1 &&
+ GetTensorDim(dilations_, data_format_, 'C') == 1),
+ errors::InvalidArgument(
+ "Current implementation does not yet support "
+ "dilations rates in the batch and depth dimensions."));
+ OP_REQUIRES(
+ context,
+ (GetTensorDim(dilations_, data_format_, '0') > 0 &&
+ GetTensorDim(dilations_, data_format_, '1') > 0 &&
+ GetTensorDim(dilations_, data_format_, '2') > 0),
+ errors::InvalidArgument("Dilated rates should be larger than 0."));
+ }
}
void Compute(OpKernelContext* context) override {
@@ -837,7 +856,8 @@ class MklConv2DOp : public OpKernel {
AllocateOutputSetMklShape(context, kOutputIndex_Dst,
&dst_tensor, src_tf_shape, dst_mkl_shape);
- // MklConv2D also outputs converted filter as 2nd output of Conv2D.
+ // MklConv2D/3D also outputs converted filter
+ // as 2nd output of Conv2D/3D.
filter_mkl_shape.SetMklTensor(false);
Tensor* output_filter_tensor = nullptr;
AllocateOutputSetMklShape(context, kOutputIndex_Filter,
@@ -846,15 +866,20 @@ class MklConv2DOp : public OpKernel {
return;
}
+ bool isConv2D = (strides_.size() == 4);
+
// Create memory for user data.
// Describe how the inputs and outputs of Convolution look like. Also
// specify buffers containing actual input and output data.
- auto tf_fmt = TFDataFormatToMklDnnDataFormat(data_format_);
+ auto tf_fmt = isConv2D ? TFDataFormatToMklDnnDataFormat(data_format_)
+ : TFDataFormatToMklDnn3DDataFormat(data_format_);
// If input is in MKL layout, then simply grab input layout; otherwise,
// construct input Tf layout. For TF layout, although input shape
// (src_dims) required is in MKL-DNN order, the layout is Tensorflow's
- // layout (NHWC or NCHW depending on data format).
+ // layout depending on data format:
+ // Conv2D: NHWC or NCHW
+ // Conv3D: NDHWC or NCDHW
auto src_md = src_mkl_shape.IsMklTensor()
? src_mkl_shape.GetMklLayout()
: memory::desc(src_dims, MklDnnType<T>(), tf_fmt);
@@ -864,31 +889,30 @@ class MklConv2DOp : public OpKernel {
auto filter_md = filter_mkl_shape.IsMklTensor() // Should NEVER be true
? filter_mkl_shape.GetMklLayout()
: memory::desc(filter_dims, MklDnnType<T>(),
- memory::format::hwio);
-
+ isConv2D ? memory::format::hwio
+ : memory::format::dhwio);
// MKLDNN dilation starts from 0.
- dilations[kDilationH] -= 1;
- dilations[kDilationW] -= 1;
+ for (int i = 0; i < dilations.size(); i++) dilations[i] -= 1;
// get a conv2d fwd from primitive pool
- MklConv2DFwdPrimitive<T>* conv2d_fwd = nullptr;
+ MklConvFwdPrimitive<T>* conv_fwd = nullptr;
if (biasEnabled) {
memory::dims bias_dims = {};
conv_utl.GetBiasSizeInMklOrder(kInputIndex_Bias, &bias_dims);
MklConvFwdParams convFwdDims(src_dims, filter_dims, bias_dims,
dst_dims_mkl_order, strides, dilations,
padding_left, padding_right);
- conv2d_fwd = MklConv2DFwdPrimitiveFactory<T>::Get(convFwdDims);
+ conv_fwd = MklConvFwdPrimitiveFactory<T>::Get(convFwdDims);
} else {
MklConvFwdParams convFwdDims(src_dims, filter_dims, NONE_DIMS,
dst_dims_mkl_order, strides, dilations,
padding_left, padding_right);
- conv2d_fwd = MklConv2DFwdPrimitiveFactory<T>::Get(convFwdDims);
+ conv_fwd = MklConvFwdPrimitiveFactory<T>::Get(convFwdDims);
}
// allocate output tensors output_tensor and filter_out_tensor
std::shared_ptr<mkldnn::convolution_forward::primitive_desc> conv_fwd_pd =
- conv2d_fwd->GetPrimitiveDesc();
+ conv_fwd->GetPrimitiveDesc();
AllocateOutputTensor(context, *conv_fwd_pd,
dst_dims_mkl_order, tf_fmt, &dst_tensor);
Tensor* filter_out_tensor = nullptr;
@@ -900,7 +924,7 @@ class MklConv2DOp : public OpKernel {
// check whether src/filter need reorder
T *src_data = nullptr;
- if (src_md.data.format != conv2d_fwd->GetSrcMemoryFormat()) {
+ if (src_md.data.format != conv_fwd->GetSrcMemoryFormat()) {
src.SetUsrMem(src_md, &src_tensor);
src.CheckReorderToOpMem(conv_fwd_pd.get()->src_primitive_desc());
src_data = static_cast<T*>(src.GetOpMem().get_data_handle());
@@ -908,7 +932,7 @@ class MklConv2DOp : public OpKernel {
src_data = static_cast<T*>(const_cast<T*>(src_tensor.flat<T>().data()));
}
T* filter_data = nullptr;
- if (filter_md.data.format != conv2d_fwd->GetFilterMemoryFormat()) {
+ if (filter_md.data.format != conv_fwd->GetFilterMemoryFormat()) {
filter.SetUsrMem(filter_md, &filter_tensor);
filter.CheckReorderToOpMem(conv_fwd_pd.get()->weights_primitive_desc(),
filter.GetTensorBuffer(filter_out_tensor));
@@ -918,16 +942,15 @@ class MklConv2DOp : public OpKernel {
static_cast<T*>(const_cast<T*>(filter_tensor.flat<T>().data()));
}
-
// execute convolution
if (biasEnabled) {
const Tensor& bias_tensor = MklGetInput(context, kInputIndex_Bias);
T* bias_data = static_cast<T*>(const_cast<T*>(
bias_tensor.flat<T>().data()));
- conv2d_fwd->Execute(src_data, filter_data, bias_data, dst_data);
+ conv_fwd->Execute(src_data, filter_data, bias_data, dst_data);
} else {
- conv2d_fwd->Execute(src_data, filter_data, dst_data);
+ conv_fwd->Execute(src_data, filter_data, dst_data);
}
} catch (mkldnn::error &e) {
string error_msg = tensorflow::strings::StrCat(
@@ -1038,17 +1061,18 @@ class MklConv2DOp : public OpKernel {
#endif
+// Register 2D operations
#define REGISTER_MKL_CPU(T) \
REGISTER_KERNEL_BUILDER(Name("_MklConv2D") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.Label(mkl_op_registry::kMklOpLabel), \
- MklConv2DOp<CPUDevice, T, false>); \
+ MklConvOp<CPUDevice, T, false>); \
REGISTER_KERNEL_BUILDER(Name("_MklConv2DWithBias") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.Label(mkl_op_registry::kMklOpLabel), \
- MklConv2DOp<CPUDevice, T, true>); \
+ MklConvOp<CPUDevice, T, true>); \
REGISTER_KERNEL_BUILDER(Name("__MklDummyConv2DWithBias") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
@@ -1057,5 +1081,14 @@ class MklConv2DOp : public OpKernel {
TF_CALL_float(REGISTER_MKL_CPU);
+// Register 3D operations
+#define REGISTER_MKL_CPU(T) \
+ REGISTER_KERNEL_BUILDER(Name("_MklConv3D") \
+ .Device(DEVICE_CPU) \
+ .TypeConstraint<T>("T") \
+ .Label(mkl_op_registry::kMklOpLabel), \
+ MklConvOp<CPUDevice, T, false>);
+TF_CALL_float(REGISTER_MKL_CPU);
+
} // namespace tensorflow
#endif // INTEL_MKL
diff --git a/tensorflow/core/kernels/mkl_conv_ops.h b/tensorflow/core/kernels/mkl_conv_ops.h
index 3f154ff33b..01cc606f41 100644
--- a/tensorflow/core/kernels/mkl_conv_ops.h
+++ b/tensorflow/core/kernels/mkl_conv_ops.h
@@ -40,7 +40,7 @@ limitations under the License.
#include "tensorflow/core/util/mkl_util.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::prop_kind;
@@ -52,7 +52,7 @@ using mkldnn::convolution_forward;
namespace tensorflow {
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
class MklDnnConvUtil {
protected:
@@ -79,9 +79,16 @@ class MklDnnConvUtil {
// For now we take the stride from the second and third dimensions only
// (we do not support striding on the batch or depth dimension).
CHECK_NOTNULL(strides);
- int stride_rows = GetTensorDim(strides_, data_format_, 'H');
- int stride_cols = GetTensorDim(strides_, data_format_, 'W');
- *strides = {stride_rows, stride_cols};
+ if (strides_.size() == 4) {
+ int stride_rows = GetTensorDim(strides_, data_format_, 'H');
+ int stride_cols = GetTensorDim(strides_, data_format_, 'W');
+ *strides = {stride_rows, stride_cols};
+ } else if (strides_.size() == 5) {
+ int stride_planes = GetTensorDim(strides_, data_format_, '0');
+ int stride_rows = GetTensorDim(strides_, data_format_, '1');
+ int stride_cols = GetTensorDim(strides_, data_format_, '2');
+ *strides = {stride_planes, stride_rows, stride_cols};
+ }
}
// Calculate Convolution dilations
@@ -89,13 +96,20 @@ class MklDnnConvUtil {
// For now we take the dilation from the second and third dimensions only
// (we do not support dilation on the batch or depth dimension).
CHECK_NOTNULL(dilations);
- int dilations_rows = GetTensorDim(dilations_, data_format_, 'H');
- int dilations_cols = GetTensorDim(dilations_, data_format_, 'W');
- *dilations = {dilations_rows, dilations_cols};
+ if (dilations_.size() == 4) {
+ int dilations_rows = GetTensorDim(dilations_, data_format_, 'H');
+ int dilations_cols = GetTensorDim(dilations_, data_format_, 'W');
+ *dilations = {dilations_rows, dilations_cols};
+ } else if (dilations_.size() == 5) {
+ int dilations_planes = GetTensorDim(dilations_, data_format_, '0');
+ int dilations_rows = GetTensorDim(dilations_, data_format_, '1');
+ int dilations_cols = GetTensorDim(dilations_, data_format_, '2');
+ *dilations = {dilations_planes, dilations_rows, dilations_cols};
+ }
}
// Calculate Convolution input size in MKL-DNN order. MKL-DNN
- // requires input in NCHW format. Function does not return anything.
+ // requires input in NCHW/NCDHW format. Function does not return anything.
// But errors arising from sanity checks are returned in context's
// status.
virtual inline void GetInputSizeInMklOrder(const TensorShape& input_shape,
@@ -113,40 +127,62 @@ class MklDnnConvUtil {
int64 input_depth_raw = GetTensorDim(input_shape, data_format_, 'C');
int input_depth = static_cast<int>(input_depth_raw);
- // Input rows/height
- int64 input_rows_raw = GetTensorDim(input_shape, data_format_, 'H');
- CHECK_BOUNDS(input_rows_raw, "Input rows too large");
- int input_rows = static_cast<int>(input_rows_raw);
-
- // Input columns/width
- int64 input_cols_raw = GetTensorDim(input_shape, data_format_, 'W');
- CHECK_BOUNDS(input_cols_raw, "Input cols too large");
- int input_cols = static_cast<int>(input_cols_raw);
-
// Input batch
int64 input_batch_raw = GetTensorDim(input_shape, data_format_, 'N');
CHECK_BOUNDS(input_batch_raw, "Input batch too large");
int input_batch = static_cast<int>(input_batch_raw);
+ if (strides_.size() == 4) { // NCHW format for Conv2D
+ // Input rows/height
+ int64 input_rows_raw = GetTensorDim(input_shape, data_format_, 'H');
+ CHECK_BOUNDS(input_rows_raw, "Input rows too large");
+ int input_rows = static_cast<int>(input_rows_raw);
+
+ // Input columns/width
+ int64 input_cols_raw = GetTensorDim(input_shape, data_format_, 'W');
+ CHECK_BOUNDS(input_cols_raw, "Input cols too large");
+ int input_cols = static_cast<int>(input_cols_raw);
+
+ // MKL-DNN always requires input in NCHW format Conv2D.
+ std::vector<int> mkldnn_sizes(4, -1);
+ mkldnn_sizes[MklDnnDims::Dim_N] = input_batch;
+ mkldnn_sizes[MklDnnDims::Dim_C] = input_depth;
+ mkldnn_sizes[MklDnnDims::Dim_H] = input_rows;
+ mkldnn_sizes[MklDnnDims::Dim_W] = input_cols;
+
+ *input_dims = mkldnn_sizes;
+ } else if (strides_.size() == 5) { // NCDHW format for Conv3D
+ // Input planes/third-dimension
+ int64 input_planes_raw = GetTensorDim(input_shape, data_format_, '0');
+ CHECK_BOUNDS(input_planes_raw, "Input depth too large");
+ int input_planes = static_cast<int>(input_planes_raw);
+
+ // Input rows/height
+ int64 input_rows_raw = GetTensorDim(input_shape, data_format_, '1');
+ CHECK_BOUNDS(input_rows_raw, "Input rows too large");
+ int input_rows = static_cast<int>(input_rows_raw);
+
+ // Input columns/width
+ int64 input_cols_raw = GetTensorDim(input_shape, data_format_, '2');
+ CHECK_BOUNDS(input_cols_raw, "Input cols too large");
+ int input_cols = static_cast<int>(input_cols_raw);
+
+ // MKL-DNN always requires input in NCDHW format for Conv3D.
+ std::vector<int> mkldnn_sizes(5, -1);
+ mkldnn_sizes[MklDnnDims3D::Dim3d_N] = input_batch;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_C] = input_depth;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_D] = input_planes;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_H] = input_rows;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_W] = input_cols;
+
+ *input_dims = mkldnn_sizes;
+ }
#undef CHECK_BOUNDS
-
- // MKL-DNN always requires input in NCHW format.
- std::vector<int> mkldnn_sizes(4, -1);
- mkldnn_sizes[MklDnnDims::Dim_N] = input_batch;
- mkldnn_sizes[MklDnnDims::Dim_C] = input_depth;
- mkldnn_sizes[MklDnnDims::Dim_H] = input_rows;
- mkldnn_sizes[MklDnnDims::Dim_W] = input_cols;
-
- *input_dims = mkldnn_sizes;
}
- // Calculate Convolution filter size in MKL-DNN order. MKL-DNN
- // requires filter in OIHW format. Function does not return anything.
- // But errors arising from sanity checks are returned in context's
- // status.
- //
- // Calculate Convolution filter size in MKL-DNN order. MKL-DNN
- // requires filter in OIHW format. Function does not return anything.
+ // Calculate Convolution filter size in MKL-DNN order.
+ // MKL-DNN requires filter in OIHW (Conv2D) or OIDHW (Conv3D) format.
+ // Function does not return anything.
// But errors arising from sanity checks are returned in context's
// status. This function differs from GetConvFilterSizeInMklOrder in
// parameter for input - it accepts src_shape since Convolution Backward
@@ -159,11 +195,13 @@ class MklDnnConvUtil {
memory::dims* filter_dims) {
CHECK_NOTNULL(filter_dims);
- OP_REQUIRES(context_, filter_shape.dims() == 4,
- errors::InvalidArgument("filter must be 4-dimensional: ",
+ OP_REQUIRES(context_, filter_shape.dims() == strides_.size(),
+ errors::InvalidArgument((strides_.size() == 4)
+ ? "filter must be 4-dimensional: "
+ : "filter must be 5-dimensional: ",
filter_shape.DebugString()));
- for (int i = 0; i < 3; i++) {
+ for (int i = 0; i < ((strides_.size() == 4) ? 3 : 5); i++) {
OP_REQUIRES(context_,
FastBoundsCheck(filter_shape.dim_size(i),
std::numeric_limits<int>::max()),
@@ -172,32 +210,57 @@ class MklDnnConvUtil {
int input_depth = GetTensorDim(input_shape, data_format_, 'C');
- OP_REQUIRES(context_, input_depth == filter_shape.dim_size(2),
- errors::InvalidArgument(
- "input and filter must have the same depth: ", input_depth,
- " vs ", filter_shape.dim_size(2)));
-
- // TF filter is always in (rows, cols, in_depth, out_depth) order.
- int filter_rows = static_cast<int>(filter_shape.dim_size(0));
- int filter_cols = static_cast<int>(filter_shape.dim_size(1));
- int in_depth = static_cast<int>(filter_shape.dim_size(2));
- int out_depth = static_cast<int>(filter_shape.dim_size(3));
-
- // MKL-DNN always needs filter in OIHW format.
- // OIHW = (out_depth, in_depth, rows, cols)
- std::vector<int> mkldnn_sizes(4, -1);
- mkldnn_sizes[MklDnnDims::Dim_O] = out_depth;
- mkldnn_sizes[MklDnnDims::Dim_I] = in_depth;
- mkldnn_sizes[MklDnnDims::Dim_H] = filter_rows;
- mkldnn_sizes[MklDnnDims::Dim_W] = filter_cols;
-
- *filter_dims = mkldnn_sizes;
+ if (strides_.size() == 4) { // Conv2D
+ OP_REQUIRES(context_, input_depth == filter_shape.dim_size(2),
+ errors::InvalidArgument(
+ "input and filter must have the same depth: ",
+ input_depth, " vs ", filter_shape.dim_size(2)));
+
+ // TF filter is always in (rows, cols, in_depth, out_depth) order.
+ int filter_rows = static_cast<int>(filter_shape.dim_size(0));
+ int filter_cols = static_cast<int>(filter_shape.dim_size(1));
+ int in_depth = static_cast<int>(filter_shape.dim_size(2));
+ int out_depth = static_cast<int>(filter_shape.dim_size(3));
+
+ // MKL-DNN always needs filter in OIHW format.
+ // OIHW = (out_depth, in_depth, rows, cols)
+ std::vector<int> mkldnn_sizes(4, -1);
+ mkldnn_sizes[MklDnnDims::Dim_O] = out_depth;
+ mkldnn_sizes[MklDnnDims::Dim_I] = in_depth;
+ mkldnn_sizes[MklDnnDims::Dim_H] = filter_rows;
+ mkldnn_sizes[MklDnnDims::Dim_W] = filter_cols;
+
+ *filter_dims = mkldnn_sizes;
+ } else { // Conv3D
+ OP_REQUIRES(context_, input_depth == filter_shape.dim_size(3),
+ errors::InvalidArgument(
+ "input and filter must have the same depth: ",
+ input_depth, " vs ", filter_shape.dim_size(3)));
+
+ // TF filter is always in (planes, rows, cols, in_depth, out_depth) order.
+ int filter_planes = static_cast<int>(filter_shape.dim_size(0));
+ int filter_rows = static_cast<int>(filter_shape.dim_size(1));
+ int filter_cols = static_cast<int>(filter_shape.dim_size(2));
+ int in_depth = static_cast<int>(filter_shape.dim_size(3));
+ int out_depth = static_cast<int>(filter_shape.dim_size(4));
+
+ // MKL-DNN always needs filter in OIDHW format.
+ // OIDHW = (out_depth, in_depth, planes, rows, cols)
+ std::vector<int> mkldnn_sizes(5, -1);
+ mkldnn_sizes[MklDnnDims3D::Dim3d_O] = out_depth;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_I] = in_depth;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_D] = filter_planes;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_H] = filter_rows;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_W] = filter_cols;
+
+ *filter_dims = mkldnn_sizes;
+ }
}
- // Calculate Convolution filter size in MKL-DNN order. MKL-DNN
- // requires filter in OIHW format. Function does not return anything.
- // But errors arising from sanity checks are returned in context's
- // status.
+ // Calculate Convolution filter size in MKL-DNN order.
+ // MKL-DNN requires filter in OIHW (Conv2D) or OIDHW(Conv3D format.
+ // Function does not return anything. But errors arising from sanity
+ // checks are returned in context's status.
virtual inline void GetFilterSizeInMklOrder(size_t src_index,
size_t filter_index,
memory::dims* filter_dims) {
@@ -206,8 +269,8 @@ class MklDnnConvUtil {
GetTfShape(context_, filter_index), filter_dims);
}
- // Calculate Bias size for 2D Convolution. Function does not return
- // anything, but sets error in context status.
+ // Calculate Bias size for 2D or 3D Convolution. Function does not
+ // return anything, but may set an error in context status.
virtual inline void GetBiasSizeInMklOrder(size_t bias_index,
memory::dims* bias_dims) {
const Tensor& bias = MklGetInput(context_, bias_index);
@@ -218,73 +281,142 @@ class MklDnnConvUtil {
*bias_dims = {static_cast<int>(bias.dim_size(0))};
}
- // Function to calculate output and padding size for 2D convolution.
+ // Function to calculate output and padding size for 2D/3D convolution.
//
// Calculate output shape of Convolution in MKL-DNN and TensorFlow order.
- // MKL-DNN uses NCHW for output order. But TensorFlow output will be in
- // NHWC or NCHW format depending on data format. Function also calculates
- // left, right, top and bottom pads. Function does not return any status -
- // status is returned via context status.
+ // MKL-DNN uses NCHW(Conv2D) or NCDHW(Conv3D) for output order.
+ // But TensorFlow output will be in NHWC||NCHW(Conv2D) or
+ // NDHWC||NCDHW(Conv3D) format depending on data format.
+ // Function also calculates left, right, top and bottom pads.
+ // Function does not return any status which is set with context status.
//
// TODO(nhasabni): Add similar function for input and filter in MklShape.
virtual inline void GetOutputAndPadSizeInMklOrder(
const TensorShape& input_shape, const TensorShape& filter_shape,
const memory::dims& strides, const memory::dims& dilations,
- memory::dims* output_dims_tf_order,
- memory::dims* output_dims_mkl_order, memory::dims* pad_l,
- memory::dims* pad_r) {
+ memory::dims* output_dims_tf_order, memory::dims* output_dims_mkl_order,
+ memory::dims* pad_l, memory::dims* pad_r) {
CHECK_NOTNULL(output_dims_tf_order);
CHECK_NOTNULL(output_dims_mkl_order);
CHECK_NOTNULL(pad_l);
CHECK_NOTNULL(pad_r);
- int input_rows = GetTensorDim(input_shape, data_format_, 'H');
- int input_cols = GetTensorDim(input_shape, data_format_, 'W');
+ bool isConv2D = (strides_.size() == 4);
+ int input_planes, input_rows, input_cols;
+ if (isConv2D) {
+ input_rows = GetTensorDim(input_shape, data_format_, 'H');
+ input_cols = GetTensorDim(input_shape, data_format_, 'W');
+ } else {
+ input_planes = GetTensorDim(input_shape, data_format_, '0');
+ input_rows = GetTensorDim(input_shape, data_format_, '1');
+ input_cols = GetTensorDim(input_shape, data_format_, '2');
+ }
- // The first dimension for filter is rows/height.
- int filter_rows = filter_shape.dim_size(0);
- // The second dimension for filter is cols/width.
- int filter_cols = filter_shape.dim_size(1);
+ // Filter dimension
+ // Conv2D:
+ // First dimension: rows/height.
+ // Second dimension: cols/width.
+ // Conv3D:
+ // First dimension: planes/depth.
+ // Second dimension: rows/height.
+ // Third dimension: cols/width.
+
+ int filter_planes, filter_rows, filter_cols;
+ if (isConv2D) {
+ filter_rows = filter_shape.dim_size(0);
+ filter_cols = filter_shape.dim_size(1);
+ } else {
+ filter_planes = filter_shape.dim_size(0);
+ filter_rows = filter_shape.dim_size(1);
+ filter_cols = filter_shape.dim_size(2);
+ }
- // Stride is vector of 2 elements: {s_r, s_c}
- int stride_rows = strides[0];
- int stride_cols = strides[1];
- int dilation_rows = dilations[0];
- int dilation_cols = dilations[1];
+ int stride_planes, stride_rows, stride_cols;
+ int dilation_planes, dilation_rows, dilation_cols;
+ if (isConv2D) {
+ // Conv2D stride is a vector of 2 elements: {s_r, s_c}
+ stride_rows = strides[0];
+ stride_cols = strides[1];
+ dilation_rows = dilations[0];
+ dilation_cols = dilations[1];
+ } else {
+ // Conv3D stride is a vector of 3 elements: {s_d, s_r, s_c}
+ stride_planes = strides[0];
+ stride_rows = strides[1];
+ stride_cols = strides[2];
+ dilation_planes = dilations[0];
+ dilation_rows = dilations[1];
+ dilation_cols = dilations[2];
+ }
// Output batch is same as input batch.
int out_batch = GetTensorDim(input_shape, data_format_, 'N');
+
// Output depth is same as last dimension for filter.
- int out_depth = filter_shape.dim_size(3);
+ int out_depth = filter_shape.dim_size(isConv2D ? 3 : 4);
- int64 out_rows = 0, out_cols = 0;
+ int64 out_rows = 0, out_cols = 0, out_planes = 0;
int64 pad_top = 0, pad_bottom = 0, pad_left, pad_right;
+ int64 pad_D1, pad_D2;
+
+ if (isConv2D) {
+ OP_REQUIRES_OK(context_,
+ GetWindowedOutputSizeVerboseV2(
+ input_rows, filter_rows, dilation_rows, stride_rows,
+ padding_, &out_rows, &pad_top, &pad_bottom));
+ OP_REQUIRES_OK(context_,
+ GetWindowedOutputSizeVerboseV2(
+ input_cols, filter_cols, dilation_cols, stride_cols,
+ padding_, &out_cols, &pad_left, &pad_right));
+ } else {
+ OP_REQUIRES_OK(context_, GetWindowedOutputSizeVerbose(
+ input_planes, filter_planes, stride_planes,
+ padding_, &out_planes, &pad_D1, &pad_D2));
+ OP_REQUIRES_OK(context_, GetWindowedOutputSizeVerbose(
+ input_rows, filter_rows, stride_rows,
+ padding_, &out_rows, &pad_top, &pad_bottom));
+ OP_REQUIRES_OK(context_, GetWindowedOutputSizeVerbose(
+ input_cols, filter_cols, stride_cols,
+ padding_, &out_cols, &pad_left, &pad_right));
+ }
- OP_REQUIRES_OK(context_,
- GetWindowedOutputSizeVerboseV2(input_rows, filter_rows,
- dilation_rows, stride_rows, padding_,
- &out_rows, &pad_top, &pad_bottom));
- OP_REQUIRES_OK(context_,
- GetWindowedOutputSizeVerboseV2(input_cols, filter_cols,
- dilation_cols, stride_cols, padding_,
- &out_cols, &pad_left, &pad_right));
-
- // Tensorflow output is in data_format order. (NHWC or NCHW)
+ // Tensorflow output is in data_format order.
+ // Conv2D: NHWC or NCHW
+ // Conv3D: NDHWC or NCDHW
+ // MKL-DNN uses asymetric padding.
TensorShape out_shape =
- ShapeFromFormat(data_format_, out_batch, out_rows, out_cols, out_depth);
+ isConv2D
+ ? ShapeFromFormat(data_format_, out_batch, out_rows, out_cols,
+ out_depth)
+ : ShapeFromFormat(data_format_, out_batch,
+ {{out_planes, out_rows, out_cols}}, out_depth);
*output_dims_tf_order = TFShapeToMklDnnDims(out_shape);
- // MKL-DNN always needs output in NCHW format.
- std::vector<int> mkldnn_sizes(4, -1);
- mkldnn_sizes[MklDnnDims::Dim_N] = out_batch;
- mkldnn_sizes[MklDnnDims::Dim_C] = out_depth;
- mkldnn_sizes[MklDnnDims::Dim_H] = static_cast<int>(out_rows);
- mkldnn_sizes[MklDnnDims::Dim_W] = static_cast<int>(out_cols);
- *output_dims_mkl_order = mkldnn_sizes;
-
- // Now handle padding. MKL-DNN uses asymetric padding.
- *pad_l = {static_cast<int>(pad_top), static_cast<int>(pad_left)};
- *pad_r = {static_cast<int>(pad_bottom), static_cast<int>(pad_right)};
+ if (isConv2D) {
+ // For Conv2D, MKL-DNN always needs output in NCHW format.
+ std::vector<int> mkldnn_sizes(4, -1);
+ mkldnn_sizes[MklDnnDims::Dim_N] = out_batch;
+ mkldnn_sizes[MklDnnDims::Dim_C] = out_depth;
+ mkldnn_sizes[MklDnnDims::Dim_H] = static_cast<int>(out_rows);
+ mkldnn_sizes[MklDnnDims::Dim_W] = static_cast<int>(out_cols);
+ *output_dims_mkl_order = mkldnn_sizes;
+
+ *pad_l = {static_cast<int>(pad_top), static_cast<int>(pad_left)};
+ *pad_r = {static_cast<int>(pad_bottom), static_cast<int>(pad_right)};
+ } else {
+ std::vector<int> mkldnn_sizes(5, -1);
+ mkldnn_sizes[MklDnnDims3D::Dim3d_N] = out_batch;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_C] = out_depth;
+ mkldnn_sizes[MklDnnDims3D::Dim3d_D] = static_cast<int>(out_planes);
+ mkldnn_sizes[MklDnnDims3D::Dim3d_H] = static_cast<int>(out_rows);
+ mkldnn_sizes[MklDnnDims3D::Dim3d_W] = static_cast<int>(out_cols);
+ *output_dims_mkl_order = mkldnn_sizes;
+
+ *pad_l = {static_cast<int>(pad_D1), static_cast<int>(pad_top),
+ static_cast<int>(pad_left)};
+ *pad_r = {static_cast<int>(pad_D2), static_cast<int>(pad_bottom),
+ static_cast<int>(pad_right)};
+ }
}
// Calculate output and pad size of forward Convolution operator.
@@ -292,10 +424,10 @@ class MklDnnConvUtil {
//
// Function does not return anything, but sets error in context status.
inline void GetOutputAndPadSizeInMklOrder(
- size_t src_index, size_t filter_index,
- const memory::dims& strides, const memory::dims& dilations,
- memory::dims* output_dims_tf_order, memory::dims* output_dims_mkl_order,
- memory::dims* pad_l, memory::dims* pad_r) {
+ size_t src_index, size_t filter_index, const memory::dims& strides,
+ const memory::dims& dilations, memory::dims* output_dims_tf_order,
+ memory::dims* output_dims_mkl_order, memory::dims* pad_l,
+ memory::dims* pad_r) {
CHECK_NOTNULL(output_dims_tf_order);
CHECK_NOTNULL(output_dims_mkl_order);
CHECK_NOTNULL(pad_l);
@@ -304,9 +436,17 @@ class MklDnnConvUtil {
auto input_tf_shape = GetTfShape(context_, src_index);
auto filter_tf_shape = GetTfShape(context_, filter_index);
- OP_REQUIRES(context_, input_tf_shape.dims() == 4,
- errors::InvalidArgument("input must be 4-dimensional",
- input_tf_shape.DebugString()));
+ if (strides_.size() == 4) {
+ // Conv2D
+ OP_REQUIRES(context_, input_tf_shape.dims() == 4,
+ errors::InvalidArgument("input must be 4-dimensional",
+ input_tf_shape.DebugString()));
+ } else {
+ // Conv3D
+ OP_REQUIRES(context_, input_tf_shape.dims() == 5,
+ errors::InvalidArgument("input must be 5-dimensional",
+ input_tf_shape.DebugString()));
+ }
GetOutputAndPadSizeInMklOrder(input_tf_shape, filter_tf_shape,
strides, dilations, output_dims_tf_order,
@@ -314,9 +454,11 @@ class MklDnnConvUtil {
}
// Wrapper function to calculate input, filter, and output sizes of
- // 2D Convolution in MKL order (NCHW for input and output; OIHW for filter.)
- // Function also calculates output shape in Tensorflow order. Additionally, it
- // also calculates strides and paddings for 2D Convolution.
+ // Conv2D/Conv3D in MKL order:
+ // Conv2D: NCHW for input and output; OIHW for filter.
+ // Conv3D: NCDHW for input and output; OIDHW for filter.
+ // Function also calculates output shape in Tensorflow order.
+ // Additionally, it also calculates strides and paddings.
//
// Function does not return anything, but sets error in context status.
inline void GetConvFwdSizesInMklOrder(
@@ -349,16 +491,15 @@ class MklDnnConvUtil {
}
};
-
/////////////////////////////////////////////////////////////////////
-/// Common class that implements Conv2DBackpropFilter and Input
+/// Common class that implements ConvBackpropFilter and Input
/////////////////////////////////////////////////////////////////////
template <typename Device, class T>
-class MklConv2DBackpropCommonOp : public OpKernel {
+class MklConvBackpropCommonOp : public OpKernel {
public:
- ~MklConv2DBackpropCommonOp() {}
- explicit MklConv2DBackpropCommonOp(OpKernelConstruction* context)
+ ~MklConvBackpropCommonOp() {}
+ explicit MklConvBackpropCommonOp(OpKernelConstruction* context)
: OpKernel(context) {
string data_format_str;
OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format_str));
@@ -372,20 +513,25 @@ class MklConv2DBackpropCommonOp : public OpKernel {
errors::InvalidArgument("Current implementation does not yet support "
"strides in the batch and depth dimensions."));
OP_REQUIRES_OK(context, context->GetAttr("dilations", &dilations_));
- OP_REQUIRES(context, dilations_.size() == 4,
- errors::InvalidArgument("Sliding window dilations field must "
- "specify 4 dimensions"));
- int dilation_n = GetTensorDim(dilations_, data_format_, 'N');
- int dilation_c = GetTensorDim(dilations_, data_format_, 'C');
- int dilation_h = GetTensorDim(dilations_, data_format_, 'H');
- int dilation_w = GetTensorDim(dilations_, data_format_, 'W');
- OP_REQUIRES(context, (dilation_n == 1 && dilation_c == 1),
- errors::InvalidArgument(
- "Current implementation does not yet support "
- "dilations in the batch and depth dimensions."));
- OP_REQUIRES(
- context, dilation_h > 0 && dilation_w > 0,
- errors::InvalidArgument("Dilated rates should be larger than 0."));
+
+ if (strides_.size() == 4) {
+ // Check Conv2D dilations
+ OP_REQUIRES(context, dilations_.size() == 4,
+ errors::InvalidArgument("Sliding window dilations field must "
+ "specify 4 dimensions"));
+ int dilation_n = GetTensorDim(dilations_, data_format_, 'N');
+ int dilation_c = GetTensorDim(dilations_, data_format_, 'C');
+ int dilation_h = GetTensorDim(dilations_, data_format_, 'H');
+ int dilation_w = GetTensorDim(dilations_, data_format_, 'W');
+ OP_REQUIRES(context, (dilation_n == 1 && dilation_c == 1),
+ errors::InvalidArgument(
+ "Current implementation does not yet support "
+ "dilations in the batch and depth dimensions."));
+ OP_REQUIRES(
+ context, dilation_h > 0 && dilation_w > 0,
+ errors::InvalidArgument("Dilated rates should be larger than 0."));
+ }
+
OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
}
@@ -397,8 +543,7 @@ class MklConv2DBackpropCommonOp : public OpKernel {
TensorFormat data_format_; // NCHW or NHWC
};
-#endif // INTEL_MKL_ML
-
+#endif // INTEL_MKL_ML_ONLY
/////////////////////////////////////////////////////////////////////
/// Dummy Mkl op that is just used for operators that are intermediate
diff --git a/tensorflow/core/kernels/mkl_fused_batch_norm_op.cc b/tensorflow/core/kernels/mkl_fused_batch_norm_op.cc
index 0149e78db5..2ec6c8fa89 100644
--- a/tensorflow/core/kernels/mkl_fused_batch_norm_op.cc
+++ b/tensorflow/core/kernels/mkl_fused_batch_norm_op.cc
@@ -21,8 +21,7 @@ limitations under the License.
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/util/tensor_format.h"
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::batch_normalization_backward;
using mkldnn::batch_normalization_forward;
@@ -41,7 +40,7 @@ using mkldnn::use_scale_shift;
namespace tensorflow {
using CPUDevice = Eigen::ThreadPoolDevice;
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklFusedBatchNormOp : public OpKernel {
@@ -684,7 +683,7 @@ class MklFusedBatchNormGradOp : public OpKernel {
};
#endif
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
struct MklBatchNormFwdParams {
memory::dims src_dims;
@@ -899,8 +898,8 @@ class MklFusedBatchNormFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
MklFusedBatchNormFwdPrimitiveFactory() {}
~MklFusedBatchNormFwdPrimitiveFactory() {}
- static std::string CreateKey(const MklBatchNormFwdParams& fwdParams) {
- std::string prefix = "bn_fwd";
+ static string CreateKey(const MklBatchNormFwdParams& fwdParams) {
+ string prefix = "bn_fwd";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(fwdParams.src_dims);
@@ -911,13 +910,13 @@ class MklFusedBatchNormFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
}
MklPrimitive* GetBatchNormFwd(const MklBatchNormFwdParams& fwdParams) {
- std::string key = CreateKey(fwdParams);
+ string key = CreateKey(fwdParams);
return this->GetOp(key);
}
void SetBatchNormFwd(const MklBatchNormFwdParams& fwdParams,
MklPrimitive* op) {
- std::string key = CreateKey(fwdParams);
+ string key = CreateKey(fwdParams);
this->SetOp(key, op);
}
};
@@ -1122,8 +1121,8 @@ class MklFusedBatchNormBwdPrimitiveFactory : public MklPrimitiveFactory<T> {
MklFusedBatchNormBwdPrimitiveFactory() {}
~MklFusedBatchNormBwdPrimitiveFactory() {}
- static std::string CreateKey(const MklBatchNormBwdParams& bwdParams) {
- std::string prefix = "bn_bwd";
+ static string CreateKey(const MklBatchNormBwdParams& bwdParams) {
+ string prefix = "bn_bwd";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(bwdParams.src_dims);
@@ -1135,13 +1134,13 @@ class MklFusedBatchNormBwdPrimitiveFactory : public MklPrimitiveFactory<T> {
}
MklPrimitive* GetBatchNormBwd(const MklBatchNormBwdParams& bwdParams) {
- std::string key = CreateKey(bwdParams);
+ string key = CreateKey(bwdParams);
return this->GetOp(key);
}
void SetBatchNormBwd(const MklBatchNormBwdParams& bwdParams,
MklPrimitive* op) {
- std::string key = CreateKey(bwdParams);
+ string key = CreateKey(bwdParams);
this->SetOp(key, op);
}
};
diff --git a/tensorflow/core/kernels/mkl_identity_op.cc b/tensorflow/core/kernels/mkl_identity_op.cc
index b02cc5384c..b57e816028 100644
--- a/tensorflow/core/kernels/mkl_identity_op.cc
+++ b/tensorflow/core/kernels/mkl_identity_op.cc
@@ -24,20 +24,20 @@ limitations under the License.
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
#include "mkl_dnn.h"
#include "mkl_dnn_types.h"
#endif
#include "tensorflow/core/util/mkl_util.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
#endif
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklIdentityOp : public OpKernel {
diff --git a/tensorflow/core/kernels/mkl_input_conversion_op.cc b/tensorflow/core/kernels/mkl_input_conversion_op.cc
index dc4da33a06..06ce820ae9 100644
--- a/tensorflow/core/kernels/mkl_input_conversion_op.cc
+++ b/tensorflow/core/kernels/mkl_input_conversion_op.cc
@@ -32,7 +32,7 @@ limitations under the License.
#include "tensorflow/core/kernels/mkl_tfconv_op.h"
#include "tensorflow/core/util/mkl_util.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::stream;
@@ -60,7 +60,7 @@ typedef Eigen::ThreadPoolDevice CPUDevice;
// convert the TF format input to MKL format
///////////////////////////////////////////////////////////
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklInputConversionOp : public OpKernel {
public:
diff --git a/tensorflow/core/kernels/mkl_lrn_op.cc b/tensorflow/core/kernels/mkl_lrn_op.cc
index 7966c271d5..22ff4cd80f 100644
--- a/tensorflow/core/kernels/mkl_lrn_op.cc
+++ b/tensorflow/core/kernels/mkl_lrn_op.cc
@@ -35,7 +35,7 @@ limitations under the License.
#include "tensorflow/core/util/work_sharder.h"
#endif
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::lrn_across_channels;
using mkldnn::lrn_backward;
@@ -69,7 +69,7 @@ void GetBandMatrix(int depth, int depth_radius,
} // namespace
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename T>
class MklLRNOp : public OpKernel {
@@ -1345,7 +1345,7 @@ class MklLRNGradOp : public OpKernel {
float beta_;
};
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
#define REGISTER_MKL_LRN_CPU(T) \
REGISTER_KERNEL_BUILDER(Name("_MklLRN") \
diff --git a/tensorflow/core/kernels/mkl_matmul_op.cc b/tensorflow/core/kernels/mkl_matmul_op.cc
index fd261433a0..077d62ce32 100644
--- a/tensorflow/core/kernels/mkl_matmul_op.cc
+++ b/tensorflow/core/kernels/mkl_matmul_op.cc
@@ -31,7 +31,7 @@ limitations under the License.
#include "tensorflow/core/kernels/fill_functor.h"
// This header file is part of MKL ML, need equivalent file in MKL DNN
-#ifndef DO_NOT_USE_ML
+#ifndef INTEL_MKL_DNN_ONLY
#include "mkl_cblas.h"
#else
#include "mkldnn.h"
@@ -155,7 +155,7 @@ class MklMatMulOp : public OpKernel {
// 1.0 and 0.0 respectively.
const float alpha = 1.0f;
const float beta = 0.0f;
-#if defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL_DNN_ONLY)
const char* const ftrans[] = {"N", "T", "C"};
int index_transa = transa ? 1 : 0;
int index_transb = transb ? 1 : 0;
@@ -173,7 +173,7 @@ class MklMatMulOp : public OpKernel {
}
// MKLDNN only supports SGEMM
-#ifndef DO_NOT_USE_ML
+#ifndef INTEL_MKL_DNN_ONLY
// Matrix-Matrix Multiplication with FP64 tensors. For detailed info about
// parameters, look at FP32 function description.
@@ -229,7 +229,7 @@ class MklMatMulOp : public OpKernel {
// additional types
TF_CALL_float(REGISTER_CPU);
-#ifndef DO_NOT_USE_ML
+#ifndef INTEL_MKL_DNN_ONLY
TF_CALL_double(REGISTER_CPU);
TF_CALL_complex64(REGISTER_CPU);
TF_CALL_complex128(REGISTER_CPU);
diff --git a/tensorflow/core/kernels/mkl_maxpooling_op.cc b/tensorflow/core/kernels/mkl_maxpooling_op.cc
index 0a2151566e..e149f003e5 100644
--- a/tensorflow/core/kernels/mkl_maxpooling_op.cc
+++ b/tensorflow/core/kernels/mkl_maxpooling_op.cc
@@ -22,7 +22,7 @@ limitations under the License.
#include "tensorflow/core/util/mkl_util.h"
#include "tensorflow/core/util/padding.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include <algorithm>
#include "mkldnn.hpp"
using mkldnn::algorithm;
@@ -40,7 +40,7 @@ namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
// MKL-DNN is now default. MKL-ML must be specified explicitly.
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// An implementation of MaxPooling (forward).
template <typename Device, typename T>
@@ -817,7 +817,7 @@ class MklMaxPoolingGradOp : public MklPoolingBackwardOpBase<T> {
}
}; // MklMaxPoolingGradOp
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
REGISTER_KERNEL_BUILDER(Name("_MklMaxPool")
.Device(DEVICE_CPU)
diff --git a/tensorflow/core/kernels/mkl_pooling_ops_common.cc b/tensorflow/core/kernels/mkl_pooling_ops_common.cc
index 915878d9ea..d7ad3f9dcd 100644
--- a/tensorflow/core/kernels/mkl_pooling_ops_common.cc
+++ b/tensorflow/core/kernels/mkl_pooling_ops_common.cc
@@ -223,7 +223,7 @@ void MklPoolParameters::Init(OpKernelContext* context,
Init(context, ksize, stride, padding, data_format);
}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// Initialization for MKL format
void MklPoolParameters::Init(OpKernelContext* context,
const std::vector<int32>& ksize,
@@ -253,7 +253,7 @@ void MklPoolParameters::Init(OpKernelContext* context,
Init(context, ksize, stride, padding, data_format);
}
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
// Common Initialization for TensorFlow and MKL formats
void MklPoolParameters::Init(OpKernelContext* context,
const std::vector<int32>& ksize,
@@ -288,7 +288,7 @@ void MklPoolParameters::Init(OpKernelContext* context,
OP_REQUIRES_OK(context, GetWindowedOutputSizeVerbose(
tensor_in_cols, window_cols, col_stride,
padding, &out_width, &pad_left, &pad_right));
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
// TF can work with int64, but mkldnn only supports int32
// Fail if the height or width are greater than MAX_INT
diff --git a/tensorflow/core/kernels/mkl_pooling_ops_common.h b/tensorflow/core/kernels/mkl_pooling_ops_common.h
index 9c516afbd0..ec7af5092d 100644
--- a/tensorflow/core/kernels/mkl_pooling_ops_common.h
+++ b/tensorflow/core/kernels/mkl_pooling_ops_common.h
@@ -22,7 +22,7 @@ limitations under the License.
#include "tensorflow/core/util/mkl_util.h"
#include "tensorflow/core/util/padding.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::memory;
using mkldnn::pooling_backward;
@@ -175,8 +175,8 @@ class MklPoolingFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
// primitive op from reuse perspective.
// A pooling key is a string which concates key parameters
// as well as algorithm kind (max versus avg).
- static std::string CreateKey(const MklPoolingParams& fwdParams) {
- std::string prefix = "pooling_fwd";
+ static string CreateKey(const MklPoolingParams& fwdParams) {
+ string prefix = "pooling_fwd";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(fwdParams.src_dims);
@@ -190,12 +190,12 @@ class MklPoolingFwdPrimitiveFactory : public MklPrimitiveFactory<T> {
}
MklPrimitive* GetPoolingFwd(const MklPoolingParams& fwdParams) {
- std::string key = CreateKey(fwdParams);
+ string key = CreateKey(fwdParams);
return this->GetOp(key);
}
void SetPoolingFwd(const MklPoolingParams& fwdParams, MklPrimitive* op) {
- std::string key = CreateKey(fwdParams);
+ string key = CreateKey(fwdParams);
this->SetOp(key, op);
}
};
@@ -326,8 +326,8 @@ class MklPoolingBwdPrimitiveFactory : public MklPrimitiveFactory<T> {
// primitive op from reuse perspective.
// A pooling key is a string which concates key parameters
// as well as algorithm kind (max versus avg).
- static std::string CreateKey(const MklPoolingParams& bwdParams) {
- std::string prefix = "pooling_bwd";
+ static string CreateKey(const MklPoolingParams& bwdParams) {
+ string prefix = "pooling_bwd";
FactoryKeyCreator key_creator;
key_creator.AddAsKey(prefix);
key_creator.AddAsKey(bwdParams.src_dims);
@@ -341,12 +341,12 @@ class MklPoolingBwdPrimitiveFactory : public MklPrimitiveFactory<T> {
}
MklPrimitive* GetPoolingBwd(const MklPoolingParams& bwdParams) {
- std::string key = CreateKey(bwdParams);
+ string key = CreateKey(bwdParams);
return this->GetOp(key);
}
void SetPoolingBwd(const MklPoolingParams& bwdParams, MklPrimitive* op) {
- std::string key = CreateKey(bwdParams);
+ string key = CreateKey(bwdParams);
this->SetOp(key, op);
}
};
@@ -405,7 +405,7 @@ struct MklPoolParameters {
void Init(OpKernelContext* context, const std::vector<int32>& ksize,
const std::vector<int32>& stride, Padding padding,
TensorFormat data_format, const TensorShape& tensor_in_shape);
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
void Init(OpKernelContext* context, const std::vector<int32>& ksize,
const std::vector<int32>& stride, Padding padding,
TensorFormat data_format, const MklShape* mkl_in_shape);
@@ -422,7 +422,7 @@ struct MklPoolParameters {
TensorFormat data_format);
};
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
template <class T>
class MklPoolingOpBase : public OpKernel {
@@ -674,7 +674,7 @@ class MklPoolingBackwardOpBase : public MklPoolingOpBase<T> {
return grad_reorder_needed ? target_diff_dst_md : original_input_grad_md;
}
};
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
//-------------------------------------------------------------------
// Utility functions
diff --git a/tensorflow/core/kernels/mkl_relu_op.cc b/tensorflow/core/kernels/mkl_relu_op.cc
index 78abbdb730..05034894e5 100644
--- a/tensorflow/core/kernels/mkl_relu_op.cc
+++ b/tensorflow/core/kernels/mkl_relu_op.cc
@@ -23,8 +23,7 @@ limitations under the License.
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/errors.h"
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::algorithm;
@@ -58,7 +57,7 @@ struct MklReluHelpers {
}
};
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
template <typename Device, typename T>
class MklReluOp : public OpKernel {
@@ -368,10 +367,7 @@ void MklReluGradOp<Device, T>::Compute(OpKernelContext* context) {
mkl_context.MklCleanup();
}
-
-
-#else // INTEL_MKL_ML
-
+#else // INTEL_MKL_ML_ONLY
template <typename Device, typename T, algorithm alg_kind>
class MklReluOpBase : public OpKernel {
@@ -874,7 +870,7 @@ class MklTanhGradOp : public MklReluGradOpBase<Device, T, eltwise_tanh> {
MklReluGradOp<CPUDevice, type>);
TF_CALL_float(REGISTER_RELU_MKL_SUPPORTED_KERNELS_TYPES);
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
// register dnn kernels for supported operations and supported types
#define REGISTER_ELU_MKL_SUPPORTED_KERNELS_TYPES(type) \
diff --git a/tensorflow/core/kernels/mkl_reshape_op.cc b/tensorflow/core/kernels/mkl_reshape_op.cc
index 9c536df215..d9a7893a53 100644
--- a/tensorflow/core/kernels/mkl_reshape_op.cc
+++ b/tensorflow/core/kernels/mkl_reshape_op.cc
@@ -24,8 +24,7 @@ limitations under the License.
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
using mkldnn::stream;
#else
@@ -42,7 +41,7 @@ class MklReshapeOp : public OpKernel {
public:
explicit MklReshapeOp(OpKernelConstruction* context) : OpKernel(context) {}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
void Compute(OpKernelContext* context) override {
const Tensor& input = MklGetInput(context, 0);
const Tensor& sizes = MklGetInput(context, 1);
@@ -317,7 +316,7 @@ class MklReshapeOp : public OpKernel {
}
}
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
private:
const int kInputSlotIdx = 0;
diff --git a/tensorflow/core/kernels/mkl_softmax_op.cc b/tensorflow/core/kernels/mkl_softmax_op.cc
index 638392954e..8bde966be9 100644
--- a/tensorflow/core/kernels/mkl_softmax_op.cc
+++ b/tensorflow/core/kernels/mkl_softmax_op.cc
@@ -15,7 +15,7 @@ limitations under the License.
// See docs in ../ops/nn_ops.cc.
#ifdef INTEL_MKL
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/numeric_op.h"
@@ -153,5 +153,5 @@ TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES);
} // namespace tensorflow
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
#endif // INTEL_MKL
diff --git a/tensorflow/core/kernels/mkl_tfconv_op.h b/tensorflow/core/kernels/mkl_tfconv_op.h
index f4f0035f26..894c2e34e8 100644
--- a/tensorflow/core/kernels/mkl_tfconv_op.h
+++ b/tensorflow/core/kernels/mkl_tfconv_op.h
@@ -32,13 +32,13 @@ limitations under the License.
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/tensor_format.h"
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
#include "mkl_dnn.h"
#include "mkl_dnn_types.h"
#endif
#include "tensorflow/core/util/mkl_util.h"
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
using mkldnn::stream;
#endif
@@ -64,7 +64,7 @@ class MklToTfOp : public OpKernel {
VLOG(1) << "MKLToTFConversion complete successfully.";
}
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
static void ConvertMklToTf(OpKernel* op_kernel, OpKernelContext* context,
string data_format_str, DataType op_data_type,
bool has_avx512f, uint input_number) {
@@ -118,12 +118,11 @@ class MklToTfOp : public OpKernel {
CHECK(output_tensor->CopyFrom(input_tensor, output_shape));
}
} catch (mkldnn::error& e) {
- string error_msg = "Status: " + std::to_string(e.status) +
- ", message: " + std::string(e.message) + ", in file " +
- std::string(__FILE__) + ":" + std::to_string(__LINE__);
OP_REQUIRES_OK(
context,
- errors::Aborted("Operation received an exception:", error_msg));
+ errors::Aborted("Operation received an exception: Status: ", e.status,
+ ", message: ", StringPiece(e.message), ", in file ",
+ __FILE__, ":", __LINE__));
}
}
#else
diff --git a/tensorflow/core/kernels/mkl_transpose_op.cc b/tensorflow/core/kernels/mkl_transpose_op.cc
index b180c2ff20..6bbe271c54 100644
--- a/tensorflow/core/kernels/mkl_transpose_op.cc
+++ b/tensorflow/core/kernels/mkl_transpose_op.cc
@@ -15,13 +15,23 @@ limitations under the License.
// See docs in ../ops/array_ops.cc.
-#if defined(INTEL_MKL) && !defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL)
#define EIGEN_USE_THREADS
+#if !defined(INTEL_MKL_DNN_ONLY)
#include "mkl_trans.h"
+#endif
+
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/kernels/transpose_op.h"
+#ifndef INTEL_MKL_ML_ONLY
+#include "mkldnn.hpp"
+#include "tensorflow/core/util/mkl_util.h"
+
+using mkldnn::stream;
+#endif
+
namespace tensorflow {
// output = TransposeOp(T<any> input, T<int32> perm) takes a tensor
@@ -40,6 +50,7 @@ namespace tensorflow {
// REQUIRES: perm is a permutation.
namespace {
+#if !defined(INTEL_MKL_DNN_ONLY)
template <typename T>
Status MKLTranspose2D(const char trans, const Tensor& in, Tensor* out);
@@ -93,11 +104,64 @@ Status MKLTranspose2D<complex128>(const char trans, const Tensor& in,
static const char kMKLTranspose = 'T';
static const char kMKLConjugateTranspose = 'C';
+#endif // if !defined(INTEL_MKL_DNN_ONLY)
+
+#ifndef INTEL_MKL_ML_ONLY
+// MKL-DNN based Transpose implementation
+template <typename T>
+Status MKLTransposeND(OpKernelContext* ctx, const Tensor& in, Tensor* out,
+ const gtl::ArraySlice<int32>& perm);
+
+static inline memory::dims ReorderStrides(const memory::dims& strides,
+ const gtl::ArraySlice<int32>& perm) {
+ memory::dims reordered_strides;
+ reordered_strides.resize(strides.size());
+ for (size_t i = 0; i < strides.size(); ++i) {
+ reordered_strides[perm[i]] = strides[i];
+ }
+ return reordered_strides;
+}
+
+// Transpose of N-dimensional tensor using MKL-DNN
+template <typename T>
+Status MKLTransposeND(OpKernelContext* context, const Tensor& in_tensor,
+ Tensor* out_tensor, const gtl::ArraySlice<int32>& perm) {
+ try {
+ engine cpu_engine = engine(engine::cpu, 0);
+ MklDnnData<T> in(&cpu_engine);
+ MklDnnData<T> out(&cpu_engine);
+
+ memory::dims in_dims = TFShapeToMklDnnDims(in_tensor.shape());
+ memory::dims out_dims = TFShapeToMklDnnDims(out_tensor->shape());
+ memory::dims in_strides = CalculateTFStrides(in_dims);
+ // Reorder output strides based on permutation requested.
+ memory::dims out_strides =
+ ReorderStrides(CalculateTFStrides(out_dims), perm);
+
+ in.SetUsrMem(in_dims, in_strides, &in_tensor);
+ // Output dimensions are same as input dimensions. We adjust the layout
+ // using strides.
+ out.SetUsrMem(in_dims, out_strides, out_tensor);
+
+ std::vector<primitive> net;
+ net.push_back(in.CreateReorder(in.GetUsrMem(), out.GetUsrMem()));
+ stream(stream::kind::eager).submit(net).wait();
+ return Status::OK();
+ } catch (mkldnn::error& e) {
+ string error_msg = "Status: " + std::to_string(e.status) +
+ ", message: " + std::string(e.message) + ", in file " +
+ std::string(__FILE__) + ":" + std::to_string(__LINE__);
+ return errors::Aborted("Operation received an exception:", error_msg);
+ }
+}
+#endif // #ifndef INTEL_MKL_ML_ONLY
+
} // namespace
Status MklTransposeCpuOp::DoTranspose(OpKernelContext* ctx, const Tensor& in,
gtl::ArraySlice<int32> perm,
Tensor* out) {
+#if !defined(INTEL_MKL_DNN_ONLY)
if (in.dims() == 2) {
if (perm[0] == 0 && perm[1] == 1) {
return Status::OK();
@@ -115,7 +179,24 @@ Status MklTransposeCpuOp::DoTranspose(OpKernelContext* ctx, const Tensor& in,
break;
}
}
- // Fallback to eigen if transpose parameters not supported by MKL
+#endif
+
+#ifndef INTEL_MKL_ML_ONLY
+ // MKL-DNN has limit on the maximum number of dimensions in a tensor.
+ // Fallback to Eigen for not supported cases.
+ if (in.dims() <= TENSOR_MAX_DIMS) {
+ switch (in.dtype()) {
+ case DT_FLOAT:
+ return MKLTransposeND<float>(ctx, in, out, perm);
+ break;
+ // TODO(nhasabni): support other types such as INT8.
+ default:
+ break;
+ }
+ }
+#endif
+
+ // Fallback to eigen if transpose parameters not supported by MKL or MKL-DNN
typedef Eigen::ThreadPoolDevice CPUDevice;
return ::tensorflow::DoTranspose(ctx->eigen_device<CPUDevice>(), in, perm,
out);
@@ -125,6 +206,7 @@ Status MklConjugateTransposeCpuOp::DoTranspose(OpKernelContext* ctx,
const Tensor& in,
gtl::ArraySlice<int32> perm,
Tensor* out) {
+#if !defined(INTEL_MKL_DNN_ONLY)
if (in.dims() == 2 && perm[0] == 1 && perm[1] == 0) {
// TODO(rmlarsen): By setting lda and ldb, we could use the MKL kernels
// for any transpose that can be reduced to swapping the last two
@@ -143,7 +225,24 @@ Status MklConjugateTransposeCpuOp::DoTranspose(OpKernelContext* ctx,
break;
}
}
- // Fallback to eigen if transpose parameters not supported by MKL
+#endif
+
+#ifndef INTEL_MKL_ML_ONLY
+ // MKL-DNN has limit on the maximum number of dimensions in a tensor.
+ // Fallback to Eigen for not supported cases.
+ if (in.dims() <= TENSOR_MAX_DIMS) {
+ switch (in.dtype()) {
+ case DT_FLOAT:
+ return MKLTransposeND<float>(ctx, in, out, perm);
+ break;
+ // TODO(nhasabni): support other types such as INT8.
+ default:
+ break;
+ }
+ }
+#endif
+
+ // Fallback to eigen if transpose parameters not supported by MKL or MKL-DNN
typedef Eigen::ThreadPoolDevice CPUDevice;
return ::tensorflow::DoConjugateTranspose(ctx->eigen_device<CPUDevice>(), in,
perm, out);
diff --git a/tensorflow/core/kernels/non_max_suppression_op.cc b/tensorflow/core/kernels/non_max_suppression_op.cc
index c7d0d4de0d..5d9257e20b 100644
--- a/tensorflow/core/kernels/non_max_suppression_op.cc
+++ b/tensorflow/core/kernels/non_max_suppression_op.cc
@@ -126,7 +126,7 @@ void DoNonMaxSuppressionOp(
const Tensor& max_output_size, const float score_threshold,
const std::function<bool(int, int)>& suppress_check_fn,
bool pad_to_max_output_size = false, int* ptr_num_valid_outputs = nullptr) {
- const int output_size = std::min(max_output_size.scalar<int>()(), num_boxes);
+ const int output_size = max_output_size.scalar<int>()();
std::vector<float> scores_data(num_boxes);
std::copy_n(scores.flat<float>().data(), num_boxes, scores_data.begin());
diff --git a/tensorflow/core/kernels/padding_fifo_queue.cc b/tensorflow/core/kernels/padding_fifo_queue.cc
index ff553f11c9..a600d32897 100644
--- a/tensorflow/core/kernels/padding_fifo_queue.cc
+++ b/tensorflow/core/kernels/padding_fifo_queue.cc
@@ -347,7 +347,7 @@ Status HandleElementToLargerSliceWithRank(const Tensor& element, Tensor* parent,
default:
return errors::Unimplemented(
"HandleElementToLargerSliceWithRank Unhandled data type: ",
- element.dtype());
+ DataTypeString(element.dtype()));
}
}
@@ -392,7 +392,7 @@ Status PaddingFIFOQueue::SetElementZero(Tensor* element) {
TF_CALL_ALL_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
return errors::Unimplemented("SetElementZero Unhandled data type: ",
- element->dtype());
+ DataTypeString(element->dtype()));
}
std::vector<TensorShape> PaddingFIFOQueue::ConvertShapesPartialDimensionsToZero(
diff --git a/tensorflow/core/kernels/partitioned_function_ops.cc b/tensorflow/core/kernels/partitioned_function_ops.cc
index 33ed044dae..8db78f9784 100644
--- a/tensorflow/core/kernels/partitioned_function_ops.cc
+++ b/tensorflow/core/kernels/partitioned_function_ops.cc
@@ -98,7 +98,8 @@ class PartitionedCallOp : public AsyncOpKernel {
done);
auto graph = tensorflow::MakeUnique<Graph>(fbody->graph->flib_def());
CopyGraph(*fbody->graph, graph.get());
- OP_REQUIRES_OK_ASYNC(ctx, PinResourceArgs(graph.get(), args), done);
+ OP_REQUIRES_OK_ASYNC(ctx, PropagateInheritedDevices(graph.get(), args),
+ done);
DeviceSet device_set;
for (auto d : lib->device_mgr()->ListDevices()) {
@@ -162,10 +163,15 @@ class PartitionedCallOp : public AsyncOpKernel {
std::vector<AllocatorAttributes>>
ArgAndRetAllocAttrs;
+ // Propagates device annotations from the outer graph to the function body.
+ //
// Pins each arg that emits a `DT_RESOURCE` tensor to the device on which the
// corresponding resource lives. This ensures that the Placer assigns ops that
- // access these resources to the appropriate devices.
- Status PinResourceArgs(Graph* graph, const OpInputList& args) {
+ // access these resources to the appropriate devices. Additionally, places
+ // nodes that are unadorned with device annotations onto PartitiondCallOp's
+ // device. This lets call-site device annotations influence the execution
+ // of the function.
+ Status PropagateInheritedDevices(Graph* graph, const OpInputList& args) {
for (Node* node : graph->op_nodes()) {
string node_type = node->type_string();
if (node_type == FunctionLibraryDefinition::kArgOp) {
@@ -178,6 +184,18 @@ class PartitionedCallOp : public AsyncOpKernel {
ResourceHandle handle = args[index].flat<ResourceHandle>()(0);
node->set_assigned_device_name(handle.device());
}
+ } else if (node_type != FunctionLibraryDefinition::kRetOp) {
+ // All non-RetVal nodes that weren't explicitly placed by the user
+ // inherit PartitionedCallOp's device. RetVal placement is inferred by
+ // the placer, to avoid forcing the function's outputs through a single
+ // device.
+ //
+ // TODO(b/112166045): Plumb the original requested device into this
+ // OpKernel (this->requested_device() isn't reliable), and merge it
+ // with node->requested_device() if possible.
+ if (node->requested_device().empty()) {
+ node->set_requested_device(local_device_name_);
+ }
}
}
return Status::OK();
@@ -243,12 +261,6 @@ class PartitionedCallOp : public AsyncOpKernel {
// device, and
// (3) records which `Arg` and `Retval` nodes live in host memory.
Status UpdateArgAndRetMetadata(const string& device, Graph* subgraph) {
- if (arg_and_ret_indices_.find(device) != arg_and_ret_indices_.end()) {
- // This function has already been partitioned, albeit for a different
- // function library.
- return Status::OK();
- }
-
ArgAndRetIndices indices;
std::vector<int>* arg_indices = &indices.first;
std::vector<int>* ret_indices = &indices.second;
@@ -256,6 +268,8 @@ class PartitionedCallOp : public AsyncOpKernel {
std::vector<std::pair<Node*, int>> ret_nodes;
const AttrValue* attr_value;
+ // Find the Arg and Retval nodes, along with their corresponding indices
+ // in the original function.
for (Node* node : subgraph->op_nodes()) {
string node_type = node->type_string();
if (node_type == FunctionLibraryDefinition::kArgOp) {
@@ -271,6 +285,8 @@ class PartitionedCallOp : public AsyncOpKernel {
}
}
+ // Rewrite the indices of the Arg and Retval nodes for this function
+ // to range from 0 to the number of Arg nodes, Retval nodes, respectively.
auto sort_by_index = [](std::pair<Node*, int> one,
std::pair<Node*, int> two) -> bool {
return one.second < two.second;
@@ -300,7 +316,12 @@ class PartitionedCallOp : public AsyncOpKernel {
arg_and_ret_alloc_attrs_[device].second.push_back(alloc_attr);
}
- arg_and_ret_indices_.emplace(device, indices);
+ // If this kernel execution corresponds to a StatefulPartitionedCallOp,
+ // `arg_and_ret_indices_` might have been populated by a previous
+ // invocation.
+ if (arg_and_ret_indices_.find(device) == arg_and_ret_indices_.end()) {
+ arg_and_ret_indices_.emplace(device, indices);
+ }
return Status::OK();
}
diff --git a/tensorflow/core/kernels/pooling_ops_3d_gpu.h b/tensorflow/core/kernels/pooling_ops_3d_gpu.h
index 350b1b6732..2c3681455e 100644
--- a/tensorflow/core/kernels/pooling_ops_3d_gpu.h
+++ b/tensorflow/core/kernels/pooling_ops_3d_gpu.h
@@ -17,8 +17,8 @@ limitations under the License.
#error This file must only be included when building with Cuda support
#endif
-#ifndef TENSORFLOW_CORE_KERNELS_POOLING_OP_3D_GPU_H_
-#define TENSORFLOW_CORE_KERNELS_POOLING_OP_3D_GPU_H_
+#ifndef TENSORFLOW_CORE_KERNELS_POOLING_OPS_3D_GPU_H_
+#define TENSORFLOW_CORE_KERNELS_POOLING_OPS_3D_GPU_H_
#define EIGEN_USE_GPU
@@ -45,4 +45,4 @@ struct MaxPool3dGradBackward {
} // namespace tensorflow
-#endif // TENSORFLOW_CORE_KERNELS_POOLING_OP_3D_H_
+#endif // TENSORFLOW_CORE_KERNELS_POOLING_OPS_3D_GPU_H_
diff --git a/tensorflow/core/kernels/qr_op_impl.h b/tensorflow/core/kernels/qr_op_impl.h
index 0552c034d2..535df9d160 100644
--- a/tensorflow/core/kernels/qr_op_impl.h
+++ b/tensorflow/core/kernels/qr_op_impl.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_QR_OP_IMPL_H_
+#define TENSORFLOW_CORE_KERNELS_QR_OP_IMPL_H_
+
// See docs in ../ops/linalg_ops.cc.
//
// This header file is used by the individual qr_*op*.cc files for registering
@@ -292,6 +295,8 @@ class QrOpGpu : public AsyncOpKernel {
TF_DISALLOW_COPY_AND_ASSIGN(QrOpGpu);
};
-#endif
+#endif // GOOGLE_CUDA
} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_QR_OP_IMPL_H_
diff --git a/tensorflow/core/kernels/reduction_gpu_kernels.cu.h b/tensorflow/core/kernels/reduction_gpu_kernels.cu.h
index 9af4cc23b6..88b3c2ac76 100644
--- a/tensorflow/core/kernels/reduction_gpu_kernels.cu.h
+++ b/tensorflow/core/kernels/reduction_gpu_kernels.cu.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_REDUCTION_GPU_KERNELS_CU_H_
+#define TENSORFLOW_CORE_KERNELS_REDUCTION_GPU_KERNELS_CU_H_
+
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
@@ -1058,4 +1061,6 @@ struct ReduceFunctor<GPUDevice, Eigen::internal::OrReducer> {
} // namespace functor
} // namespace tensorflow
-#endif
+#endif // GOOGLE_CUDA
+
+#endif // TENSORFLOW_CORE_KERNELS_REDUCTION_GPU_KERNELS_CU_H_
diff --git a/tensorflow/core/kernels/regex_replace_op.cc b/tensorflow/core/kernels/regex_replace_op.cc
index 59ec854a79..a1b948891d 100644
--- a/tensorflow/core/kernels/regex_replace_op.cc
+++ b/tensorflow/core/kernels/regex_replace_op.cc
@@ -20,8 +20,43 @@ limitations under the License.
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
+#include "tensorflow/core/util/ptr_util.h"
namespace tensorflow {
+namespace {
+
+// Execute the specified regex using the given context.
+// Context requirements:
+// - "input" string Tensor at input_index=0
+// - "output" string Tensor at output_index=0
+Status InternalCompute(const RE2& match, const string& rewrite,
+ const bool replace_global, OpKernelContext* ctx) {
+ const Tensor* input_tensor;
+ TF_RETURN_IF_ERROR(ctx->input("input", &input_tensor));
+ Tensor* output_tensor;
+ std::unique_ptr<Tensor> maybe_forwarded =
+ ctx->forward_input(0 /*input_index*/, 0 /*output_index*/,
+ tensorflow::DT_STRING, input_tensor->shape(),
+ ctx->input_memory_type(0), ctx->input_alloc_attr(0));
+ if (maybe_forwarded) {
+ output_tensor = maybe_forwarded.get();
+ TF_RETURN_IF_ERROR(ctx->set_output("output", *output_tensor));
+ } else {
+ TF_RETURN_IF_ERROR(
+ ctx->allocate_output("output", input_tensor->shape(), &output_tensor));
+ output_tensor->flat<string>() = input_tensor->flat<string>();
+ }
+ auto output_flat = output_tensor->flat<string>();
+ for (size_t i = 0; i < output_flat.size(); ++i) {
+ if (replace_global) {
+ RE2::GlobalReplace(&output_flat(i), match, rewrite);
+ } else {
+ RE2::Replace(&output_flat(i), match, rewrite);
+ }
+ }
+ return Status::OK();
+}
+} // namespace
class RegexReplaceOp : public OpKernel {
public:
@@ -30,10 +65,6 @@ class RegexReplaceOp : public OpKernel {
}
void Compute(OpKernelContext* ctx) override {
- const Tensor* input_tensor;
- OP_REQUIRES_OK(ctx, ctx->input("input", &input_tensor));
- const auto& input_flat = input_tensor->flat<string>();
-
const Tensor* pattern_tensor;
OP_REQUIRES_OK(ctx, ctx->input("pattern", &pattern_tensor));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(pattern_tensor->shape()),
@@ -51,19 +82,7 @@ class RegexReplaceOp : public OpKernel {
errors::InvalidArgument("Rewrite must be scalar, but received ",
rewrite_tensor->shape().DebugString()));
const string rewrite = rewrite_tensor->flat<string>()(0);
-
- Tensor* output_tensor = nullptr;
- OP_REQUIRES_OK(ctx, ctx->allocate_output("output", input_tensor->shape(),
- &output_tensor));
- auto output_flat = output_tensor->flat<string>();
- for (size_t i = 0; i < input_flat.size(); ++i) {
- output_flat(i) = input_flat(i);
- if (replace_global_) {
- RE2::GlobalReplace(&output_flat(i), match, rewrite);
- } else {
- RE2::Replace(&output_flat(i), match, rewrite);
- }
- }
+ OP_REQUIRES_OK(ctx, InternalCompute(match, rewrite, replace_global_, ctx));
}
private:
@@ -73,4 +92,31 @@ class RegexReplaceOp : public OpKernel {
REGISTER_KERNEL_BUILDER(Name("RegexReplace").Device(DEVICE_CPU),
RegexReplaceOp);
+class StaticRegexReplaceOp : public OpKernel {
+ public:
+ explicit StaticRegexReplaceOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
+ string pattern;
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("pattern", &pattern));
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("rewrite", &rewrite_str_));
+ re_ = MakeUnique<RE2>(pattern);
+ OP_REQUIRES(ctx, re_->ok(),
+ errors::InvalidArgument("Invalid pattern: ", pattern,
+ ", error: ", re_->error()));
+ OP_REQUIRES_OK(ctx, ctx->GetAttr("replace_global", &replace_global_));
+ }
+
+ void Compute(OpKernelContext* ctx) override {
+ OP_REQUIRES_OK(ctx,
+ InternalCompute(*re_, rewrite_str_, replace_global_, ctx));
+ }
+
+ private:
+ string rewrite_str_;
+ std::unique_ptr<RE2> re_;
+ bool replace_global_;
+};
+
+REGISTER_KERNEL_BUILDER(Name("StaticRegexReplace").Device(DEVICE_CPU),
+ StaticRegexReplaceOp);
+
} // namespace tensorflow
diff --git a/tensorflow/core/kernels/regex_replace_op_test.cc b/tensorflow/core/kernels/regex_replace_op_test.cc
new file mode 100644
index 0000000000..9691d4a89f
--- /dev/null
+++ b/tensorflow/core/kernels/regex_replace_op_test.cc
@@ -0,0 +1,137 @@
+/* Copyright 2016 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.
+==============================================================================*/
+
+#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
+#include "tensorflow/core/framework/allocator.h"
+#include "tensorflow/core/framework/fake_input.h"
+#include "tensorflow/core/framework/node_def_builder.h"
+#include "tensorflow/core/framework/op_kernel.h"
+#include "tensorflow/core/framework/tensor.h"
+#include "tensorflow/core/framework/tensor_testutil.h"
+#include "tensorflow/core/framework/types.h"
+#include "tensorflow/core/framework/types.pb.h"
+#include "tensorflow/core/graph/node_builder.h"
+#include "tensorflow/core/kernels/ops_testutil.h"
+#include "tensorflow/core/kernels/ops_util.h"
+#include "tensorflow/core/lib/core/status_test_util.h"
+#include "tensorflow/core/platform/test.h"
+#include "tensorflow/core/platform/test_benchmark.h"
+
+namespace tensorflow {
+
+// Test data from the TensorFlow README.md.
+const char* lines[] = {
+ "**TensorFlow** is an open source software library for numerical "
+ "computation using 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/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 "
+ "organization for the purposes of conducting machine learning and deep "
+ "neural networks research.",
+ "The system is general enough to be applicable in a wide variety of other "
+ "domains, as well.",
+ "TensorFlow provides stable Python API and C APIs as well as without API "
+ "backwards compatibility guarantee like C++, Go, Java, JavaScript and "
+ "Swift."};
+
+const char kRegExPattern[] = "\\p{P}";
+const char kRewrite[] = " ";
+
+Tensor GetTestTensor(int batch) {
+ const int sz = TF_ARRAYSIZE(lines);
+ Tensor t(DT_STRING, {batch});
+ auto s = t.flat<string>();
+ for (int i = 0; i < batch; ++i) {
+ s(i) = lines[i % sz];
+ }
+ return t;
+}
+
+Graph* SetupRegexReplaceGraph(const Tensor& input, const string& input_pattern,
+ const string& input_rewrite) {
+ Graph* g = new Graph(OpRegistry::Global());
+ Tensor pattern(DT_STRING, TensorShape({}));
+ pattern.flat<string>().setConstant(input_pattern);
+ Tensor rewrite(DT_STRING, TensorShape({}));
+ rewrite.flat<string>().setConstant(input_rewrite);
+
+ TF_CHECK_OK(NodeBuilder("regex_replace_op", "RegexReplace")
+ .Input(test::graph::Constant(g, input))
+ .Input(test::graph::Constant(g, pattern))
+ .Input(test::graph::Constant(g, rewrite))
+ .Attr("replace_global", true)
+ .Finalize(g, nullptr /* node */));
+ return g;
+}
+
+void BM_RegexReplace(int iters, int batch_size) {
+ testing::StopTiming();
+ testing::ItemsProcessed(static_cast<int64>(iters));
+ testing::UseRealTime();
+ Tensor input = GetTestTensor(batch_size);
+ Graph* g = SetupRegexReplaceGraph(input, kRegExPattern, kRewrite);
+ testing::StartTiming();
+ test::Benchmark("cpu", g).Run(iters);
+}
+
+BENCHMARK(BM_RegexReplace)
+ ->Arg(1)
+ ->Arg(8)
+ ->Arg(16)
+ ->Arg(32)
+ ->Arg(64)
+ ->Arg(128)
+ ->Arg(256);
+
+Graph* SetupStaticGraph(const Tensor& input, const string& input_pattern,
+ const string& rewrite) {
+ Graph* g = new Graph(OpRegistry::Global());
+
+ TF_CHECK_OK(NodeBuilder("static_regex_replace_op", "StaticRegexReplace")
+ .Attr("pattern", input_pattern)
+ .Attr("rewrite", rewrite)
+ .Input(test::graph::Constant(g, input))
+ .Attr("replace_global", true)
+ .Finalize(g, nullptr /* node */));
+ return g;
+}
+void BM_StaticRegexReplace(int iters, int batch_size) {
+ testing::StopTiming();
+ testing::ItemsProcessed(static_cast<int64>(iters));
+ testing::UseRealTime();
+ Tensor input = GetTestTensor(batch_size);
+ Graph* g = SetupStaticGraph(input, kRegExPattern, kRewrite);
+ testing::StartTiming();
+ test::Benchmark("cpu", g).Run(iters);
+}
+
+BENCHMARK(BM_StaticRegexReplace)
+ ->Arg(1)
+ ->Arg(8)
+ ->Arg(16)
+ ->Arg(32)
+ ->Arg(64)
+ ->Arg(128)
+ ->Arg(256);
+
+} // end namespace tensorflow
diff --git a/tensorflow/core/kernels/resource_variable_ops.cc b/tensorflow/core/kernels/resource_variable_ops.cc
index cab9eb729d..ebcfb673d1 100644
--- a/tensorflow/core/kernels/resource_variable_ops.cc
+++ b/tensorflow/core/kernels/resource_variable_ops.cc
@@ -211,7 +211,8 @@ class AssignVariableOp : public OpKernel {
OP_REQUIRES(context, dtype_ == context->input(1).dtype(),
errors::InvalidArgument(
"Variable and value dtypes don't match; respectively, ",
- dtype_, " and ", context->input(1).dtype()));
+ DataTypeString(dtype_), " and ",
+ DataTypeString(context->input(1).dtype())));
Var* variable = nullptr;
const Tensor& value = context->input(1);
// Note: every resource-variable-manipulating op assumes copy-on-write
@@ -231,12 +232,12 @@ class AssignVariableOp : public OpKernel {
return Status::OK();
}));
core::ScopedUnref s(variable);
+ mutex_lock ml(*variable->mu());
OP_REQUIRES(context, variable->tensor()->dtype() == dtype_,
errors::InvalidArgument(
"Trying to assign variable with wrong dtype. Expected ",
DataTypeString(variable->tensor()->dtype()), " got ",
DataTypeString(dtype_)));
- mutex_lock ml(*variable->mu());
variable->is_initialized = true;
*variable->tensor() = value;
}
@@ -267,11 +268,6 @@ class AssignVariableOp<Device, Variant> : public OpKernel {
return Status::OK();
}));
core::ScopedUnref s(variable);
- OP_REQUIRES(context, variable->tensor()->dtype() == DT_VARIANT,
- errors::InvalidArgument(
- "Trying to assign variable with wrong dtype. Expected ",
- DataTypeString(variable->tensor()->dtype()), " got ",
- DataTypeString(DT_VARIANT)));
// For purposes of forwarding DT_VARIANT, we want the least
// restrictive attr; we already know the input is on host.
@@ -292,6 +288,11 @@ class AssignVariableOp<Device, Variant> : public OpKernel {
attr);
mutex_lock ml(*variable->mu());
+ OP_REQUIRES(context, variable->tensor()->dtype() == DT_VARIANT,
+ errors::InvalidArgument(
+ "Trying to assign variable with wrong dtype. Expected ",
+ DataTypeString(variable->tensor()->dtype()), " got ",
+ DataTypeString(DT_VARIANT)));
variable->is_initialized = true;
*variable->tensor() = Tensor(DT_VARIANT, value.shape());
diff --git a/tensorflow/core/kernels/save_restore_tensor.cc b/tensorflow/core/kernels/save_restore_tensor.cc
index 7930ce4615..e335e38bdc 100644
--- a/tensorflow/core/kernels/save_restore_tensor.cc
+++ b/tensorflow/core/kernels/save_restore_tensor.cc
@@ -25,6 +25,7 @@ limitations under the License.
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
+#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/logging.h"
@@ -96,7 +97,7 @@ void SaveTensors(
return tensor_names_flat(a) < tensor_names_flat(b);
});
- for (size_t i : sorted_name_idx) {
+ for (const size_t i : sorted_name_idx) {
const string& name = tensor_names_flat(i);
const Tensor& input = context->input(i + kFixedInputs);
TensorShape shape(input.shape());
@@ -333,6 +334,26 @@ Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix,
BundleReader default_reader(Env::Default(), prefix_string);
TF_RETURN_IF_ERROR(default_reader.status());
+ std::vector<string> mismatched_errors;
+ for (const size_t i : sorted_name_idx) {
+ TensorShape restored_full_shape;
+ DataType original_dtype;
+ const string& tensor_name = tensor_names_flat(i);
+ TF_RETURN_IF_ERROR(default_reader.LookupDtypeAndShape(
+ tensor_name, &original_dtype, &restored_full_shape));
+ if (dtypes[i] != original_dtype) {
+ string error_msg = strings::StrCat(
+ "tensor_name = ", tensor_name, "; expected dtype ",
+ DataTypeString(dtypes[i]), " does not equal original dtype ",
+ DataTypeString(original_dtype));
+ mismatched_errors.emplace_back(error_msg);
+ }
+ }
+ if (!mismatched_errors.empty()) {
+ const string error_msg = str_util::Join(mismatched_errors, "\n");
+ return errors::InvalidArgument(error_msg);
+ }
+
for (auto i : sorted_name_idx) {
const string& tensor_name = tensor_names_flat(i);
const string& shape_and_slice = shape_and_slices_flat(i);
diff --git a/tensorflow/core/kernels/scoped_allocator_ops.cc b/tensorflow/core/kernels/scoped_allocator_ops.cc
index 1d2fb6996a..69e754fd60 100644
--- a/tensorflow/core/kernels/scoped_allocator_ops.cc
+++ b/tensorflow/core/kernels/scoped_allocator_ops.cc
@@ -104,10 +104,11 @@ class ScopedAllocatorConcatOp : public OpKernel {
void Compute(OpKernelContext* context) override {
const Tensor& backing_tensor = context->input(0);
// Check that type matches.
- OP_REQUIRES(
- context, backing_tensor.dtype() == dtype_,
- errors::InvalidArgument("Backing tensor type ", backing_tensor.dtype(),
- " does not match expected type ", dtype_));
+ OP_REQUIRES(context, backing_tensor.dtype() == dtype_,
+ errors::InvalidArgument("Backing tensor type ",
+ DataTypeString(backing_tensor.dtype()),
+ " does not match expected type ",
+ DataTypeString(dtype_)));
// Check that backing tensor is at least as large as the shape of the
// output.
OP_REQUIRES(context, backing_tensor.NumElements() >= shape_.num_elements(),
@@ -182,10 +183,11 @@ class ScopedAllocatorSplitOp : public OpKernel {
void Compute(OpKernelContext* context) override {
Tensor backing_copy(context->input(0));
// Check that type matches.
- OP_REQUIRES(
- context, backing_copy.dtype() == dtype_,
- errors::InvalidArgument("Backing tensor type ", backing_copy.dtype(),
- " does not match expected type ", dtype_));
+ OP_REQUIRES(context, backing_copy.dtype() == dtype_,
+ errors::InvalidArgument("Backing tensor type ",
+ DataTypeString(backing_copy.dtype()),
+ " does not match expected type ",
+ DataTypeString(dtype_)));
const TensorBuffer* backing_buf = DMAHelper::buffer(&backing_copy);
const void* backing_tensor_lb = backing_buf->data();
const void* backing_tensor_ub = static_cast<const void*>(
@@ -195,10 +197,11 @@ class ScopedAllocatorSplitOp : public OpKernel {
<< " to output " << i - 1 << " buf addr "
<< DMAHelper::base(&context->input(i));
Tensor copy(context->input(i));
- OP_REQUIRES(
- context, copy.dtype() == dtype_,
- errors::InvalidArgument("Input ", i, " tensor type ", copy.dtype(),
- " does not match expected type ", dtype_));
+ OP_REQUIRES(context, copy.dtype() == dtype_,
+ errors::InvalidArgument("Input ", i, " tensor type ",
+ DataTypeString(copy.dtype()),
+ " does not match expected type ",
+ DataTypeString(dtype_)));
context->set_output(i - 1, copy);
const TensorBuffer* input_buf = DMAHelper::buffer(&copy);
const void* input_lb = input_buf->data();
diff --git a/tensorflow/core/kernels/self_adjoint_eig_v2_op_impl.h b/tensorflow/core/kernels/self_adjoint_eig_v2_op_impl.h
index 271dd2c485..b5274f8788 100644
--- a/tensorflow/core/kernels/self_adjoint_eig_v2_op_impl.h
+++ b/tensorflow/core/kernels/self_adjoint_eig_v2_op_impl.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_SELF_ADJOINT_EIG_V2_OP_IMPL_H_
+#define TENSORFLOW_CORE_KERNELS_SELF_ADJOINT_EIG_V2_OP_IMPL_H_
+
// See docs in ../ops/linalg_ops.cc.
#include "third_party/eigen3/Eigen/Core"
@@ -85,3 +88,5 @@ class SelfAdjointEigV2Op : public LinearAlgebraOp<Scalar> {
};
} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_SELF_ADJOINT_EIG_V2_OP_IMPL_H_
diff --git a/tensorflow/core/kernels/shape_ops.h b/tensorflow/core/kernels/shape_ops.h
index 55be308901..f75723af7d 100644
--- a/tensorflow/core/kernels/shape_ops.h
+++ b/tensorflow/core/kernels/shape_ops.h
@@ -154,6 +154,9 @@ class ExpandDimsOp : public OpKernel {
OP_REQUIRES(ctx, ctx->input(0).dtype() != DT_VARIANT,
errors::InvalidArgument("ExpandDims on Variant not supported"));
+ OP_REQUIRES(
+ ctx, (ctx->input(1).NumElements() == 1),
+ errors::InvalidArgument("'dim' must be a tensor with a single value"));
Tdim dim = ctx->input(1).flat<Tdim>()(0);
OP_REQUIRES(
ctx, (dim >= -1 - ctx->input(0).dims() && dim <= ctx->input(0).dims()),
@@ -236,9 +239,8 @@ class SqueezeOp : public OpKernel {
if (wrapped_squeeze_dims.count(i) > 0) {
OP_REQUIRES(ctx, existing_dim == 1,
errors::InvalidArgument(
- "Tried to explicitly squeeze "
- "dimension ",
- i, " but dimension was not 1: ", existing_dim));
+ "Can not squeeze dim[", i,
+ "], expected a dimension of 1, got ", existing_dim));
} else {
// This dimension is not being squeezed.
new_shape.push_back(existing_dim);
diff --git a/tensorflow/core/kernels/sparse_xent_op.h b/tensorflow/core/kernels/sparse_xent_op.h
index b5587aa9d7..6ba7931ab5 100644
--- a/tensorflow/core/kernels/sparse_xent_op.h
+++ b/tensorflow/core/kernels/sparse_xent_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_XENT_OP_H_
-#define TENSORFLOW_KERNELS_XENT_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_SPARSE_XENT_OP_H_
+#define TENSORFLOW_CORE_KERNELS_SPARSE_XENT_OP_H_
// Functor definition for SparseXentOp, must be compilable by nvcc.
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
@@ -224,4 +224,4 @@ struct SparseXentEigenImpl {
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_XENT_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_SPARSE_XENT_OP_H_
diff --git a/tensorflow/core/kernels/string_length_op.cc b/tensorflow/core/kernels/string_length_op.cc
new file mode 100644
index 0000000000..a6829b29d9
--- /dev/null
+++ b/tensorflow/core/kernels/string_length_op.cc
@@ -0,0 +1,45 @@
+/* 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.
+==============================================================================*/
+#include "tensorflow/core/framework/op_kernel.h"
+#include "tensorflow/core/framework/types.h"
+
+namespace tensorflow {
+namespace {
+
+class StringLengthOp : public OpKernel {
+ public:
+ using OpKernel::OpKernel;
+
+ void Compute(OpKernelContext* context) override {
+ const Tensor& input = context->input(0);
+
+ Tensor* output;
+ OP_REQUIRES_OK(context,
+ context->allocate_output(0, input.shape(), &output));
+
+ auto src = input.flat<string>();
+ auto dst = output->flat<int32>();
+
+ for (int n = 0; n < src.size(); ++n) {
+ dst(n) = src(n).size();
+ }
+ }
+};
+
+REGISTER_KERNEL_BUILDER(Name("StringLength").Device(DEVICE_CPU),
+ StringLengthOp);
+
+} // namespace
+} // namespace tensorflow
diff --git a/tensorflow/core/kernels/string_split_op.cc b/tensorflow/core/kernels/string_split_op.cc
index 26ab72f12e..3884370a6c 100644
--- a/tensorflow/core/kernels/string_split_op.cc
+++ b/tensorflow/core/kernels/string_split_op.cc
@@ -26,25 +26,81 @@ limitations under the License.
#include "tensorflow/core/lib/strings/str_util.h"
namespace tensorflow {
-
namespace {
+// Split input string `str` based on a character delimiter.
+// Returns a vector of StringPieces which are valid as long as input `str`
+// is valid.
+// Note: The single character delimiter is a common case and is implemented as
+// a series of finds in the input string, making it much more effcient than
+// SplitOnCharSet.
+template <typename Predicate>
+std::vector<StringPiece> SplitOnChar(const string& str, const char delim,
+ Predicate p) {
+ std::vector<StringPiece> result;
+ StringPiece text(str);
+ auto f = text.find(delim);
+ while (f != StringPiece::npos) {
+ StringPiece token = text.substr(0, f);
+ if (p(token)) {
+ result.emplace_back(token);
+ }
+ text.remove_prefix(f + 1);
+ f = text.find(delim);
+ }
+ if (p(text)) {
+ result.push_back(text);
+ }
+ return result;
+}
-std::vector<string> Split(const string& str, const string& delimiter,
- const bool skipEmpty) {
- if (!delimiter.empty()) {
- if (skipEmpty) {
- return str_util::Split(str, delimiter, str_util::SkipEmpty());
+// Split input string `str` based on a set of character delimiters.
+// Returns a vector of StringPieces which are valid as long as input `str`
+// is valid.
+// Based on str_util::Split.
+template <typename Predicate>
+std::vector<StringPiece> SplitOnCharSet(const string& str,
+ const string& delim_set, Predicate p) {
+ std::vector<StringPiece> result;
+ StringPiece text(str);
+ StringPiece delims(delim_set);
+ size_t token_start = 0;
+ for (size_t i = 0; i < text.size() + 1; i++) {
+ if ((i == text.size()) || (delims.find(text[i]) != StringPiece::npos)) {
+ StringPiece token(text.data() + token_start, i - token_start);
+ if (p(token)) {
+ result.emplace_back(token);
+ }
+ token_start = i + 1;
}
- return str_util::Split(str, delimiter);
}
- std::vector<string> char_vector(str.size());
- for (size_t i = 0; i < str.size(); ++i) {
- char_vector[i] = str[i];
+ return result;
+}
+
+// Split input string `str` based on given delimiter.
+// Returns a vector of StringPieces which are valid as long as input `str`
+// is valid.
+template <typename Predicate>
+std::vector<StringPiece> Split(const string& str, const string& delimiter,
+ Predicate predicate) {
+ if (str.empty()) {
+ return std::vector<StringPiece>();
+ }
+ if (delimiter.empty()) {
+ std::vector<StringPiece> result;
+ result.resize(str.size());
+ for (size_t i = 0; i < str.size(); ++i) {
+ result[i] = StringPiece(str.data() + i, 1);
+ }
+ return result;
}
- return char_vector;
+ if (delimiter.size() == 1) {
+ return SplitOnChar(str, delimiter[0], predicate);
+ }
+ return SplitOnCharSet(str, delimiter, predicate);
}
-std::vector<string> SplitV2(const string& str, StringPiece sep, int maxsplit) {
+std::vector<StringPiece> SplitV2(const string& str, StringPiece sep,
+ int maxsplit) {
// This SplitV2 method matches the behavior of python's str.split:
// If sep is given, consecutive delimiters are not grouped together
// and are deemed to delimit empty strings (for example, '1,,2'.split(',')
@@ -59,11 +115,11 @@ std::vector<string> SplitV2(const string& str, StringPiece sep, int maxsplit) {
// splitting an empty string or a string consisting of just whitespace
// with a None separator returns [].
- std::vector<string> result;
+ std::vector<StringPiece> result;
StringPiece text(str);
if (maxsplit == 0) {
- result.emplace_back(std::string(text));
+ result.emplace_back(text);
return result;
}
@@ -73,11 +129,11 @@ std::vector<string> SplitV2(const string& str, StringPiece sep, int maxsplit) {
str_util::RemoveLeadingWhitespace(&text);
int split = 0;
while (str_util::ConsumeNonWhitespace(&text, &token)) {
- result.emplace_back(std::string(token));
+ result.push_back(token);
str_util::RemoveLeadingWhitespace(&text);
++split;
if (maxsplit > 0 && split == maxsplit) {
- result.emplace_back(std::string(text));
+ result.push_back(text);
return result;
}
}
@@ -87,17 +143,17 @@ std::vector<string> SplitV2(const string& str, StringPiece sep, int maxsplit) {
int split = 0;
while (p != text.end()) {
StringPiece token = text.substr(0, p - text.begin());
- result.emplace_back(std::string(token));
+ result.push_back(token);
text.remove_prefix(token.size());
text.remove_prefix(sep.size());
++split;
if (maxsplit > 0 && split == maxsplit) {
- result.emplace_back(std::string(text));
+ result.push_back(StringPiece(text));
return result;
}
p = std::search(text.begin(), text.end(), sep.begin(), sep.end());
}
- result.emplace_back(std::string(text));
+ result.push_back(text);
return result;
}
@@ -134,7 +190,7 @@ class StringSplitOp : public OpKernel {
const auto delimiter_vec = delimiter_tensor->flat<string>();
const string& delimiter = delimiter_vec(0);
// Empty delimiter means split the input character by character.
- std::vector<string> tokens;
+ std::vector<StringPiece> tokens;
// Guess that we'll be unpacking a handful of tokens per example.
static constexpr int kReserveSize = 4;
tokens.reserve(batch_size * kReserveSize);
@@ -143,12 +199,15 @@ class StringSplitOp : public OpKernel {
int64 max_num_entries = 0;
std::vector<int64> num_indices(batch_size);
for (int64 i = 0; i < batch_size; ++i) {
- std::vector<string> parts = Split(input_vec(i), delimiter, skip_empty_);
+ std::vector<StringPiece> parts =
+ skip_empty_ ? Split(input_vec(i), delimiter, str_util::SkipEmpty())
+ : Split(input_vec(i), delimiter, str_util::AllowEmpty());
int64 n_entries = parts.size();
num_indices[i] = n_entries;
output_size += n_entries;
max_num_entries = std::max(max_num_entries, n_entries);
- tokens.insert(tokens.end(), parts.begin(), parts.end());
+ tokens.insert(tokens.end(), std::make_move_iterator(parts.begin()),
+ std::make_move_iterator(parts.end()));
}
Tensor* sp_indices_t;
@@ -170,7 +229,7 @@ class StringSplitOp : public OpKernel {
for (size_t j = 0; j < num_indices[i]; ++j) {
sp_indices(c, 0) = i;
sp_indices(c, 1) = j;
- sp_tokens(c) = tokens[c];
+ sp_tokens(c).assign(tokens[c].data(), tokens[c].size());
++c;
}
}
@@ -204,7 +263,7 @@ class StringSplitV2Op : public OpKernel {
sep_tensor->shape().DebugString()));
const auto sep_vec = sep_tensor->flat<string>();
StringPiece sep(sep_vec(0));
- std::vector<string> tokens;
+ std::vector<StringPiece> tokens;
// Guess that we'll be unpacking a handful of tokens per example.
static constexpr int kReserveSize = 4;
tokens.reserve(batch_size * kReserveSize);
@@ -213,7 +272,7 @@ class StringSplitV2Op : public OpKernel {
int64 max_num_entries = 0;
std::vector<int64> num_indices(batch_size);
for (int64 i = 0; i < batch_size; ++i) {
- std::vector<string> parts = SplitV2(input_vec(i), sep, maxsplit_);
+ std::vector<StringPiece> parts = SplitV2(input_vec(i), sep, maxsplit_);
int64 n_entries = parts.size();
num_indices[i] = n_entries;
output_size += n_entries;
@@ -240,7 +299,7 @@ class StringSplitV2Op : public OpKernel {
for (size_t j = 0; j < num_indices[i]; ++j) {
sp_indices(c, 0) = i;
sp_indices(c, 1) = j;
- sp_tokens(c) = tokens[c];
+ sp_tokens(c).assign(tokens[c].data(), tokens[c].size());
++c;
}
}
diff --git a/tensorflow/core/kernels/string_split_op_test.cc b/tensorflow/core/kernels/string_split_op_test.cc
new file mode 100644
index 0000000000..58ad61adc8
--- /dev/null
+++ b/tensorflow/core/kernels/string_split_op_test.cc
@@ -0,0 +1,129 @@
+/* Copyright 2016 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.
+==============================================================================*/
+
+#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
+#include "tensorflow/core/framework/allocator.h"
+#include "tensorflow/core/framework/fake_input.h"
+#include "tensorflow/core/framework/node_def_builder.h"
+#include "tensorflow/core/framework/op_kernel.h"
+#include "tensorflow/core/framework/tensor.h"
+#include "tensorflow/core/framework/tensor_testutil.h"
+#include "tensorflow/core/framework/types.h"
+#include "tensorflow/core/framework/types.pb.h"
+#include "tensorflow/core/graph/node_builder.h"
+#include "tensorflow/core/kernels/ops_testutil.h"
+#include "tensorflow/core/kernels/ops_util.h"
+#include "tensorflow/core/lib/core/status_test_util.h"
+#include "tensorflow/core/platform/test.h"
+#include "tensorflow/core/platform/test_benchmark.h"
+
+namespace tensorflow {
+
+// Test data from the TensorFlow README.md.
+const char* lines[] = {
+ "**TensorFlow** is an open source software library for numerical "
+ "computation using 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/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 "
+ "organization for the purposes of conducting machine learning and deep "
+ "neural networks research.",
+ "The system is general enough to be applicable in a wide variety of other "
+ "domains, as well.",
+ "TensorFlow provides stable Python API and C APIs as well as without API "
+ "backwards compatibility guarantee like C++, Go, Java, JavaScript and "
+ "Swift."};
+
+Tensor GetTestTensor(int batch) {
+ const int sz = TF_ARRAYSIZE(lines);
+ Tensor t(DT_STRING, {batch});
+ auto s = t.flat<string>();
+ for (int i = 0; i < batch; ++i) {
+ s(i) = lines[i % sz];
+ }
+ return t;
+}
+
+Graph* SetupStringSplitGraph(const Tensor& input) {
+ Graph* g = new Graph(OpRegistry::Global());
+ Tensor delim(DT_STRING, TensorShape({}));
+ delim.flat<string>().setConstant(" ");
+
+ TF_CHECK_OK(NodeBuilder("string_split_op", "StringSplit")
+ .Input(test::graph::Constant(g, input))
+ .Input(test::graph::Constant(g, delim))
+ .Finalize(g, nullptr /* node */));
+ return g;
+}
+
+void BM_StringSplit(int iters, int batch_size) {
+ testing::StopTiming();
+ testing::ItemsProcessed(static_cast<int64>(iters));
+ testing::UseRealTime();
+ Tensor input = GetTestTensor(batch_size);
+ Graph* g = SetupStringSplitGraph(input);
+ testing::StartTiming();
+ test::Benchmark("cpu", g).Run(iters);
+}
+
+BENCHMARK(BM_StringSplit)
+ ->Arg(1)
+ ->Arg(8)
+ ->Arg(16)
+ ->Arg(32)
+ ->Arg(64)
+ ->Arg(128)
+ ->Arg(256);
+
+Graph* SetupStringSplitV2Graph(const Tensor& input) {
+ Graph* g = new Graph(OpRegistry::Global());
+ Tensor sep(DT_STRING, TensorShape({}));
+ sep.flat<string>().setConstant(" ");
+
+ TF_CHECK_OK(NodeBuilder("string_split_op", "StringSplitV2")
+ .Input(test::graph::Constant(g, input))
+ .Input(test::graph::Constant(g, sep))
+ .Finalize(g, nullptr /* node */));
+ return g;
+}
+
+void BM_StringSplitV2(int iters, int batch_size) {
+ testing::StopTiming();
+ testing::ItemsProcessed(static_cast<int64>(iters));
+ testing::UseRealTime();
+ Tensor input = GetTestTensor(batch_size);
+ Graph* g = SetupStringSplitV2Graph(input);
+ testing::StartTiming();
+ test::Benchmark("cpu", g).Run(iters);
+}
+
+BENCHMARK(BM_StringSplitV2)
+ ->Arg(1)
+ ->Arg(8)
+ ->Arg(16)
+ ->Arg(32)
+ ->Arg(64)
+ ->Arg(128)
+ ->Arg(256);
+
+} // end namespace tensorflow
diff --git a/tensorflow/core/kernels/svd_op_impl.h b/tensorflow/core/kernels/svd_op_impl.h
index a996b67c62..2a67700c12 100644
--- a/tensorflow/core/kernels/svd_op_impl.h
+++ b/tensorflow/core/kernels/svd_op_impl.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_SVD_OP_IMPL_H_
+#define TENSORFLOW_CORE_KERNELS_SVD_OP_IMPL_H_
+
// See docs in ../ops/linalg_ops.cc.
//
// This header file is used by the individual svd_*op*.cc files for registering
@@ -101,3 +104,5 @@ class SvdOp : public LinearAlgebraOp<Scalar> {
};
} // namespace tensorflow
+
+#endif // TENSORFLOW_CORE_KERNELS_SVD_OP_IMPL_H_
diff --git a/tensorflow/core/kernels/tensor_array_ops.cc b/tensorflow/core/kernels/tensor_array_ops.cc
index 5aa5d20b1a..632b65e9b6 100644
--- a/tensorflow/core/kernels/tensor_array_ops.cc
+++ b/tensorflow/core/kernels/tensor_array_ops.cc
@@ -40,6 +40,7 @@ limitations under the License.
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
+#include "tensorflow/core/util/ptr_util.h"
typedef Eigen::ThreadPoolDevice CPUDevice;
#if GOOGLE_CUDA
@@ -683,7 +684,7 @@ class TensorArrayPackOrGatherOp : public OpKernel {
output_tensor->shaped<T, 2>({1, output_shape.num_elements()});
// Insert the first value
- input_tensors_flat.emplace_back(new ConstMatrix(
+ input_tensors_flat.push_back(MakeUnique<ConstMatrix>(
value_0_t->shaped<T, 2>({1, value_0_t->NumElements()})));
for (int i = 1; i < num_indices; ++i) {
@@ -694,8 +695,8 @@ class TensorArrayPackOrGatherOp : public OpKernel {
"TensorArray has inconsistent shapes. Index 0 has shape: ",
value_0_t->shape().DebugString(), " but index ", i,
" has shape: ", value_t->shape().DebugString()));
- input_tensors_flat.emplace_back(
- new ConstMatrix(value_t->shaped<T, 2>({1, value_t->NumElements()})));
+ input_tensors_flat.push_back(MakeUnique<ConstMatrix>(
+ value_t->shaped<T, 2>({1, value_t->NumElements()})));
}
#if GOOGLE_CUDA
@@ -922,7 +923,7 @@ class TensorArrayConcatOp : public OpKernel {
for (size_t i = 0; i < values.size(); ++i) {
const Tensor* value_t = value_tensors[i];
if (value_t->NumElements() > 0) {
- input_tensors_flat.emplace_back(new ConstMatrix(
+ input_tensors_flat.push_back(MakeUnique<ConstMatrix>(
value_t->shaped<T, 2>({1, value_t->NumElements()})));
}
}
@@ -1118,8 +1119,8 @@ class TensorArrayUnpackOrScatterOp : public OpKernel {
{1, num_values, element_shape.num_elements()});
Eigen::DSizes<Eigen::DenseIndex, 3> indices{0, 0, 0};
- Eigen::DSizes<Eigen::DenseIndex, 3> sizes{1, 1,
- element_shape.num_elements()};
+ Eigen::DSizes<Eigen::DenseIndex, 3> sizes{
+ 1, 1, static_cast<Eigen::DenseIndex>(element_shape.num_elements())};
std::vector<PersistentTensor> write_values;
write_values.reserve(num_values);
@@ -1314,9 +1315,11 @@ class TensorArraySplitOp : public OpKernel {
PersistentTensor persistent_tensor;
int64 previous_length = (i == 0) ? 0 : cumulative_lengths[i - 1];
- Eigen::DSizes<Eigen::DenseIndex, 3> indices{0, previous_length, 0};
- Eigen::DSizes<Eigen::DenseIndex, 3> sizes{1, tensor_lengths_t(i),
- elements_per_row};
+ Eigen::DSizes<Eigen::DenseIndex, 3> indices{
+ 0, static_cast<Eigen::DenseIndex>(previous_length), 0};
+ Eigen::DSizes<Eigen::DenseIndex, 3> sizes{
+ 1, static_cast<Eigen::DenseIndex>(tensor_lengths_t(i)),
+ static_cast<Eigen::DenseIndex>(elements_per_row)};
OP_REQUIRES_OK(ctx, ctx->allocate_persistent(
tensor_array->ElemType(), element_shapes[i],
diff --git a/tensorflow/core/kernels/tile_ops.cc b/tensorflow/core/kernels/tile_ops.cc
index 68cdae3249..d5d4fa82c7 100644
--- a/tensorflow/core/kernels/tile_ops.cc
+++ b/tensorflow/core/kernels/tile_ops.cc
@@ -31,6 +31,7 @@ limitations under the License.
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/type_index.h"
+#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/macros.h"
@@ -149,10 +150,12 @@ class TileOp : public OpKernel {
#undef HANDLE_TYPE_NAME
#undef HANDLE_TYPE
- OP_REQUIRES(context, false,
- errors::Unimplemented(
- "TileOp : Unhandled input dimensions, DT : ",
- context->input(0).dtype(), ", dims : ", input_dims));
+ OP_REQUIRES(
+ context, false,
+ errors::Unimplemented(
+ "TileOp : The input data type is not supported, DataType : ",
+ DataTypeString(context->input(0).dtype()),
+ ", Dimension : ", input_dims));
}
private:
@@ -330,9 +333,10 @@ class TileGradientOp : public OpKernel {
#undef HANDLE_DIM
OP_REQUIRES(context, false,
- errors::Unimplemented(
- "TileGradientOp : Unhandled input dimensions, DT : ",
- context->input(0).dtype(), ", dims : ", input_dims));
+ errors::Unimplemented("TileGradientOp : The input data type or "
+ "dimension is not supported, DataType : ",
+ DataTypeString(context->input(0).dtype()),
+ ", Dimension : ", input_dims));
}
private:
diff --git a/tensorflow/core/kernels/transpose_op.cc b/tensorflow/core/kernels/transpose_op.cc
index 886b3e7492..0f0f65c5a3 100644
--- a/tensorflow/core/kernels/transpose_op.cc
+++ b/tensorflow/core/kernels/transpose_op.cc
@@ -218,7 +218,7 @@ Status ConjugateTransposeCpuOp::DoTranspose(OpKernelContext* ctx,
perm, out);
}
-#if defined(INTEL_MKL) && !defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL)
#define REGISTER(T) \
REGISTER_KERNEL_BUILDER(Name("Transpose") \
.Device(DEVICE_CPU) \
diff --git a/tensorflow/core/kernels/transpose_op.h b/tensorflow/core/kernels/transpose_op.h
index 709b0a92e9..9e8c573761 100644
--- a/tensorflow/core/kernels/transpose_op.h
+++ b/tensorflow/core/kernels/transpose_op.h
@@ -42,7 +42,7 @@ class TransposeCpuOp : public TransposeOp {
gtl::ArraySlice<int32> perm, Tensor* out) override;
};
-#if defined(INTEL_MKL) && !defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL)
class MklTransposeCpuOp : public TransposeOp {
public:
explicit MklTransposeCpuOp(OpKernelConstruction* ctx) : TransposeOp(ctx) {}
@@ -85,7 +85,7 @@ class ConjugateTransposeCpuOp : public TransposeOp {
bool IsConjugate() const override { return true; }
};
-#if defined(INTEL_MKL) && !defined(DO_NOT_USE_ML)
+#if defined(INTEL_MKL)
class MklConjugateTransposeCpuOp : public TransposeOp {
public:
explicit MklConjugateTransposeCpuOp(OpKernelConstruction* ctx)
diff --git a/tensorflow/core/kernels/unique_op.cc b/tensorflow/core/kernels/unique_op.cc
index 31388e4290..3559baa18e 100644
--- a/tensorflow/core/kernels/unique_op.cc
+++ b/tensorflow/core/kernels/unique_op.cc
@@ -69,7 +69,7 @@ class UniqueOp : public OpKernel {
axis_tensor.dtype() == DT_INT64),
errors::InvalidArgument(
"axis tensor should be int32 or int64, but got ",
- axis_tensor.dtype()));
+ DataTypeString(axis_tensor.dtype())));
if (axis_tensor.dtype() == DT_INT32) {
axis = internal::SubtleMustCopy(axis_tensor.scalar<int32>()());
} else {
diff --git a/tensorflow/core/kernels/where_op_gpu.cu.h b/tensorflow/core/kernels/where_op_gpu.cu.h
index 57f51889de..8879d9dd4c 100644
--- a/tensorflow/core/kernels/where_op_gpu.cu.h
+++ b/tensorflow/core/kernels/where_op_gpu.cu.h
@@ -13,6 +13,9 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
+#ifndef TENSORFLOW_CORE_KERNELS_WHERE_OP_GPU_CU_H_
+#define TENSORFLOW_CORE_KERNELS_WHERE_OP_GPU_CU_H_
+
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
@@ -346,3 +349,5 @@ TF_CALL_WHERE_GPU_TYPES(DECLARE_GPU_SPEC);
} // namespace tensorflow
#endif // GOOGLE_CUDA
+
+#endif // TENSORFLOW_CORE_KERNELS_WHERE_OP_GPU_CU_H_
diff --git a/tensorflow/core/kernels/xent_op.h b/tensorflow/core/kernels/xent_op.h
index 87be17fca9..23d3ad39a8 100644
--- a/tensorflow/core/kernels/xent_op.h
+++ b/tensorflow/core/kernels/xent_op.h
@@ -13,8 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_KERNELS_XENT_OP_H_
-#define TENSORFLOW_KERNELS_XENT_OP_H_
+#ifndef TENSORFLOW_CORE_KERNELS_XENT_OP_H_
+#define TENSORFLOW_CORE_KERNELS_XENT_OP_H_
// Functor definition for XentOp, must be compilable by nvcc.
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
@@ -125,4 +125,4 @@ struct XentEigenImpl {
} // namespace functor
} // namespace tensorflow
-#endif // TENSORFLOW_KERNELS_XENT_OP_H_
+#endif // TENSORFLOW_CORE_KERNELS_XENT_OP_H_
diff --git a/tensorflow/core/lib/core/stringpiece.h b/tensorflow/core/lib/core/stringpiece.h
index d7ecc44e50..329f115608 100644
--- a/tensorflow/core/lib/core/stringpiece.h
+++ b/tensorflow/core/lib/core/stringpiece.h
@@ -31,6 +31,7 @@ limitations under the License.
#include <string.h>
#include <iosfwd>
#include <string>
+#include <type_traits>
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
@@ -101,11 +102,18 @@ class StringPiece {
// > 0 iff "*this" > "b"
int compare(StringPiece b) const;
- // Converts to `std::basic_string`.
- template <typename A>
- explicit operator std::basic_string<char, std::char_traits<char>, A>() const {
+ // Converts to various kinds of strings, including `std::basic_string`.
+ template <typename S>
+ explicit operator S() const {
+ static_assert(
+ std::is_same<char, typename S::value_type>::value,
+ "Type mismatch: S must be a string with character type char.");
+ static_assert(
+ std::is_same<std::char_traits<char>, typename S::traits_type>::value,
+ "Type mismatch: S must be a string with traits type "
+ "std::char_traits<char>.");
if (!data()) return {};
- return std::basic_string<char, std::char_traits<char>, A>(data(), size());
+ return S(data(), size());
}
private:
diff --git a/tensorflow/core/lib/core/stringpiece_test.cc b/tensorflow/core/lib/core/stringpiece_test.cc
index 952b9eaaaa..e4b489fe17 100644
--- a/tensorflow/core/lib/core/stringpiece_test.cc
+++ b/tensorflow/core/lib/core/stringpiece_test.cc
@@ -56,8 +56,8 @@ TEST(StringPiece, Ctor) {
}
TEST(StringPiece, ConversionToString) {
- EXPECT_EQ("", std::string(StringPiece("")));
- EXPECT_EQ("foo", std::string(StringPiece("foo")));
+ EXPECT_EQ("", string(StringPiece("")));
+ EXPECT_EQ("foo", string(StringPiece("foo")));
}
} // namespace tensorflow
diff --git a/tensorflow/core/lib/png/png_io.cc b/tensorflow/core/lib/png/png_io.cc
index 62c803afb2..e226a15ccc 100644
--- a/tensorflow/core/lib/png/png_io.cc
+++ b/tensorflow/core/lib/png/png_io.cc
@@ -232,11 +232,19 @@ bool CommonInitDecode(StringPiece png_string, int desired_channels,
CommonFreeDecode(context);
return false;
}
- if (context->channels == 0) { // Autodetect number of channels
- context->channels = png_get_channels(context->png_ptr, context->info_ptr);
- }
const bool has_tRNS =
(png_get_valid(context->png_ptr, context->info_ptr, PNG_INFO_tRNS)) != 0;
+ if (context->channels == 0) { // Autodetect number of channels
+ if (context->color_type == PNG_COLOR_TYPE_PALETTE) {
+ if (has_tRNS) {
+ context->channels = 4; // RGB + A(tRNS)
+ } else {
+ context->channels = 3; // RGB
+ }
+ } else {
+ context->channels = png_get_channels(context->png_ptr, context->info_ptr);
+ }
+ }
const bool has_alpha = (context->color_type & PNG_COLOR_MASK_ALPHA) != 0;
if ((context->channels & 1) == 0) { // We desire alpha
if (has_alpha) { // There is alpha
diff --git a/tensorflow/core/lib/png/testdata/lena_palette.png b/tensorflow/core/lib/png/testdata/lena_palette.png
new file mode 100644
index 0000000000..d19ec04895
--- /dev/null
+++ b/tensorflow/core/lib/png/testdata/lena_palette.png
Binary files differ
diff --git a/tensorflow/core/lib/png/testdata/lena_palette_trns.png b/tensorflow/core/lib/png/testdata/lena_palette_trns.png
new file mode 100644
index 0000000000..c298fee9ff
--- /dev/null
+++ b/tensorflow/core/lib/png/testdata/lena_palette_trns.png
Binary files differ
diff --git a/tensorflow/core/ops/array_grad.cc b/tensorflow/core/ops/array_grad.cc
index 38bd851da8..1f2e57e9a9 100644
--- a/tensorflow/core/ops/array_grad.cc
+++ b/tensorflow/core/ops/array_grad.cc
@@ -244,6 +244,27 @@ Status SplitGrad(const AttrSlice& attrs, FunctionDef* g) {
}
REGISTER_OP_GRADIENT("Split", SplitGrad);
+Status SplitVGrad(const AttrSlice& attrs, FunctionDef* g) {
+ // clang-format off
+ *g = FDH::Define(
+ // Arg defs
+ {"x: T", "size_splits: Tlen", "dim: int32", "dy: num_split*T"},
+ // Ret val defs
+ {"dx: T", "d_size_splits: Tlen", "d_dim: int32"},
+ // Attr defs
+ {"T: type", "Tlen: type", "num_split: int"},
+ // Nodes
+ {
+ {{"dx"}, "Concat", {"dim", "dy"}, {{"T", "$T"}, {"N", "$num_split"}}},
+ {{"d_size_splits"}, "ZerosLike", {"size_splits"}, {{"T", "$Tlen"}}},
+ {{"d_dim"}, "ZerosLike", {"dim"}, {{"T", DT_INT32}}},
+ });
+ // clang-format on
+ VLOG(1) << "SplitVGrad " << DebugString(*g);
+ return Status::OK();
+}
+REGISTER_OP_GRADIENT("SplitV", SplitVGrad);
+
Status ArrayToListGrad(const AttrSlice& attrs, FunctionDef* g) {
int N;
TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "N", &N));
diff --git a/tensorflow/core/ops/array_grad_test.cc b/tensorflow/core/ops/array_grad_test.cc
index e665d17938..79d28a83cc 100644
--- a/tensorflow/core/ops/array_grad_test.cc
+++ b/tensorflow/core/ops/array_grad_test.cc
@@ -238,6 +238,39 @@ std::vector<Tensor> SplitGrad(int dim, const Tensor& x, const Tensor& dy0,
return out;
}
+std::vector<Tensor> SplitVGrad(const Tensor& x, const Tensor& size_splits,
+ int dim, const Tensor& dy0, const Tensor& dy1) {
+ auto T = DT_FLOAT;
+ auto Tlen = DT_INT64;
+ auto gdef = test::function::GDef(
+ {f::NDef("x", "Placeholder", {}, {{"dtype", T}}),
+ f::NDef("size_splits", "Placeholder", {}, {{"dtype", Tlen}}),
+ f::NDef("dim", "Placeholder", {}, {{"dtype", DT_INT32}}),
+ f::NDef("dy0", "Placeholder", {}, {{"dtype", T}}),
+ f::NDef("dy1", "Placeholder", {}, {{"dtype", T}}),
+ f::NDef("dx", "SymbolicGradient",
+ {"x", "size_splits", "dim", "dy0", "dy1"},
+ {{"f", FDH::FunctionRef("SplitV", {{"split_dim", dim},
+ {"num_split", 2},
+ {"T", T},
+ {"Tlen", Tlen}})},
+ {"Tin", DataTypeSlice{T, Tlen, DT_INT32, T, T}},
+ {"Tout", DataTypeSlice{T, Tlen, DT_INT32}}})});
+ VLOG(1) << DebugStringWhole(gdef);
+ auto sess = NewSession();
+ TF_CHECK_OK(sess->Create(gdef));
+ std::vector<Tensor> out;
+ TF_CHECK_OK(sess->Run({{"x:0", x},
+ {"size_splits:0", size_splits},
+ {"dim", test::AsScalar(dim)},
+ {"dy0:0", dy0},
+ {"dy1:0", dy1}},
+ {"dx:0", "dx:1", "dx:2"}, {}, &out));
+ CHECK_EQ(out.size(), 3);
+ TF_CHECK_OK(sess->Close());
+ return out;
+}
+
TEST(ArrayGradTest, SplitGrad) {
Tensor x(DT_FLOAT, {2, 4, 5});
x.flat<float>().setZero();
@@ -245,15 +278,30 @@ TEST(ArrayGradTest, SplitGrad) {
Tensor dy1(DT_FLOAT, {2, 2, 5});
test::FillIota<float>(&dy0, 0);
test::FillIota<float>(&dy1, 100);
- auto dx = SplitGrad(1, x, dy0, dy1);
- test::ExpectTensorEqual<int32>(dx[0], test::AsScalar(0));
- test::ExpectClose(
- dx[1], test::AsTensor<float>(
- {0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
- 100., 101., 102., 103., 104., 105., 106., 107., 108., 109.,
- 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
- 110., 111., 112., 113., 114., 115., 116., 117., 118., 119.},
- {2, 4, 5}));
+ auto expected_dx = test::AsTensor<float>(
+ {0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
+ 100., 101., 102., 103., 104., 105., 106., 107., 108., 109.,
+ 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
+ 110., 111., 112., 113., 114., 115., 116., 117., 118., 119.},
+ {2, 4, 5});
+ auto expected_d_dim = test::AsScalar(0);
+
+ // SplitGrad
+ {
+ auto dx = SplitGrad(1, x, dy0, dy1);
+ test::ExpectTensorEqual<int32>(dx[0], expected_d_dim);
+ test::ExpectClose(dx[1], expected_dx);
+ }
+ // SplitVGrad
+ {
+ Tensor size_splits(DT_INT64, {2});
+ size_splits.flat<int64>().setConstant(2);
+ auto expected_d_size_splits = test::AsTensor<int64>({0, 0}, {2});
+ auto dx = SplitVGrad(x, size_splits, 1, dy0, dy1);
+ test::ExpectClose(dx[0], expected_dx);
+ test::ExpectTensorEqual<int64>(dx[1], expected_d_size_splits);
+ test::ExpectTensorEqual<int32>(dx[2], expected_d_dim);
+ }
}
std::vector<Tensor> ReshapeGrad(const Tensor& x, const Tensor& s,
diff --git a/tensorflow/core/ops/array_ops.cc b/tensorflow/core/ops/array_ops.cc
index d6ae75473f..1d11ec00ce 100644
--- a/tensorflow/core/ops/array_ops.cc
+++ b/tensorflow/core/ops/array_ops.cc
@@ -427,7 +427,19 @@ REGISTER_OP("UnravelIndex")
.Input("dims: Tidx")
.Output("output: Tidx")
.Attr("Tidx: {int32, int64} = DT_INT32")
- .SetShapeFn([](InferenceContext* c) { return Status::OK(); });
+ .SetShapeFn([](InferenceContext* c) {
+ ShapeHandle indices = c->input(0);
+ ShapeHandle dims;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &dims));
+ if (c->RankKnown(indices) && c->Rank(indices) == 0) {
+ c->set_output(0, c->Vector(c->Dim(dims, 0)));
+ } else if (c->RankKnown(indices)) {
+ c->set_output(0, c->Matrix(c->Dim(dims, 0), c->NumElements(indices)));
+ } else {
+ c->set_output(0, c->UnknownShape());
+ }
+ return Status::OK();
+ });
REGISTER_OP("BroadcastTo")
.Input("input: T")
@@ -631,38 +643,41 @@ REGISTER_OP("SplitV")
return errors::InvalidArgument(
"Length of size_splits should be equal to num_outputs");
}
- int64_t cumsum_outputs = 0;
+ int64_t total_size = 0;
bool has_neg_one = false;
+ for (const auto size : data) {
+ if (size == -1) {
+ if (has_neg_one) {
+ return errors::InvalidArgument(
+ "size_splits can only have one -1");
+ }
+ has_neg_one = true;
+ } else {
+ total_size += size;
+ }
+ }
+ auto split_dim_size = c->Value(c->Dim(input, split_dim));
// If the sizes of the splits are known, then
// make sure that the sizes add up to the expected
// dimension size, with the possibility of a -1.
// Specify the full output shapes.
for (int i = 0; i < num_outputs; ++i) {
- output_shape = c->UnknownShapeOfRank(rank);
- TF_RETURN_IF_ERROR(c->ReplaceDim(input, split_dim,
- c->MakeDim(data[i]), &output_shape));
+ auto size = data[i];
+ if (data[i] == -1 && c->ValueKnown(split_dim_size)) {
+ size = split_dim_size - total_size;
+ }
+ TF_RETURN_IF_ERROR(
+ c->ReplaceDim(input, split_dim, c->MakeDim(size), &output_shape));
c->set_output(i, output_shape);
- if (data[i] == -1 && !has_neg_one)
- has_neg_one = true;
- else if (data[i] == -1 && has_neg_one)
- return errors::InvalidArgument("size_splits can only have one -1");
- else
- cumsum_outputs += data[i];
}
- auto split_dim_size = c->Value(c->Dim(input, split_dim));
- if (has_neg_one) {
- if (cumsum_outputs < split_dim_size)
- cumsum_outputs = split_dim_size;
- else
- cumsum_outputs = split_dim_size + 1;
+ if (c->ValueKnown(split_dim_size)) {
+ if (has_neg_one ? total_size > split_dim_size
+ : total_size != split_dim_size) {
+ return errors::InvalidArgument(
+ "can't split axis of size ", split_dim_size,
+ " into pieces of size [", str_util::Join(data, ","), "]");
+ }
}
- if (c->ValueKnown(c->Dim(input, split_dim)) &&
- cumsum_outputs != c->Value(c->Dim(input, split_dim)))
- return errors::InvalidArgument(
- "Sum of output sizes must match "
- "the size of the original Tensor along the split dimension "
- "or the sum of the positive sizes must be less if it contains a "
- "-1");
}
return Status::OK();
@@ -687,6 +702,16 @@ REGISTER_OP("Const")
return Status::OK();
});
+// Returns a constant tensor on the host. Useful for writing C++ tests
+// and benchmarks which run on GPU but require arguments pinned to the host.
+// Used by test::graph::HostConstant.
+// value: Attr `value` is the tensor to return.
+REGISTER_OP("HostConst")
+ .Output("output: dtype")
+ .Attr("value: tensor")
+ .Attr("dtype: type")
+ .SetShapeFn(shape_inference::UnknownShape);
+
// --------------------------------------------------------------------------
// TODO(mgubin): Update the doc when the freeze_graph script supports converting
// into memmapped format.
diff --git a/tensorflow/core/ops/array_ops_test.cc b/tensorflow/core/ops/array_ops_test.cc
index b1463338fb..03dab390a7 100644
--- a/tensorflow/core/ops/array_ops_test.cc
+++ b/tensorflow/core/ops/array_ops_test.cc
@@ -27,6 +27,21 @@ limitations under the License.
namespace tensorflow {
+TEST(ArrayOpsTest, UnravelIndex_ShapeFn) {
+ ShapeInferenceTestOp op("UnravelIndex");
+
+ INFER_OK(op, "?;?", "?");
+
+ INFER_OK(op, "[];[?]", "[d1_0]");
+
+ INFER_OK(op, "[4,5];[?]", "[d1_0,20]");
+ INFER_OK(op, "[2,3,4];[?]", "[d1_0,24]");
+ INFER_OK(op, "?;[?]", "?");
+ INFER_OK(op, "[?];[?]", "[d1_0,?]");
+
+ INFER_ERROR("Shape must be rank 1 but is rank 2", op, "?;[1,1]");
+}
+
TEST(ArrayOpsTest, Pack_ShapeFn) {
ShapeInferenceTestOp op("Pack");
auto set_axis = [&op](int axis) {
@@ -1605,6 +1620,24 @@ TEST(ArrayOpsTest, Slice_ShapeFn) {
INFER_ERROR("cannot be < -1", op, "[2,3,4,5];[4];[4]");
}
+TEST(ArrayOpsTest, StridedSlice_ShapeFn) {
+ ShapeInferenceTestOp op("StridedSlice");
+ TF_ASSERT_OK(NodeDefBuilder("test", "StridedSlice")
+ .Input("input", 0, DT_FLOAT)
+ .Input("begin", 1, DT_INT32)
+ .Input("end", 2, DT_INT32)
+ .Input("strides", 3, DT_INT32)
+ .Attr("shrink_axis_mask", 1)
+ .Finalize(&op.node_def));
+ op.input_tensors.resize(4);
+ Tensor strides = test::AsTensor<int32>({1});
+ op.input_tensors[3] = &strides;
+ // Slicing on the 0-th dimension.
+ INFER_OK(op, "[2,3,4,5];[1];[1];[1]", "[3,4,5]");
+ // Slicing on the 0-th dimension. This time some of the result dimension is 0.
+ INFER_OK(op, "[2,0,3,4];[1];[1];[1]", "[0,3,4]");
+}
+
TEST(ArrayOpsTest, StridedSliceGrad_ShapeFn) {
ShapeInferenceTestOp op("StridedSliceGrad");
op.input_tensors.resize(5);
diff --git a/tensorflow/core/ops/compat/ops_history.v1.pbtxt b/tensorflow/core/ops/compat/ops_history.v1.pbtxt
index 31db467693..d708b5a5e3 100644
--- a/tensorflow/core/ops/compat/ops_history.v1.pbtxt
+++ b/tensorflow/core/ops/compat/ops_history.v1.pbtxt
@@ -6488,6 +6488,69 @@ op {
}
}
op {
+ name: "AsString"
+ input_arg {
+ name: "input"
+ type_attr: "T"
+ }
+ output_arg {
+ name: "output"
+ type: DT_STRING
+ }
+ attr {
+ name: "T"
+ type: "type"
+ allowed_values {
+ list {
+ type: DT_INT8
+ type: DT_INT16
+ type: DT_INT32
+ type: DT_INT64
+ type: DT_COMPLEX64
+ type: DT_COMPLEX128
+ type: DT_FLOAT
+ type: DT_DOUBLE
+ type: DT_BOOL
+ }
+ }
+ }
+ attr {
+ name: "precision"
+ type: "int"
+ default_value {
+ i: -1
+ }
+ }
+ attr {
+ name: "scientific"
+ type: "bool"
+ default_value {
+ b: false
+ }
+ }
+ attr {
+ name: "shortest"
+ type: "bool"
+ default_value {
+ b: false
+ }
+ }
+ attr {
+ name: "width"
+ type: "int"
+ default_value {
+ i: -1
+ }
+ }
+ attr {
+ name: "fill"
+ type: "string"
+ default_value {
+ s: ""
+ }
+ }
+}
+op {
name: "Asin"
input_arg {
name: "x"
@@ -20254,6 +20317,31 @@ op {
}
}
op {
+ name: "DivNoNan"
+ input_arg {
+ name: "x"
+ type_attr: "T"
+ }
+ input_arg {
+ name: "y"
+ type_attr: "T"
+ }
+ output_arg {
+ name: "z"
+ type_attr: "T"
+ }
+ attr {
+ name: "T"
+ type: "type"
+ allowed_values {
+ list {
+ type: DT_FLOAT
+ type: DT_DOUBLE
+ }
+ }
+ }
+}
+op {
name: "DrawBoundingBoxes"
input_arg {
name: "images"
@@ -25550,6 +25638,21 @@ op {
}
}
op {
+ name: "HostConst"
+ output_arg {
+ name: "output"
+ type_attr: "dtype"
+ }
+ attr {
+ name: "value"
+ type: "tensor"
+ }
+ attr {
+ name: "dtype"
+ type: "type"
+ }
+}
+op {
name: "IFFT"
input_arg {
name: "input"
@@ -68339,6 +68442,43 @@ op {
is_stateful: true
}
op {
+ name: "StatelessIf"
+ input_arg {
+ name: "cond"
+ type_attr: "Tcond"
+ }
+ input_arg {
+ name: "input"
+ type_list_attr: "Tin"
+ }
+ output_arg {
+ name: "output"
+ type_list_attr: "Tout"
+ }
+ attr {
+ name: "Tcond"
+ type: "type"
+ }
+ attr {
+ name: "Tin"
+ type: "list(type)"
+ has_minimum: true
+ }
+ attr {
+ name: "Tout"
+ type: "list(type)"
+ has_minimum: true
+ }
+ attr {
+ name: "then_branch"
+ type: "func"
+ }
+ attr {
+ name: "else_branch"
+ type: "func"
+ }
+}
+op {
name: "StatelessMultinomial"
input_arg {
name: "logits"
@@ -68695,6 +68835,56 @@ op {
}
}
op {
+ name: "StatelessWhile"
+ input_arg {
+ name: "input"
+ type_list_attr: "T"
+ }
+ output_arg {
+ name: "output"
+ type_list_attr: "T"
+ }
+ attr {
+ name: "T"
+ type: "list(type)"
+ has_minimum: true
+ }
+ attr {
+ name: "cond"
+ type: "func"
+ }
+ attr {
+ name: "body"
+ type: "func"
+ }
+}
+op {
+ name: "StaticRegexReplace"
+ input_arg {
+ name: "input"
+ type: DT_STRING
+ }
+ output_arg {
+ name: "output"
+ type: DT_STRING
+ }
+ attr {
+ name: "pattern"
+ type: "string"
+ }
+ attr {
+ name: "rewrite"
+ type: "string"
+ }
+ attr {
+ name: "replace_global"
+ type: "bool"
+ default_value {
+ b: true
+ }
+ }
+}
+op {
name: "StatsAggregatorHandle"
output_arg {
name: "handle"
@@ -68995,6 +69185,17 @@ op {
}
}
op {
+ name: "StringLength"
+ input_arg {
+ name: "input"
+ type: DT_STRING
+ }
+ output_arg {
+ name: "output"
+ type: DT_INT32
+ }
+}
+op {
name: "StringSplit"
input_arg {
name: "input"
diff --git a/tensorflow/core/ops/image_ops.cc b/tensorflow/core/ops/image_ops.cc
index 31267f72b8..11ca0bd259 100644
--- a/tensorflow/core/ops/image_ops.cc
+++ b/tensorflow/core/ops/image_ops.cc
@@ -108,6 +108,29 @@ Status ColorspaceShapeFn(InferenceContext* c) {
return Status::OK();
}
+Status NMSShapeFn(InferenceContext* c) {
+ // Get inputs and validate ranks.
+ ShapeHandle boxes;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &boxes));
+ 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 iou_threshold;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &iou_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(boxes, 0), c->Dim(scores, 0), &unused));
+ // The boxes[1] is 4.
+ TF_RETURN_IF_ERROR(c->WithValue(c->Dim(boxes, 1), 4, &unused));
+
+ c->set_output(0, c->Vector(c->UnknownDim()));
+ return Status::OK();
+}
+
} // namespace
// --------------------------------------------------------------------------
@@ -348,6 +371,11 @@ REGISTER_OP("AdjustContrast")
.Attr("T: {uint8, int8, int16, int32, int64, float, double}")
.Deprecated(2, "Use AdjustContrastv2 instead")
.SetShapeFn([](InferenceContext* c) {
+ // The contrast_factor, min_value, max_value should be scalar only.
+ ShapeHandle unused;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused));
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 0, &unused));
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &unused));
return shape_inference::UnchangedShapeWithRankAtLeast(c, 3);
});
@@ -357,6 +385,9 @@ REGISTER_OP("AdjustContrastv2")
.Input("contrast_factor: float")
.Output("output: float")
.SetShapeFn([](InferenceContext* c) {
+ // The contrast_factor should be scalar only.
+ ShapeHandle unused;
+ TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused));
return shape_inference::UnchangedShapeWithRankAtLeast(c, 3);
});
@@ -686,29 +717,7 @@ REGISTER_OP("NonMaxSuppressionV3")
.Input("iou_threshold: float")
.Input("score_threshold: float")
.Output("selected_indices: int32")
- .SetShapeFn([](InferenceContext* c) {
- // Get inputs and validate ranks.
- ShapeHandle boxes;
- TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &boxes));
- 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 iou_threshold;
- TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &iou_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(boxes, 0), c->Dim(scores, 0), &unused));
- // The boxes[1] is 4.
- TF_RETURN_IF_ERROR(c->WithValue(c->Dim(boxes, 1), 4, &unused));
-
- c->set_output(0, c->Vector(c->UnknownDim()));
- return Status::OK();
- });
+ .SetShapeFn(NMSShapeFn);
REGISTER_OP("NonMaxSuppressionV4")
.Input("boxes: float")
@@ -720,26 +729,16 @@ REGISTER_OP("NonMaxSuppressionV4")
.Output("valid_outputs: int32")
.Attr("pad_to_max_output_size: bool = false")
.SetShapeFn([](InferenceContext* c) {
- // Get inputs and validate ranks.
- ShapeHandle boxes;
- TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &boxes));
- 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 iou_threshold;
- TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &iou_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(boxes, 0), c->Dim(scores, 0), &unused));
- // The boxes[1] is 4.
- TF_RETURN_IF_ERROR(c->WithValue(c->Dim(boxes, 1), 4, &unused));
-
- c->set_output(0, c->Vector(c->UnknownDim()));
+ TF_RETURN_IF_ERROR(NMSShapeFn(c));
+
+ bool pad_to_max;
+ TF_RETURN_IF_ERROR(c->GetAttr("pad_to_max_output_size", &pad_to_max));
+ if (pad_to_max) {
+ // If padded, overwrite the shape of the output to be static.
+ DimensionHandle output_dim;
+ TF_RETURN_IF_ERROR(c->MakeDimForScalarInput(2, &output_dim));
+ c->set_output(0, c->MakeShape({output_dim}));
+ }
c->set_output(1, c->MakeShape({}));
return Status::OK();
});
diff --git a/tensorflow/core/ops/lookup_ops.cc b/tensorflow/core/ops/lookup_ops.cc
index 2059741da9..7c71406c6b 100644
--- a/tensorflow/core/ops/lookup_ops.cc
+++ b/tensorflow/core/ops/lookup_ops.cc
@@ -23,6 +23,7 @@ namespace tensorflow {
using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
+using shape_inference::ShapeAndType;
using shape_inference::ShapeHandle;
// --------------------------------------------------------------------------
@@ -86,6 +87,74 @@ REGISTER_OP("LookupTableFind")
return Status::OK();
});
+Status ValidateTableResourceHandle(InferenceContext* c, ShapeHandle keys,
+ const string& key_dtype_attr,
+ const string& value_dtype_attr,
+ bool is_lookup,
+ ShapeAndType* output_shape_and_type) {
+ auto* handle_data = c->input_handle_shapes_and_types(0);
+ if (handle_data == nullptr || handle_data->size() != 2) {
+ output_shape_and_type->shape = c->UnknownShape();
+ output_shape_and_type->dtype = DT_INVALID;
+ } else {
+ const ShapeAndType& key_shape_and_type = (*handle_data)[0];
+ const ShapeAndType& value_shape_and_type = (*handle_data)[1];
+ DataType key_dtype;
+ TF_RETURN_IF_ERROR(c->GetAttr(key_dtype_attr, &key_dtype));
+ if (key_shape_and_type.dtype != key_dtype) {
+ return errors::InvalidArgument(
+ "Trying to read value with wrong dtype. "
+ "Expected ",
+ DataTypeString(key_shape_and_type.dtype), " got ",
+ DataTypeString(key_dtype));
+ }
+ DataType value_dtype;
+ TF_RETURN_IF_ERROR(c->GetAttr(value_dtype_attr, &value_dtype));
+ if (value_shape_and_type.dtype != value_dtype) {
+ return errors::InvalidArgument(
+ "Trying to read value with wrong dtype. "
+ "Expected ",
+ DataTypeString(value_shape_and_type.dtype), " got ",
+ DataTypeString(value_dtype));
+ }
+ output_shape_and_type->dtype = value_shape_and_type.dtype;
+
+ if (is_lookup) {
+ if (c->RankKnown(key_shape_and_type.shape) && c->RankKnown(keys)) {
+ int keys_rank = c->Rank(keys);
+ int key_suffix_rank = c->Rank(key_shape_and_type.shape);
+ if (keys_rank < key_suffix_rank) {
+ return errors::InvalidArgument(
+ "Expected keys to have suffix ",
+ c->DebugString(key_shape_and_type.shape),
+ " but saw shape: ", c->DebugString(keys));
+ }
+ for (int d = 0; d < key_suffix_rank; d++) {
+ // Ensure the suffix of keys match what's in the Table.
+ DimensionHandle dim = c->Dim(key_shape_and_type.shape, d);
+ TF_RETURN_IF_ERROR(
+ c->ReplaceDim(keys, keys_rank - key_suffix_rank + d, dim, &keys));
+ }
+ std::vector<DimensionHandle> keys_prefix_vec;
+ keys_prefix_vec.reserve(keys_rank - key_suffix_rank);
+ for (int d = 0; d < keys_rank - key_suffix_rank; ++d) {
+ keys_prefix_vec.push_back(c->Dim(keys, d));
+ }
+ ShapeHandle keys_prefix = c->MakeShape(keys_prefix_vec);
+ TF_RETURN_IF_ERROR(c->Concatenate(keys_prefix,
+ value_shape_and_type.shape,
+ &output_shape_and_type->shape));
+ } else {
+ output_shape_and_type->shape = c->UnknownShape();
+ }
+ } else {
+ TF_RETURN_IF_ERROR(c->Concatenate(keys, value_shape_and_type.shape,
+ &output_shape_and_type->shape));
+ }
+ }
+ return Status::OK();
+}
+
REGISTER_OP("LookupTableFindV2")
.Input("table_handle: resource")
.Input("keys: Tin")
@@ -98,9 +167,18 @@ REGISTER_OP("LookupTableFindV2")
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &handle));
// Default value must be scalar or vector.
- ShapeHandle unused;
- TF_RETURN_IF_ERROR(c->WithRankAtMost(c->input(2), 1, &unused));
- c->set_output(0, c->UnknownShape());
+ ShapeHandle keys;
+ TF_RETURN_IF_ERROR(c->WithRankAtMost(c->input(2), 1, &keys));
+
+ ShapeAndType value_shape_and_type;
+ TF_RETURN_IF_ERROR(ValidateTableResourceHandle(
+ c,
+ /*keys=*/c->input(1),
+ /*key_dtype_attr=*/"Tin",
+ /*value_dtype_attr=*/"Tout",
+ /*is_lookup=*/true, &value_shape_and_type));
+ c->set_output(0, value_shape_and_type.shape);
+
return Status::OK();
});
WHITELIST_STATEFUL_OP_FOR_DATASET_FUNCTIONS("LookupTableFindV2");
@@ -177,12 +255,16 @@ REGISTER_OP("LookupTableExportV2")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle handle;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &handle));
-
- ShapeHandle values = c->UnknownShape();
- TF_RETURN_IF_ERROR(c->WithRankAtLeast(values, 1, &values));
- ShapeHandle keys = c->Vector(c->Dim(values, 0));
+ ShapeHandle keys = c->UnknownShapeOfRank(1);
+ ShapeAndType value_shape_and_type;
+ TF_RETURN_IF_ERROR(ValidateTableResourceHandle(
+ c,
+ /*keys=*/keys,
+ /*key_dtype_attr=*/"Tkeys",
+ /*value_dtype_attr=*/"Tvalues",
+ /*is_lookup=*/false, &value_shape_and_type));
c->set_output(0, keys);
- c->set_output(1, values);
+ c->set_output(1, value_shape_and_type.shape);
return Status::OK();
});
@@ -216,6 +298,26 @@ REGISTER_OP("LookupTableImportV2")
return Status::OK();
});
+Status MutableHashTableShape(InferenceContext* c, const ShapeHandle& key,
+ const ShapeHandle& value) {
+ c->set_output(0, c->Scalar());
+
+ ShapeHandle key_s;
+ TF_RETURN_IF_ERROR(c->WithRankAtMost(key, 1, &key_s));
+
+ DataType key_t;
+ TF_RETURN_IF_ERROR(c->GetAttr("key_dtype", &key_t));
+
+ DataType value_t;
+ TF_RETURN_IF_ERROR(c->GetAttr("value_dtype", &value_t));
+
+ // ShapeAndType vector for {key, value}.
+ c->set_output_handle_shapes_and_types(
+ 0, std::vector<ShapeAndType>{{key_s, key_t}, {value, value_t}});
+
+ return Status::OK();
+}
+
REGISTER_OP("HashTable")
.Output("table_handle: Ref(string)")
.Attr("container: string = ''")
@@ -254,7 +356,10 @@ REGISTER_OP("MutableHashTableV2")
.Attr("key_dtype: type")
.Attr("value_dtype: type")
.SetIsStateful()
- .SetShapeFn(ScalarOutput);
+ .SetShapeFn([](InferenceContext* c) {
+ return MutableHashTableShape(c, /*key=*/c->Scalar(),
+ /*value=*/c->Scalar());
+ });
REGISTER_OP("MutableHashTableOfTensors")
.Output("table_handle: Ref(string)")
@@ -276,7 +381,13 @@ REGISTER_OP("MutableHashTableOfTensorsV2")
.Attr("value_dtype: type")
.Attr("value_shape: shape = {}")
.SetIsStateful()
- .SetShapeFn(ScalarOutput);
+ .SetShapeFn([](InferenceContext* c) {
+ PartialTensorShape value_p;
+ TF_RETURN_IF_ERROR(c->GetAttr("value_shape", &value_p));
+ ShapeHandle value_s;
+ TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(value_p, &value_s));
+ return MutableHashTableShape(c, /*key=*/c->Scalar(), /*value=*/value_s);
+ });
REGISTER_OP("MutableDenseHashTable")
.Input("empty_key: key_dtype")
@@ -304,7 +415,13 @@ REGISTER_OP("MutableDenseHashTableV2")
.Attr("initial_num_buckets: int = 131072") // 2^17
.Attr("max_load_factor: float = 0.8")
.SetIsStateful()
- .SetShapeFn(ScalarOutput);
+ .SetShapeFn([](InferenceContext* c) {
+ PartialTensorShape value_p;
+ TF_RETURN_IF_ERROR(c->GetAttr("value_shape", &value_p));
+ ShapeHandle value_s;
+ TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(value_p, &value_s));
+ return MutableHashTableShape(c, /*key=*/c->input(0), /*value=*/value_s);
+ });
REGISTER_OP("InitializeTable")
.Input("table_handle: Ref(string)")
diff --git a/tensorflow/core/ops/math_grad.cc b/tensorflow/core/ops/math_grad.cc
index 783d292389..07f876cb90 100644
--- a/tensorflow/core/ops/math_grad.cc
+++ b/tensorflow/core/ops/math_grad.cc
@@ -495,6 +495,19 @@ Status RealDivGrad(const AttrSlice& attrs, FunctionDef* g) {
}
REGISTER_OP_GRADIENT("RealDiv", RealDivGrad);
+Status DivNoNanGrad(const AttrSlice& attrs, FunctionDef* g) {
+ // clang-format off
+ return GradForBinaryCwise(g, {
+ {{"gx"}, "DivNoNan", {"dz", "y"}},
+ {{"nx"}, "Neg", {"x"}, {}, {"dz"}},
+ {{"y2"}, "Square", {"y"}, {}, {"dz"}},
+ {{"nx_y2"}, "DivNoNan", {"nx", "y2"}},
+ {{"gy"}, "Mul", {"dz", "nx_y2"}}, // dz * (- x / y^2)
+ });
+ // clang-format on
+}
+REGISTER_OP_GRADIENT("DivNoNan", DivNoNanGrad);
+
Status PowGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
std::vector<FDH::Node> nodes = {
diff --git a/tensorflow/core/ops/math_grad_test.cc b/tensorflow/core/ops/math_grad_test.cc
index 2a27ef3ddb..5ee79809ac 100644
--- a/tensorflow/core/ops/math_grad_test.cc
+++ b/tensorflow/core/ops/math_grad_test.cc
@@ -753,6 +753,78 @@ TEST_F(MathGradTest, Div) {
}
}
+TEST_F(MathGradTest, DivNoNan) {
+ auto x = test::AsTensor<float>(
+ {0.f, -3.f, -2.f, -1.f, 0.f, 1.f, 2.f, 3.f, 0.f}, TensorShape({3, 3}));
+ auto y = test::AsTensor<float>({-10.f, 0.f, 10.f}, TensorShape({3, 1}));
+ Tensor dx;
+ Tensor dy;
+ {
+ SymGrad("DivNoNan", x, y, &dx, &dy);
+ {
+ auto g = [](float x, float y) {
+ if (y == 0.f) {
+ return 0.f;
+ } else {
+ return 1.f / y;
+ }
+ };
+ test::ExpectClose(dx, test::AsTensor<float>(
+ {g(0.f, -10.f), g(-3.f, -10.f), g(-2.f, -10.f),
+ g(-1.f, 0.f), g(0.f, 0.f), g(1.f, 0.f),
+ g(2.f, 10.f), g(3.f, 10.f), g(0.f, 10.f)},
+ TensorShape({3, 3})));
+ }
+ {
+ auto g = [](float x, float y) {
+ if (y == 0.f) {
+ return 0.f;
+ } else {
+ return -x / (y * y);
+ }
+ };
+ test::ExpectClose(dy,
+ test::AsTensor<float>(
+ {g(0.f, -10.f) + g(-3.f, -10.f) + g(-2.f, -10.f),
+ g(-1.f, 0.f) + g(0.f, 0.f) + g(1.f, 0.f),
+ g(2.f, 10.f) + g(3.f, 10.f) + g(0.f, 10.f)},
+ TensorShape({3, 1})));
+ }
+ }
+ { // Swap x and y.
+ SymGrad("DivNoNan", y, x, &dy, &dx);
+ {
+ auto g = [](float x, float y) {
+ if (y == 0.f) {
+ return 0.f;
+ } else {
+ return 1.f / y;
+ }
+ };
+ test::ExpectClose(dy,
+ test::AsTensor<float>(
+ {g(-10.f, 0.f) + g(-10.f, -3.f) + g(-10.f, -2.f),
+ g(0.f, -1.f) + g(0.f, 0.f) + g(0.f, 1.f),
+ g(10.f, 2.f) + g(10.f, 3.f) + g(10.f, 0.f)},
+ TensorShape({3, 1})));
+ }
+ {
+ auto g = [](float x, float y) {
+ if (y == 0.f) {
+ return 0.f;
+ } else {
+ return -x / (y * y);
+ }
+ };
+ test::ExpectClose(dx, test::AsTensor<float>(
+ {g(-10.f, 0.f), g(-10.f, -3.f), g(-10.f, -2.f),
+ g(0.f, -1.f), g(0.f, 0.f), g(0.f, 1.f),
+ g(10.f, 2.f), g(10.f, 3.f), g(10.f, 0.f)},
+ TensorShape({3, 3})));
+ }
+ }
+}
+
TEST_F(MathGradTest, Pow) {
auto x = test::AsTensor<float>({0.f, 1.f, 2.f, 3.f, 4.f, 5.f},
TensorShape({2, 3}));
diff --git a/tensorflow/core/ops/math_ops.cc b/tensorflow/core/ops/math_ops.cc
index 1667c398f4..717263a9b0 100644
--- a/tensorflow/core/ops/math_ops.cc
+++ b/tensorflow/core/ops/math_ops.cc
@@ -392,6 +392,13 @@ Returns x * y element-wise.
REGISTER_OP("Div").BINARY_MORE().SetShapeFn(
shape_inference::BroadcastBinaryOpShapeFn);
+REGISTER_OP("DivNoNan")
+ .Input("x: T")
+ .Input("y: T")
+ .Output("z: T")
+ .Attr("T: {float, double}")
+ .SetShapeFn(shape_inference::BroadcastBinaryOpShapeFn);
+
REGISTER_OP("FloorDiv")
.BINARY_MORE()
.SetShapeFn(shape_inference::BroadcastBinaryOpShapeFn);
diff --git a/tensorflow/core/ops/math_ops_test.cc b/tensorflow/core/ops/math_ops_test.cc
index 23f1538912..be4c3ed2b6 100644
--- a/tensorflow/core/ops/math_ops_test.cc
+++ b/tensorflow/core/ops/math_ops_test.cc
@@ -120,7 +120,8 @@ TEST(MathOpsTest, BroadcastBinaryOps_ShapeFn) {
"Maximum", "Minimum",
"Mod", "Mul",
"NotEqual", "Pow",
- "Sub", "SquaredDifference"}) {
+ "Sub", "SquaredDifference",
+ "DivNoNan"}) {
ShapeInferenceTestOp op(op_name);
INFER_OK(op, "?;?", "?");
INFER_OK(op, "[1,2];?", "?");
diff --git a/tensorflow/core/ops/nn_ops.cc b/tensorflow/core/ops/nn_ops.cc
index f947d4c30d..385021b168 100644
--- a/tensorflow/core/ops/nn_ops.cc
+++ b/tensorflow/core/ops/nn_ops.cc
@@ -1687,7 +1687,7 @@ NOTE Do not invoke this operator directly in Python. Graph rewrite pass is
expected to invoke these operators.
)doc");
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
REGISTER_OP("_MklConv2DWithBiasBackpropBias")
.Input("out_backprop: T")
.Input("mkl_out_backprop: uint8")
@@ -1736,6 +1736,87 @@ NOTE Do not invoke this operator directly in Python. Graph rewrite pass is
expected to invoke these operators.
)doc");
+REGISTER_OP("_MklConv3D")
+ .Input("input: T")
+ .Input("filter: T")
+ .Input("mkl_input: uint8")
+ .Input("mkl_filter: uint8")
+ .Output("output: T")
+ .Output("filter_output: T")
+ .Output("mkl_output: uint8")
+ .Output("mkl_filter_output: uint8")
+ .Attr("T: {half, float, double}")
+ .Attr("strides: list(int) >= 5")
+ .Attr(GetPaddingAttrString())
+ .Attr(GetConvnet3dDataFormatAttrString())
+ .Attr("dilations: list(int) = [1, 1, 1, 1, 1]")
+ .SetShapeFn(shape_inference::Conv3DShape)
+ .Doc(R"doc(
+MKL version of Conv3D operator. Uses MKL DNN APIs to perform 3D convolution.
+
+NOTE Do not invoke this operator directly in Python. Graph rewrite pass is
+expected to invoke these operators.
+)doc");
+
+REGISTER_OP("_MklConv3DBackpropInputV2")
+ .Input("input_sizes: Tshape")
+ .Input("filter: T")
+ .Input("out_backprop: T")
+ .Input("mkl_input_sizes: uint8")
+ .Input("mkl_filter: uint8")
+ .Input("mkl_out_backprop: uint8")
+ .Output("output: T")
+ .Output("mkl_output: uint8")
+ .Attr("T: {half, float, double}")
+ .Attr("strides: list(int) >= 5")
+ .Attr("dilations: list(int) = [1, 1, 1, 1, 1]")
+ .Attr("Tshape: {int32, int64} = DT_INT32")
+ .Attr(GetPaddingAttrString())
+ .Attr(GetConvnet3dDataFormatAttrString())
+ .SetShapeFn([](InferenceContext* c) {
+ ShapeHandle s;
+ TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(0, &s));
+ TF_RETURN_IF_ERROR(c->WithRank(s, 5, &s));
+ c->set_output(0, s);
+ return Status::OK();
+ })
+ .Doc(R"doc(
+MKL version of Convolution3D backward input. Uses MKL DNN APIs to compute the
+gradients of convolution with respect to the input.
+
+NOTE Do not invoke this operator directly in Python. Graph rewrite pass is
+expected to invoke these operators.
+)doc");
+
+REGISTER_OP("_MklConv3DBackpropFilterV2")
+ .Input("input: T")
+ .Input("filter_sizes: int32")
+ .Input("out_backprop: T")
+ .Input("mkl_input: uint8")
+ .Input("mkl_filter_size: uint8")
+ .Input("mkl_out_backprop: uint8")
+ .Output("output: T")
+ .Output("mkl_output: uint8")
+ .Attr("T: {half, float, double}")
+ .Attr("strides: list(int)")
+ .Attr(GetPaddingAttrString())
+ .Attr(GetConvnet3dDataFormatAttrString())
+ .Attr("dilations: list(int) = [1, 1, 1, 1, 1]")
+ .SetShapeFn([](InferenceContext* c) {
+ ShapeHandle s;
+ TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(1, &s));
+ TF_RETURN_IF_ERROR(c->WithRank(s, 5, &s));
+ c->set_output(0, s);
+ return Status::OK();
+ })
+ .Doc(R"doc(
+MKL version of Conv3DBackpropFilter. Uses MKL DNN APIs to compute the
+gradients of convolution with respect to the filter.
+
+NOTE Do not invoke this operator directly in Python. Graph rewrite pass is
+expected to invoke these operators.
+)doc");
+
REGISTER_OP("_MklRelu")
.Input("features: T")
.Input("mkl_features: uint8")
@@ -1849,7 +1930,7 @@ REGISTER_OP("_MklMaxPool")
.Input("input: T")
.Input("mkl_input: uint8")
.Output("output: T")
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
.Output("workspace: T")
#else
.Output("workspace: uint8")
@@ -1875,7 +1956,7 @@ REGISTER_OP("_MklMaxPoolGrad")
.Input("orig_input: T")
.Input("orig_output: T")
.Input("grad: T")
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
.Input("workspace: T")
#else
.Input("workspace: uint8")
@@ -1947,7 +2028,7 @@ REGISTER_OP("_MklLRN")
.Input("input: T")
.Input("mkl_input: uint8")
.Output("output: T")
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
.Output("workspace: T")
#else
.Output("workspace: uint8")
@@ -1975,7 +2056,7 @@ REGISTER_OP("_MklLRNGrad")
.Input("input_grads: T")
.Input("input_image: T")
.Input("output_image: T")
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
.Input("workspace: T")
#else
.Input("workspace: uint8")
@@ -2161,7 +2242,7 @@ REGISTER_OP("_MklToTf")
.Input("mkl_input: uint8")
.Output("output: T")
.Attr("T: {half, float, double}")
- .Attr(GetConvnetDataFormatAttrString())
+ .Attr(GetConvnetDataFormat2D3DAttrString())
.SetShapeFn(shape_inference::UnknownShape)
.Doc(R"doc(
MKL operator to convert a tensor from MKL layout to TensorFlow layout.
@@ -2183,7 +2264,7 @@ REGISTER_OP("_MklInputConversion")
.Attr(
"T: {half, float, double, uint8, int8, uint16, int16, int32, int64, "
"complex64, complex128}")
- .Attr(GetConvnetDataFormatAttrString())
+ .Attr(GetConvnetDataFormat2D3DAttrString())
.SetShapeFn(shape_inference::UnknownShape)
.Doc(R"doc(
MKL operator to process the inputs to an elementwise MKL op. Both inputs
diff --git a/tensorflow/core/ops/ops.pbtxt b/tensorflow/core/ops/ops.pbtxt
index 0f21a4f28c..560e706931 100644
--- a/tensorflow/core/ops/ops.pbtxt
+++ b/tensorflow/core/ops/ops.pbtxt
@@ -1982,6 +1982,7 @@ op {
type: DT_INT32
type: DT_INT64
type: DT_COMPLEX64
+ type: DT_COMPLEX128
type: DT_FLOAT
type: DT_DOUBLE
type: DT_BOOL
@@ -9189,6 +9190,31 @@ op {
}
}
op {
+ name: "DivNoNan"
+ input_arg {
+ name: "x"
+ type_attr: "T"
+ }
+ input_arg {
+ name: "y"
+ type_attr: "T"
+ }
+ output_arg {
+ name: "z"
+ type_attr: "T"
+ }
+ attr {
+ name: "T"
+ type: "type"
+ allowed_values {
+ list {
+ type: DT_FLOAT
+ type: DT_DOUBLE
+ }
+ }
+ }
+}
+op {
name: "DrawBoundingBoxes"
input_arg {
name: "images"
@@ -12256,6 +12282,21 @@ op {
}
}
op {
+ name: "HostConst"
+ output_arg {
+ name: "output"
+ type_attr: "dtype"
+ }
+ attr {
+ name: "value"
+ type: "tensor"
+ }
+ attr {
+ name: "dtype"
+ type: "type"
+ }
+}
+op {
name: "IFFT"
input_arg {
name: "input"
@@ -31513,6 +31554,43 @@ op {
is_stateful: true
}
op {
+ name: "StatelessIf"
+ input_arg {
+ name: "cond"
+ type_attr: "Tcond"
+ }
+ input_arg {
+ name: "input"
+ type_list_attr: "Tin"
+ }
+ output_arg {
+ name: "output"
+ type_list_attr: "Tout"
+ }
+ attr {
+ name: "Tcond"
+ type: "type"
+ }
+ attr {
+ name: "Tin"
+ type: "list(type)"
+ has_minimum: true
+ }
+ attr {
+ name: "Tout"
+ type: "list(type)"
+ has_minimum: true
+ }
+ attr {
+ name: "then_branch"
+ type: "func"
+ }
+ attr {
+ name: "else_branch"
+ type: "func"
+ }
+}
+op {
name: "StatelessMultinomial"
input_arg {
name: "logits"
@@ -31743,6 +31821,56 @@ op {
}
}
op {
+ name: "StatelessWhile"
+ input_arg {
+ name: "input"
+ type_list_attr: "T"
+ }
+ output_arg {
+ name: "output"
+ type_list_attr: "T"
+ }
+ attr {
+ name: "T"
+ type: "list(type)"
+ has_minimum: true
+ }
+ attr {
+ name: "cond"
+ type: "func"
+ }
+ attr {
+ name: "body"
+ type: "func"
+ }
+}
+op {
+ name: "StaticRegexReplace"
+ input_arg {
+ name: "input"
+ type: DT_STRING
+ }
+ output_arg {
+ name: "output"
+ type: DT_STRING
+ }
+ attr {
+ name: "pattern"
+ type: "string"
+ }
+ attr {
+ name: "rewrite"
+ type: "string"
+ }
+ attr {
+ name: "replace_global"
+ type: "bool"
+ default_value {
+ b: true
+ }
+ }
+}
+op {
name: "StatsAggregatorHandle"
output_arg {
name: "handle"
@@ -32043,6 +32171,17 @@ op {
}
}
op {
+ name: "StringLength"
+ input_arg {
+ name: "input"
+ type: DT_STRING
+ }
+ output_arg {
+ name: "output"
+ type: DT_INT32
+ }
+}
+op {
name: "StringSplit"
input_arg {
name: "input"
diff --git a/tensorflow/core/ops/string_ops.cc b/tensorflow/core/ops/string_ops.cc
index 4423062362..7aa1e71809 100644
--- a/tensorflow/core/ops/string_ops.cc
+++ b/tensorflow/core/ops/string_ops.cc
@@ -37,6 +37,14 @@ REGISTER_OP("RegexReplace")
return Status::OK();
});
+REGISTER_OP("StaticRegexReplace")
+ .Input("input: string")
+ .Attr("pattern: string")
+ .Attr("rewrite: string")
+ .Output("output: string")
+ .Attr("replace_global: bool = true")
+ .SetShapeFn(shape_inference::UnchangedShape);
+
REGISTER_OP("RegexFullMatch")
.Input("input: string")
.Input("pattern: string")
@@ -78,7 +86,9 @@ REGISTER_OP("ReduceJoin")
REGISTER_OP("AsString")
.Input("input: T")
.Output("output: string")
- .Attr("T: {int8, int16, int32, int64, complex64, float, double, bool}")
+ .Attr(
+ "T: {int8, int16, int32, int64, complex64, complex128, float, double, "
+ "bool}")
.Attr("precision: int = -1")
.Attr("scientific: bool = false")
.Attr("shortest: bool = false")
@@ -157,6 +167,11 @@ REGISTER_OP("StringStrip")
.Output("output: string")
.SetShapeFn(shape_inference::UnchangedShape);
+REGISTER_OP("StringLength")
+ .Input("input: string")
+ .Output("output: int32")
+ .SetShapeFn(shape_inference::UnchangedShape);
+
REGISTER_OP("EncodeBase64")
.Input("input: string")
.Output("output: string")
diff --git a/tensorflow/core/platform/cloud/gcs_file_system.cc b/tensorflow/core/platform/cloud/gcs_file_system.cc
index 67c872ac67..9d33787bd5 100644
--- a/tensorflow/core/platform/cloud/gcs_file_system.cc
+++ b/tensorflow/core/platform/cloud/gcs_file_system.cc
@@ -618,9 +618,11 @@ bool StringPieceIdentity(StringPiece str, StringPiece* value) {
}
/// \brief Utility function to split a comma delimited list of strings to an
-/// unordered set
-bool SplitByCommaToSet(StringPiece list, std::unordered_set<string>* set) {
- std::vector<string> vector = str_util::Split(list, ",");
+/// unordered set, lowercasing all values.
+bool SplitByCommaToLowercaseSet(StringPiece list,
+ std::unordered_set<string>* set) {
+ std::vector<string> vector =
+ str_util::Split(tensorflow::str_util::Lowercase(list), ",");
*set = std::unordered_set<string>(vector.begin(), vector.end());
return true;
}
@@ -778,7 +780,8 @@ GcsFileSystem::GcsFileSystem() {
throttle_.SetConfig(config);
}
- GetEnvVar(kAllowedBucketLocations, SplitByCommaToSet, &allowed_locations_);
+ GetEnvVar(kAllowedBucketLocations, SplitByCommaToLowercaseSet,
+ &allowed_locations_);
}
GcsFileSystem::GcsFileSystem(
@@ -1155,8 +1158,11 @@ Status GcsFileSystem::GetBucketLocation(const string& bucket,
Status status = GetBucketMetadata(bucket, &result_buffer);
Json::Value result;
TF_RETURN_IF_ERROR(ParseJson(result_buffer, &result));
+ string bucket_location;
TF_RETURN_IF_ERROR(
- GetStringValue(result, kBucketMetadataLocationKey, location));
+ GetStringValue(result, kBucketMetadataLocationKey, &bucket_location));
+ // Lowercase the GCS location to be case insensitive for allowed locations.
+ *location = tensorflow::str_util::Lowercase(bucket_location);
return Status::OK();
};
diff --git a/tensorflow/core/platform/cloud/gcs_file_system_test.cc b/tensorflow/core/platform/cloud/gcs_file_system_test.cc
index ee2b034d74..14376ad339 100644
--- a/tensorflow/core/platform/cloud/gcs_file_system_test.cc
+++ b/tensorflow/core/platform/cloud/gcs_file_system_test.cc
@@ -98,7 +98,7 @@ TEST(GcsFileSystemTest,
"Timeouts: 5 1 10\n",
R"(
{
- "location":"us-east1"
+ "location":"US-EAST1"
})")});
GcsFileSystem fs(std::unique_ptr<AuthProvider>(new FakeAuthProvider),
@@ -124,7 +124,7 @@ TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintCaching) {
"Timeouts: 5 1 10\n",
R"(
{
- "location":"us-east1"
+ "location":"US-EAST1"
})"),
new FakeHttpRequest(
"Uri: https://www.googleapis.com/storage/v1/b/anotherbucket\n"
@@ -132,7 +132,7 @@ TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintCaching) {
"Timeouts: 5 1 10\n",
R"(
{
- "location":"us-east1"
+ "location":"US-EAST1"
})"),
new FakeHttpRequest(
"Uri: https://www.googleapis.com/storage/v1/b/bucket\n"
@@ -140,7 +140,7 @@ TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintCaching) {
"Timeouts: 5 1 10\n",
R"(
{
- "location":"us-east1"
+ "location":"US-EAST1"
})")});
GcsFileSystem fs(std::unique_ptr<AuthProvider>(new FakeAuthProvider),
@@ -181,7 +181,7 @@ TEST(GcsFileSystemTest,
"Timeouts: 5 1 10\n",
R"(
{
- "location":"barfoo"
+ "location":"BARFOO"
})")});
GcsFileSystem fs(std::unique_ptr<AuthProvider>(new FakeAuthProvider),
@@ -3076,7 +3076,7 @@ TEST(GcsFileSystemTest, BucketLocationConstraintEnvironmentVariableTest) {
GcsFileSystem fs1;
EXPECT_EQ(*kAllowedLocationsAuto, fs1.allowed_locations());
- setenv("GCS_ALLOWED_BUCKET_LOCATIONS", "custom,list", 1);
+ setenv("GCS_ALLOWED_BUCKET_LOCATIONS", "CUSTOM,list", 1);
GcsFileSystem fs2;
EXPECT_EQ(std::unordered_set<string>({"custom", "list"}),
fs2.allowed_locations());
diff --git a/tensorflow/core/platform/default/build_config.bzl b/tensorflow/core/platform/default/build_config.bzl
index 28891320c4..5ec7a82ae9 100644
--- a/tensorflow/core/platform/default/build_config.bzl
+++ b/tensorflow/core/platform/default/build_config.bzl
@@ -8,224 +8,229 @@ load("//tensorflow/core:platform/default/build_config_root.bzl", "if_static")
load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda")
load(
"//third_party/mkl:build_defs.bzl",
- "if_mkl",
+ "if_mkl_ml",
)
# Appends a suffix to a list of deps.
def tf_deps(deps, suffix):
- tf_deps = []
+ tf_deps = []
- # If the package name is in shorthand form (ie: does not contain a ':'),
- # expand it to the full name.
- for dep in deps:
- tf_dep = dep
+ # If the package name is in shorthand form (ie: does not contain a ':'),
+ # expand it to the full name.
+ for dep in deps:
+ tf_dep = dep
- if not ":" in dep:
- dep_pieces = dep.split("/")
- tf_dep += ":" + dep_pieces[len(dep_pieces) - 1]
+ if not ":" in dep:
+ dep_pieces = dep.split("/")
+ tf_dep += ":" + dep_pieces[len(dep_pieces) - 1]
- tf_deps += [tf_dep + suffix]
+ tf_deps += [tf_dep + suffix]
- return tf_deps
+ return tf_deps
# Modified from @cython//:Tools/rules.bzl
def pyx_library(
- name,
- deps=[],
- py_deps=[],
- srcs=[],
- **kwargs):
- """Compiles a group of .pyx / .pxd / .py files.
-
- First runs Cython to create .cpp files for each input .pyx or .py + .pxd
- pair. Then builds a shared object for each, passing "deps" to each cc_binary
- rule (includes Python headers by default). Finally, creates a py_library rule
- with the shared objects and any pure Python "srcs", with py_deps as its
- dependencies; the shared objects can be imported like normal Python files.
-
- Args:
- name: Name for the rule.
- deps: C/C++ dependencies of the Cython (e.g. Numpy headers).
- py_deps: Pure Python dependencies of the final library.
- srcs: .py, .pyx, or .pxd files to either compile or pass through.
- **kwargs: Extra keyword arguments passed to the py_library.
- """
- # First filter out files that should be run compiled vs. passed through.
- py_srcs = []
- pyx_srcs = []
- pxd_srcs = []
- for src in srcs:
- if src.endswith(".pyx") or (src.endswith(".py")
- and src[:-3] + ".pxd" in srcs):
- pyx_srcs.append(src)
- elif src.endswith(".py"):
- py_srcs.append(src)
- else:
- pxd_srcs.append(src)
- if src.endswith("__init__.py"):
- pxd_srcs.append(src)
-
- # Invoke cython to produce the shared object libraries.
- for filename in pyx_srcs:
- native.genrule(
- name = filename + "_cython_translation",
- srcs = [filename],
- outs = [filename.split(".")[0] + ".cpp"],
- # Optionally use PYTHON_BIN_PATH on Linux platforms so that python 3
- # works. Windows has issues with cython_binary so skip PYTHON_BIN_PATH.
- cmd = "PYTHONHASHSEED=0 $(location @cython//:cython_binary) --cplus $(SRCS) --output-file $(OUTS)",
- tools = ["@cython//:cython_binary"] + pxd_srcs,
+ name,
+ deps = [],
+ py_deps = [],
+ srcs = [],
+ **kwargs):
+ """Compiles a group of .pyx / .pxd / .py files.
+
+ First runs Cython to create .cpp files for each input .pyx or .py + .pxd
+ pair. Then builds a shared object for each, passing "deps" to each cc_binary
+ rule (includes Python headers by default). Finally, creates a py_library rule
+ with the shared objects and any pure Python "srcs", with py_deps as its
+ dependencies; the shared objects can be imported like normal Python files.
+
+ Args:
+ name: Name for the rule.
+ deps: C/C++ dependencies of the Cython (e.g. Numpy headers).
+ py_deps: Pure Python dependencies of the final library.
+ srcs: .py, .pyx, or .pxd files to either compile or pass through.
+ **kwargs: Extra keyword arguments passed to the py_library.
+ """
+
+ # First filter out files that should be run compiled vs. passed through.
+ py_srcs = []
+ pyx_srcs = []
+ pxd_srcs = []
+ for src in srcs:
+ if src.endswith(".pyx") or (src.endswith(".py") and
+ src[:-3] + ".pxd" in srcs):
+ pyx_srcs.append(src)
+ elif src.endswith(".py"):
+ py_srcs.append(src)
+ else:
+ pxd_srcs.append(src)
+ if src.endswith("__init__.py"):
+ pxd_srcs.append(src)
+
+ # Invoke cython to produce the shared object libraries.
+ for filename in pyx_srcs:
+ native.genrule(
+ name = filename + "_cython_translation",
+ srcs = [filename],
+ outs = [filename.split(".")[0] + ".cpp"],
+ # Optionally use PYTHON_BIN_PATH on Linux platforms so that python 3
+ # works. Windows has issues with cython_binary so skip PYTHON_BIN_PATH.
+ cmd = "PYTHONHASHSEED=0 $(location @cython//:cython_binary) --cplus $(SRCS) --output-file $(OUTS)",
+ tools = ["@cython//:cython_binary"] + pxd_srcs,
+ )
+
+ shared_objects = []
+ for src in pyx_srcs:
+ stem = src.split(".")[0]
+ shared_object_name = stem + ".so"
+ native.cc_binary(
+ name = shared_object_name,
+ srcs = [stem + ".cpp"],
+ deps = deps + ["//third_party/python_runtime:headers"],
+ linkshared = 1,
+ )
+ shared_objects.append(shared_object_name)
+
+ # Now create a py_library with these shared objects as data.
+ native.py_library(
+ name = name,
+ srcs = py_srcs,
+ deps = py_deps,
+ srcs_version = "PY2AND3",
+ data = shared_objects,
+ **kwargs
)
- shared_objects = []
- for src in pyx_srcs:
- stem = src.split(".")[0]
- shared_object_name = stem + ".so"
- native.cc_binary(
- name=shared_object_name,
- srcs=[stem + ".cpp"],
- deps=deps + ["//third_party/python_runtime:headers"],
- linkshared = 1,
- )
- shared_objects.append(shared_object_name)
-
- # Now create a py_library with these shared objects as data.
- native.py_library(
- name=name,
- srcs=py_srcs,
- deps=py_deps,
- srcs_version = "PY2AND3",
- data=shared_objects,
- **kwargs
- )
-
-def _proto_cc_hdrs(srcs, use_grpc_plugin=False):
- ret = [s[:-len(".proto")] + ".pb.h" for s in srcs]
- if use_grpc_plugin:
- ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs]
- return ret
-
-def _proto_cc_srcs(srcs, use_grpc_plugin=False):
- ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs]
- if use_grpc_plugin:
- ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
- return ret
-
-def _proto_py_outs(srcs, use_grpc_plugin=False):
- ret = [s[:-len(".proto")] + "_pb2.py" for s in srcs]
- if use_grpc_plugin:
- ret += [s[:-len(".proto")] + "_pb2_grpc.py" for s in srcs]
- return ret
+def _proto_cc_hdrs(srcs, use_grpc_plugin = False):
+ ret = [s[:-len(".proto")] + ".pb.h" for s in srcs]
+ if use_grpc_plugin:
+ ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs]
+ return ret
+
+def _proto_cc_srcs(srcs, use_grpc_plugin = False):
+ ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs]
+ if use_grpc_plugin:
+ ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
+ return ret
+
+def _proto_py_outs(srcs, use_grpc_plugin = False):
+ ret = [s[:-len(".proto")] + "_pb2.py" for s in srcs]
+ if use_grpc_plugin:
+ ret += [s[:-len(".proto")] + "_pb2_grpc.py" for s in srcs]
+ return ret
# Re-defined protocol buffer rule to allow building "header only" protocol
# buffers, to avoid duplicate registrations. Also allows non-iterable cc_libs
# containing select() statements.
def cc_proto_library(
- name,
- srcs=[],
- deps=[],
- cc_libs=[],
- include=None,
- protoc="@protobuf_archive//:protoc",
- internal_bootstrap_hack=False,
- use_grpc_plugin=False,
- use_grpc_namespace=False,
- default_header=False,
- **kargs):
- """Bazel rule to create a C++ protobuf library from proto source files.
-
- Args:
- name: the name of the cc_proto_library.
- srcs: the .proto files of the cc_proto_library.
- deps: a list of dependency labels; must be cc_proto_library.
- cc_libs: a list of other cc_library targets depended by the generated
- cc_library.
- include: a string indicating the include path of the .proto files.
- protoc: the label of the protocol compiler to generate the sources.
- internal_bootstrap_hack: a flag indicate the cc_proto_library is used only
- for bootstraping. When it is set to True, no files will be generated.
- The rule will simply be a provider for .proto files, so that other
- cc_proto_library can depend on it.
- use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin
- when processing the proto files.
- default_header: Controls the naming of generated rules. If True, the `name`
- rule will be header-only, and an _impl rule will contain the
- implementation. Otherwise the header-only rule (name + "_headers_only")
- must be referred to explicitly.
- **kargs: other keyword arguments that are passed to cc_library.
- """
-
- includes = []
- if include != None:
- includes = [include]
-
- if internal_bootstrap_hack:
- # For pre-checked-in generated files, we add the internal_bootstrap_hack
- # which will skip the codegen action.
+ name,
+ srcs = [],
+ deps = [],
+ cc_libs = [],
+ include = None,
+ protoc = "@protobuf_archive//:protoc",
+ internal_bootstrap_hack = False,
+ use_grpc_plugin = False,
+ use_grpc_namespace = False,
+ default_header = False,
+ **kargs):
+ """Bazel rule to create a C++ protobuf library from proto source files.
+
+ Args:
+ name: the name of the cc_proto_library.
+ srcs: the .proto files of the cc_proto_library.
+ deps: a list of dependency labels; must be cc_proto_library.
+ cc_libs: a list of other cc_library targets depended by the generated
+ cc_library.
+ include: a string indicating the include path of the .proto files.
+ protoc: the label of the protocol compiler to generate the sources.
+ internal_bootstrap_hack: a flag indicate the cc_proto_library is used only
+ for bootstraping. When it is set to True, no files will be generated.
+ The rule will simply be a provider for .proto files, so that other
+ cc_proto_library can depend on it.
+ use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin
+ when processing the proto files.
+ default_header: Controls the naming of generated rules. If True, the `name`
+ rule will be header-only, and an _impl rule will contain the
+ implementation. Otherwise the header-only rule (name + "_headers_only")
+ must be referred to explicitly.
+ **kargs: other keyword arguments that are passed to cc_library.
+ """
+
+ includes = []
+ if include != None:
+ includes = [include]
+
+ if internal_bootstrap_hack:
+ # For pre-checked-in generated files, we add the internal_bootstrap_hack
+ # which will skip the codegen action.
+ proto_gen(
+ name = name + "_genproto",
+ srcs = srcs,
+ deps = [s + "_genproto" for s in deps],
+ includes = includes,
+ protoc = protoc,
+ visibility = ["//visibility:public"],
+ )
+
+ # An empty cc_library to make rule dependency consistent.
+ native.cc_library(
+ name = name,
+ **kargs
+ )
+ return
+
+ grpc_cpp_plugin = None
+ plugin_options = []
+ if use_grpc_plugin:
+ grpc_cpp_plugin = "//external:grpc_cpp_plugin"
+ if use_grpc_namespace:
+ plugin_options = ["services_namespace=grpc"]
+
+ gen_srcs = _proto_cc_srcs(srcs, use_grpc_plugin)
+ gen_hdrs = _proto_cc_hdrs(srcs, use_grpc_plugin)
+ outs = gen_srcs + gen_hdrs
+
proto_gen(
- name=name + "_genproto",
- srcs=srcs,
- deps=[s + "_genproto" for s in deps],
- includes=includes,
- protoc=protoc,
- visibility=["//visibility:public"],
+ name = name + "_genproto",
+ srcs = srcs,
+ deps = [s + "_genproto" for s in deps],
+ includes = includes,
+ protoc = protoc,
+ plugin = grpc_cpp_plugin,
+ plugin_language = "grpc",
+ plugin_options = plugin_options,
+ gen_cc = 1,
+ outs = outs,
+ visibility = ["//visibility:public"],
)
- # An empty cc_library to make rule dependency consistent.
- native.cc_library(
- name=name,
- **kargs)
- return
-
- grpc_cpp_plugin = None
- plugin_options = []
- if use_grpc_plugin:
- grpc_cpp_plugin = "//external:grpc_cpp_plugin"
- if use_grpc_namespace:
- plugin_options = ["services_namespace=grpc"]
-
- gen_srcs = _proto_cc_srcs(srcs, use_grpc_plugin)
- gen_hdrs = _proto_cc_hdrs(srcs, use_grpc_plugin)
- outs = gen_srcs + gen_hdrs
-
- proto_gen(
- name=name + "_genproto",
- srcs=srcs,
- deps=[s + "_genproto" for s in deps],
- includes=includes,
- protoc=protoc,
- plugin=grpc_cpp_plugin,
- plugin_language="grpc",
- plugin_options=plugin_options,
- gen_cc=1,
- outs=outs,
- visibility=["//visibility:public"],
- )
-
- if use_grpc_plugin:
- cc_libs += select({
- "//tensorflow:linux_s390x": ["//external:grpc_lib_unsecure"],
- "//conditions:default": ["//external:grpc_lib"],
- })
- if default_header:
- header_only_name = name
- impl_name = name + "_impl"
- else:
- header_only_name = name + "_headers_only"
- impl_name = name
-
- native.cc_library(
- name=impl_name,
- srcs=gen_srcs,
- hdrs=gen_hdrs,
- deps=cc_libs + deps,
- includes=includes,
- **kargs)
- native.cc_library(
- name=header_only_name,
- deps=["@protobuf_archive//:protobuf_headers"] + if_static([impl_name]),
- hdrs=gen_hdrs,
- **kargs)
+ if use_grpc_plugin:
+ cc_libs += select({
+ "//tensorflow:linux_s390x": ["//external:grpc_lib_unsecure"],
+ "//conditions:default": ["//external:grpc_lib"],
+ })
+
+ if default_header:
+ header_only_name = name
+ impl_name = name + "_impl"
+ else:
+ header_only_name = name + "_headers_only"
+ impl_name = name
+
+ native.cc_library(
+ name = impl_name,
+ srcs = gen_srcs,
+ hdrs = gen_hdrs,
+ deps = cc_libs + deps,
+ includes = includes,
+ **kargs
+ )
+ native.cc_library(
+ name = header_only_name,
+ deps = ["@protobuf_archive//:protobuf_headers"] + if_static([impl_name]),
+ hdrs = gen_hdrs,
+ **kargs
+ )
# Re-defined protocol buffer rule to bring in the change introduced in commit
# https://github.com/google/protobuf/commit/294b5758c373cbab4b72f35f4cb62dc1d8332b68
@@ -234,477 +239,512 @@ def cc_proto_library(
# to include the above commit.
def py_proto_library(
name,
- srcs=[],
- deps=[],
- py_libs=[],
- py_extra_srcs=[],
- include=None,
- default_runtime="@protobuf_archive//:protobuf_python",
- protoc="@protobuf_archive//:protoc",
- use_grpc_plugin=False,
+ srcs = [],
+ deps = [],
+ py_libs = [],
+ py_extra_srcs = [],
+ include = None,
+ default_runtime = "@protobuf_archive//:protobuf_python",
+ protoc = "@protobuf_archive//:protoc",
+ use_grpc_plugin = False,
**kargs):
- """Bazel rule to create a Python protobuf library from proto source files
-
- NOTE: the rule is only an internal workaround to generate protos. The
- interface may change and the rule may be removed when bazel has introduced
- the native rule.
-
- Args:
- name: the name of the py_proto_library.
- srcs: the .proto files of the py_proto_library.
- deps: a list of dependency labels; must be py_proto_library.
- py_libs: a list of other py_library targets depended by the generated
- py_library.
- py_extra_srcs: extra source files that will be added to the output
- py_library. This attribute is used for internal bootstrapping.
- include: a string indicating the include path of the .proto files.
- default_runtime: the implicitly default runtime which will be depended on by
- the generated py_library target.
- protoc: the label of the protocol compiler to generate the sources.
- use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin
- when processing the proto files.
- **kargs: other keyword arguments that are passed to cc_library.
- """
- outs = _proto_py_outs(srcs, use_grpc_plugin)
-
- includes = []
- if include != None:
- includes = [include]
-
- grpc_python_plugin = None
- if use_grpc_plugin:
- grpc_python_plugin = "//external:grpc_python_plugin"
- # Note: Generated grpc code depends on Python grpc module. This dependency
- # is not explicitly listed in py_libs. Instead, host system is assumed to
- # have grpc installed.
-
- proto_gen(
- name=name + "_genproto",
- srcs=srcs,
- deps=[s + "_genproto" for s in deps],
- includes=includes,
- protoc=protoc,
- gen_py=1,
- outs=outs,
- visibility=["//visibility:public"],
- plugin=grpc_python_plugin,
- plugin_language="grpc"
- )
-
- if default_runtime and not default_runtime in py_libs + deps:
- py_libs = py_libs + [default_runtime]
-
- native.py_library(
- name=name,
- srcs=outs+py_extra_srcs,
- deps=py_libs+deps,
- imports=includes,
- **kargs)
-
-def tf_proto_library_cc(name, srcs = [], has_services = None,
- protodeps = [],
- visibility = [], testonly = 0,
- cc_libs = [],
- cc_stubby_versions = None,
- cc_grpc_version = None,
- j2objc_api_version = 1,
- cc_api_version = 2,
- dart_api_version = 2,
- java_api_version = 2, py_api_version = 2,
- js_api_version = 2, js_codegen = "jspb",
- default_header = False):
- js_codegen = js_codegen # unused argument
- js_api_version = js_api_version # unused argument
- native.filegroup(
- name = name + "_proto_srcs",
- srcs = srcs + tf_deps(protodeps, "_proto_srcs"),
- testonly = testonly,
- visibility = visibility,
- )
-
- use_grpc_plugin = None
- if cc_grpc_version:
- use_grpc_plugin = True
-
- cc_deps = tf_deps(protodeps, "_cc")
- cc_name = name + "_cc"
- if not srcs:
- # This is a collection of sub-libraries. Build header-only and impl
- # libraries containing all the sources.
+ """Bazel rule to create a Python protobuf library from proto source files
+
+ NOTE: the rule is only an internal workaround to generate protos. The
+ interface may change and the rule may be removed when bazel has introduced
+ the native rule.
+
+ Args:
+ name: the name of the py_proto_library.
+ srcs: the .proto files of the py_proto_library.
+ deps: a list of dependency labels; must be py_proto_library.
+ py_libs: a list of other py_library targets depended by the generated
+ py_library.
+ py_extra_srcs: extra source files that will be added to the output
+ py_library. This attribute is used for internal bootstrapping.
+ include: a string indicating the include path of the .proto files.
+ default_runtime: the implicitly default runtime which will be depended on by
+ the generated py_library target.
+ protoc: the label of the protocol compiler to generate the sources.
+ use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin
+ when processing the proto files.
+ **kargs: other keyword arguments that are passed to cc_library.
+ """
+ outs = _proto_py_outs(srcs, use_grpc_plugin)
+
+ includes = []
+ if include != None:
+ includes = [include]
+
+ grpc_python_plugin = None
+ if use_grpc_plugin:
+ grpc_python_plugin = "//external:grpc_python_plugin"
+ # Note: Generated grpc code depends on Python grpc module. This dependency
+ # is not explicitly listed in py_libs. Instead, host system is assumed to
+ # have grpc installed.
+
proto_gen(
- name = cc_name + "_genproto",
- deps = [s + "_genproto" for s in cc_deps],
- protoc = "@protobuf_archive//:protoc",
- visibility=["//visibility:public"],
+ name = name + "_genproto",
+ srcs = srcs,
+ deps = [s + "_genproto" for s in deps],
+ includes = includes,
+ protoc = protoc,
+ gen_py = 1,
+ outs = outs,
+ visibility = ["//visibility:public"],
+ plugin = grpc_python_plugin,
+ plugin_language = "grpc",
)
- native.cc_library(
- name = cc_name,
- deps = cc_deps + ["@protobuf_archive//:protobuf_headers"] +
- if_static([name + "_cc_impl"]),
+
+ if default_runtime and not default_runtime in py_libs + deps:
+ py_libs = py_libs + [default_runtime]
+
+ native.py_library(
+ name = name,
+ srcs = outs + py_extra_srcs,
+ deps = py_libs + deps,
+ imports = includes,
+ **kargs
+ )
+
+def tf_proto_library_cc(
+ name,
+ srcs = [],
+ has_services = None,
+ protodeps = [],
+ visibility = [],
+ testonly = 0,
+ cc_libs = [],
+ cc_stubby_versions = None,
+ cc_grpc_version = None,
+ j2objc_api_version = 1,
+ cc_api_version = 2,
+ dart_api_version = 2,
+ java_api_version = 2,
+ py_api_version = 2,
+ js_api_version = 2,
+ js_codegen = "jspb",
+ default_header = False):
+ js_codegen = js_codegen # unused argument
+ js_api_version = js_api_version # unused argument
+ native.filegroup(
+ name = name + "_proto_srcs",
+ srcs = srcs + tf_deps(protodeps, "_proto_srcs"),
testonly = testonly,
visibility = visibility,
)
- native.cc_library(
- name = cc_name + "_impl",
- deps = [s + "_impl" for s in cc_deps] + ["@protobuf_archive//:cc_wkt_protos"],
- )
- return
-
- cc_proto_library(
- name = cc_name,
- srcs = srcs,
- deps = cc_deps + ["@protobuf_archive//:cc_wkt_protos"],
- cc_libs = cc_libs + if_static(
- ["@protobuf_archive//:protobuf"],
- ["@protobuf_archive//:protobuf_headers"]
- ),
- copts = if_not_windows([
- "-Wno-unknown-warning-option",
- "-Wno-unused-but-set-variable",
- "-Wno-sign-compare",
- ]),
- protoc = "@protobuf_archive//:protoc",
- use_grpc_plugin = use_grpc_plugin,
- testonly = testonly,
- visibility = visibility,
- default_header = default_header,
- )
-
-def tf_proto_library_py(name, srcs=[], protodeps=[], deps=[], visibility=[],
- testonly=0, srcs_version="PY2AND3", use_grpc_plugin=False):
- py_deps = tf_deps(protodeps, "_py")
- py_name = name + "_py"
- if not srcs:
- # This is a collection of sub-libraries. Build header-only and impl
- # libraries containing all the sources.
- proto_gen(
- name = py_name + "_genproto",
- deps = [s + "_genproto" for s in py_deps],
+ use_grpc_plugin = None
+ if cc_grpc_version:
+ use_grpc_plugin = True
+
+ cc_deps = tf_deps(protodeps, "_cc")
+ cc_name = name + "_cc"
+ if not srcs:
+ # This is a collection of sub-libraries. Build header-only and impl
+ # libraries containing all the sources.
+ proto_gen(
+ name = cc_name + "_genproto",
+ deps = [s + "_genproto" for s in cc_deps],
+ protoc = "@protobuf_archive//:protoc",
+ visibility = ["//visibility:public"],
+ )
+ native.cc_library(
+ name = cc_name,
+ deps = cc_deps + ["@protobuf_archive//:protobuf_headers"] +
+ if_static([name + "_cc_impl"]),
+ testonly = testonly,
+ visibility = visibility,
+ )
+ native.cc_library(
+ name = cc_name + "_impl",
+ deps = [s + "_impl" for s in cc_deps] + ["@protobuf_archive//:cc_wkt_protos"],
+ )
+
+ return
+
+ cc_proto_library(
+ name = cc_name,
+ srcs = srcs,
+ deps = cc_deps + ["@protobuf_archive//:cc_wkt_protos"],
+ cc_libs = cc_libs + if_static(
+ ["@protobuf_archive//:protobuf"],
+ ["@protobuf_archive//:protobuf_headers"],
+ ),
+ copts = if_not_windows([
+ "-Wno-unknown-warning-option",
+ "-Wno-unused-but-set-variable",
+ "-Wno-sign-compare",
+ ]),
protoc = "@protobuf_archive//:protoc",
- visibility=["//visibility:public"],
+ use_grpc_plugin = use_grpc_plugin,
+ testonly = testonly,
+ visibility = visibility,
+ default_header = default_header,
)
- native.py_library(
+
+def tf_proto_library_py(
+ name,
+ srcs = [],
+ protodeps = [],
+ deps = [],
+ visibility = [],
+ testonly = 0,
+ srcs_version = "PY2AND3",
+ use_grpc_plugin = False):
+ py_deps = tf_deps(protodeps, "_py")
+ py_name = name + "_py"
+ if not srcs:
+ # This is a collection of sub-libraries. Build header-only and impl
+ # libraries containing all the sources.
+ proto_gen(
+ name = py_name + "_genproto",
+ deps = [s + "_genproto" for s in py_deps],
+ protoc = "@protobuf_archive//:protoc",
+ visibility = ["//visibility:public"],
+ )
+ native.py_library(
+ name = py_name,
+ deps = py_deps + ["@protobuf_archive//:protobuf_python"],
+ testonly = testonly,
+ visibility = visibility,
+ )
+ return
+
+ py_proto_library(
name = py_name,
- deps = py_deps + ["@protobuf_archive//:protobuf_python"],
- testonly = testonly,
+ srcs = srcs,
+ srcs_version = srcs_version,
+ deps = deps + py_deps + ["@protobuf_archive//:protobuf_python"],
+ protoc = "@protobuf_archive//:protoc",
+ default_runtime = "@protobuf_archive//:protobuf_python",
visibility = visibility,
+ testonly = testonly,
+ use_grpc_plugin = use_grpc_plugin,
)
- return
-
- py_proto_library(
- name = py_name,
- srcs = srcs,
- srcs_version = srcs_version,
- deps = deps + py_deps + ["@protobuf_archive//:protobuf_python"],
- protoc = "@protobuf_archive//:protoc",
- default_runtime = "@protobuf_archive//:protobuf_python",
- visibility = visibility,
- testonly = testonly,
- use_grpc_plugin = use_grpc_plugin,
- )
def tf_jspb_proto_library(**kwargs):
- pass
+ pass
def tf_nano_proto_library(**kwargs):
- pass
-
-def tf_proto_library(name, srcs = [], has_services = None,
- protodeps = [],
- visibility = [], testonly = 0,
- cc_libs = [],
- cc_api_version = 2, cc_grpc_version = None,
- dart_api_version = 2, j2objc_api_version = 1,
- java_api_version = 2, py_api_version = 2,
- js_api_version = 2, js_codegen = "jspb",
- provide_cc_alias = False,
- default_header = False):
- """Make a proto library, possibly depending on other proto libraries."""
- _ignore = (js_api_version, js_codegen, provide_cc_alias)
-
- tf_proto_library_cc(
- name = name,
- srcs = srcs,
- protodeps = protodeps,
- cc_grpc_version = cc_grpc_version,
- cc_libs = cc_libs,
- testonly = testonly,
- visibility = visibility,
- default_header = default_header,
- )
-
- tf_proto_library_py(
- name = name,
- srcs = srcs,
- protodeps = protodeps,
- srcs_version = "PY2AND3",
- testonly = testonly,
- visibility = visibility,
- use_grpc_plugin = has_services,
- )
+ pass
+
+def tf_proto_library(
+ name,
+ srcs = [],
+ has_services = None,
+ protodeps = [],
+ visibility = [],
+ testonly = 0,
+ cc_libs = [],
+ cc_api_version = 2,
+ cc_grpc_version = None,
+ dart_api_version = 2,
+ j2objc_api_version = 1,
+ java_api_version = 2,
+ py_api_version = 2,
+ js_api_version = 2,
+ js_codegen = "jspb",
+ provide_cc_alias = False,
+ default_header = False):
+ """Make a proto library, possibly depending on other proto libraries."""
+ _ignore = (js_api_version, js_codegen, provide_cc_alias)
+
+ tf_proto_library_cc(
+ name = name,
+ srcs = srcs,
+ protodeps = protodeps,
+ cc_grpc_version = cc_grpc_version,
+ cc_libs = cc_libs,
+ testonly = testonly,
+ visibility = visibility,
+ default_header = default_header,
+ )
+
+ tf_proto_library_py(
+ name = name,
+ srcs = srcs,
+ protodeps = protodeps,
+ srcs_version = "PY2AND3",
+ testonly = testonly,
+ visibility = visibility,
+ use_grpc_plugin = has_services,
+ )
# A list of all files under platform matching the pattern in 'files'. In
# contrast with 'tf_platform_srcs' below, which seletive collects files that
# must be compiled in the 'default' platform, this is a list of all headers
# mentioned in the platform/* files.
def tf_platform_hdrs(files):
- return native.glob(["platform/*/" + f for f in files])
+ return native.glob(["platform/*/" + f for f in files])
def tf_platform_srcs(files):
- base_set = ["platform/default/" + f for f in files]
- windows_set = base_set + ["platform/windows/" + f for f in files]
- posix_set = base_set + ["platform/posix/" + f for f in files]
-
- # Handle cases where we must also bring the posix file in. Usually, the list
- # of files to build on windows builds is just all the stuff in the
- # windows_set. However, in some cases the implementations in 'posix/' are
- # just what is necessary and historically we choose to simply use the posix
- # file instead of making a copy in 'windows'.
- for f in files:
- if f == "error.cc":
- windows_set.append("platform/posix/" + f)
-
- return select({
- "//tensorflow:windows" : native.glob(windows_set),
- "//tensorflow:windows_msvc" : native.glob(windows_set),
- "//conditions:default" : native.glob(posix_set),
- })
+ base_set = ["platform/default/" + f for f in files]
+ windows_set = base_set + ["platform/windows/" + f for f in files]
+ posix_set = base_set + ["platform/posix/" + f for f in files]
+
+ # Handle cases where we must also bring the posix file in. Usually, the list
+ # of files to build on windows builds is just all the stuff in the
+ # windows_set. However, in some cases the implementations in 'posix/' are
+ # just what is necessary and historically we choose to simply use the posix
+ # file instead of making a copy in 'windows'.
+ for f in files:
+ if f == "error.cc":
+ windows_set.append("platform/posix/" + f)
+
+ return select({
+ "//tensorflow:windows": native.glob(windows_set),
+ "//conditions:default": native.glob(posix_set),
+ })
def tf_additional_lib_hdrs(exclude = []):
- windows_hdrs = native.glob([
- "platform/default/*.h",
- "platform/windows/*.h",
- "platform/posix/error.h",
- ], exclude = exclude)
- return select({
- "//tensorflow:windows" : windows_hdrs,
- "//tensorflow:windows_msvc" : windows_hdrs,
- "//conditions:default" : native.glob([
+ windows_hdrs = native.glob([
"platform/default/*.h",
- "platform/posix/*.h",
- ], exclude = exclude),
- })
+ "platform/windows/*.h",
+ "platform/posix/error.h",
+ ], exclude = exclude)
+ return select({
+ "//tensorflow:windows": windows_hdrs,
+ "//conditions:default": native.glob([
+ "platform/default/*.h",
+ "platform/posix/*.h",
+ ], exclude = exclude),
+ })
def tf_additional_lib_srcs(exclude = []):
- windows_srcs = native.glob([
- "platform/default/*.cc",
- "platform/windows/*.cc",
- "platform/posix/error.cc",
- ], exclude = exclude)
- return select({
- "//tensorflow:windows" : windows_srcs,
- "//tensorflow:windows_msvc" : windows_srcs,
- "//conditions:default" : native.glob([
+ windows_srcs = native.glob([
"platform/default/*.cc",
- "platform/posix/*.cc",
- ], exclude = exclude),
- })
+ "platform/windows/*.cc",
+ "platform/posix/error.cc",
+ ], exclude = exclude)
+ return select({
+ "//tensorflow:windows": windows_srcs,
+ "//conditions:default": native.glob([
+ "platform/default/*.cc",
+ "platform/posix/*.cc",
+ ], exclude = exclude),
+ })
def tf_additional_minimal_lib_srcs():
- return [
- "platform/default/integral_types.h",
- "platform/default/mutex.h",
- ]
+ return [
+ "platform/default/integral_types.h",
+ "platform/default/mutex.h",
+ ]
def tf_additional_proto_hdrs():
- return [
- "platform/default/integral_types.h",
- "platform/default/logging.h",
- "platform/default/protobuf.h"
- ] + if_windows([
- "platform/windows/integral_types.h",
- ])
+ return [
+ "platform/default/integral_types.h",
+ "platform/default/logging.h",
+ "platform/default/protobuf.h",
+ ] + if_windows([
+ "platform/windows/integral_types.h",
+ ])
+
+def tf_additional_proto_compiler_hdrs():
+ return [
+ "platform/default/protobuf_compiler.h",
+ ]
def tf_additional_proto_srcs():
- return [
- "platform/default/protobuf.cc",
- ]
+ return [
+ "platform/default/protobuf.cc",
+ ]
def tf_additional_human_readable_json_deps():
- return []
+ return []
def tf_additional_all_protos():
- return ["//tensorflow/core:protos_all"]
+ return ["//tensorflow/core:protos_all"]
def tf_protos_all_impl():
- return ["//tensorflow/core:protos_all_cc_impl"]
+ return ["//tensorflow/core:protos_all_cc_impl"]
def tf_protos_all():
- return if_static(
- extra_deps=tf_protos_all_impl(),
- otherwise=["//tensorflow/core:protos_all_cc"])
+ return if_static(
+ extra_deps = tf_protos_all_impl(),
+ otherwise = ["//tensorflow/core:protos_all_cc"],
+ )
def tf_protos_grappler_impl():
- return ["//tensorflow/core/grappler/costs:op_performance_data_cc_impl"]
+ return ["//tensorflow/core/grappler/costs:op_performance_data_cc_impl"]
def tf_protos_grappler():
- return if_static(
- extra_deps=tf_protos_grappler_impl(),
- otherwise=["//tensorflow/core/grappler/costs:op_performance_data_cc"])
+ return if_static(
+ extra_deps = tf_protos_grappler_impl(),
+ otherwise = ["//tensorflow/core/grappler/costs:op_performance_data_cc"],
+ )
def tf_additional_cupti_wrapper_deps():
- return ["//tensorflow/core/platform/default/gpu:cupti_wrapper"]
+ return ["//tensorflow/core/platform/default/gpu:cupti_wrapper"]
def tf_additional_device_tracer_srcs():
- return ["platform/default/device_tracer.cc"]
+ return ["platform/default/device_tracer.cc"]
def tf_additional_device_tracer_cuda_deps():
- return []
+ return []
def tf_additional_device_tracer_deps():
- return []
+ return []
def tf_additional_libdevice_data():
- return []
+ return []
def tf_additional_libdevice_deps():
- return ["@local_config_cuda//cuda:cuda_headers"]
+ return ["@local_config_cuda//cuda:cuda_headers"]
def tf_additional_libdevice_srcs():
- return ["platform/default/cuda_libdevice_path.cc"]
+ return ["platform/default/cuda_libdevice_path.cc"]
def tf_additional_test_deps():
- return []
+ return []
def tf_additional_test_srcs():
- return [
- "platform/default/test_benchmark.cc",
- ] + select({
- "//tensorflow:windows" : [
- "platform/windows/test.cc"
+ return [
+ "platform/default/test_benchmark.cc",
+ ] + select({
+ "//tensorflow:windows": [
+ "platform/windows/test.cc",
],
- "//conditions:default" : [
- "platform/posix/test.cc",
+ "//conditions:default": [
+ "platform/posix/test.cc",
],
})
def tf_kernel_tests_linkstatic():
- return 0
+ return 0
def tf_additional_lib_defines():
- """Additional defines needed to build TF libraries."""
- return select({
- "//tensorflow:with_jemalloc_linux_x86_64": ["TENSORFLOW_USE_JEMALLOC"],
- "//tensorflow:with_jemalloc_linux_ppc64le":["TENSORFLOW_USE_JEMALLOC"],
- "//conditions:default": [],
- }) + if_not_mobile(["TENSORFLOW_USE_ABSL"])
+ """Additional defines needed to build TF libraries."""
+ return select({
+ "//tensorflow:with_jemalloc_linux_x86_64": ["TENSORFLOW_USE_JEMALLOC"],
+ "//tensorflow:with_jemalloc_linux_ppc64le": ["TENSORFLOW_USE_JEMALLOC"],
+ "//conditions:default": [],
+ }) + if_not_mobile(["TENSORFLOW_USE_ABSL"])
def tf_additional_lib_deps():
- """Additional dependencies needed to build TF libraries."""
- return if_not_mobile(["@com_google_absl//absl/base:base"]) + if_static(
- ["@nsync//:nsync_cpp"],
- ["@nsync//:nsync_headers"]
- ) + select({
- "//tensorflow:with_jemalloc_linux_x86_64_dynamic": ["@jemalloc//:jemalloc_headers"],
- "//tensorflow:with_jemalloc_linux_ppc64le_dynamic": ["@jemalloc//:jemalloc_headers"],
- "//tensorflow:with_jemalloc_linux_x86_64": ["@jemalloc//:jemalloc_impl"],
- "//tensorflow:with_jemalloc_linux_ppc64le": ["@jemalloc//:jemalloc_impl"],
- "//conditions:default": [],
- })
+ """Additional dependencies needed to build TF libraries."""
+ return if_not_mobile(["@com_google_absl//absl/base:base"]) + if_static(
+ ["@nsync//:nsync_cpp"],
+ ["@nsync//:nsync_headers"],
+ ) + select({
+ "//tensorflow:with_jemalloc_linux_x86_64_dynamic": ["@jemalloc//:jemalloc_headers"],
+ "//tensorflow:with_jemalloc_linux_ppc64le_dynamic": ["@jemalloc//:jemalloc_headers"],
+ "//tensorflow:with_jemalloc_linux_x86_64": ["@jemalloc//:jemalloc_impl"],
+ "//tensorflow:with_jemalloc_linux_ppc64le": ["@jemalloc//:jemalloc_impl"],
+ "//conditions:default": [],
+ })
def tf_additional_core_deps():
- return select({
- "//tensorflow:with_gcp_support_android_override": [],
- "//tensorflow:with_gcp_support_ios_override": [],
- "//tensorflow:with_gcp_support": [
- "//tensorflow/core/platform/cloud:gcs_file_system",
- ],
- "//conditions:default": [],
- }) + select({
- "//tensorflow:with_hdfs_support_windows_override": [],
- "//tensorflow:with_hdfs_support_android_override": [],
- "//tensorflow:with_hdfs_support_ios_override": [],
- "//tensorflow:with_hdfs_support": [
- "//tensorflow/core/platform/hadoop:hadoop_file_system",
- ],
- "//conditions:default": [],
- }) + select({
- "//tensorflow:with_aws_support_windows_override": [],
- "//tensorflow:with_aws_support_android_override": [],
- "//tensorflow:with_aws_support_ios_override": [],
- "//tensorflow:with_aws_support": [
- "//tensorflow/core/platform/s3:s3_file_system",
- ],
- "//conditions:default": [],
- })
+ return select({
+ "//tensorflow:with_gcp_support_android_override": [],
+ "//tensorflow:with_gcp_support_ios_override": [],
+ "//tensorflow:with_gcp_support": [
+ "//tensorflow/core/platform/cloud:gcs_file_system",
+ ],
+ "//conditions:default": [],
+ }) + select({
+ "//tensorflow:with_hdfs_support_windows_override": [],
+ "//tensorflow:with_hdfs_support_android_override": [],
+ "//tensorflow:with_hdfs_support_ios_override": [],
+ "//tensorflow:with_hdfs_support": [
+ "//tensorflow/core/platform/hadoop:hadoop_file_system",
+ ],
+ "//conditions:default": [],
+ }) + select({
+ "//tensorflow:with_aws_support_windows_override": [],
+ "//tensorflow:with_aws_support_android_override": [],
+ "//tensorflow:with_aws_support_ios_override": [],
+ "//tensorflow:with_aws_support": [
+ "//tensorflow/core/platform/s3:s3_file_system",
+ ],
+ "//conditions:default": [],
+ })
# TODO(jart, jhseu): Delete when GCP is default on.
def tf_additional_cloud_op_deps():
- return select({
- "//tensorflow:with_gcp_support_windows_override": [],
- "//tensorflow:with_gcp_support_android_override": [],
- "//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": [],
- })
+ return select({
+ "//tensorflow:with_gcp_support_windows_override": [],
+ "//tensorflow:with_gcp_support_android_override": [],
+ "//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": [],
+ })
# TODO(jart, jhseu): Delete when GCP is default on.
def tf_additional_cloud_kernel_deps():
- return select({
- "//tensorflow:with_gcp_support_windows_override": [],
- "//tensorflow:with_gcp_support_android_override": [],
- "//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": [],
- })
+ return select({
+ "//tensorflow:with_gcp_support_windows_override": [],
+ "//tensorflow:with_gcp_support_android_override": [],
+ "//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": [],
+ })
def tf_lib_proto_parsing_deps():
- return [
- ":protos_all_cc",
- "//third_party/eigen3",
- "//tensorflow/core/platform/default/build_config:proto_parsing",
- ]
+ return [
+ ":protos_all_cc",
+ "//third_party/eigen3",
+ "//tensorflow/core/platform/default/build_config:proto_parsing",
+ ]
+
+def tf_lib_proto_compiler_deps():
+ return [
+ "@protobuf_archive//:protoc_lib",
+ ]
def tf_additional_verbs_lib_defines():
- return select({
- "//tensorflow:with_verbs_support": ["TENSORFLOW_USE_VERBS"],
- "//conditions:default": [],
- })
+ return select({
+ "//tensorflow:with_verbs_support": ["TENSORFLOW_USE_VERBS"],
+ "//conditions:default": [],
+ })
def tf_additional_mpi_lib_defines():
- return select({
- "//tensorflow:with_mpi_support": ["TENSORFLOW_USE_MPI"],
- "//conditions:default": [],
- })
+ return select({
+ "//tensorflow:with_mpi_support": ["TENSORFLOW_USE_MPI"],
+ "//conditions:default": [],
+ })
def tf_additional_gdr_lib_defines():
- return select({
- "//tensorflow:with_gdr_support": ["TENSORFLOW_USE_GDR"],
- "//conditions:default": [],
- })
+ return select({
+ "//tensorflow:with_gdr_support": ["TENSORFLOW_USE_GDR"],
+ "//conditions:default": [],
+ })
-def tf_py_clif_cc(name, visibility=None, **kwargs):
- pass
+def tf_py_clif_cc(name, visibility = None, **kwargs):
+ pass
-def tf_pyclif_proto_library(name, proto_lib, proto_srcfile="", visibility=None,
- **kwargs):
- pass
+def tf_pyclif_proto_library(
+ name,
+ proto_lib,
+ proto_srcfile = "",
+ visibility = None,
+ **kwargs):
+ pass
def tf_additional_binary_deps():
- return ["@nsync//:nsync_cpp"] + if_cuda(
- [
- "//tensorflow/stream_executor:cuda_platform",
- "//tensorflow/core/platform/default/build_config:cuda",
- ],
- ) + select({
- "//tensorflow:with_jemalloc_linux_x86_64": ["@jemalloc//:jemalloc_impl"],
- "//tensorflow:with_jemalloc_linux_ppc64le": ["@jemalloc//:jemalloc_impl"],
- "//conditions:default": [],
- }) + [
- # TODO(allenl): Split these out into their own shared objects (they are
- # here because they are shared between contrib/ op shared objects and
- # core).
- "//tensorflow/core/kernels:lookup_util",
- "//tensorflow/core/util/tensor_bundle",
- ] + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- ],
- )
+ return ["@nsync//:nsync_cpp"] + if_cuda(
+ [
+ "//tensorflow/stream_executor:cuda_platform",
+ "//tensorflow/core/platform/default/build_config:cuda",
+ ],
+ ) + select({
+ "//tensorflow:with_jemalloc_linux_x86_64": ["@jemalloc//:jemalloc_impl"],
+ "//tensorflow:with_jemalloc_linux_ppc64le": ["@jemalloc//:jemalloc_impl"],
+ "//conditions:default": [],
+ }) + [
+ # TODO(allenl): Split these out into their own shared objects (they are
+ # here because they are shared between contrib/ op shared objects and
+ # core).
+ "//tensorflow/core/kernels:lookup_util",
+ "//tensorflow/core/util/tensor_bundle",
+ ] + if_mkl_ml(
+ [
+ "//third_party/mkl:intel_binary_blob",
+ ],
+ )
diff --git a/tensorflow/core/platform/default/protobuf.h b/tensorflow/core/platform/default/protobuf.h
index c732c76ff7..bd9d41c62b 100644
--- a/tensorflow/core/platform/default/protobuf.h
+++ b/tensorflow/core/platform/default/protobuf.h
@@ -20,8 +20,8 @@ limitations under the License.
// IWYU pragma: friend third_party/tensorflow/core/platform/protobuf.h
#include "google/protobuf/arena.h"
-#include "google/protobuf/compiler/importer.h"
#include "google/protobuf/descriptor.h"
+#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream.h"
diff --git a/tensorflow/core/platform/default/protobuf_compiler.h b/tensorflow/core/platform/default/protobuf_compiler.h
new file mode 100644
index 0000000000..a93d7a184b
--- /dev/null
+++ b/tensorflow/core/platform/default/protobuf_compiler.h
@@ -0,0 +1,25 @@
+/* Copyright 2015 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_CORE_PLATFORM_DEFAULT_PROTOBUF_COMPILER_H_
+#define TENSORFLOW_CORE_PLATFORM_DEFAULT_PROTOBUF_COMPILER_H_
+
+// IWYU pragma: private, include "third_party/tensorflow/core/platform/protobuf_compiler.h"
+// IWYU pragma: friend third_party/tensorflow/core/platform/protobuf_compiler.h
+
+#include "google/protobuf/compiler/importer.h"
+#include "tensorflow/core/platform/default/protobuf.h"
+
+#endif // TENSORFLOW_CORE_PLATFORM_DEFAULT_PROTOBUF_H_
diff --git a/tensorflow/core/platform/protobuf_compiler.h b/tensorflow/core/platform/protobuf_compiler.h
new file mode 100644
index 0000000000..29679e0089
--- /dev/null
+++ b/tensorflow/core/platform/protobuf_compiler.h
@@ -0,0 +1,25 @@
+/* Copyright 2015 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.
+==============================================================================*/
+
+#ifndef TENSORFLOW_PLATFORM_PROTOBUF_COMPILER_H_
+#define TENSORFLOW_PLATFORM_PROTOBUF_COMPILER_H_
+
+#if defined(PLATFORM_GOOGLE) && !defined(USE_DEFAULT_PROTOBUF)
+#include "tensorflow/core/platform/google/protobuf_compiler.h"
+#else
+#include "tensorflow/core/platform/default/protobuf_compiler.h"
+#endif
+
+#endif // TENSORFLOW_PLATFORM_PROTOBUF_COMPILER_H_
diff --git a/tensorflow/core/platform/s3/s3_file_system.cc b/tensorflow/core/platform/s3/s3_file_system.cc
index d5f5dec390..462113f9bb 100644
--- a/tensorflow/core/platform/s3/s3_file_system.cc
+++ b/tensorflow/core/platform/s3/s3_file_system.cc
@@ -26,7 +26,6 @@ limitations under the License.
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/AWSLogging.h>
#include <aws/core/utils/logging/LogSystemInterface.h>
-#include <aws/core/utils/StringUtils.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/S3Errors.h>
#include <aws/s3/model/CopyObjectRequest.h>
@@ -254,10 +253,8 @@ class S3WritableFile : public WritableFile {
outfile_->clear();
outfile_->seekp(offset);
if (!putObjectOutcome.IsSuccess()) {
- string error = strings::StrCat(
- putObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
- putObjectOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(putObjectOutcome.GetError().GetExceptionName(),
+ ": ", putObjectOutcome.GetError().GetMessage());
}
return Status::OK();
}
@@ -410,10 +407,8 @@ Status S3FileSystem::GetChildren(const string& dir,
auto listObjectsOutcome =
this->GetS3Client()->ListObjects(listObjectsRequest);
if (!listObjectsOutcome.IsSuccess()) {
- string error = strings::StrCat(
- listObjectsOutcome.GetError().GetExceptionName().c_str(), ": ",
- listObjectsOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(listObjectsOutcome.GetError().GetExceptionName(),
+ ": ", listObjectsOutcome.GetError().GetMessage());
}
listObjectsResult = listObjectsOutcome.GetResult();
@@ -447,10 +442,8 @@ Status S3FileSystem::Stat(const string& fname, FileStatistics* stats) {
headBucketRequest.WithBucket(bucket.c_str());
auto headBucketOutcome = this->GetS3Client()->HeadBucket(headBucketRequest);
if (!headBucketOutcome.IsSuccess()) {
- string error = strings::StrCat(
- headBucketOutcome.GetError().GetExceptionName().c_str(), ": ",
- headBucketOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(headBucketOutcome.GetError().GetExceptionName(),
+ ": ", headBucketOutcome.GetError().GetMessage());
}
stats->length = 0;
stats->is_directory = 1;
@@ -511,10 +504,8 @@ Status S3FileSystem::DeleteFile(const string& fname) {
auto deleteObjectOutcome =
this->GetS3Client()->DeleteObject(deleteObjectRequest);
if (!deleteObjectOutcome.IsSuccess()) {
- string error = strings::StrCat(
- deleteObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
- deleteObjectOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(deleteObjectOutcome.GetError().GetExceptionName(),
+ ": ", deleteObjectOutcome.GetError().GetMessage());
}
return Status::OK();
}
@@ -612,10 +603,8 @@ Status S3FileSystem::RenameFile(const string& src, const string& target) {
auto listObjectsOutcome =
this->GetS3Client()->ListObjects(listObjectsRequest);
if (!listObjectsOutcome.IsSuccess()) {
- string error = strings::StrCat(
- listObjectsOutcome.GetError().GetExceptionName().c_str(), ": ",
- listObjectsOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(listObjectsOutcome.GetError().GetExceptionName(),
+ ": ", listObjectsOutcome.GetError().GetMessage());
}
listObjectsResult = listObjectsOutcome.GetResult();
@@ -633,10 +622,8 @@ Status S3FileSystem::RenameFile(const string& src, const string& target) {
auto copyObjectOutcome =
this->GetS3Client()->CopyObject(copyObjectRequest);
if (!copyObjectOutcome.IsSuccess()) {
- string error = strings::StrCat(
- copyObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
- copyObjectOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(copyObjectOutcome.GetError().GetExceptionName(),
+ ": ", copyObjectOutcome.GetError().GetMessage());
}
deleteObjectRequest.SetBucket(src_bucket.c_str());
@@ -645,10 +632,9 @@ Status S3FileSystem::RenameFile(const string& src, const string& target) {
auto deleteObjectOutcome =
this->GetS3Client()->DeleteObject(deleteObjectRequest);
if (!deleteObjectOutcome.IsSuccess()) {
- string error = strings::StrCat(
- deleteObjectOutcome.GetError().GetExceptionName().c_str(), ": ",
- deleteObjectOutcome.GetError().GetMessage().c_str());
- return errors::Internal(error);
+ return errors::Unknown(
+ deleteObjectOutcome.GetError().GetExceptionName(), ": ",
+ deleteObjectOutcome.GetError().GetMessage());
}
}
listObjectsRequest.SetMarker(listObjectsResult.GetNextMarker());
diff --git a/tensorflow/core/public/version.h b/tensorflow/core/public/version.h
index 6f564e7e1e..563564119f 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 "-rc1"
+#define TF_VERSION_SUFFIX ""
#define TF_STR_HELPER(x) #x
#define TF_STR(x) TF_STR_HELPER(x)
diff --git a/tensorflow/core/util/env_var.h b/tensorflow/core/util/env_var.h
index 47f9ff3a3b..724ca35729 100644
--- a/tensorflow/core/util/env_var.h
+++ b/tensorflow/core/util/env_var.h
@@ -13,7 +13,8 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
-#ifndef TENSORFLOW_UTIL_ENV_VAR_H_
+#ifndef TENSORFLOW_CORE_UTIL_ENV_VAR_H_
+#define TENSORFLOW_CORE_UTIL_ENV_VAR_H_
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
@@ -42,4 +43,4 @@ Status ReadStringFromEnvVar(StringPiece env_var_name, StringPiece default_val,
} // namespace tensorflow
-#endif // TENSORFLOW_UTIL_ENV_VAR_H_
+#endif // TENSORFLOW_CORE_UTIL_ENV_VAR_H_
diff --git a/tensorflow/core/util/events_writer.cc b/tensorflow/core/util/events_writer.cc
index c50e329bda..aaaba913a7 100644
--- a/tensorflow/core/util/events_writer.cc
+++ b/tensorflow/core/util/events_writer.cc
@@ -69,6 +69,10 @@ Status EventsWriter::InitIfNeeded() {
static_cast<int64>(time_in_seconds),
port::Hostname().c_str(), file_suffix_.c_str());
+ // Reset recordio_writer (which has a reference to recordio_file_) so final
+ // Flush() and Close() call have access to recordio_file_.
+ recordio_writer_.reset();
+
TF_RETURN_WITH_CONTEXT_IF_ERROR(
env_->NewWritableFile(filename_, &recordio_file_),
"Creating writable file ", filename_);
diff --git a/tensorflow/core/util/mkl_util.h b/tensorflow/core/util/mkl_util.h
index a66b1215bd..422be9356d 100644
--- a/tensorflow/core/util/mkl_util.h
+++ b/tensorflow/core/util/mkl_util.h
@@ -22,7 +22,17 @@ limitations under the License.
#include <utility>
#include <vector>
-#ifdef INTEL_MKL_ML
+#if defined(INTEL_MKL_ML_ONLY) || defined(INTEL_MKL_DNN_ONLY)
+#ifndef INTEL_MKL
+#error "INTEL_MKL_{ML,DNN}_ONLY require INTEL_MKL"
+#endif
+#endif
+
+#if defined(INTEL_MKL_ML_ONLY) && defined(INTEL_MKL_DNN_ONLY)
+#error "at most one of INTEL_MKL_ML_ONLY and INTEL_MKL_DNN_ONLY may be defined"
+#endif
+
+#ifdef INTEL_MKL_ML_ONLY
#include "mkl_dnn.h"
#include "mkl_dnn_types.h"
#include "mkl_service.h"
@@ -40,7 +50,8 @@ limitations under the License.
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/tensor_format.h"
-#ifndef INTEL_MKL_ML
+
+#ifndef INTEL_MKL_ML_ONLY
#include "mkldnn.hpp"
#include "tensorflow/core/lib/core/stringpiece.h"
@@ -76,7 +87,17 @@ typedef enum {
Dim_I = 1
} MklDnnDims;
-#ifdef INTEL_MKL_ML
+typedef enum {
+ Dim3d_N = 0,
+ Dim3d_C = 1,
+ Dim3d_D = 2,
+ Dim3d_H = 3,
+ Dim3d_W = 4,
+ Dim3d_O = 0,
+ Dim3d_I = 1
+} MklDnnDims3D;
+
+#ifdef INTEL_MKL_ML_ONLY
class MklShape {
public:
MklShape() {}
@@ -340,6 +361,7 @@ class MklShape {
#else
// Forward decl
+TensorFormat MklDnn3DDataFormatToTFDataFormat(memory::format format);
TensorFormat MklDnnDataFormatToTFDataFormat(memory::format format);
memory::dims CalculateTFStrides(const memory::dims& dims_tf_order);
memory::desc CreateBlockedMemDescHelper(const memory::dims& dim,
@@ -442,6 +464,13 @@ class MklDnnShape {
return this->DimSize(index);
}
+ inline size_t GetDimension3D(char dimension) const {
+ int index = GetMklDnnTensor3DDimIndex(dimension);
+ CHECK(index >= 0 && index < this->GetDimension())
+ << "Invalid index from the dimension: " << index << ", " << dimension;
+ return this->DimSize(index);
+ }
+
inline int32 GetMklDnnTensorDimIndex(char dimension) const {
switch (dimension) {
case 'N':
@@ -458,6 +487,24 @@ class MklDnnShape {
}
}
+ inline int32 GetMklDnnTensor3DDimIndex(char dimension) const {
+ switch (dimension) {
+ case 'N':
+ return MklDnnDims3D::Dim3d_N;
+ case 'C':
+ return MklDnnDims3D::Dim3d_C;
+ case 'D':
+ return MklDnnDims3D::Dim3d_D;
+ case 'H':
+ return MklDnnDims3D::Dim3d_H;
+ case 'W':
+ return MklDnnDims3D::Dim3d_W;
+ default:
+ LOG(FATAL) << "Invalid dimension: " << dimension;
+ return -1; // Avoid compiler warning about missing return value
+ }
+ }
+
inline size_t GetDimension() const { return data_.dimension_; }
inline const int* GetSizes() const {
return reinterpret_cast<const int*>(&data_.sizes_[0]);
@@ -576,13 +623,26 @@ class MklDnnShape {
}
inline void SetTfDimOrder(const size_t dimension, TensorFormat data_format) {
- // TODO(nhasabni): Why do we restrict this to 4D?
- CHECK_EQ(dimension, 4);
- CHECK(dimension == data_.dimension_);
- data_.map_[GetTensorDimIndex<2>(data_format, 'W')] = MklDnnDims::Dim_W;
- data_.map_[GetTensorDimIndex<2>(data_format, 'H')] = MklDnnDims::Dim_H;
- data_.map_[GetTensorDimIndex<2>(data_format, 'C')] = MklDnnDims::Dim_C;
- data_.map_[GetTensorDimIndex<2>(data_format, 'N')] = MklDnnDims::Dim_N;
+ if (dimension == 5) {
+ CHECK(dimension == data_.dimension_);
+ data_.map_[GetTensorDimIndex<3>(data_format, '0')] =
+ MklDnnDims3D::Dim3d_D;
+ data_.map_[GetTensorDimIndex<3>(data_format, '1')] =
+ MklDnnDims3D::Dim3d_H;
+ data_.map_[GetTensorDimIndex<3>(data_format, '2')] =
+ MklDnnDims3D::Dim3d_W;
+ data_.map_[GetTensorDimIndex<3>(data_format, 'C')] =
+ MklDnnDims3D::Dim3d_C;
+ data_.map_[GetTensorDimIndex<3>(data_format, 'N')] =
+ MklDnnDims3D::Dim3d_N;
+ } else {
+ CHECK_EQ(dimension, 4);
+ CHECK(dimension == data_.dimension_);
+ data_.map_[GetTensorDimIndex<2>(data_format, 'W')] = MklDnnDims::Dim_W;
+ data_.map_[GetTensorDimIndex<2>(data_format, 'H')] = MklDnnDims::Dim_H;
+ data_.map_[GetTensorDimIndex<2>(data_format, 'C')] = MklDnnDims::Dim_C;
+ data_.map_[GetTensorDimIndex<2>(data_format, 'N')] = MklDnnDims::Dim_N;
+ }
}
inline void SetTfDimOrder(const size_t dimension, memory::format format) {
@@ -670,14 +730,13 @@ class MklDnnShape {
// List of MklShape objects. Used in Concat/Split layers.
-
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
typedef std::vector<MklDnnShape> MklDnnShapeList;
#else
typedef std::vector<MklShape> MklShapeList;
#endif
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// Check if all tensors specified by MklShapes are MKL tensors.
inline bool AreAllMklTensors(const MklShapeList& shapes) {
for (auto& s : shapes) {
@@ -760,7 +819,7 @@ inline Tensor ConvertMklToTF(OpKernelContext* context, const Tensor& mkl_tensor,
#endif
// Get the MKL shape from the second string tensor
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
inline void GetMklShape(OpKernelContext* ctext, int n, MklShape* mklshape) {
mklshape->DeSerializeMklShape(
ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs()))
@@ -795,7 +854,7 @@ inline void GetMklInputList(OpKernelContext* ctext, StringPiece name,
ctext->input_list(name, input_tensors);
}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
inline void GetMklShapeList(OpKernelContext* ctext, StringPiece name,
MklShapeList* mkl_shapes) {
@@ -825,7 +884,7 @@ inline void GetMklShapeList(OpKernelContext* ctext, StringPiece name,
#endif
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
/// Get shape of input tensor pointed by 'input_idx' in TensorShape format.
/// If the input tensor is in MKL layout, then obtains TensorShape from
/// MklShape.
@@ -845,7 +904,7 @@ inline TensorShape GetTfShape(OpKernelContext* context, size_t input_idx) {
}
#endif
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// Allocate the second output tensor that will contain
// the MKL shape serialized
inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n,
@@ -878,7 +937,7 @@ inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n,
}
#endif
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// Allocate the output tensor, create a second output tensor that will contain
// the MKL shape serialized
inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n,
@@ -923,7 +982,7 @@ inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n,
// Allocates a temp tensor and returns the data buffer for temporary storage.
// Currently
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
template <typename T>
inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out,
const memory::primitive_desc& pd, void** buf_out) {
@@ -972,7 +1031,7 @@ inline void GetStridesFromSizes(TensorFormat data_format, size_t* strides,
}
}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
inline void MklSizesToTFSizes(OpKernelContext* context,
TensorFormat data_format_,
const MklShape& mkl_shape,
@@ -1016,7 +1075,7 @@ inline int32 GetMklTensorDimIndex(char dimension) {
}
}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
inline int64 GetMklTensorDim(const MklShape& mkl_shape, char dimension) {
int index = GetMklTensorDimIndex(dimension);
CHECK(index >= 0 && index < mkl_shape.GetDimension())
@@ -1046,7 +1105,7 @@ inline void CopyMklTensorInToOut(OpKernelContext* context, int idx_in,
context->set_output(idx_meta_out, meta_output);
}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
inline void CopyTfTensorInToOutWithShape(OpKernelContext* context, int idx_in,
int idx_out,
const TensorShape& shape) {
@@ -1084,7 +1143,7 @@ inline void CopyTfTensorInToOutWithShape(OpKernelContext* context, int idx_in,
}
#endif
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
inline void ForwardTfTensorInToOut(OpKernelContext* context, int idx_in,
int idx_out) {
@@ -1142,7 +1201,7 @@ inline void ForwardMklTensorInToOut(OpKernelContext* context, int idx_in,
}
}
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
// Set a dummy MKLDNN shape (called when the output is in TF format)
inline void SetDummyMklDnnShapeOutput(OpKernelContext* context,
uint32 idx_data_out) {
@@ -1186,7 +1245,7 @@ inline void ForwardMklMetaDataInToOut(OpKernelContext* context,
}
}
-#ifdef INTEL_MKL_ML
+#ifdef INTEL_MKL_ML_ONLY
// Set a dummy MKL shape (called when the output is in TF format)
inline void SetDummyMklShapeOutput(OpKernelContext* context,
uint32 idx_data_out) {
@@ -1303,7 +1362,7 @@ inline void MklNCHWToNHWC(const Tensor& input, Tensor** output) {
#endif
// -------------------------------------------------------------------
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
/// Return MKL-DNN data type (memory::data_type) for input type T
///
@@ -1319,6 +1378,19 @@ memory::data_type MklDnnType<float>() {
return memory::data_type::f32;
}
+/// Map TensorFlow's data format into MKL-DNN 3D data format
+/// @input: TensorFlow data format
+/// @return: memory::format corresponding to TensorFlow data format;
+/// Fails with an error if invalid data format.
+inline memory::format TFDataFormatToMklDnn3DDataFormat(TensorFormat format) {
+ if (format == FORMAT_NHWC)
+ return memory::format::ndhwc;
+ else if (format == FORMAT_NCHW)
+ return memory::format::ncdhw;
+ TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format"));
+ return memory::format::format_undef;
+}
+
/// Map TensorFlow's data format into MKL-DNN data format
///
/// @input: TensorFlow data format
@@ -1330,7 +1402,6 @@ inline memory::format TFDataFormatToMklDnnDataFormat(TensorFormat format) {
else if (format == FORMAT_NCHW)
return memory::format::nchw;
TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format"));
- // Return to get rid of compiler warning
return memory::format::format_undef;
}
@@ -1340,9 +1411,9 @@ inline memory::format TFDataFormatToMklDnnDataFormat(TensorFormat format) {
/// @return: Tensorflow data format corresponding to memory::format
/// Fails with an error if invalid data format.
inline TensorFormat MklDnnDataFormatToTFDataFormat(memory::format format) {
- if (format == memory::format::nhwc)
+ if (format == memory::format::nhwc || format == memory::format::ndhwc)
return FORMAT_NHWC;
- else if (format == memory::format::nchw)
+ else if (format == memory::format::nchw || format == memory::format::ncdhw)
return FORMAT_NCHW;
TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format"));
@@ -1392,6 +1463,22 @@ inline memory::dims TFShapeToMklDnnDimsInNCHW(const TensorShape& shape,
return memory::dims({n, c, h, w});
}
+inline memory::dims TFShapeToMklDnnDimsInNCDHW(const TensorShape& shape,
+ TensorFormat format) {
+ // Check validity of format.
+ CHECK_NE(TFDataFormatToMklDnn3DDataFormat(format),
+ memory::format::format_undef);
+
+ int n = shape.dim_size(GetTensorDimIndex<3>(format, 'N'));
+ int c = shape.dim_size(GetTensorDimIndex<3>(format, 'C'));
+ int d = shape.dim_size(GetTensorDimIndex<3>(format, '0'));
+ int h = shape.dim_size(GetTensorDimIndex<3>(format, '1'));
+ int w = shape.dim_size(GetTensorDimIndex<3>(format, '2'));
+
+ // MKL-DNN requires dimensions in NCDHW format.
+ return memory::dims({n, c, d, h, w});
+}
+
/// Overloaded version of function above. Input parameters are
/// self-explanatory.
inline memory::dims MklDnnDimsInNCHW(const memory::dims& in_dims,
@@ -1504,6 +1591,8 @@ class MklDnnData {
/// Operations memory descriptor
memory::desc* op_md_;
+ // flat to indicate if data is 3D or not.
+ bool bIs3D;
/// Operations temp buffer
void* allocated_buffer_;
/// CPU engine on which operation will be executed
@@ -1530,6 +1619,10 @@ class MklDnnData {
static_cast<const void*>(tensor->flat<T>().data()));
}
+ void SetIs3DData(bool bIs3D_) { bIs3D = bIs3D_; }
+
+ bool GetIs3D() { return bIs3D; }
+
/// Set user memory primitive using specified dimensions, memory format and
/// data_buffer. Function automatically uses element data type by using
/// input type T used for creating call object.
diff --git a/tensorflow/core/util/mkl_util_test.cc b/tensorflow/core/util/mkl_util_test.cc
index cd1d0713ad..4f837f105d 100644
--- a/tensorflow/core/util/mkl_util_test.cc
+++ b/tensorflow/core/util/mkl_util_test.cc
@@ -22,7 +22,7 @@ limitations under the License.
namespace tensorflow {
namespace {
-#ifndef INTEL_MKL_ML
+#ifndef INTEL_MKL_ML_ONLY
TEST(MklUtilTest, MklDnnTfShape) {
auto cpu_engine = engine(engine::cpu, 0);
@@ -84,7 +84,7 @@ TEST(MklUtilTest, MklDnnBlockedFormatTest) {
EXPECT_EQ(b_md2.data.format, mkldnn_blocked);
}
-#endif // INTEL_MKL_ML
+#endif // INTEL_MKL_ML_ONLY
} // namespace
} // namespace tensorflow
diff --git a/tensorflow/core/util/strided_slice_op.cc b/tensorflow/core/util/strided_slice_op.cc
index aca60b942d..ad8a44a518 100644
--- a/tensorflow/core/util/strided_slice_op.cc
+++ b/tensorflow/core/util/strided_slice_op.cc
@@ -326,7 +326,7 @@ Status ValidateStridedSliceOp(
// Even if we don't have values for begin or end, we do know that this
// dimension covers the whole interval. If we have shape information for
// this dimension, that tells us the interval length.
- if (dim_i > 0) {
+ if (dim_i >= 0) {
if (stride_i < 0) {
interval_length = -dim_i;
} else {
diff --git a/tensorflow/core/util/tensor_format.cc b/tensorflow/core/util/tensor_format.cc
index a5f7ecf0d1..f331973f5c 100644
--- a/tensorflow/core/util/tensor_format.cc
+++ b/tensorflow/core/util/tensor_format.cc
@@ -25,6 +25,10 @@ string GetConvnet3dDataFormatAttrString() {
return "data_format: { 'NDHWC', 'NCDHW' } = 'NDHWC' ";
}
+string GetConvnetDataFormat2D3DAttrString() {
+ return "data_format: { 'NHWC', 'NCHW', 'NDHWC', 'NCDHW' } = 'NHWC' ";
+}
+
string GetConvnetFilterFormatAttrString() {
return "filter_format: { 'HWIO', 'OIHW' } = 'HWIO' ";
}
diff --git a/tensorflow/core/util/tensor_format.h b/tensorflow/core/util/tensor_format.h
index 918835e1fb..b0c349dd90 100644
--- a/tensorflow/core/util/tensor_format.h
+++ b/tensorflow/core/util/tensor_format.h
@@ -483,6 +483,7 @@ string GetConvnet3dDataFormatAttrString();
// Return the string that specifies the filter format for convnet operations.
string GetConvnetFilterFormatAttrString();
string GetConvnet3dFilterFormatAttrString();
+string GetConvnetDataFormat2D3DAttrString();
// Returns a tensor shape for the specified format and dimension sizes.
// Works for both 2D and 3D operations. The output shapes are as follows:
diff --git a/tensorflow/docs_src/about/index.md b/tensorflow/docs_src/about/index.md
index dc1e9af876..c3c13ff329 100644
--- a/tensorflow/docs_src/about/index.md
+++ b/tensorflow/docs_src/about/index.md
@@ -3,9 +3,9 @@
This section provides a few documents about TensorFlow itself,
including the following:
- * @{$uses$TensorFlow in Use}, which provides a link to our model zoo and
+ * [TensorFlow in Use](../about/uses.md), which provides a link to our model zoo and
lists some popular ways that TensorFlow is being used.
- * @{$bib$TensorFlow White Papers}, which provides abstracts of white papers
+ * [TensorFlow White Papers](../about/bib.md), which provides abstracts of white papers
about TensorFlow.
- * @{$attribution$Attribution}, which specifies how to attribute and refer
+ * [Attribution](../about/attribution.md), which specifies how to attribute and refer
to TensorFlow.
diff --git a/tensorflow/docs_src/api_guides/cc/guide.md b/tensorflow/docs_src/api_guides/cc/guide.md
index 0cea1d266e..2cd645afa7 100644
--- a/tensorflow/docs_src/api_guides/cc/guide.md
+++ b/tensorflow/docs_src/api_guides/cc/guide.md
@@ -7,6 +7,12 @@ You should, as a result, be sure you are following the
[`master` version of this doc](https://www.tensorflow.org/versions/master/api_guides/cc/guide),
in case there have been any changes.
+Note: The C++ API is only designed to work with TensorFlow `bazel build`.
+If you need a stand-alone option use the [C-api](../../install/install_c.md).
+See [these instructions](https://docs.bazel.build/versions/master/external.html)
+for details on how to include TensorFlow as a subproject (instead of building
+your project from inside TensorFlow, as in this example).
+
[TOC]
TensorFlow's C++ API provides mechanisms for constructing and executing a data
diff --git a/tensorflow/docs_src/api_guides/python/client.md b/tensorflow/docs_src/api_guides/python/client.md
index 56367e6671..fdd48e66dc 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.
-@{$guide/low_level_intro$This guide} has examples of how a graph
+[This guide](../../guide/low_level_intro.md) has examples of how a graph
is launched in a `tf.Session`.
## Session management
diff --git a/tensorflow/docs_src/api_guides/python/constant_op.md b/tensorflow/docs_src/api_guides/python/constant_op.md
index 498ec3db5d..9ba95b0f55 100644
--- a/tensorflow/docs_src/api_guides/python/constant_op.md
+++ b/tensorflow/docs_src/api_guides/python/constant_op.md
@@ -64,7 +64,7 @@ print(sess.run(norm))
```
Another common use of random values is the initialization of variables. Also see
-the @{$variables$Variables How To}.
+the [Variables How To](../../guide/variables.md).
```python
# Use random uniform values in [0, 1) as the initializer for a variable of shape
diff --git a/tensorflow/docs_src/api_guides/python/input_dataset.md b/tensorflow/docs_src/api_guides/python/input_dataset.md
index ab572e53d4..911a76c2df 100644
--- a/tensorflow/docs_src/api_guides/python/input_dataset.md
+++ b/tensorflow/docs_src/api_guides/python/input_dataset.md
@@ -2,7 +2,7 @@
[TOC]
`tf.data.Dataset` allows you to build complex input pipelines. See the
-@{$guide/datasets} for an in-depth explanation of how to use this API.
+[Importing Data](../../guide/datasets.md) for an in-depth explanation of how to use this API.
## Reader classes
diff --git a/tensorflow/docs_src/api_guides/python/io_ops.md b/tensorflow/docs_src/api_guides/python/io_ops.md
index ab3c70daa0..d7ce6fdfde 100644
--- a/tensorflow/docs_src/api_guides/python/io_ops.md
+++ b/tensorflow/docs_src/api_guides/python/io_ops.md
@@ -8,7 +8,7 @@ Note: Functions taking `Tensor` arguments can also take anything accepted by
## Placeholders
TensorFlow provides a placeholder operation that must be fed with data
-on execution. For more info, see the section on @{$reading_data#Feeding$Feeding data}.
+on execution. For more info, see the section on [Feeding data](../../api_guides/python/reading_data.md#Feeding).
* `tf.placeholder`
* `tf.placeholder_with_default`
@@ -21,7 +21,7 @@ there is a convenience function:
## Readers
TensorFlow provides a set of Reader classes for reading data formats.
-For more information on inputs and readers, see @{$reading_data$Reading data}.
+For more information on inputs and readers, see [Reading data](../../api_guides/python/reading_data.md).
* `tf.ReaderBase`
* `tf.TextLineReader`
@@ -42,7 +42,7 @@ formats into tensors.
### Example protocol buffer
-TensorFlow's @{$reading_data#standard_tensorflow_format$recommended format for training examples}
+TensorFlow's [recommended format for training examples](../../api_guides/python/reading_data.md#standard_tensorflow_format)
is serialized `Example` protocol buffers, [described
here](https://www.tensorflow.org/code/tensorflow/core/example/example.proto).
They contain `Features`, [described
@@ -62,7 +62,7 @@ here](https://www.tensorflow.org/code/tensorflow/core/example/feature.proto).
TensorFlow provides several implementations of 'Queues', which are
structures within the TensorFlow computation graph to stage pipelines
of tensors together. The following describe the basic Queue interface
-and some implementations. To see an example use, see @{$threading_and_queues$Threading and Queues}.
+and some implementations. To see an example use, see [Threading and Queues](../../api_guides/python/threading_and_queues.md).
* `tf.QueueBase`
* `tf.FIFOQueue`
@@ -85,7 +85,7 @@ and some implementations. To see an example use, see @{$threading_and_queues$Th
## Input pipeline
TensorFlow functions for setting up an input-prefetching pipeline.
-Please see the @{$reading_data$reading data how-to}
+Please see the [reading data how-to](../../api_guides/python/reading_data.md)
for context.
### Beginning of an input pipeline
diff --git a/tensorflow/docs_src/api_guides/python/meta_graph.md b/tensorflow/docs_src/api_guides/python/meta_graph.md
index 7dbd9a56f4..5e8a8b4d0f 100644
--- a/tensorflow/docs_src/api_guides/python/meta_graph.md
+++ b/tensorflow/docs_src/api_guides/python/meta_graph.md
@@ -23,7 +23,7 @@ protocol buffer. It contains the following fields:
* [`SaverDef`](https://www.tensorflow.org/code/tensorflow/core/protobuf/saver.proto) for the saver.
* [`CollectionDef`](https://www.tensorflow.org/code/tensorflow/core/protobuf/meta_graph.proto)
map that further describes additional components of the model such as
-@{$python/state_ops$`Variables`},
+[`Variables`](../../api_guides/python/state_ops.md),
`tf.train.QueueRunner`, etc.
In order for a Python object to be serialized
diff --git a/tensorflow/docs_src/api_guides/python/reading_data.md b/tensorflow/docs_src/api_guides/python/reading_data.md
index 78c36d965c..9f555ee85d 100644
--- a/tensorflow/docs_src/api_guides/python/reading_data.md
+++ b/tensorflow/docs_src/api_guides/python/reading_data.md
@@ -1,7 +1,7 @@
# Reading data
Note: The preferred way to feed data into a tensorflow program is using the
-@{$datasets$`tf.data` API}.
+[`tf.data` API](../../guide/datasets.md).
There are four methods of getting data into a TensorFlow program:
@@ -16,7 +16,7 @@ There are four methods of getting data into a TensorFlow program:
## `tf.data` API
-See the @{$guide/datasets} for an in-depth explanation of `tf.data.Dataset`.
+See the [Importing Data](../../guide/datasets.md) 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
@@ -56,8 +56,8 @@ in
## `QueueRunner`
Warning: This section discusses implementing input pipelines using the
-queue-based APIs which can be cleanly replaced by the @{$datasets$`tf.data`
-API}.
+queue-based APIs which can be cleanly replaced by the [`tf.data`
+API](../../guide/datasets.md).
A typical queue-based pipeline for reading records from files has the following stages:
@@ -154,14 +154,14 @@ a uint8 tensor, standard operations can slice out each piece and reformat as
needed. For CIFAR-10, you can see how to do the reading and decoding in
[`tensorflow_models/tutorials/image/cifar10/cifar10_input.py`](https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10/cifar10_input.py)
and described in
-@{$deep_cnn#prepare-the-data$this tutorial}.
+[this tutorial](../../tutorials/images/deep_cnn.md#prepare-the-data).
#### Standard TensorFlow format
Another approach is to convert whatever data you have into a supported format.
This approach makes it easier to mix and match data sets and network
architectures. The recommended format for TensorFlow is a
-@{$python/python_io#tfrecords_format_details$TFRecords file}
+[TFRecords file](../../api_guides/python/python_io.md#tfrecords_format_details)
containing
[`tf.train.Example` protocol buffers](https://www.tensorflow.org/code/tensorflow/core/example/example.proto)
(which contain
@@ -279,7 +279,7 @@ This can be important:
How many threads do you need? the `tf.train.shuffle_batch*` functions add a
summary to the graph that indicates how full the example queue is. If you have
enough reading threads, that summary will stay above zero. You can
-@{$summaries_and_tensorboard$view your summaries as training progresses using TensorBoard}.
+[view your summaries as training progresses using TensorBoard](../../guide/summaries_and_tensorboard.md).
### Creating threads to prefetch using `QueueRunner` objects
@@ -368,7 +368,7 @@ threads got an error when running some operation (or an ordinary Python
exception).
For more about threading, queues, QueueRunners, and Coordinators
-@{$threading_and_queues$see here}.
+[see here](../../api_guides/python/threading_and_queues.md).
#### Aside: How clean shut-down when limiting epochs works
@@ -501,18 +501,18 @@ sessions, maybe in separate processes:
model that reads validation input data.
This is what is done `tf.estimator` and manually in
-@{$deep_cnn#save-and-restore-checkpoints$the example CIFAR-10 model}.
+[the example CIFAR-10 model](../../tutorials/images/deep_cnn.md#save-and-restore-checkpoints).
This has a couple of benefits:
* The eval is performed on a single snapshot of the trained variables.
* You can perform the eval even after training has completed and exited.
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}.
+their trained variables or layers. See [the shared variables tutorial](../../guide/variables.md).
To support the single-graph approach
-@{$guide/datasets$`tf.data`} also supplies
-@{$guide/datasets#creating_an_iterator$advanced iterator types} that
+[`tf.data`](../../guide/datasets.md) also supplies
+[advanced iterator types](../../guide/datasets.md#creating_an_iterator) that
that allow the user to change the input pipeline without rebuilding the graph or
session.
diff --git a/tensorflow/docs_src/api_guides/python/regression_examples.md b/tensorflow/docs_src/api_guides/python/regression_examples.md
index f8abbf0f97..d67f38f57a 100644
--- a/tensorflow/docs_src/api_guides/python/regression_examples.md
+++ b/tensorflow/docs_src/api_guides/python/regression_examples.md
@@ -66,7 +66,7 @@ watch the following video:
<a name="running"></a>
## Running the examples
-You must @{$install$install TensorFlow} prior to running these examples.
+You must [install TensorFlow](../../install/index.md) prior to running these examples.
Depending on the way you've installed TensorFlow, you might also
need to activate your TensorFlow environment. Then, do the following:
diff --git a/tensorflow/docs_src/api_guides/python/summary.md b/tensorflow/docs_src/api_guides/python/summary.md
index e290703b7d..fc45e7b4c3 100644
--- a/tensorflow/docs_src/api_guides/python/summary.md
+++ b/tensorflow/docs_src/api_guides/python/summary.md
@@ -2,7 +2,7 @@
[TOC]
Summaries provide a way to export condensed information about a model, which is
-then accessible in tools such as @{$summaries_and_tensorboard$TensorBoard}.
+then accessible in tools such as [TensorBoard](../../guide/summaries_and_tensorboard.md).
## Generation of Summaries
diff --git a/tensorflow/docs_src/api_guides/python/threading_and_queues.md b/tensorflow/docs_src/api_guides/python/threading_and_queues.md
index 48f0778b73..e00f17f955 100644
--- a/tensorflow/docs_src/api_guides/python/threading_and_queues.md
+++ b/tensorflow/docs_src/api_guides/python/threading_and_queues.md
@@ -3,7 +3,7 @@
Note: In versions of TensorFlow before 1.2, we recommended using multi-threaded,
queue-based input pipelines for performance. Beginning with TensorFlow 1.4,
however, we recommend using the `tf.data` module instead. (See
-@{$datasets$Datasets} for details. In TensorFlow 1.2 and 1.3, the module was
+[Datasets](../../guide/datasets.md) for details. In TensorFlow 1.2 and 1.3, the module was
called `tf.contrib.data`.) The `tf.data` module offers an easier-to-use
interface for constructing efficient input pipelines. Furthermore, we've stopped
developing the old multi-threaded, queue-based input pipelines. We've retained
diff --git a/tensorflow/docs_src/api_guides/python/train.md b/tensorflow/docs_src/api_guides/python/train.md
index a118123665..4b4c6a4fe3 100644
--- a/tensorflow/docs_src/api_guides/python/train.md
+++ b/tensorflow/docs_src/api_guides/python/train.md
@@ -74,9 +74,9 @@ moving averages for evaluations often improve results significantly.
## Coordinator and QueueRunner
-See @{$threading_and_queues$Threading and Queues}
+See [Threading and Queues](../../api_guides/python/threading_and_queues.md)
for how to use threads and queues. For documentation on the Queue API,
-see @{$python/io_ops#queues$Queues}.
+see [Queues](../../api_guides/python/io_ops.md#queues).
* `tf.train.Coordinator`
@@ -87,7 +87,7 @@ see @{$python/io_ops#queues$Queues}.
## Distributed execution
-See @{$distributed$Distributed TensorFlow} for
+See [Distributed TensorFlow](../../deploy/distributed.md) for
more information about how to configure a distributed TensorFlow program.
* `tf.train.Server`
@@ -105,7 +105,7 @@ more information about how to configure a distributed TensorFlow program.
## Reading Summaries from Event Files
-See @{$summaries_and_tensorboard$Summaries and TensorBoard} for an
+See [Summaries and TensorBoard](../../guide/summaries_and_tensorboard.md) for an
overview of summaries, event files, and visualization in TensorBoard.
* `tf.train.summary_iterator`
diff --git a/tensorflow/docs_src/community/contributing.md b/tensorflow/docs_src/community/contributing.md
index afbb8bbdd0..ece4a7c70b 100644
--- a/tensorflow/docs_src/community/contributing.md
+++ b/tensorflow/docs_src/community/contributing.md
@@ -25,12 +25,12 @@ guidelines](https://github.com/tensorflow/tensorflow/blob/master/CONTRIBUTING.md
[developers@tensorflow.org](https://groups.google.com/a/tensorflow.org/d/forum/developers)
mailing list, to coordinate and discuss with others contributing to TensorFlow.
-* For coding style conventions, read the @{$style_guide$TensorFlow Style Guide}.
+* For coding style conventions, read the [TensorFlow Style Guide](../community/style_guide.md).
-* Finally, review @{$documentation$Writing TensorFlow Documentation}, which
+* Finally, review [Writing TensorFlow Documentation](../community/documentation.md), which
explains documentation conventions.
-You may also wish to review our guide to @{$benchmarks$defining and running benchmarks}.
+You may also wish to review our guide to [defining and running benchmarks](../community/benchmarks.md).
## Special Interest Groups
diff --git a/tensorflow/docs_src/community/index.md b/tensorflow/docs_src/community/index.md
index eec2e51a87..1a30be32a5 100644
--- a/tensorflow/docs_src/community/index.md
+++ b/tensorflow/docs_src/community/index.md
@@ -25,10 +25,10 @@ the appropriate repository for the project. Major repositories include:
### Security
-Before using TensorFlow, please take a look at our security model, list of
-recent security announcements, and ways you can report security issues to the
-TensorFlow team at the
-[Using TensorFlow Securely](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) page on GitHub.
+Before using TensorFlow, please take a look at our [security model](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md#tensorflow-models-are-programs),
+[list of recent security advisories and announcements](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/security/index.md),
+and [ways you can report security issues](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md#reporting-vulnerabilities)
+to the TensorFlow team at the [Using TensorFlow Securely](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) page on GitHub.
## Stay Informed
@@ -40,7 +40,7 @@ We recommend that you join this list if you depend on TensorFlow in any way.
### Development Roadmap
-The @{$roadmap$Roadmap} summarizes plans for upcoming additions to TensorFlow.
+The [Roadmap](../community/roadmap.md) summarizes plans for upcoming additions to TensorFlow.
### Social Media
@@ -54,7 +54,7 @@ with content from the TensorFlow team and the best articles from the community.
### YouTube
-Our [YouTube Channel](http://youtube.com/tensorflow/) focuses on machine learing
+Our [YouTube Channel](http://youtube.com/tensorflow/) focuses on machine learning
and AI with TensorFlow. On it we have a number of new shows, including:
- TensorFlow Meets: meet with community contributors to learn and share what they're doing
@@ -70,12 +70,12 @@ the [TensorFlow discuss mailing
list](https://groups.google.com/a/tensorflow.org/d/forum/discuss).
A number of other mailing lists exist, focused on different project areas, which
-can be found at @{$lists$TensorFlow Mailing Lists}.
+can be found at [TensorFlow Mailing Lists](../community/lists.md).
### User Groups
To meet with like-minded people local to you, check out the many
-@{$groups$TensorFlow user groups} around the world.
+[TensorFlow user groups](../community/groups.md) around the world.
## Contributing To TensorFlow
diff --git a/tensorflow/docs_src/community/lists.md b/tensorflow/docs_src/community/lists.md
index 7450ab36c4..bc2f573c29 100644
--- a/tensorflow/docs_src/community/lists.md
+++ b/tensorflow/docs_src/community/lists.md
@@ -32,6 +32,8 @@ These projects inside the TensorFlow GitHub organization have lists dedicated to
and peer support for TensorFlow.js.
* [tflite](https://groups.google.com/a/tensorflow.org/d/forum/tflite) - Discussion and
peer support for TensorFlow Lite.
+* [tfprobability](https://groups.google.com/a/tensorflow.org/d/forum/tfprobability) - Discussion and
+ peer support for TensorFlow Probability.
* [tpu-users](https://groups.google.com/a/tensorflow.org/d/forum/tpu-users) - Community discussion
and support for TPU users.
diff --git a/tensorflow/docs_src/community/style_guide.md b/tensorflow/docs_src/community/style_guide.md
index daf0d2fdc0..c78da20edd 100644
--- a/tensorflow/docs_src/community/style_guide.md
+++ b/tensorflow/docs_src/community/style_guide.md
@@ -88,7 +88,7 @@ creates a part of the graph and returns output tensors.
* Operations should contain an extensive Python comment with Args and Returns
declarations that explain both the type and meaning of each value. Possible
shapes, dtypes, or ranks should be specified in the description.
- @{$documentation$See documentation details}
+ [See documentation details](../community/documentation.md)
* For increased usability include an example of usage with inputs / outputs
of the op in Example section.
diff --git a/tensorflow/docs_src/deploy/distributed.md b/tensorflow/docs_src/deploy/distributed.md
index 6a760f53c8..2fba36cfa7 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 @{$guide/low_level_intro$basic concepts} of
+familiar with the [basic concepts](../guide/low_level_intro.md) of
writing low level TensorFlow programs.
## Hello distributed TensorFlow!
diff --git a/tensorflow/docs_src/deploy/hadoop.md b/tensorflow/docs_src/deploy/hadoop.md
index c4471562b9..b0d416df2e 100644
--- a/tensorflow/docs_src/deploy/hadoop.md
+++ b/tensorflow/docs_src/deploy/hadoop.md
@@ -6,7 +6,7 @@ at the moment.
## HDFS
-We assume that you are familiar with @{$reading_data$reading data}.
+We assume that you are familiar with [reading data](../api_guides/python/reading_data.md).
To use HDFS with TensorFlow, change the file paths you use to read and write
data to an HDFS path. For example:
@@ -61,5 +61,5 @@ be set:
export KRB5CCNAME=/tmp/krb5cc_10002
```
-If you are running @{$distributed$Distributed TensorFlow}, then all
+If you are running [Distributed TensorFlow](../deploy/distributed.md), then all
workers must have the environment variables set and Hadoop installed.
diff --git a/tensorflow/docs_src/deploy/index.md b/tensorflow/docs_src/deploy/index.md
index 3322004189..08b28de639 100644
--- a/tensorflow/docs_src/deploy/index.md
+++ b/tensorflow/docs_src/deploy/index.md
@@ -3,11 +3,11 @@
This section focuses on deploying real-world models. It contains
the following documents:
- * @{$distributed$Distributed TensorFlow}, which explains how to create
+ * [Distributed TensorFlow](../deploy/distributed.md), which explains how to create
a cluster of TensorFlow servers.
- * @{$hadoop$How to run TensorFlow on Hadoop}, which has a highly
+ * [How to run TensorFlow on Hadoop](../deploy/hadoop.md), which has a highly
self-explanatory title.
- * @{$s3$How to run TensorFlow with the S3 filesystem}, which explains how
+ * [How to run TensorFlow with the S3 filesystem](../deploy/s3.md), which explains how
to run TensorFlow with the S3 file system.
* The entire document set for [TensorFlow serving](/serving), an open-source,
flexible, high-performance serving system for machine-learned models
diff --git a/tensorflow/docs_src/deploy/s3.md b/tensorflow/docs_src/deploy/s3.md
index 7028249e94..b4a759d687 100644
--- a/tensorflow/docs_src/deploy/s3.md
+++ b/tensorflow/docs_src/deploy/s3.md
@@ -40,7 +40,7 @@ AWS_SECRET_ACCESS_KEY=XXXXX
AWS_REGION=us-east-1 # Region for the S3 bucket, this is not always needed. Default is us-east-1.
S3_ENDPOINT=s3.us-east-1.amazonaws.com # The S3 API Endpoint to connect to. This is specified in a HOST:PORT format.
S3_USE_HTTPS=1 # Whether or not to use HTTPS. Disable with 0.
-S3_VERIFY_SSL=1 # If HTTPS is used, conterols if SSL should be enabled. Disable with 0.
+S3_VERIFY_SSL=1 # If HTTPS is used, controls if SSL should be enabled. Disable with 0.
```
## Usage
@@ -64,7 +64,7 @@ You should see output similar to this:
### Reading Data
-When @{$reading_data$reading data}, change the file paths you use to read and write
+When [reading data](../api_guides/python/reading_data.md), change the file paths you use to read and write
data to an S3 path. For example:
```python
diff --git a/tensorflow/docs_src/extend/add_filesys.md b/tensorflow/docs_src/extend/add_filesys.md
index bc0f662f0c..5f8ac64d25 100644
--- a/tensorflow/docs_src/extend/add_filesys.md
+++ b/tensorflow/docs_src/extend/add_filesys.md
@@ -225,7 +225,7 @@ it will use the `FooBarFileSystem` implementation.
Next, you must build a shared object containing this implementation. An example
of doing so using bazel's `cc_binary` rule can be found
[here](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/BUILD#L244),
-but you may use any build system to do so. See the section on @{$adding_an_op#build_the_op_library$building the op library} for similar
+but you may use any build system to do so. See the section on [building the op library](../extend/adding_an_op.md#build_the_op_library) for similar
instructions.
The result of building this target is a `.so` shared object file.
diff --git a/tensorflow/docs_src/extend/adding_an_op.md b/tensorflow/docs_src/extend/adding_an_op.md
index 6e96cfc532..cc25ab9b45 100644
--- a/tensorflow/docs_src/extend/adding_an_op.md
+++ b/tensorflow/docs_src/extend/adding_an_op.md
@@ -56,8 +56,8 @@ PREREQUISITES:
* Some familiarity with C++.
* Must have installed the
- @{$install$TensorFlow binary}, or must have
- @{$install_sources$downloaded TensorFlow source},
+ [TensorFlow binary](../install/index.md), or must have
+ [downloaded TensorFlow source](../install/install_sources.md),
and be able to build it.
[TOC]
@@ -649,7 +649,7 @@ define an attr with constraints, you can use the following `<attr-type-expr>`s:
```
Lists can be combined with other lists and single types. The following
- op allows attr `t` to be any of the numberic types, or the bool type:
+ op allows attr `t` to be any of the numeric types, or the bool type:
```c++
REGISTER_OP("NumberOrBooleanType")
@@ -1140,7 +1140,7 @@ In general, changes to existing, checked-in specifications must be
backwards-compatible: changing the specification of an op must not break prior
serialized `GraphDef` protocol buffers constructed from older specifications.
The details of `GraphDef` compatibility are
-@{$version_compat#compatibility_of_graphs_and_checkpoints$described here}.
+[described here](../guide/version_compat.md#compatibility_of_graphs_and_checkpoints).
There are several ways to preserve backwards-compatibility.
@@ -1190,7 +1190,7 @@ callers. The Python API may be kept compatible by careful changes in a
hand-written Python wrapper, by keeping the old signature except possibly adding
new optional arguments to the end. Generally incompatible changes may only be
made when TensorFlow's changes major versions, and must conform to the
-@{$version_compat#compatibility_of_graphs_and_checkpoints$`GraphDef` version semantics}.
+[`GraphDef` version semantics](../guide/version_compat.md#compatibility_of_graphs_and_checkpoints).
### GPU Support
@@ -1262,7 +1262,7 @@ For example, add `-L /usr/local/cuda-8.0/lib64/` if your CUDA is installed in
Given a graph of ops, TensorFlow uses automatic differentiation
(backpropagation) to add new ops representing gradients with respect to the
existing ops (see
-@{$python/train#gradient_computation$Gradient Computation}).
+[Gradient Computation](../api_guides/python/train.md#gradient_computation)).
To make automatic differentiation work for new ops, you must register a gradient
function which computes gradients with respect to the ops' inputs given
gradients with respect to the ops' outputs.
diff --git a/tensorflow/docs_src/extend/architecture.md b/tensorflow/docs_src/extend/architecture.md
index 83d70c9468..eb33336bee 100644
--- a/tensorflow/docs_src/extend/architecture.md
+++ b/tensorflow/docs_src/extend/architecture.md
@@ -7,8 +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 @{$guide/low_level_intro$this document} for an introduction to
-these topics. Some familiarity with @{$distributed$distributed TensorFlow}
+and sessions. See [this document](../guide/low_level_intro.md) for an introduction to
+these topics. Some familiarity with [distributed TensorFlow](../deploy/distributed.md)
will also be helpful.
This document is for developers who want to extend TensorFlow in some way not
@@ -199,7 +199,7 @@ Many of the operation kernels are implemented using Eigen::Tensor, which uses
C++ templates to generate efficient parallel code for multicore CPUs and GPUs;
however, we liberally use libraries like cuDNN where a more efficient kernel
implementation is possible. We have also implemented
-@{$quantization$quantization}, which enables
+[quantization](../performance/quantization.md), which enables
faster inference in environments such as mobile devices and high-throughput
datacenter applications, and use the
[gemmlowp](https://github.com/google/gemmlowp) low-precision matrix library to
@@ -209,7 +209,7 @@ If it is difficult or inefficient to represent a subcomputation as a composition
of operations, users can register additional kernels that provide an efficient
implementation written in C++. For example, we recommend registering your own
fused kernels for some performance critical operations, such as the ReLU and
-Sigmoid activation functions and their corresponding gradients. The @{$xla$XLA Compiler} has an
+Sigmoid activation functions and their corresponding gradients. The [XLA Compiler](../performance/xla/index.md) has an
experimental implementation of automatic kernel fusion.
### Code
diff --git a/tensorflow/docs_src/extend/index.md b/tensorflow/docs_src/extend/index.md
index d48340a777..bbf4a8139b 100644
--- a/tensorflow/docs_src/extend/index.md
+++ b/tensorflow/docs_src/extend/index.md
@@ -3,32 +3,32 @@
This section explains how developers can add functionality to TensorFlow's
capabilities. Begin by reading the following architectural overview:
- * @{$architecture$TensorFlow Architecture}
+ * [TensorFlow Architecture](../extend/architecture.md)
The following guides explain how to extend particular aspects of
TensorFlow:
- * @{$adding_an_op$Adding a New Op}, which explains how to create your own
+ * [Adding a New Op](../extend/adding_an_op.md), which explains how to create your own
operations.
- * @{$add_filesys$Adding a Custom Filesystem Plugin}, which explains how to
+ * [Adding a Custom Filesystem Plugin](../extend/add_filesys.md), which explains how to
add support for your own shared or distributed filesystem.
- * @{$new_data_formats$Custom Data Readers}, which details how to add support
+ * [Custom Data Readers](../extend/new_data_formats.md), which details how to add support
for your own file and record formats.
Python is currently the only language supported by TensorFlow's API stability
promises. However, TensorFlow also provides functionality in C++, Go, Java and
-[JavaScript](https://js.tensorflow.org) (incuding
+[JavaScript](https://js.tensorflow.org) (including
[Node.js](https://github.com/tensorflow/tfjs-node)),
plus community support for [Haskell](https://github.com/tensorflow/haskell) and
[Rust](https://github.com/tensorflow/rust). If you'd like to create or
develop TensorFlow features in a language other than these languages, read the
following guide:
- * @{$language_bindings$TensorFlow in Other Languages}
+ * [TensorFlow in Other Languages](../extend/language_bindings.md)
To create tools compatible with TensorFlow's model format, read the following
guide:
- * @{$tool_developers$A Tool Developer's Guide to TensorFlow Model Files}
+ * [A Tool Developer's Guide to TensorFlow Model Files](../extend/tool_developers/index.md)
diff --git a/tensorflow/docs_src/extend/language_bindings.md b/tensorflow/docs_src/extend/language_bindings.md
index 9a968d365b..4727eabdc1 100644
--- a/tensorflow/docs_src/extend/language_bindings.md
+++ b/tensorflow/docs_src/extend/language_bindings.md
@@ -125,7 +125,7 @@ The `OpDef` specifies the following:
instead of CamelCase for the op's function name.
- A list of inputs and outputs. The types for these may be polymorphic by
referencing attributes, as described in the inputs and outputs section of
- @{$adding_an_op$Adding an op}.
+ [Adding an op](../extend/adding_an_op.md).
- A list of attributes, along with their default values (if any). Note that
some of these will be inferred (if they are determined by an input), some
will be optional (if they have a default), and some will be required (no
diff --git a/tensorflow/docs_src/extend/new_data_formats.md b/tensorflow/docs_src/extend/new_data_formats.md
index 47a8344b70..7ca50c9c76 100644
--- a/tensorflow/docs_src/extend/new_data_formats.md
+++ b/tensorflow/docs_src/extend/new_data_formats.md
@@ -4,7 +4,7 @@ PREREQUISITES:
* Some familiarity with C++.
* Must have
- @{$install_sources$downloaded TensorFlow source}, and be
+ [downloaded TensorFlow source](../install/install_sources.md), and be
able to build it.
We divide the task of supporting a file format into two pieces:
@@ -67,7 +67,7 @@ need to:
You can put all the C++ code in a single file, such as
`my_reader_dataset_op.cc`. It will help if you are
-familiar with @{$adding_an_op$the adding an op how-to}. The following skeleton
+familiar with [the adding an op how-to](../extend/adding_an_op.md). The following skeleton
can be used as a starting point for your implementation:
```c++
@@ -227,8 +227,8 @@ REGISTER_KERNEL_BUILDER(Name("MyReaderDataset").Device(tensorflow::DEVICE_CPU),
```
The last step is to build the C++ code and add a Python wrapper. The easiest way
-to do this is by @{$adding_an_op#build_the_op_library$compiling a dynamic
-library} (e.g. called `"my_reader_dataset_op.so"`), and adding a Python class
+to do this is by [compiling a dynamic
+library](../extend/adding_an_op.md#build_the_op_library) (e.g. called `"my_reader_dataset_op.so"`), and adding a Python class
that subclasses `tf.data.Dataset` to wrap it. An example Python program is
given here:
@@ -285,7 +285,7 @@ You can see some examples of `Dataset` wrapper classes in
## Writing an Op for a record format
Generally this is an ordinary op that takes a scalar string record as input, and
-so follow @{$adding_an_op$the instructions to add an Op}.
+so follow [the instructions to add an Op](../extend/adding_an_op.md).
You may optionally take a scalar string key as input, and include that in error
messages reporting improperly formatted data. That way users can more easily
track down where the bad data came from.
diff --git a/tensorflow/docs_src/guide/checkpoints.md b/tensorflow/docs_src/guide/checkpoints.md
index e1add29852..3c92cbbd40 100644
--- a/tensorflow/docs_src/guide/checkpoints.md
+++ b/tensorflow/docs_src/guide/checkpoints.md
@@ -9,13 +9,13 @@ Estimators. TensorFlow provides two model formats:
the model.
This document focuses on checkpoints. For details on `SavedModel`, see the
-@{$saved_model$Saving and Restoring} guide.
+[Saving and Restoring](../guide/saved_model.md) guide.
## Sample code
This document relies on the same
-[Iris classification example](https://github.com/tensorflow/models/blob/master/samples/core/get_started/premade_estimator.py) detailed in @{$premade_estimators$Getting Started with TensorFlow}.
+[Iris classification example](https://github.com/tensorflow/models/blob/master/samples/core/get_started/premade_estimator.py) detailed in [Getting Started with TensorFlow](../guide/premade_estimators.md).
To download and access the example, invoke the following two commands:
```shell
@@ -160,7 +160,7 @@ checkpoint to the `model_dir`. Each subsequent call to the Estimator's
1. The Estimator builds the model's
[graph](https://developers.google.com/machine-learning/glossary/#graph)
by running the `model_fn()`. (For details on the `model_fn()`, see
- @{$custom_estimators$Creating Custom Estimators.})
+ [Creating Custom Estimators.](../guide/custom_estimators.md))
2. The Estimator initializes the weights of the new model from the data
stored in the most recent checkpoint.
@@ -231,7 +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} guide for details about:
+See the [Saving and Restoring](../guide/saved_model.md) 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/guide/custom_estimators.md b/tensorflow/docs_src/guide/custom_estimators.md
index 199a0e93de..913a35920f 100644
--- a/tensorflow/docs_src/guide/custom_estimators.md
+++ b/tensorflow/docs_src/guide/custom_estimators.md
@@ -5,7 +5,7 @@ This document introduces custom Estimators. In particular, this document
demonstrates how to create a custom `tf.estimator.Estimator` that
mimics the behavior of the pre-made Estimator
`tf.estimator.DNNClassifier` in solving the Iris problem. See
-the @{$premade_estimators$Pre-Made Estimators chapter} for details
+the [Pre-Made Estimators chapter](../guide/premade_estimators.md) for details
on the Iris problem.
To download and access the example code invoke the following two commands:
@@ -84,7 +84,7 @@ and a logits output layer.
## Write an Input function
Our custom Estimator implementation uses the same input function as our
-@{$premade_estimators$pre-made Estimator implementation}, from
+[pre-made Estimator implementation](../guide/premade_estimators.md), from
[`iris_data.py`](https://github.com/tensorflow/models/blob/master/samples/core/get_started/iris_data.py).
Namely:
@@ -106,8 +106,8 @@ This input function builds an input pipeline that yields batches of
## Create feature columns
-As detailed in the @{$premade_estimators$Premade Estimators} and
-@{$feature_columns$Feature Columns} chapters, you must define
+As detailed in the [Premade Estimators](../guide/premade_estimators.md) and
+[Feature Columns](../guide/feature_columns.md) chapters, you must define
your model's feature columns to specify how the model should use each feature.
Whether working with pre-made Estimators or custom Estimators, you define
feature columns in the same fashion.
@@ -145,7 +145,7 @@ to the constructor are in turn passed on to the `model_fn`. In
[`custom_estimator.py`](https://github.com/tensorflow/models/blob/master/samples/core/get_started/custom_estimator.py)
the following lines create the estimator and set the params to configure the
model. This configuration step is similar to how we configured the `tf.estimator.DNNClassifier` in
-@{$premade_estimators}.
+[Premade Estimators](../guide/premade_estimators.md).
```python
classifier = tf.estimator.Estimator(
@@ -489,7 +489,7 @@ configure your Estimator without modifying the code in the `model_fn`.
The rest of the code to train, evaluate, and generate predictions using our
Estimator is the same as in the
-@{$premade_estimators$Premade Estimators} chapter. For
+[Premade Estimators](../guide/premade_estimators.md) chapter. For
example, the following line will train the model:
```python
@@ -597,6 +597,6 @@ For more details, be sure to check out:
which contains more curated examples using custom estimators.
* This [TensorBoard video](https://youtu.be/eBbEDRsCmv4), which introduces
TensorBoard.
-* The @{$low_level_intro$Low Level Introduction}, which demonstrates
+* The [Low Level Introduction](../guide/low_level_intro.md), which demonstrates
how to experiment directly with TensorFlow's low level APIs, making debugging
easier.
diff --git a/tensorflow/docs_src/guide/datasets.md b/tensorflow/docs_src/guide/datasets.md
index bb18e8b79c..60de181b21 100644
--- a/tensorflow/docs_src/guide/datasets.md
+++ b/tensorflow/docs_src/guide/datasets.md
@@ -335,7 +335,7 @@ restore the current state of the iterator (and, effectively, the whole input
pipeline). A saveable object thus created can be added to `tf.train.Saver`
variables list or the `tf.GraphKeys.SAVEABLE_OBJECTS` collection for saving and
restoring in the same manner as a `tf.Variable`. Refer to
-@{$saved_model$Saving and Restoring} for details on how to save and restore
+[Saving and Restoring](../guide/saved_model.md) for details on how to save and restore
variables.
```python
@@ -782,8 +782,9 @@ with tf.train.MonitoredTrainingSession(...) as sess:
sess.run(training_op)
```
-To use a `Dataset` in the `input_fn` of a `tf.estimator.Estimator`, we also
-recommend using `Dataset.make_one_shot_iterator()`. For example:
+To use a `Dataset` in the `input_fn` of a `tf.estimator.Estimator`, simply
+return the `Dataset` and the framework will take care of creating an iterator
+and initializing it for you. For example:
```python
def dataset_input_fn():
@@ -814,10 +815,9 @@ def dataset_input_fn():
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.batch(32)
dataset = dataset.repeat(num_epochs)
- iterator = dataset.make_one_shot_iterator()
- # `features` is a dictionary in which each value is a batch of values for
- # that feature; `labels` is a batch of labels.
- features, labels = iterator.get_next()
- return features, labels
+ # Each element of `dataset` is tuple containing a dictionary of features
+ # (in which each value is a batch of values for that feature), and a batch of
+ # labels.
+ return dataset
```
diff --git a/tensorflow/docs_src/guide/datasets_for_estimators.md b/tensorflow/docs_src/guide/datasets_for_estimators.md
index 969ea579f7..09a3830ca9 100644
--- a/tensorflow/docs_src/guide/datasets_for_estimators.md
+++ b/tensorflow/docs_src/guide/datasets_for_estimators.md
@@ -14,7 +14,7 @@ introduces the API by walking through two simple examples:
Taking slices from an array is the simplest way to get started with `tf.data`.
-The @{$premade_estimators$Premade Estimators} chapter describes
+The [Premade Estimators](../guide/premade_estimators.md) chapter describes
the following `train_input_fn`, from
[`iris_data.py`](https://github.com/tensorflow/models/blob/master/samples/core/get_started/iris_data.py),
to pipe the data into the Estimator:
@@ -91,8 +91,8 @@ print(mnist_ds)
```
This will print the following line, showing the
-@{$guide/tensors#shapes$shapes} and
-@{$guide/tensors#data_types$types} of the items in
+[shapes](../guide/tensors.md#shapes) and
+[types](../guide/tensors.md#data_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 @{$guide/tensors#rank$scalars}, all of type
+dictionaries of [scalars](../guide/tensors.md#rank), all of type
`tf.float64`.
The first line of the iris `train_input_fn` uses the same functionality, but
@@ -377,11 +377,11 @@ Now you have the basic idea of how to efficiently load data into an
Estimator. Consider the following documents next:
-* @{$custom_estimators}, which demonstrates how to build your own
+* [Creating Custom Estimators](../guide/custom_estimators.md), which demonstrates how to build your own
custom `Estimator` model.
-* The @{$low_level_intro#datasets$Low Level Introduction}, which demonstrates
+* The [Low Level Introduction](../guide/low_level_intro.md#datasets), which demonstrates
how to experiment directly with `tf.data.Datasets` using TensorFlow's low
level APIs.
-* @{$guide/datasets} which goes into great detail about additional
+* [Importing Data](../guide/datasets.md) which goes into great detail about additional
functionality of `Datasets`.
diff --git a/tensorflow/docs_src/guide/debugger.md b/tensorflow/docs_src/guide/debugger.md
index 0b4a063c10..5af27471a2 100644
--- a/tensorflow/docs_src/guide/debugger.md
+++ b/tensorflow/docs_src/guide/debugger.md
@@ -95,7 +95,7 @@ intermediate tensors (tensors that are neither inputs or outputs of the
`Session.run()` call, but are in the path leading from the inputs to the
outputs). This filter is for `nan`s and `inf`s is a common enough use case that
we ship it with the
-@{$python/tfdbg#Classes_for_debug_dump_data_and_directories$`debug_data`}
+[`debug_data`](../api_guides/python/tfdbg.md#Classes_for_debug_dump_data_and_directories)
module.
Note: You can also write your own custom filters. See `tfdbg.DebugDumpDir.find`
@@ -627,7 +627,7 @@ hooks = [tf_debug.DumpingDebugHook("/shared/storage/location/tfdbg_dumps_1")]
Then this `hook` can be used in the same way as the `LocalCLIDebugHook` examples
described earlier in this document.
-As the training, evalution or prediction happens with `Estimator`,
+As the training, evaluation or prediction happens with `Estimator`,
tfdbg creates directories having the following name pattern:
`/shared/storage/location/tfdbg_dumps_1/run_<epoch_timestamp_microsec>_<uuid>`.
Each directory corresponds to a `Session.run()` call that underlies
@@ -768,7 +768,7 @@ sess.run(b)
**A**: The reason why you see no data dumped is because every node in the
executed TensorFlow graph is constant-folded by the TensorFlow runtime.
- In this exapmle, `a` is a constant tensor; therefore, the fetched
+ In this example, `a` is a constant tensor; therefore, the fetched
tensor `b` is effectively also a constant tensor. TensorFlow's graph
optimization folds the graph that contains `a` and `b` into a single
node to speed up future runs of the graph, which is why `tfdbg` does
diff --git a/tensorflow/docs_src/guide/eager.md b/tensorflow/docs_src/guide/eager.md
index 24f6e4ee95..3b5797a638 100644
--- a/tensorflow/docs_src/guide/eager.md
+++ b/tensorflow/docs_src/guide/eager.md
@@ -558,7 +558,7 @@ m.result() # => 5.5
#### Summaries and TensorBoard
-@{$summaries_and_tensorboard$TensorBoard} is a visualization tool for
+[TensorBoard](../guide/summaries_and_tensorboard.md) is a visualization tool for
understanding, debugging and optimizing the model training process. It uses
summary events that are written while executing the program.
@@ -568,9 +568,8 @@ inserted during model construction. For example, to record summaries once every
100 global steps:
```py
+global_step = tf.train.get_or_create_global_step()
writer = tf.contrib.summary.create_file_writer(logdir)
-global_step=tf.train.get_or_create_global_step() # return global step var
-
writer.set_as_default()
for _ in range(iterations):
diff --git a/tensorflow/docs_src/guide/embedding.md b/tensorflow/docs_src/guide/embedding.md
index 8a98367dfb..6007e6847b 100644
--- a/tensorflow/docs_src/guide/embedding.md
+++ b/tensorflow/docs_src/guide/embedding.md
@@ -78,7 +78,7 @@ Embeddings can be trained in many network types, and with various loss
functions and data sets. For example, one could use a recurrent neural network
to predict the next word from the previous one given a large corpus of
sentences, or one could train two networks to do multi-lingual translation.
-These methods are described in the @{$word2vec$Vector Representations of Words}
+These methods are described in the [Vector Representations of Words](../tutorials/representation/word2vec.md)
tutorial.
## Visualizing Embeddings
diff --git a/tensorflow/docs_src/guide/estimators.md b/tensorflow/docs_src/guide/estimators.md
index 7b54e3de29..3903bfd126 100644
--- a/tensorflow/docs_src/guide/estimators.md
+++ b/tensorflow/docs_src/guide/estimators.md
@@ -84,7 +84,7 @@ of the following four steps:
... # manipulate dataset, extracting the feature dict and the label
return feature_dict, label
- (See @{$guide/datasets} for full details.)
+ (See [Importing Data](../guide/datasets.md) for full details.)
2. **Define the feature columns.** Each `tf.feature_column`
identifies a feature name, its type, and any input pre-processing.
@@ -136,7 +136,7 @@ The heart of every Estimator--whether pre-made or custom--is its
evaluation, and prediction. When you are using a pre-made Estimator,
someone else has already implemented the model function. When relying
on a custom Estimator, you must write the model function yourself. A
-@{$custom_estimators$companion document}
+[companion document](../guide/custom_estimators.md)
explains how to write the model function.
diff --git a/tensorflow/docs_src/guide/faq.md b/tensorflow/docs_src/guide/faq.md
index 8370097560..a02635ebba 100644
--- a/tensorflow/docs_src/guide/faq.md
+++ b/tensorflow/docs_src/guide/faq.md
@@ -2,7 +2,7 @@
This document provides answers to some of the frequently asked questions about
TensorFlow. If you have a question that is not covered here, you might find an
-answer on one of the TensorFlow @{$about$community resources}.
+answer on one of the TensorFlow [community resources](../about/index.md).
[TOC]
@@ -11,7 +11,7 @@ answer on one of the TensorFlow @{$about$community resources}.
#### Can I run distributed training on multiple computers?
Yes! TensorFlow gained
-@{$distributed$support for distributed computation} in
+[support for distributed computation](../deploy/distributed.md) in
version 0.8. TensorFlow now supports multiple devices (CPUs and GPUs) in one or
more computers.
@@ -23,7 +23,7 @@ As of the 0.6.0 release timeframe (Early December 2015), we do support Python
## Building a TensorFlow graph
See also the
-@{$python/framework$API documentation on building graphs}.
+[API documentation on building graphs](../api_guides/python/framework.md).
#### Why does `c = tf.matmul(a, b)` not execute the matrix multiplication immediately?
@@ -48,16 +48,16 @@ device, and `"/device:GPU:i"` (or `"/gpu:i"`) for the *i*th GPU device.
To place a group of operations on a device, create them within a
`tf.device` context. See
the how-to documentation on
-@{$using_gpu$using GPUs with TensorFlow} for details of how
+[using GPUs with TensorFlow](../guide/using_gpu.md) for details of how
TensorFlow assigns operations to devices, and the
-@{$deep_cnn$CIFAR-10 tutorial} for an example model that
+[CIFAR-10 tutorial](../tutorials/images/deep_cnn.md) for an example model that
uses multiple GPUs.
## Running a TensorFlow computation
See also the
-@{$python/client$API documentation on running graphs}.
+[API documentation on running graphs](../api_guides/python/client.md).
#### What's the deal with feeding and placeholders?
@@ -106,7 +106,7 @@ a significant amount of memory, and can be released when the session is closed b
`tf.Session.close`.
The intermediate tensors that are created as part of a call to
-@{$python/client$`Session.run()`} will be freed at or before the
+[`Session.run()`](../api_guides/python/client.md) will be freed at or before the
end of the call.
#### Does the runtime parallelize parts of graph execution?
@@ -118,7 +118,7 @@ dimensions:
CPU, or multiple threads in a GPU.
* Independent nodes in a TensorFlow graph can run in parallel on multiple
devices, which makes it possible to speed up
- @{$deep_cnn$CIFAR-10 training using multiple GPUs}.
+ [CIFAR-10 training using multiple GPUs](../tutorials/images/deep_cnn.md).
* The Session API allows multiple concurrent steps (i.e. calls to
`tf.Session.run` in parallel). This
enables the runtime to get higher throughput, if a single step does not use
@@ -141,9 +141,9 @@ Bindings for various other languages (such as [C#](https://github.com/migueldeic
#### Does TensorFlow make use of all the devices (GPUs and CPUs) available on my machine?
TensorFlow supports multiple GPUs and CPUs. See the how-to documentation on
-@{$using_gpu$using GPUs with TensorFlow} for details of how
+[using GPUs with TensorFlow](../guide/using_gpu.md) for details of how
TensorFlow assigns operations to devices, and the
-@{$deep_cnn$CIFAR-10 tutorial} for an example model that
+[CIFAR-10 tutorial](../tutorials/images/deep_cnn.md) for an example model that
uses multiple GPUs.
Note that TensorFlow only uses GPU devices with a compute capability greater
@@ -155,16 +155,16 @@ The `tf.ReaderBase` and
`tf.QueueBase` classes provide special operations that
can *block* until input (or free space in a bounded queue) becomes
available. These operations allow you to build sophisticated
-@{$reading_data$input pipelines}, at the cost of making the
+[input pipelines](../api_guides/python/reading_data.md), at the cost of making the
TensorFlow computation somewhat more complicated. See the how-to documentation
for
-@{$reading_data#creating_threads_to_prefetch_using_queuerunner_objects$using `QueueRunner` objects to drive queues and readers}
+[using `QueueRunner` objects to drive queues and readers](../api_guides/python/reading_data.md#creating_threads_to_prefetch_using_queuerunner_objects)
for more information on how to use them.
## Variables
-See also the how-to documentation on @{$variables$variables} and
-@{$python/state_ops$the API documentation for variables}.
+See also the how-to documentation on [variables](../guide/variables.md) and
+[the API documentation for variables](../api_guides/python/state_ops.md).
#### What is the lifetime of a variable?
@@ -231,7 +231,7 @@ to encode the batch size as a Python constant, but instead to use a symbolic
#### How can I visualize a TensorFlow graph?
-See the @{$graph_viz$graph visualization tutorial}.
+See the [graph visualization tutorial](../guide/graph_viz.md).
#### What is the simplest way to send data to TensorBoard?
@@ -241,7 +241,7 @@ these summaries to a log directory. Then, start TensorBoard using
python tensorflow/tensorboard/tensorboard.py --logdir=path/to/log-directory
For more details, see the
-@{$summaries_and_tensorboard$Summaries and TensorBoard tutorial}.
+[Summaries and TensorBoard tutorial](../guide/summaries_and_tensorboard.md).
#### Every time I launch TensorBoard, I get a network security popup!
@@ -251,7 +251,7 @@ the flag --host=localhost. This should quiet any security warnings.
## Extending TensorFlow
See the how-to documentation for
-@{$adding_an_op$adding a new operation to TensorFlow}.
+[adding a new operation to TensorFlow](../extend/adding_an_op.md).
#### My data is in a custom format. How do I read it using TensorFlow?
@@ -273,8 +273,8 @@ consider converting it, offline, to a format that is easily parsable, such
as `tf.python_io.TFRecordWriter` format.
The most efficient method to customize the parsing behavior is to
-@{$adding_an_op$add a new op written in C++} that parses your
-data format. The @{$new_data_formats$guide to handling new data formats} has
+[add a new op written in C++](../extend/adding_an_op.md) that parses your
+data format. The [guide to handling new data formats](../extend/new_data_formats.md) has
more information about the steps for doing this.
diff --git a/tensorflow/docs_src/guide/feature_columns.md b/tensorflow/docs_src/guide/feature_columns.md
index 9cd695cc25..3ad41855e4 100644
--- a/tensorflow/docs_src/guide/feature_columns.md
+++ b/tensorflow/docs_src/guide/feature_columns.md
@@ -5,7 +5,7 @@ intermediaries between raw data and Estimators. Feature columns are very rich,
enabling you to transform a diverse range of raw data into formats that
Estimators can use, allowing easy experimentation.
-In @{$premade_estimators$Premade Estimators}, we used the premade
+In [Premade Estimators](../guide/premade_estimators.md), we used the premade
Estimator, `tf.estimator.DNNClassifier` to train a model to
predict different types of Iris flowers from four input features. That example
created only numerical feature columns (of type
@@ -289,7 +289,7 @@ pseudocode:
```python
# pseudocode
-feature_id = hash(raw_feature) % hash_buckets_size
+feature_id = hash(raw_feature) % hash_bucket_size
```
The code to create the `feature_column` might look something like this:
@@ -298,7 +298,7 @@ The code to create the `feature_column` might look something like this:
hashed_feature_column =
tf.feature_column.categorical_column_with_hash_bucket(
key = "some_feature",
- hash_buckets_size = 100) # The number of categories
+ hash_bucket_size = 100) # The number of categories
```
At this point, you might rightfully think: "This is crazy!" After all, we are
forcing the different input values to a smaller set of categories. This means
@@ -534,7 +534,7 @@ embedding_column = tf.feature_column.embedding_column(
dimension=embedding_dimensions)
```
-@{$guide/embedding$Embeddings} is a significant topic within machine
+[Embeddings](../guide/embedding.md) is a significant topic within machine
learning. This information was just to get you started using them as feature
columns.
@@ -559,7 +559,7 @@ As the following list indicates, not all Estimators permit all types of
For more examples on feature columns, view the following:
-* The @{$low_level_intro#feature_columns$Low Level Introduction} demonstrates how
+* The [Low Level Introduction](../guide/low_level_intro.md#feature_columns) demonstrates how
experiment directly with `feature_columns` using TensorFlow's low level APIs.
* The [Estimator wide and deep learning tutorial](https://github.com/tensorflow/models/tree/master/official/wide_deep)
solves a binary classification problem using `feature_columns` on a variety of
diff --git a/tensorflow/docs_src/guide/graph_viz.md b/tensorflow/docs_src/guide/graph_viz.md
index 97b0e2d4de..23f722bbe7 100644
--- a/tensorflow/docs_src/guide/graph_viz.md
+++ b/tensorflow/docs_src/guide/graph_viz.md
@@ -5,7 +5,7 @@ TensorFlow computation graphs are powerful but complicated. The graph visualizat
![Visualization of a TensorFlow graph](https://www.tensorflow.org/images/graph_vis_animation.gif "Visualization of a TensorFlow graph")
*Visualization of a TensorFlow graph.*
-To see your own graph, run TensorBoard pointing it to the log directory of the job, click on the graph tab on the top pane and select the appropriate run using the menu at the upper left corner. For in depth information on how to run TensorBoard and make sure you are logging all the necessary information, see @{$summaries_and_tensorboard$TensorBoard: Visualizing Learning}.
+To see your own graph, run TensorBoard pointing it to the log directory of the job, click on the graph tab on the top pane and select the appropriate run using the menu at the upper left corner. For in depth information on how to run TensorBoard and make sure you are logging all the necessary information, see [TensorBoard: Visualizing Learning](../guide/summaries_and_tensorboard.md).
## Name scoping and nodes
@@ -251,7 +251,7 @@ is a snippet from the train and test section of a modification of the
[Estimators MNIST tutorial](../tutorials/estimators/cnn.md), in which we have
recorded summaries and
runtime statistics. See the
-@{$summaries_and_tensorboard#serializing-the-data$Summaries Tutorial}
+[Summaries Tutorial](../guide/summaries_and_tensorboard.md#serializing-the-data)
for details on how to record summaries.
Full source is [here](https://www.tensorflow.org/code/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py).
diff --git a/tensorflow/docs_src/guide/graphs.md b/tensorflow/docs_src/guide/graphs.md
index 2bb44fbb32..c70479dba2 100644
--- a/tensorflow/docs_src/guide/graphs.md
+++ b/tensorflow/docs_src/guide/graphs.md
@@ -38,13 +38,13 @@ programs:
machines. TensorFlow inserts the necessary communication and coordination
between devices.
-* **Compilation.** TensorFlow's @{$performance/xla$XLA compiler} can
+* **Compilation.** TensorFlow's [XLA compiler](../performance/xla/index.md) can
use the information in your dataflow graph to generate faster code, for
example, by fusing together adjacent operations.
* **Portability.** The dataflow graph is a language-independent representation
of the code in your model. You can build a dataflow graph in Python, store it
- in a @{$saved_model$SavedModel}, and restore it in a C++ program for
+ in a [SavedModel](../guide/saved_model.md), and restore it in a C++ program for
low-latency inference.
@@ -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` and `tf.Variable.assign_add` that
create `tf.Operation` objects that, when executed, update the stored value.
- (See @{$guide/variables} for more information about variables.)
+ (See [Variables](../guide/variables.md) 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,
@@ -210,7 +210,7 @@ with tf.device("/device:GPU:0"):
# Operations created in this context will be pinned to the GPU.
result = tf.matmul(weights, img)
```
-If you are deploying TensorFlow in a @{$distributed$typical distributed configuration},
+If you are deploying TensorFlow in a [typical distributed configuration](../deploy/distributed.md),
you might specify the job name and task ID to place variables on
a task in the parameter server job (`"/job:ps"`), and the other operations on
task in the worker job (`"/job:worker"`):
diff --git a/tensorflow/docs_src/guide/index.md b/tensorflow/docs_src/guide/index.md
index 1c920e7d70..50499582cc 100644
--- a/tensorflow/docs_src/guide/index.md
+++ b/tensorflow/docs_src/guide/index.md
@@ -5,38 +5,38 @@ works. The units are as follows:
## High Level APIs
- * @{$guide/keras}, TensorFlow's high-level API for building and
+ * [Keras](../guide/keras.md), TensorFlow's high-level API for building and
training deep learning models.
- * @{$guide/eager}, an API for writing TensorFlow code
+ * [Eager Execution](../guide/eager.md), an API for writing TensorFlow code
imperatively, like you would use Numpy.
- * @{$guide/datasets}, easy input pipelines to bring your data into
+ * [Importing Data](../guide/datasets.md), easy input pipelines to bring your data into
your TensorFlow program.
- * @{$guide/estimators}, a high-level API that provides
+ * [Estimators](../guide/estimators.md), a high-level API that provides
fully-packaged models ready for large-scale training and production.
## Estimators
-* @{$premade_estimators}, the basics of premade Estimators.
-* @{$checkpoints}, save training progress and resume where you left off.
-* @{$feature_columns}, handle a variety of input data types without changes to the model.
-* @{$datasets_for_estimators}, use `tf.data` to input data.
-* @{$custom_estimators}, write your own Estimator.
+* [Premade Estimators](../guide/premade_estimators.md), the basics of premade Estimators.
+* [Checkpoints](../guide/checkpoints.md), save training progress and resume where you left off.
+* [Feature Columns](../guide/feature_columns.md), handle a variety of input data types without changes to the model.
+* [Datasets for Estimators](../guide/datasets_for_estimators.md), use `tf.data` to input data.
+* [Creating Custom Estimators](../guide/custom_estimators.md), write your own Estimator.
## Accelerators
- * @{$using_gpu} explains how TensorFlow assigns operations to
+ * [Using GPUs](../guide/using_gpu.md) explains how TensorFlow assigns operations to
devices and how you can change the arrangement manually.
- * @{$using_tpu} explains how to modify `Estimator` programs to run on a TPU.
+ * [Using TPUs](../guide/using_tpu.md) explains how to modify `Estimator` programs to run on a TPU.
## Low Level APIs
- * @{$guide/low_level_intro}, which introduces the
+ * [Introduction](../guide/low_level_intro.md), which introduces the
basics of how you can use TensorFlow outside of the high Level APIs.
- * @{$guide/tensors}, which explains how to create,
+ * [Tensors](../guide/tensors.md), which explains how to create,
manipulate, and access Tensors--the fundamental object in TensorFlow.
- * @{$guide/variables}, which details how
+ * [Variables](../guide/variables.md), which details how
to represent shared, persistent state in your program.
- * @{$guide/graphs}, which explains:
+ * [Graphs and Sessions](../guide/graphs.md), 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
@@ -46,19 +46,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.
- * @{$guide/saved_model}, which
+ * [Save and Restore](../guide/saved_model.md), which
explains how to save and restore variables and models.
## ML Concepts
- * @{$guide/embedding}, which introduces the concept
+ * [Embeddings](../guide/embedding.md), 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
- * @{$guide/debugger}, which
+ * [TensorFlow Debugger](../guide/debugger.md), which
explains how to use the TensorFlow debugger (tfdbg).
## TensorBoard
@@ -66,17 +66,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:
- * @{$guide/summaries_and_tensorboard},
+ * [TensorBoard: Visualizing Learning](../guide/summaries_and_tensorboard.md),
which introduces TensorBoard.
- * @{$guide/graph_viz}, which
+ * [TensorBoard: Graph Visualization](../guide/graph_viz.md), which
explains how to visualize the computational graph.
- * @{$guide/tensorboard_histograms} which demonstrates the how to
+ * [TensorBoard Histogram Dashboard](../guide/tensorboard_histograms.md) which demonstrates the how to
use TensorBoard's histogram dashboard.
## Misc
- * @{$guide/version_compat},
+ * [TensorFlow Version Compatibility](../guide/version_compat.md),
which explains backward compatibility guarantees and non-guarantees.
- * @{$guide/faq}, which contains frequently asked
+ * [Frequently Asked Questions](../guide/faq.md), which contains frequently asked
questions about TensorFlow.
diff --git a/tensorflow/docs_src/guide/low_level_intro.md b/tensorflow/docs_src/guide/low_level_intro.md
index dc6cb9ee0d..d002f8af0b 100644
--- a/tensorflow/docs_src/guide/low_level_intro.md
+++ b/tensorflow/docs_src/guide/low_level_intro.md
@@ -9,7 +9,7 @@ This guide gets you started programming in the low-level TensorFlow APIs
* Use high level components ([datasets](#datasets), [layers](#layers), and
[feature_columns](#feature_columns)) in this low level environment.
* Build your own training loop, instead of using the one
- @{$premade_estimators$provided by Estimators}.
+ [provided by Estimators](../guide/premade_estimators.md).
We recommend using the higher level APIs to build models when possible.
Knowing TensorFlow Core is valuable for the following reasons:
@@ -21,7 +21,7 @@ Knowing TensorFlow Core is valuable for the following reasons:
## Setup
-Before using this guide, @{$install$install TensorFlow}.
+Before using this guide, [install TensorFlow](../install/index.md).
To get the most out of this guide, you should know the following:
@@ -145,7 +145,7 @@ browser, and you should see a graph similar to the following:
![TensorBoard screenshot](https://www.tensorflow.org/images/getting_started_add.png)
-For more about TensorBoard's graph visualization tools see @{$graph_viz}.
+For more about TensorBoard's graph visualization tools see [TensorBoard: Graph Visualization](../guide/graph_viz.md).
### Session
@@ -303,7 +303,7 @@ while True:
break
```
-For more details on Datasets and Iterators see: @{$guide/datasets}.
+For more details on Datasets and Iterators see: [Importing Data](../guide/datasets.md).
## Layers
@@ -398,7 +398,7 @@ and layer reuse impossible.
The easiest way to experiment with feature columns is using the
`tf.feature_column.input_layer` function. This function only accepts
-@{$feature_columns$dense columns} as inputs, so to view the result
+[dense columns](../guide/feature_columns.md) as inputs, so to view the result
of a categorical column you must wrap it in an
`tf.feature_column.indicator_column`. For example:
@@ -589,7 +589,7 @@ print(sess.run(y_pred))
To learn more about building models with TensorFlow consider the following:
-* @{$custom_estimators$Custom Estimators}, to learn how to build
+* [Custom Estimators](../guide/custom_estimators.md), to learn how to build
customized models with TensorFlow. Your knowledge of TensorFlow Core will
help you understand and debug your own models.
@@ -597,8 +597,8 @@ If you want to learn more about the inner workings of TensorFlow consider the
following documents, which go into more depth on many of the topics discussed
here:
-* @{$graphs}
-* @{$tensors}
-* @{$variables}
+* [Graphs and Sessions](../guide/graphs.md)
+* [Tensors](../guide/tensors.md)
+* [Variables](../guide/variables.md)
diff --git a/tensorflow/docs_src/guide/premade_estimators.md b/tensorflow/docs_src/guide/premade_estimators.md
index dc38f0c1d3..a1703058c3 100644
--- a/tensorflow/docs_src/guide/premade_estimators.md
+++ b/tensorflow/docs_src/guide/premade_estimators.md
@@ -8,7 +8,7 @@ how to solve the Iris classification problem in TensorFlow.
Prior to using the sample code in this document, you'll need to do the
following:
-* @{$install$Install TensorFlow}.
+* [Install TensorFlow](../install/index.md).
* If you installed TensorFlow with virtualenv or Anaconda, activate your
TensorFlow environment.
* Install or upgrade pandas by issuing the following command:
@@ -78,10 +78,10 @@ provides a programming stack consisting of multiple API layers:
We strongly recommend writing TensorFlow programs with the following APIs:
-* @{$guide/estimators$Estimators}, which represent a complete model.
+* [Estimators](../guide/estimators.md), which represent a complete model.
The Estimator API provides methods to train the model, to judge the model's
accuracy, and to generate predictions.
-* @{$guide/datasets_for_estimators}, which build a data input
+* [Datasets for Estimators](../guide/datasets_for_estimators.md), 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,14 +173,14 @@ 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
-@{$guide/estimators}.
+[Estimators](../guide/estimators.md).
An Estimator is any class derived from `tf.estimator.Estimator`. TensorFlow
provides a collection of
`tf.estimator`
(for example, `LinearRegressor`) to implement common ML algorithms. Beyond
those, you may write your own
-@{$custom_estimators$custom Estimators}.
+[custom Estimators](../guide/custom_estimators.md).
We recommend using pre-made Estimators when just getting started.
To write a TensorFlow program based on pre-made Estimators, you must perform the
@@ -287,7 +287,7 @@ for key in train_x.keys():
```
Feature columns can be far more sophisticated than those we're showing here. We
-detail feature columns @{$feature_columns$later on} in our Getting
+detail feature columns [later on](../guide/feature_columns.md) in our Getting
Started guide.
Now that we have the description of how we want the model to represent the raw
@@ -423,8 +423,8 @@ Pre-made Estimators are an effective way to quickly create standard models.
Now that you've gotten started writing TensorFlow programs, consider the
following material:
-* @{$checkpoints$Checkpoints} to learn how to save and restore models.
-* @{$guide/datasets_for_estimators} to learn more about importing
+* [Checkpoints](../guide/checkpoints.md) to learn how to save and restore models.
+* [Datasets for Estimators](../guide/datasets_for_estimators.md) to learn more about importing
data into your model.
-* @{$custom_estimators$Creating Custom Estimators} to learn how to
+* [Creating Custom Estimators](../guide/custom_estimators.md) to learn how to
write your own Estimator, customized for a particular problem.
diff --git a/tensorflow/docs_src/guide/saved_model.md b/tensorflow/docs_src/guide/saved_model.md
index c260da7966..6c967fd882 100644
--- a/tensorflow/docs_src/guide/saved_model.md
+++ b/tensorflow/docs_src/guide/saved_model.md
@@ -7,7 +7,7 @@ automatically save and restore variables in the `model_dir`.
## Save and restore variables
-TensorFlow @{$variables} are the best way to represent shared, persistent state
+TensorFlow [Variables](../guide/variables.md) are the best way to represent shared, persistent state
manipulated by your program. The `tf.train.Saver` constructor adds `save` and
`restore` ops to the graph for all, or a specified list, of the variables in the
graph. The `Saver` object provides methods to run these ops, specifying paths
@@ -274,7 +274,7 @@ Ops has not changed.
The `tf.saved_model.builder.SavedModelBuilder` class allows
users to control whether default-valued attributes must be stripped from the
-@{$extend/tool_developers#nodes$`NodeDefs`}
+[`NodeDefs`](../extend/tool_developers/index.md#nodes)
while adding a meta graph to the SavedModel bundle. Both
`tf.saved_model.builder.SavedModelBuilder.add_meta_graph_and_variables`
and `tf.saved_model.builder.SavedModelBuilder.add_meta_graph`
@@ -413,7 +413,7 @@ SavedModel format. This section explains how to:
### Prepare serving inputs
-During training, an @{$premade_estimators#input_fn$`input_fn()`} ingests data
+During training, an [`input_fn()`](../guide/premade_estimators.md#input_fn) ingests data
and prepares it for use by the model. At serving time, similarly, a
`serving_input_receiver_fn()` accepts inference requests and prepares them for
the model. This function has the following purposes:
@@ -616,7 +616,7 @@ result = stub.Classify(request, 10.0) # 10 secs timeout
The returned result in this example is a `ClassificationResponse` protocol
buffer.
-This is a skeletal example; please see the @{$deploy$Tensorflow Serving}
+This is a skeletal example; please see the [Tensorflow Serving](../deploy/index.md)
documentation and [examples](https://github.com/tensorflow/serving/tree/master/tensorflow_serving/example)
for more details.
@@ -647,7 +647,7 @@ You can use the SavedModel Command Line Interface (CLI) to inspect and
execute a SavedModel.
For example, you can use the CLI to inspect the model's `SignatureDef`s.
The CLI enables you to quickly confirm that the input
-@{$tensors$Tensor dtype and shape} match the model. Moreover, if you
+[Tensor dtype and shape](../guide/tensors.md) match the model. Moreover, if you
want to test your model, you can use the CLI to do a sanity check by
passing in sample inputs in various formats (for example, Python
expressions) and then fetching the output.
diff --git a/tensorflow/docs_src/guide/summaries_and_tensorboard.md b/tensorflow/docs_src/guide/summaries_and_tensorboard.md
index 6177c3393b..788c556b9d 100644
--- a/tensorflow/docs_src/guide/summaries_and_tensorboard.md
+++ b/tensorflow/docs_src/guide/summaries_and_tensorboard.md
@@ -36,7 +36,7 @@ lifecycle for summary data within TensorBoard.
First, create the TensorFlow graph that you'd like to collect summary
data from, and decide which nodes you would like to annotate with
-@{$python/summary$summary operations}.
+[summary operations](../api_guides/python/summary.md).
For example, suppose you are training a convolutional neural network for
recognizing MNIST digits. You'd like to record how the learning rate
@@ -53,7 +53,7 @@ this data by attaching
the gradient outputs and to the variable that holds your weights, respectively.
For details on all of the summary operations available, check out the docs on
-@{$python/summary$summary operations}.
+[summary operations](../api_guides/python/summary.md).
Operations in TensorFlow don't do anything until you run them, or an op that
depends on their output. And the summary nodes that we've just created are
@@ -74,7 +74,7 @@ Also, the `FileWriter` can optionally take a `Graph` in its constructor.
If it receives a `Graph` object, then TensorBoard will visualize your graph
along with tensor shape information. This will give you a much better sense of
what flows through the graph: see
-@{$graph_viz#tensor-shape-information$Tensor shape information}.
+[Tensor shape information](../guide/graph_viz.md#tensor-shape-information).
Now that you've modified your graph and have a `FileWriter`, you're ready to
start running your network! If you want, you could run the merged summary op
@@ -219,7 +219,7 @@ When looking at TensorBoard, you will see the navigation tabs in the top right
corner. Each tab represents a set of serialized data that can be visualized.
For in depth information on how to use the *graph* tab to visualize your graph,
-see @{$graph_viz$TensorBoard: Graph Visualization}.
+see [TensorBoard: Graph Visualization](../guide/graph_viz.md).
For more usage information on TensorBoard in general, see the
[TensorBoard GitHub](https://github.com/tensorflow/tensorboard).
diff --git a/tensorflow/docs_src/guide/tensors.md b/tensorflow/docs_src/guide/tensors.md
index 6b5a110a1c..4f0ddb21b5 100644
--- a/tensorflow/docs_src/guide/tensors.md
+++ b/tensorflow/docs_src/guide/tensors.md
@@ -298,7 +298,7 @@ to call `tf.train.start_queue_runners` before evaluating any `tf.Tensor`s.
## Printing Tensors
For debugging purposes you might want to print the value of a `tf.Tensor`. While
- @{$debugger$tfdbg} provides advanced debugging support, TensorFlow also has an
+ [tfdbg](../guide/debugger.md) provides advanced debugging support, TensorFlow also has an
operation to directly print the value of a `tf.Tensor`.
Note that you rarely want to use the following pattern when printing a
diff --git a/tensorflow/docs_src/guide/using_gpu.md b/tensorflow/docs_src/guide/using_gpu.md
index c0218fd12e..8cb9b354c7 100644
--- a/tensorflow/docs_src/guide/using_gpu.md
+++ b/tensorflow/docs_src/guide/using_gpu.md
@@ -211,5 +211,5 @@ AddN: /job:localhost/replica:0/task:0/cpu:0
[ 98. 128.]]
```
-The @{$deep_cnn$cifar10 tutorial} is a good example
+The [cifar10 tutorial](../tutorials/images/deep_cnn.md) is a good example
demonstrating how to do training with multiple GPUs.
diff --git a/tensorflow/docs_src/guide/using_tpu.md b/tensorflow/docs_src/guide/using_tpu.md
index 90a663b75e..59b34e19e0 100644
--- a/tensorflow/docs_src/guide/using_tpu.md
+++ b/tensorflow/docs_src/guide/using_tpu.md
@@ -22,8 +22,8 @@ Standard `Estimators` can drive models on CPU and GPUs. You must use
`tf.contrib.tpu.TPUEstimator` to drive a model on TPUs.
Refer to TensorFlow's Getting Started section for an introduction to the basics
-of using a @{$premade_estimators$pre-made `Estimator`}, and
-@{$custom_estimators$custom `Estimator`s}.
+of using a [pre-made `Estimator`](../guide/premade_estimators.md), and
+[custom `Estimator`s](../guide/custom_estimators.md).
The `TPUEstimator` class differs somewhat from the `Estimator` class.
@@ -171,9 +171,9 @@ 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 @{$guide/tensors#shape$Tensor Shapes} for more details.
+see [Tensor Shapes](../guide/tensors.md#shape) for more details.
-To run on Cloud TPUs TensorFlow models are compiled using @{$xla$XLA}.
+To run on Cloud TPUs TensorFlow models are compiled using [XLA](../performance/xla/index.md).
XLA uses a similar system for determining shapes at compile time. XLA requires
that all tensor dimensions be statically defined at compile time. All shapes
must evaluate to a constant, and not depend on external data, or stateful
@@ -184,7 +184,7 @@ operations like variables or a random number generator.
Remove any use of `tf.summary` from your model.
-@{$summaries_and_tensorboard$TensorBoard summaries} are a great way see inside
+[TensorBoard summaries](../guide/summaries_and_tensorboard.md) are a great way see inside
your model. A minimal set of basic summaries are automatically recorded by the
`TPUEstimator`, to `event` files in the `model_dir`. Custom summaries, however,
are currently unsupported when training on a Cloud TPU. So while the
@@ -343,7 +343,7 @@ weight when creating your `tf.metrics`.
Efficient use of the `tf.data.Dataset` API is critical when using a Cloud
TPU, as it is impossible to use the Cloud TPU's unless you can feed it data
-quickly enough. See @{$datasets_performance} for details on dataset performance.
+quickly enough. See [Input Pipeline Performance Guide](../performance/datasets_performance.md) for details on dataset performance.
For all but the simplest experimentation (using
`tf.data.Dataset.from_tensor_slices` or other in-graph data) you will need to
@@ -361,7 +361,7 @@ Small datasets can be loaded entirely into memory using
`tf.data.Dataset.cache`.
Regardless of the data format used, it is strongly recommended that you
-@{$performance_guide#use_large_files$use large files}, on the order of
+[use large files](../performance/performance_guide.md#use_large_files), on the order of
100MB. This is especially important in this networked setting as the overhead
of opening a file is significantly higher.
@@ -391,5 +391,5 @@ to make a Cloud TPU compatible model are the example models published in:
For more information about tuning TensorFlow code for performance see:
- * The @{$performance$Performance Section.}
+ * The [Performance Section.](../performance/index.md)
diff --git a/tensorflow/docs_src/guide/version_compat.md b/tensorflow/docs_src/guide/version_compat.md
index 0e472c3381..de93d225e3 100644
--- a/tensorflow/docs_src/guide/version_compat.md
+++ b/tensorflow/docs_src/guide/version_compat.md
@@ -38,6 +38,9 @@ patch versions. The public APIs consist of
`tensorflow` module and its submodules, except for
* functions and classes in `tf.contrib`
* functions and classes whose names start with `_` (as these are private)
+ * functions, arguments, properties and classes whose name starts with
+ `experimental`, or whose fully qualified name includes a module called
+ `experimental`
Note that the code in the `examples/` and `tools/` directories is not
reachable through the `tensorflow` Python module and is thus not covered by
the compatibility guarantee.
@@ -75,10 +78,11 @@ backward incompatible ways between minor releases. These include:
* **Other languages**: TensorFlow APIs in languages other than Python and C,
such as:
- - @{$cc/guide$C++} (exposed through header files in
+ - [C++](../api_guides/cc/guide.md) (exposed through header files in
[`tensorflow/cc`](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/cc)).
- [Java](../api_docs/java/reference/org/tensorflow/package-summary),
- [Go](https://godoc.org/github.com/tensorflow/tensorflow/tensorflow/go)
+ - [JavaScript](https://js.tensorflow.org)
* **Details of composite ops:** Many public functions in Python expand to
several primitive ops in the graph, and these details will be part of any
@@ -97,7 +101,7 @@ backward incompatible ways between minor releases. These include:
accuracy for the overall system.
* **Random numbers:** The specific random numbers computed by the
- @{$python/constant_op#Random_Tensors$random ops} may change at any time.
+ [random ops](../api_guides/python/constant_op.md#Random_Tensors) may change at any time.
Users should rely only on approximately correct distributions and
statistical strength, not the specific bits computed. However, we will make
changes to random bits rarely (or perhaps never) for patch releases. We
@@ -174,6 +178,8 @@ This section is relevant only when making incompatible changes to the `GraphDef`
format, such as when adding ops, removing ops, or changing the functionality
of existing ops. The previous section should suffice for most users.
+<a id="backward_forward"/>
+
### Backward and partial forward compatibility
Our versioning scheme has three requirements:
diff --git a/tensorflow/docs_src/install/index.md b/tensorflow/docs_src/install/index.md
index 55481cc400..76e590e1e1 100644
--- a/tensorflow/docs_src/install/index.md
+++ b/tensorflow/docs_src/install/index.md
@@ -17,23 +17,23 @@ systems listed above.
The following guides explain how to install a version of TensorFlow
that enables you to write applications in Python:
- * @{$install_linux$Install TensorFlow on Ubuntu}
- * @{$install_mac$Install TensorFlow on macOS}
- * @{$install_windows$Install TensorFlow on Windows}
- * @{$install_raspbian$Install TensorFlow on a Raspberry Pi}
- * @{$install_sources$Install TensorFlow from source code}
+ * [Install TensorFlow on Ubuntu](../install/install_linux.md)
+ * [Install TensorFlow on macOS](../install/install_mac.md)
+ * [Install TensorFlow on Windows](../install/install_windows.md)
+ * [Install TensorFlow on a Raspberry Pi](../install/install_raspbian.md)
+ * [Install TensorFlow from source code](../install/install_sources.md)
Many aspects of the Python TensorFlow API changed from version 0.n to 1.0.
The following guide explains how to migrate older TensorFlow applications
to Version 1.0:
- * @{$migration$Transition to TensorFlow 1.0}
+ * [Transition to TensorFlow 1.0](../install/migration.md)
The following guides explain how to install TensorFlow libraries for use in
other programming languages. These APIs are aimed at deploying TensorFlow
models in applications and are not as extensive as the Python APIs.
- * @{$install_java$Install TensorFlow for Java}
- * @{$install_c$Install TensorFlow for C}
- * @{$install_go$Install TensorFlow for Go}
+ * [Install TensorFlow for Java](../install/install_java.md)
+ * [Install TensorFlow for C](../install/install_c.md)
+ * [Install TensorFlow for Go](../install/install_go.md)
diff --git a/tensorflow/docs_src/install/install_c.md b/tensorflow/docs_src/install/install_c.md
index 5e26facaba..084634bc9c 100644
--- a/tensorflow/docs_src/install/install_c.md
+++ b/tensorflow/docs_src/install/install_c.md
@@ -28,8 +28,8 @@ enable TensorFlow for C:
entitled "Determine which TensorFlow to install" in one of the
following guides:
- * @{$install_linux#determine_which_tensorflow_to_install$Installing TensorFlow on Linux}
- * @{$install_mac#determine_which_tensorflow_to_install$Installing TensorFlow on macOS}
+ * [Installing TensorFlow on Linux](../install/install_linux.md#determine_which_tensorflow_to_install)
+ * [Installing TensorFlow on macOS](../install/install_mac.md#determine_which_tensorflow_to_install)
2. Download and extract the TensorFlow C library into `/usr/local/lib` by
invoking the following shell commands:
@@ -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.10.0-rc1.tar.gz" |
+ "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-${OS}-x86_64-1.10.0.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 83d16bc4b7..0c604d7713 100644
--- a/tensorflow/docs_src/install/install_go.md
+++ b/tensorflow/docs_src/install/install_go.md
@@ -29,8 +29,8 @@ steps to install this library and enable TensorFlow for Go:
the help of GPU(s). To help you decide, read the section entitled
"Determine which TensorFlow to install" in one of the following guides:
- * @{$install_linux#determine_which_tensorflow_to_install$Installing TensorFlow on Linux}
- * @{$install_mac#determine_which_tensorflow_to_install$Installing TensorFlow on macOS}
+ * [Installing TensorFlow on Linux](../install/install_linux.md#determine_which_tensorflow_to_install)
+ * [Installing TensorFlow on macOS](../install/install_mac.md#determine_which_tensorflow_to_install)
2. Download and extract the TensorFlow C library into `/usr/local/lib` by
invoking the following shell commands:
@@ -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.10.0-rc1.tar.gz" |
+ "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-$(go env GOOS)-x86_64-1.10.0.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 e9c6650c92..c411cb78fe 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:
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
</dependency>
```
@@ -65,7 +65,7 @@ As an example, these steps will create a Maven project that uses TensorFlow:
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
</dependency>
</dependencies>
</project>
@@ -124,18 +124,18 @@ instead:
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>libtensorflow</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
</dependency>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>libtensorflow_jni_gpu</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
</dependency>
```
GPU acceleration is available via Maven only for Linux and only if your system
meets the
-@{$install_linux#determine_which_tensorflow_to_install$requirements for GPU}.
+[requirements for GPU](../install/install_linux.md#determine_which_tensorflow_to_install).
## Using TensorFlow with JDK
@@ -148,15 +148,15 @@ 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.10.0-rc1.jar),
+ [libtensorflow.jar](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.10.0.jar),
which is the TensorFlow Java Archive (JAR).
2. Decide whether you will run TensorFlow for Java on CPU(s) only or with
the help of GPU(s). To help you decide, read the section entitled
"Determine which TensorFlow to install" in one of the following guides:
- * @{$install_linux#determine_which_tensorflow_to_install$Installing TensorFlow on Linux}
- * @{$install_mac#determine_which_tensorflow_to_install$Installing TensorFlow on macOS}
+ * [Installing TensorFlow on Linux](../install/install_linux.md#determine_which_tensorflow_to_install)
+ * [Installing TensorFlow on macOS](../install/install_mac.md#determine_which_tensorflow_to_install)
3. Download and extract the appropriate Java Native Interface (JNI)
file for your operating system and processor support by running the
@@ -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.10.0-rc1.tar.gz" |
+ "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-${TF_TYPE}-${OS}-x86_64-1.10.0.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.10.0-rc1.jar),
+ [libtensorflow.jar](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-1.10.0.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.10.0-rc1.zip).
+ [TensorFlow for Java on Windows](https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-cpu-windows-x86_64-1.10.0.zip).
3. Extract this .zip file.
__Note__: The native library (`tensorflow_jni.dll`) requires `msvcp140.dll` at runtime, which is included in the [Visual C++ 2015 Redistributable](https://www.microsoft.com/en-us/download/details.aspx?id=48145) package.
@@ -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:
-<pre><b>javac -cp libtensorflow-1.10.0-rc1.jar HelloTF.java</b></pre>
+<pre><b>javac -cp libtensorflow-1.10.0.jar HelloTF.java</b></pre>
### 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:
-<pre><b>java -cp libtensorflow-1.10.0-rc1.jar:. -Djava.library.path=./jni HelloTF</b></pre>
+<pre><b>java -cp libtensorflow-1.10.0.jar:. -Djava.library.path=./jni HelloTF</b></pre>
And the following command line executes the `HelloTF` program on Windows:
-<pre><b>java -cp libtensorflow-1.10.0-rc1.jar;. -Djava.library.path=jni HelloTF</b></pre>
+<pre><b>java -cp libtensorflow-1.10.0.jar;. -Djava.library.path=jni HelloTF</b></pre>
If the program prints <tt>Hello from <i>version</i></tt>, 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 005ad437bc..5fcfa4b988 100644
--- a/tensorflow/docs_src/install/install_linux.md
+++ b/tensorflow/docs_src/install/install_linux.md
@@ -436,7 +436,7 @@ Take the following steps to install TensorFlow in an Anaconda environment:
<pre>
(tensorflow)$ <b>pip install --ignore-installed --upgrade \
- https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0rc1-cp34-cp34m-linux_x86_64.whl</b></pre>
+ https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp34-cp34m-linux_x86_64.whl</b></pre>
<a name="ValidateYourInstallation"></a>
@@ -520,7 +520,7 @@ The following NVIDIA® <i>software</i> must be installed on your system:
To use a GPU with CUDA Compute Capability 3.0, or different versions of the
preceding NVIDIA libraries see
-@{$install_sources$installing TensorFlow from Sources}. If using Ubuntu 16.04
+[installing TensorFlow from Sources](../install/install_sources.md). If using Ubuntu 16.04
and possibly other Debian based linux distros, `apt-get` can be used with the
NVIDIA repository to simplify installation.
@@ -650,13 +650,13 @@ This section documents the relevant values for Linux installations.
CPU only:
<pre>
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0rc1-cp27-none-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp27-none-linux_x86_64.whl
</pre>
GPU support:
<pre>
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0rc1-cp27-none-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp27-none-linux_x86_64.whl
</pre>
Note that GPU support requires the NVIDIA hardware and software described in
@@ -667,13 +667,13 @@ Note that GPU support requires the NVIDIA hardware and software described in
CPU only:
<pre>
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0rc1-cp34-cp34m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp34-cp34m-linux_x86_64.whl
</pre>
GPU support:
<pre>
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0rc1-cp34-cp34m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp34-cp34m-linux_x86_64.whl
</pre>
Note that GPU support requires the NVIDIA hardware and software described in
@@ -684,13 +684,13 @@ Note that GPU support requires the NVIDIA hardware and software described in
CPU only:
<pre>
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0rc1-cp35-cp35m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp35-cp35m-linux_x86_64.whl
</pre>
GPU support:
<pre>
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0rc1-cp35-cp35m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp35-cp35m-linux_x86_64.whl
</pre>
Note that GPU support requires the NVIDIA hardware and software described in
@@ -701,13 +701,13 @@ Note that GPU support requires the NVIDIA hardware and software described in
CPU only:
<pre>
-https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0rc1-cp36-cp36m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp36-cp36m-linux_x86_64.whl
</pre>
GPU support:
<pre>
-https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0rc1-cp36-cp36m-linux_x86_64.whl
+https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp36-cp36m-linux_x86_64.whl
</pre>
Note that GPU support requires the NVIDIA hardware and software described in
diff --git a/tensorflow/docs_src/install/install_mac.md b/tensorflow/docs_src/install/install_mac.md
index 3a8637bfb1..c4d63cc107 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:
<pre> $ <b>pip3 install --upgrade \
- https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0rc1-py3-none-any.whl</b></pre>
+ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py3-none-any.whl</b></pre>
If you encounter installation problems, see
[Common Installation Problems](#common-installation-problems).
@@ -242,7 +242,7 @@ take the following steps:
issue the following command:
<pre> $ <b>sudo pip3 install --upgrade \
- https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0rc1-py3-none-any.whl</b> </pre>
+ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py3-none-any.whl</b> </pre>
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:
<pre> (<i>targetDirectory</i>)$ <b>pip install --ignore-installed --upgrade \
- https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0rc1-py2-none-any.whl</b></pre>
+ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py2-none-any.whl</b></pre>
<a name="ValidateYourInstallation"></a>
@@ -517,7 +517,7 @@ The value you specify depends on your Python version.
<pre>
-https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0rc1-py2-none-any.whl
+https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py2-none-any.whl
</pre>
@@ -525,5 +525,5 @@ https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0rc1-py2-none-
<pre>
-https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0rc1-py3-none-any.whl
+https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py3-none-any.whl
</pre>
diff --git a/tensorflow/docs_src/install/install_raspbian.md b/tensorflow/docs_src/install/install_raspbian.md
index 58a5285c78..cf6b6b4f79 100644
--- a/tensorflow/docs_src/install/install_raspbian.md
+++ b/tensorflow/docs_src/install/install_raspbian.md
@@ -60,7 +60,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:
<pre>$ sudo apt-get install python3-pip # for Python 3.n
-sudo apt-get install python-pip # for Python 2.7</pre>
+$ sudo apt-get install python-pip # for Python 2.7</pre>
You can find more help on installing and upgrading pip in
[the Raspberry Pi documentation](https://www.raspberrypi.org/documentation/linux/software/python.md).
@@ -78,8 +78,8 @@ your system, run the following command:
Assuming the prerequisite software is installed on your Pi, install TensorFlow
by invoking **one** of the following commands:
- <pre> $ <b>pip3 install tensorflow</b> # Python 3.n
- $ <b>pip install tensorflow</b> # Python 2.7</pre>
+<pre>$ <b>pip3 install tensorflow</b> # Python 3.n
+$ <b>pip install tensorflow</b> # Python 2.7</pre>
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
diff --git a/tensorflow/docs_src/install/install_sources.md b/tensorflow/docs_src/install/install_sources.md
index 8bb09f4021..e8e13142e9 100644
--- a/tensorflow/docs_src/install/install_sources.md
+++ b/tensorflow/docs_src/install/install_sources.md
@@ -180,13 +180,16 @@ If you follow these instructions, you will not need to disable SIP.
After installing pip, invoke the following commands:
-<pre> $ <b>sudo pip install six numpy wheel mock</b> </pre>
+<pre> $ <b>sudo pip install six numpy wheel mock h5py</b>
+ $ <b>sudo pip install keras_applications==1.0.4 --no-deps</b>
+ $ <b>sudo pip install keras_preprocessing==1.0.2 --no-deps</b>
+</pre>
Note: These are just the minimum requirements to _build_ tensorflow. Installing
the pip package will download additional packages required to _run_ it. If you
plan on executing tasks directly with `bazel` , without the pip installation,
you may need to install additional python packages. For example, you should `pip
-install mock enum34` before running TensorFlow's tests with bazel.
+install enum34` before running TensorFlow's tests with bazel.
<a name="ConfigureInstallation"></a>
@@ -361,6 +364,8 @@ continue to work against your built package.
If RAM is an issue on your system, you may limit RAM usage by specifying
<code>--local_resources 2048,.5,1.0</code> while invoking `bazel`.
+### Run the build_pip_package script
+
The <code>bazel build</code> command builds a script named `build_pip_package`.
Running this script as follows will build a `.whl` file within the
`/tmp/tensorflow_pkg` directory:
@@ -375,10 +380,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.10.0rc1 on Linux:
+for TensorFlow 1.10.0 on Linux:
<pre>
-$ <b>sudo pip install /tmp/tensorflow_pkg/tensorflow-1.10.0rc1-py2-none-any.whl</b>
+$ <b>sudo pip install /tmp/tensorflow_pkg/tensorflow-1.10.0-py2-none-any.whl</b>
</pre>
## Validate your installation
diff --git a/tensorflow/docs_src/install/install_sources_windows.md b/tensorflow/docs_src/install/install_sources_windows.md
new file mode 100644
index 0000000000..a1da122317
--- /dev/null
+++ b/tensorflow/docs_src/install/install_sources_windows.md
@@ -0,0 +1,320 @@
+# Install TensorFlow from Sources on Windows
+
+This guide explains how to build TensorFlow sources into a TensorFlow binary and
+how to install that TensorFlow binary on Windows.
+
+## Determine which TensorFlow to install
+
+You must choose one of the following types of TensorFlow to build and install:
+
+* **TensorFlow with CPU support only**. If your system does not have a NVIDIA®
+ GPU, build and install this version. Note that this version of TensorFlow is
+ typically easier to build and install, so even if you have an NVIDIA GPU, we
+ recommend building and installing this version first.
+* **TensorFlow with GPU support**. TensorFlow programs typically run
+ significantly faster on a GPU than on a CPU. Therefore, if your system has a
+ NVIDIA GPU and you need to run performance-critical applications, you should
+ ultimately build and install this version. Beyond the NVIDIA GPU itself,
+ your system must also fulfill the NVIDIA software requirements described in
+ the following document:
+
+ * [Installing TensorFlow on Windows](install_windows.md#NVIDIARequirements)
+
+## Prepare environment for Windows
+
+Before building TensorFlow on Windows, install the following build tools on your
+system:
+
+* [MSYS2](#InstallMSYS2)
+* [Visual C++ build tools](#InstallVCBuildTools)
+* [Bazel for Windows](#InstallBazel)
+* [TensorFlow Python dependencies](#InstallPython)
+* [optionally, NVIDIA packages to support TensorFlow for GPU](#InstallCUDA)
+
+<a name="InstallMSYS2"></a>
+
+### Install MSYS2
+
+Bash bin tools are used in TensorFlow Bazel build, you can install them through [MSYS2](https://www.msys2.org/).
+
+Assume you installed MSYS2 at `C:\msys64`, add `C:\msys64\usr\bin` to your `%PATH%` environment variable.
+
+To install necessary bash bin tools, issue the following command under `cmd.exe`:
+
+<pre>
+C:\> <b>pacman -S git patch unzip</b>
+</pre>
+
+<a name="InstallVCBuildTools"></a>
+
+### Install Visual C++ Build Tools 2015
+
+To build TensorFlow, you need to install Visual C++ build tools 2015. It is a part of Visual Studio 2015.
+But you can install it separately by the following way:
+
+ * Open the [official downloand page](https://visualstudio.microsoft.com/vs/older-downloads/).
+ * Go to <b>Redistributables and Build Tools</b> section.
+ * Find <b>Microsoft Build Tools 2015 Update 3</b> and click download.
+ * Run the installer.
+
+It's possible to build TensorFlow with newer version of Visual C++ build tools,
+but we only test against Visual Studio 2015 Update 3.
+
+<a name="InstallBazel"></a>
+
+### Install Bazel
+
+If bazel is not installed on your system, install it now by following
+[these instructions](https://docs.bazel.build/versions/master/install-windows.html).
+It is recommended to use a Bazel version >= `0.15.0`.
+
+Add the directory where you installed Bazel to your `%PATH%` environment variable.
+
+<a name="InstallPython"></a>
+
+### Install TensorFlow Python dependencies
+
+If you don't have Python 3.5 or Python 3.6 installed, install it now:
+
+ * [Python 3.5.x 64-bit from python.org](https://www.python.org/downloads/release/python-352/)
+ * [Python 3.6.x 64-bit from python.org](https://www.python.org/downloads/release/python-362/)
+
+To build and install TensorFlow, you must install the following python packages:
+
+* `six`, which provides simple utilities for wrapping over differences between
+ Python 2 and Python 3.
+* `numpy`, which is a numerical processing package that TensorFlow requires.
+* `wheel`, which enables you to manage Python compressed packages in the wheel
+ (.whl) format.
+* `keras_applications`, the applications module of the Keras deep learning library.
+* `keras_preprocessing`, the data preprocessing and data augmentation module
+ of the Keras deep learning library.
+
+Assume you already have `pip3` in `%PATH%`, issue the following command:
+
+<pre>
+C:\> <b>pip3 install six numpy wheel</b>
+C:\> <b>pip3 install keras_applications==1.0.4 --no-deps</b>
+C:\> <b>pip3 install keras_preprocessing==1.0.2 --no-deps</b>
+</pre>
+
+<a name="InstallCUDA"></a>
+
+### Optional: install TensorFlow for GPU prerequisites
+
+If you are building TensorFlow without GPU support, skip this section.
+
+The following NVIDIA® _hardware_ must be installed on your system:
+
+* GPU card with CUDA Compute Capability 3.5 or higher. See
+ [NVIDIA documentation](https://developer.nvidia.com/cuda-gpus) for a list of
+ supported GPU cards.
+
+The following NVIDIA® _software_ must be installed on your system:
+
+* [GPU drivers](http://nvidia.com/driver). CUDA 9.0 requires 384.x or higher.
+* [CUDA Toolkit](http://nvidia.com/cuda) (>= 8.0). We recommend version 9.0.
+* [cuDNN SDK](http://developer.nvidia.com/cudnn) (>= 6.0). We recommend
+ version 7.1.x.
+* [CUPTI](http://docs.nvidia.com/cuda/cupti/) ships with the CUDA Toolkit, but
+ you also need to append its path to `%PATH%` environment
+ variable.
+
+Assume you have CUDA Toolkit installed at `C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0`
+and cuDNN at `C:\tools\cuda`, issue the following commands.
+
+<pre>
+C:\> SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin;%PATH%
+C:\> SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\extras\CUPTI\libx64;%PATH%
+C:\> SET PATH=C:\tools\cuda\bin;%PATH%
+</pre>
+
+## Clone the TensorFlow repository
+
+Now you need to clone **the latest** TensorFlow repository,
+thanks to MSYS2 we already have `git` avaiable, issue the following command:
+
+<pre>C:\> <b>git clone https://github.com/tensorflow/tensorflow.git</b> </pre>
+
+The preceding <code>git clone</code> 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:
+
+<pre>
+C:\> <b>cd tensorflow</b>
+C:\> <b>git checkout</b> <i>Branch</i> # where <i>Branch</i> is the desired branch
+</pre>
+
+For example, to work with the `r1.11` release instead of the master release,
+issue the following command:
+
+<pre>C:\> <b>git checkout r1.11</b></pre>
+
+Next, you must now configure the installation.
+
+## Configure the installation
+
+The root of the source tree contains a python script named <code>configure.py</code>.
+This script asks you to identify the pathname of all relevant TensorFlow
+dependencies and specify other build configuration options such as compiler
+flags. You must run this script *prior* to creating the pip package and
+installing TensorFlow.
+
+If you wish to build TensorFlow with GPU, `configure.py` will ask you to specify
+the version numbers of CUDA and cuDNN. If several versions of CUDA or cuDNN are
+installed on your system, explicitly select the desired version instead of
+relying on the default.
+
+One of the questions that `configure.py` will ask is as follows:
+
+<pre>
+Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is /arch:AVX]:
+</pre>
+
+Here is an example execution of the `configure.py` script. Note that your own input
+will likely differ from our sample input:
+
+<pre>
+C:\> <b>cd tensorflow</b> # cd to the top-level directory created
+C:\tensorflow> <b>python ./configure.py</b>
+Starting local Bazel server and connecting to it...
+................
+You have bazel 0.15.0 installed.
+Please specify the location of python. [Default is C:\python36\python.exe]:
+
+Found possible Python library paths:
+ C:\python36\lib\site-packages
+Please input the desired Python library path to use. Default is [C:\python36\lib\site-packages]
+
+Do you wish to build TensorFlow with CUDA support? [y/N]: <b>Y</b>
+CUDA support will be enabled for TensorFlow.
+
+Please specify the CUDA SDK version you want to use. [Leave empty to default to CUDA 9.0]:
+
+Please specify the location where CUDA 9.0 toolkit is installed. Refer to README.md for more details. [Default is C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0]:
+
+Please specify the cuDNN version you want to use. [Leave empty to default to cuDNN 7.0]: <b>7.0</b>
+
+Please specify the location where cuDNN 7 library is installed. Refer to README.md for more details. [Default is C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0]: <b>C:\tools\cuda</b>
+
+Please specify a list of comma-separated Cuda compute capabilities you want to build with.
+You can find the compute capability of your device at: https://developer.nvidia.com/cuda-gpus.
+Please note that each additional compute capability significantly increases your build time and binary size. [Default is: 3.5,7.0]: <b>3.7</b>
+
+Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is /arch:AVX]:
+
+Would you like to override eigen strong inline for some C++ compilation to reduce the compilation time? [Y/n]:
+Eigen strong inline overridden.
+
+Configuration finished
+</pre>
+
+## Build the pip package
+
+### CPU-only support
+
+To build a pip package for TensorFlow with CPU-only support:
+
+<pre>
+C:\tensorflow> <b>bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package</b>
+</pre>
+
+### GPU support
+
+To build a pip package for TensorFlow with GPU support:
+
+<pre>
+C:\tensorflow> <b>bazel build --config=opt --config=cuda //tensorflow/tools/pip_package:build_pip_package</b>
+</pre>
+
+**NOTE :** When building with GPU support, you might want to add `--copt=-nvcc_options=disable-warnings`
+to suppress nvcc warning messages.
+
+The `bazel build` command builds a binary named `build_pip_package`
+(an executable binary to launch bash and run a bash script to create the pip package).
+Running this binary as follows will build a `.whl` file within the `C:/tmp/tensorflow_pkg` directory:
+
+<pre>
+C:\tensorflow> <b>bazel-bin\tensorflow\tools\pip_package\build_pip_package C:/tmp/tensorflow_pkg</b>
+</pre>
+
+## Install the pip package
+
+Invoke `pip3 install` to install that pip package. The filename of the `.whl`
+file depends on the TensorFlow version and your platform. For example, the
+following command will install the pip package for TensorFlow 1.11.0rc0:
+
+<pre>
+C:\tensorflow> <b>pip3 install C:/tmp/tensorflow_pkg/tensorflow-1.11.0rc0-cp36-cp36m-win_amd64.whl</b>
+</pre>
+
+## Validate your installation
+
+Validate your TensorFlow installation by doing the following:
+
+Start a terminal.
+
+Change directory (`cd`) to any directory on your system other than the
+`tensorflow` subdirectory from which you invoked the `configure` command.
+
+Invoke python:
+
+<pre>$ <b>python</b></pre>
+
+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:
+
+<pre>Hello, TensorFlow!</pre>
+
+To learn more, see the [TensorFlow tutorials](../tutorials/).
+
+## Build under MSYS shell
+The above instruction assumes you are building under the Windows native command line (`cmd.exe`), but you can also
+build TensorFlow from MSYS shell. There are a few things to notice:
+
+* Disable the path conversion heuristic in MSYS. MSYS automatically converts arguments that look
+ like a Unix path to Windows path when running a program, this will confuse Bazel.
+ (eg. A Bazel label `//foo/bar:bin` is considered a Unix absolute path, only because it starts with a slash)
+
+ ```sh
+$ export MSYS_NO_PATHCONV=1
+$ export MSYS2_ARG_CONV_EXCL="*"
+```
+
+* Add the directory where you install Bazel in `$PATH`. Assume you have Bazel
+ installed at `C:\tools\bazel.exe`, issue the following command:
+
+ ```sh
+# `:` is used as path separator, so we have to convert the path to Unix style.
+$ export PATH="/c/tools:$PATH"
+```
+
+* Add the directory where you install Python in `$PATH`. Assume you have
+ Python installed at `C:\Python36\python.exe`, issue the following command:
+
+ ```sh
+$ export PATH="/c/Python36:$PATH"
+```
+
+* If you have Python in `$PATH`, you can run configure script just by
+ `./configure`, a shell script will help you invoke python.
+
+* (For GPU build only) Add Cuda and cuDNN bin directories in `$PATH` in the following way:
+
+ ```sh
+$ export PATH="/c/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/bin:$PATH"
+$ export PATH="/c/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/extras/CUPTI/libx64:$PATH"
+$ export PATH="/c/tools/cuda/bin:$PATH"
+```
+
+The rest steps should be the same as building under `cmd.exe`.
diff --git a/tensorflow/docs_src/install/install_windows.md b/tensorflow/docs_src/install/install_windows.md
index e9061bf3c1..0bb0e5aeb9 100644
--- a/tensorflow/docs_src/install/install_windows.md
+++ b/tensorflow/docs_src/install/install_windows.md
@@ -24,6 +24,8 @@ You must choose one of the following types of TensorFlow to install:
and you need to run performance-critical applications, you should
ultimately install this version.
+<a name="NVIDIARequirements"></a>
+
### Requirements to run TensorFlow with GPU support
If you are installing TensorFlow with GPU support using one of the mechanisms
diff --git a/tensorflow/docs_src/install/leftnav_files b/tensorflow/docs_src/install/leftnav_files
index ace275c0e8..59292f7121 100644
--- a/tensorflow/docs_src/install/leftnav_files
+++ b/tensorflow/docs_src/install/leftnav_files
@@ -6,6 +6,7 @@ install_mac.md: MacOS
install_windows.md: Windows
install_raspbian.md: Raspbian
install_sources.md: From source
+install_sources_windows.md: From source on Windows
>>>
migration.md
diff --git a/tensorflow/docs_src/performance/index.md b/tensorflow/docs_src/performance/index.md
index 131d28fa3e..a0f26a8c3a 100644
--- a/tensorflow/docs_src/performance/index.md
+++ b/tensorflow/docs_src/performance/index.md
@@ -7,18 +7,18 @@ details on the high level APIs to use along with best practices to build
and train high performance models, and quantize models for the least latency
and highest throughput for inference.
- * @{$performance_guide$Performance Guide} contains a collection of best
+ * [Performance Guide](../performance/performance_guide.md) contains a collection of best
practices for optimizing your TensorFlow code.
- * @{$datasets_performance$Data input pipeline guide} describes the tf.data
+ * [Data input pipeline guide](../performance/datasets_performance.md) describes the tf.data
API for building efficient data input pipelines for TensorFlow.
- * @{$performance/benchmarks$Benchmarks} contains a collection of
+ * [Benchmarks](../performance/benchmarks.md) contains a collection of
benchmark results for a variety of hardware configurations.
* For improving inference efficiency on mobile and
embedded hardware, see
- @{$quantization$How to Quantize Neural Networks with TensorFlow}, which
+ [How to Quantize Neural Networks with TensorFlow](../performance/quantization.md), which
explains how to use quantization to reduce model size, both in storage
and at runtime.
@@ -31,20 +31,20 @@ XLA (Accelerated Linear Algebra) is an experimental compiler for linear
algebra that optimizes TensorFlow computations. The following guides explore
XLA:
- * @{$xla$XLA Overview}, which introduces XLA.
- * @{$broadcasting$Broadcasting Semantics}, which describes XLA's
+ * [XLA Overview](../performance/xla/index.md), which introduces XLA.
+ * [Broadcasting Semantics](../performance/xla/broadcasting.md), which describes XLA's
broadcasting semantics.
- * @{$developing_new_backend$Developing a new back end for XLA}, which
+ * [Developing a new back end for XLA](../performance/xla/developing_new_backend.md), which
explains how to re-target TensorFlow in order to optimize the performance
of the computational graph for particular hardware.
- * @{$jit$Using JIT Compilation}, which describes the XLA JIT compiler that
+ * [Using JIT Compilation](../performance/xla/jit.md), which describes the XLA JIT compiler that
compiles and runs parts of TensorFlow graphs via XLA in order to optimize
performance.
- * @{$operation_semantics$Operation Semantics}, which is a reference manual
+ * [Operation Semantics](../performance/xla/operation_semantics.md), which is a reference manual
describing the semantics of operations in the `ComputationBuilder`
interface.
- * @{$shapes$Shapes and Layout}, which details the `Shape` protocol buffer.
- * @{$tfcompile$Using AOT compilation}, which explains `tfcompile`, a
+ * [Shapes and Layout](../performance/xla/shapes.md), which details the `Shape` protocol buffer.
+ * [Using AOT compilation](../performance/xla/tfcompile.md), which explains `tfcompile`, a
standalone tool that compiles TensorFlow graphs into executable code in
order to optimize performance.
diff --git a/tensorflow/docs_src/performance/performance_guide.md b/tensorflow/docs_src/performance/performance_guide.md
index df70309568..9ea1d6a705 100644
--- a/tensorflow/docs_src/performance/performance_guide.md
+++ b/tensorflow/docs_src/performance/performance_guide.md
@@ -41,7 +41,7 @@ approaches to identifying issues:
utilization is not approaching 80-100%, then the input pipeline may be the
bottleneck.
* Generate a timeline and look for large blocks of white space (waiting). An
- example of generating a timeline exists as part of the @{$jit$XLA JIT}
+ example of generating a timeline exists as part of the [XLA JIT](../performance/xla/jit.md)
tutorial.
* Check CPU usage. It is possible to have an optimized input pipeline and lack
the CPU cycles to process the pipeline.
@@ -68,7 +68,7 @@ the CPU.
#### Using the tf.data API
-The @{$datasets$tf.data API} is replacing `queue_runner` as the recommended API
+The [tf.data API](../guide/datasets.md) is replacing `queue_runner` as the recommended API
for building input pipelines. This
[ResNet example](https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10_estimator/cifar10_main.py)
([arXiv:1512.03385](https://arxiv.org/abs/1512.03385))
@@ -78,7 +78,7 @@ training CIFAR-10 illustrates the use of the `tf.data` API along with
The `tf.data` API utilizes C++ multi-threading and has a much lower overhead
than the Python-based `queue_runner` that is limited by Python's multi-threading
performance. A detailed performance guide for the `tf.data` API can be found
-@{$datasets_performance$here}.
+[here](../performance/datasets_performance.md).
While feeding data using a `feed_dict` offers a high level of flexibility, in
general `feed_dict` does not provide a scalable solution. If only a single GPU
@@ -174,7 +174,7 @@ faster using `NHWC` than the normally most efficient `NCHW`.
### Common fused Ops
Fused Ops combine multiple operations into a single kernel for improved
-performance. There are many fused Ops within TensorFlow and @{$xla$XLA} will
+performance. There are many fused Ops within TensorFlow and [XLA](../performance/xla/index.md) will
create fused Ops when possible to automatically improve performance. Collected
below are select fused Ops that can greatly improve performance and may be
overlooked.
@@ -257,7 +257,7 @@ the CPU in use. Speedups for training and inference on CPU are documented below
in [Comparing compiler optimizations](#comparing-compiler-optimizations).
To install the most optimized version of TensorFlow,
-@{$install_sources$build and install} from source. If there is a need to build
+[build and install](../install/install_sources.md) from source. If there is a need to build
TensorFlow on a platform that has different hardware than the target, then
cross-compile with the highest optimizations for the target platform. The
following command is an example of using `bazel` to compile for a specific
@@ -298,7 +298,7 @@ each of the towers. How each tower gets the updated variables and how the
gradients are applied has an impact on the performance, scaling, and convergence
of the model. The rest of this section provides an overview of variable
placement and the towering of a model on multiple GPUs.
-@{$performance_models$High-Performance Models} gets into more details regarding
+[High-Performance Models](../performance/performance_models.md) gets into more details regarding
more complex methods that can be used to share and update variables between
towers.
@@ -307,7 +307,7 @@ and even how the hardware has been configured. An example of this, is that two
systems can be built with NVIDIA Tesla P100s but one may be using PCIe and the
other [NVLink](http://www.nvidia.com/object/nvlink.html). In that scenario, the
optimal solution for each system may be different. For real world examples, read
-the @{$performance/benchmarks$benchmark} page which details the settings that
+the [benchmark](../performance/benchmarks.md) page which details the settings that
were optimal for a variety of platforms. Below is a summary of what was learned
from benchmarking various platforms and configurations:
@@ -433,7 +433,7 @@ scenarios.
## Optimizing for CPU
CPUs, which includes Intel® Xeon Phi™, achieve optimal performance when
-TensorFlow is @{$install_sources$built from source} with all of the instructions
+TensorFlow is [built from source](../install/install_sources.md) with all of the instructions
supported by the target CPU.
Beyond using the latest instruction sets, Intel® has added support for the
diff --git a/tensorflow/docs_src/performance/performance_models.md b/tensorflow/docs_src/performance/performance_models.md
index 66bf684d5b..151c0b2946 100644
--- a/tensorflow/docs_src/performance/performance_models.md
+++ b/tensorflow/docs_src/performance/performance_models.md
@@ -9,7 +9,7 @@ incorporated into high-level APIs.
## Input Pipeline
-The @{$performance_guide$Performance Guide} explains how to identify possible
+The [Performance Guide](../performance/performance_guide.md) explains how to identify possible
input pipeline issues and best practices. We found that using `tf.FIFOQueue`
and `tf.train.queue_runner` could not saturate multiple current generation GPUs
when using large inputs and processing with higher samples per second, such
diff --git a/tensorflow/docs_src/performance/quantization.md b/tensorflow/docs_src/performance/quantization.md
index 4499f5715c..3326d82964 100644
--- a/tensorflow/docs_src/performance/quantization.md
+++ b/tensorflow/docs_src/performance/quantization.md
@@ -80,7 +80,7 @@ need for a separate calibration step.
TensorFlow can train models with quantization in the loop. Because training
requires small gradient adjustments, floating point values are still used. To
keep models as floating point while adding the quantization error in the training
-loop, @{$array_ops#Fake_quantization$fake quantization} nodes simulate the
+loop, [fake quantization](../api_guides/python/array_ops.md#Fake_quantization) nodes simulate the
effect of quantization in the forward and backward passes.
Since it's difficult to add these fake quantization operations to all the
diff --git a/tensorflow/docs_src/performance/xla/index.md b/tensorflow/docs_src/performance/xla/index.md
index 8f5de83ea6..770737c34c 100644
--- a/tensorflow/docs_src/performance/xla/index.md
+++ b/tensorflow/docs_src/performance/xla/index.md
@@ -14,7 +14,7 @@ XLA (Accelerated Linear Algebra) is a domain-specific compiler for linear
algebra that optimizes TensorFlow computations. The results are improvements in
speed, memory usage, and portability on server and mobile platforms. Initially,
most users will not see large benefits from XLA, but are welcome to experiment
-by using XLA via @{$jit$just-in-time (JIT) compilation} or @{$tfcompile$ahead-of-time (AOT) compilation}. Developers targeting new hardware accelerators are
+by using XLA via [just-in-time (JIT) compilation](../../performance/xla/jit.md) or [ahead-of-time (AOT) compilation](../../performance/xla/tfcompile.md). Developers targeting new hardware accelerators are
especially encouraged to try out XLA.
The XLA framework is experimental and in active development. In particular,
@@ -54,13 +54,13 @@ We had several objectives for XLA to work with TensorFlow:
The input language to XLA is called "HLO IR", or just HLO (High Level
Optimizer). The semantics of HLO are described on the
-@{$operation_semantics$Operation Semantics} page. It
+[Operation Semantics](../../performance/xla/operation_semantics.md) page. It
is most convenient to think of HLO as a [compiler
IR](https://en.wikipedia.org/wiki/Intermediate_representation).
XLA takes graphs ("computations") defined in HLO and compiles them into machine
instructions for various architectures. XLA is modular in the sense that it is
-easy to slot in an alternative backend to @{$developing_new_backend$target some novel HW architecture}. The CPU backend for x64 and ARM64 as
+easy to slot in an alternative backend to [target some novel HW architecture](../../performance/xla/developing_new_backend.md). The CPU backend for x64 and ARM64 as
well as the NVIDIA GPU backend are in the TensorFlow source tree.
The following diagram shows the compilation process in XLA:
@@ -94,5 +94,5 @@ CPU backend supports multiple CPU ISAs.
## Supported Platforms
-XLA currently supports @{$jit$JIT compilation} on x86-64 and NVIDIA GPUs; and
-@{$tfcompile$AOT compilation} for x86-64 and ARM.
+XLA currently supports [JIT compilation](../../performance/xla/jit.md) on x86-64 and NVIDIA GPUs; and
+[AOT compilation](../../performance/xla/tfcompile.md) for x86-64 and ARM.
diff --git a/tensorflow/docs_src/performance/xla/jit.md b/tensorflow/docs_src/performance/xla/jit.md
index 7202ef47f7..83b3e71566 100644
--- a/tensorflow/docs_src/performance/xla/jit.md
+++ b/tensorflow/docs_src/performance/xla/jit.md
@@ -133,7 +133,7 @@ Execute the python script to train the model with XLA and turn on a debugging
feature of XLA via an environmental variable that outputs the XLA graph.
```shell
-TF_XLA_FLAGS=--xla_generate_hlo_graph=.* python mnist_softmax_xla.py
+TF_XLA_FLAGS="--xla_hlo_graph_path=/tmp --xla_generate_hlo_graph=.*" python mnist_softmax_xla.py
```
Open the timeline file created (`timeline.ctf.json`). The rendered timeline
diff --git a/tensorflow/docs_src/performance/xla/operation_semantics.md b/tensorflow/docs_src/performance/xla/operation_semantics.md
index 02af71f8a3..2de30d1b3d 100644
--- a/tensorflow/docs_src/performance/xla/operation_semantics.md
+++ b/tensorflow/docs_src/performance/xla/operation_semantics.md
@@ -22,7 +22,7 @@ Alltoall is a collective operation that sends data from all cores to all cores.
It has two phases:
1. the scatter phase. On each core, the operand is split into `split_count`
- number of blocks along the `split_dimensions`, and the blocks are scatterd
+ number of blocks along the `split_dimensions`, and the blocks are scattered
to all cores, e.g., the ith block is send to the ith core.
2. the gather phase. Each core concatenates the received blocks along the
`concat_dimension`.
@@ -505,16 +505,17 @@ Computes a convolution of the kind used in neural networks. Here, a convolution
can be thought of as a n-dimensional window moving across a n-dimensional base
area and a computation is performed for each possible position of the window.
-| Arguments | Type | Semantics |
-| ---------------- | ----------------------- | ----------------------------- |
-| `lhs` | `XlaOp` | rank n+2 array of inputs |
-| `rhs` | `XlaOp` | rank n+2 array of kernel |
-: : : weights :
-| `window_strides` | `ArraySlice<int64>` | n-d array of kernel strides |
-| `padding` | `ArraySlice<pair<int64, | n-d array of (low, high) |
-: : int64>>` : padding :
-| `lhs_dilation` | `ArraySlice<int64>` | n-d lhs dilation factor array |
-| `rhs_dilation` | `ArraySlice<int64>` | n-d rhs dilation factor array |
+| Arguments | Type | Semantics |
+| --------------------- | -------------------- | ----------------------------- |
+| `lhs` | `XlaOp` | rank n+2 array of inputs |
+| `rhs` | `XlaOp` | rank n+2 array of kernel |
+: : : weights :
+| `window_strides` | `ArraySlice<int64>` | n-d array of kernel strides |
+| `padding` | `ArraySlice< | n-d array of (low, high) |
+: : pair<int64, int64>>` : padding :
+| `lhs_dilation` | `ArraySlice<int64>` | n-d lhs dilation factor array |
+| `rhs_dilation` | `ArraySlice<int64>` | n-d rhs dilation factor array |
+| `feature_group_count` | int64 | the number of feature groups |
Let n be the number of spatial dimensions. The `lhs` argument is a rank n+2
array describing the base area. This is called the input, even though of course
@@ -532,8 +533,8 @@ The `rhs` argument is a rank n+2 array describing the convolutional
filter/kernel/window. The dimensions are, in this order:
* `output-z`: The `z` dimension of the output.
-* `input-z`: The size of this dimension should equal the size of the `z`
- dimension in lhs.
+* `input-z`: The size of this dimension times `feature_group_count` should
+ equal the size of the `z` dimension in lhs.
* `spatial_dims`: Describes the `n` spatial dimensions that define the n-d
window that moves across the base area.
@@ -566,6 +567,24 @@ Dilation of the rhs is also called atrous convolution. For more details, see
`tf.nn.atrous_conv2d`. Dilation of the lhs is also called transposed
convolution. For more details, see `tf.nn.conv2d_transpose`.
+The `feature_group_count` argument (default value 1) can be used for grouped
+convolutions. `feature_group_count` needs to be a divisor of both the input and
+the output feature dimension. If `feature_group_count` is greater than 1, it
+means that conceptually the input and output feature dimension and the `rhs`
+output feature dimension are split evenly into `feature_group_count` many
+groups, each group consisting of a consecutive subsequence of features. The
+input feature dimension of `rhs` needs to be equal to the `lhs` input feature
+dimension divided by `feature_group_count` (so it already has the size of a
+group of input features). The i-th groups are used together to compute
+`feature_group_count` many separate convolutions. The results of these
+convolutions are concatenated together in the output feature dimension.
+
+For depthwise convolution the `feature_group_count` argument would be set to the
+input feature dimension, and the filter would be reshaped from
+`[filter_height, filter_width, in_channels, channel_multiplier]` to
+`[filter_height, filter_width, 1, in_channels * channel_multiplier]`. For more
+details, see `tf.nn.depthwise_conv2d`.
+
The output shape has these dimensions, in this order:
* `batch`: Same size as `batch` on the input (`lhs`).
@@ -1009,7 +1028,7 @@ Arguments | Type | Semantics
`rhs` | `XlaOp` | right-hand-side operand: array of type T
The arguments' shapes have to be either similar or compatible. See the
-@{$broadcasting$broadcasting} documentation about what it means for shapes to
+[broadcasting](../../performance/xla/broadcasting.md) documentation about what it means for shapes to
be compatible. The result of an operation has a shape which is the result of
broadcasting the two input arrays. In this variant, operations between arrays of
different ranks are *not* supported, unless one of the operands is a scalar.
@@ -1033,7 +1052,7 @@ the dimensions of the higher-rank shape. The unmapped dimensions of the expanded
shape are filled with dimensions of size one. Degenerate-dimension broadcasting
then broadcasts the shapes along these degenerate dimensions to equalize the
shapes of both operands. The semantics are described in detail on the
-@{$broadcasting$broadcasting page}.
+[broadcasting page](../../performance/xla/broadcasting.md).
## Element-wise comparison operations
@@ -1056,7 +1075,7 @@ Arguments | Type | Semantics
`rhs` | `XlaOp` | right-hand-side operand: array of type T
The arguments' shapes have to be either similar or compatible. See the
-@{$broadcasting$broadcasting} documentation about what it means for shapes to
+[broadcasting](../../performance/xla/broadcasting.md) documentation about what it means for shapes to
be compatible. The result of an operation has a shape which is the result of
broadcasting the two input arrays with the element type `PRED`. In this variant,
operations between arrays of different ranks are *not* supported, unless one of
@@ -1073,7 +1092,7 @@ matrix to a vector).
The additional `broadcast_dimensions` operand is a slice of integers specifying
the dimensions to use for broadcasting the operands. The semantics are described
-in detail on the @{$broadcasting$broadcasting page}.
+in detail on the [broadcasting page](../../performance/xla/broadcasting.md).
## Element-wise unary functions
@@ -1119,7 +1138,7 @@ array with the same shape. It is allowed for `operand` to be a scalar (rank 0).
## Gather
The XLA gather operation stitches together several slices (each slice at a
-potentially different runtime offset) of an input tensor into an output tensor.
+potentially different runtime offset) of an input array.
### General Semantics
@@ -1127,151 +1146,141 @@ See also
[`XlaBuilder::Gather`](https://www.tensorflow.org/code/tensorflow/compiler/xla/client/xla_builder.h).
For a more intuitive description, see the "Informal Description" section below.
-<b> `gather(operand, gather_indices, output_window_dims, elided_window_dims, window_bounds, gather_dims_to_operand_dims)` </b>
+<b> `gather(operand, start_indices, offset_dims, collapsed_slice_dims, slice_sizes, start_index_map)` </b>
|Arguments | Type | Semantics |
|----------------- | ----------------------- | --------------------------------|
-|`operand` | `XlaOp` | The tensor we’re gathering |
+|`operand` | `XlaOp` | The array we’re gathering |
: : : from. :
-|`gather_indices` | `XlaOp` | Tensor containing the starting |
-: : : indices of the slices we're :
-: : : stitching together into the :
-: : : output tensor. :
-|`index_vector_dim` | `int64` | The dimension in |
-: : : `gather_indices` that contains :
-: : : the starting indices. :
-|`output_window_dims` | `ArraySlice<int64>` | The set of dimensions in the |
-: : : output shape that are _window :
-: : : dimensions_ (defined below). :
-: : : Not all window dimensions may :
-: : : be present in the output shape. :
-|`elided_window_dims` | `ArraySlice<int64>` | The set of _window dimensions_ |
-: : : that are not present in the output shape. :
-: : : `window_bounds[i]` must be `1` for all `i` :
-: : : in `elided_window_dims`. :
-|`window_bounds` | `ArraySlice<int64>` | `window_bounds[i]` is the bounds |
-: : : for window dimension `i`. This includes :
-: : : both the window dimensions that are :
-: : : explicitly part of the output shape (via :
-: : : `output_window_dims`) and the window :
-: : : dimensions that are elided (via :
-: : : `elided_window_dims`). :
-|`gather_dims_to_operand_dims` | `ArraySlice<int64>` | A dimension map (the |
-: : : array is interpreted as mapping `i` to :
-: : : `gather_dims_to_operand_dims[i]`) from :
-: : : the gather indices in `gather_indices` to :
-: : : the operand index space. It has to be :
-: : : one-to-one and total. :
-
-For every index `Out` in the output tensor, we compute two things (more
-precisely described later):
-
- - An index into `gather_indices.rank` - `1` dimensions of `gather_indices`,
- which gives us a starting index of a slice, _operand slice_, in the operand
- tensor. These `gather_indices.rank` - `1` dimensions are all the dimensions
- in `gather_indices` except `index_vector_dim`.
-
- - A _window index_ that has the same rank as the operand. This index is
- composed of the values in `Out` at dimensions `output_window_dims`, embedded
- with zeroes according to `elided_window_dims`.
-
-The _window index_ is the relative index of the element in _operand slice_ that
-should be present in the output at index `Out`.
-
-The output is a tensor of rank `output_window_dims.size` + `gather_indices.rank`
-- `1`. Additionally, as a shorthand, we define `output_gather_dims` of type
-`ArraySlice<int64>` as the set of dimensions in the output shape but not in
-`output_window_dims`, in ascending order. E.g. if the output tensor has rank
-`5`, `output_window_dims` is {`2`, `4`} then `output_gather_dims` is {`0`, `1`,
-`3`}
-
-If `index_vector_dim` is equal to `gather_indices.rank` we implicitly
-consider `gather_indices` to have a trailing `1` dimension (i.e. if
-`gather_indices` was of shape `[6,7]` and `index_vector_dim` is `2` then
-we implicitly consider the shape of `gather_indices` to be `[6,7,1]`).
-
-The bounds for the output tensor along dimension `i` is computed as follows:
-
- 1. If `i` is present in `output_gather_dims` (i.e. is equal to
- `output_gather_dims[k]` for some `k`) then we pick the corresponding
- dimension bounds out of `gather_indices.shape`, skipping
- `index_vector_dim` (i.e. pick `gather_indices.shape.dims`[`k`] if `k`
- < `index_vector_dim` and `gather_indices.shape.dims`[`k`+`1`]
- otherwise).
- 2. If `i` is present in `output_window_dims` (i.e. equal to
- `output_window_dims`[`k`] for some `k`) then we pick the corresponding
- bound out of `window_bounds` after accounting for `elided_window_dims`
- (i.e. we pick `adjusted_window_bounds`[`k`] where `adjusted_window_bounds`
- is `window_bounds` with the bounds at indices `elided_window_dims`
- removed).
-
-The operand index `In` corresponding to an output index `Out` is computed as
-follows:
-
- 1. Let `G` = { `Out`[`k`] for `k` in `output_gather_dims` }. Use `G` to slice
- out vector `S` such that `S`[`i`] = `gather_indices`[Combine(`G`, `i`)]
- where Combine(A, b) inserts b at position `index_vector_dim` into A.
- Note that this is well defined even if `G` is empty -- if `G` is empty then
- `S` = `gather_indices`.
- 2. Create an index, `S`<sub>`in`</sub>, into `operand` using `S` by
- scattering `S` using the `gather_dims_to_operand_dims` map
- (`S`<sub>`in`</sub> is the starting indices for _operand slice_ mentioned
- above). More precisely:
- 1. `S`<sub>`in`</sub>[`gather_dims_to_operand_dims`[`k`]] = `S`[`k`] if `k` <
- `gather_dims_to_operand_dims.size`.
+|`start_indices` | `XlaOp` | Array containing the starting |
+: : : indices of the slices we gather.:
+|`index_vector_dim` | `int64` | The dimension in |
+: : : `start_indices` that "contains" :
+: : : the starting indices. See :
+: : : below for a detailed :
+: : : description. :
+|`offset_dims` | `ArraySlice<int64>` | The set of dimensions in the :
+: : : output shape that offset into a :
+: : : array sliced from operand. :
+|`slice_sizes` | `ArraySlice<int64>` | `slice_sizes[i]` is the bounds |
+: : : for the slice on dimension `i`.:
+|`collapsed_slice_dims` | `ArraySlice<int64>` | The set of dimensions in each :
+| : | slice that are collapsed away. :
+| : | These dimensions must have size:
+| : | 1. |
+|`start_index_map` | `ArraySlice<int64>` | A map that describes how to map|
+: : : indices in `start_indices` to :
+: : : to legal indices into operand. :
+
+For convenience, we label dimensions in the output array not in `offset_dims`
+as `batch_dims`.
+
+The output is an array of rank `batch_dims.size` + `operand.rank` -
+`collapsed_slice_dims`.size.
+
+If `index_vector_dim` is equal to `start_indices.rank` we implicitly consider
+`start_indices` to have a trailing `1` dimension (i.e. if `start_indices` was of
+shape `[6,7]` and `index_vector_dim` is `2` then we implicitly consider the
+shape of `start_indices` to be `[6,7,1]`).
+
+The bounds for the output array along dimension `i` is computed as follows:
+
+ 1. If `i` is present in `batch_dims` (i.e. is equal to `batch_dims[k]` for
+ some `k`) then we pick the corresponding dimension bounds out of
+ `start_indices.shape`, skipping `index_vector_dim` (i.e. pick
+ `start_indices.shape.dims`[`k`] if `k` < `index_vector_dim` and
+ `start_indices.shape.dims`[`k`+`1`] otherwise).
+
+ 2. If `i` is present in `offset_dims` (i.e. equal to `offset_dims`[`k`] for
+ some `k`) then we pick the corresponding bound out of `slice_sizes` after
+ accounting for `collapsed_slice_dims` (i.e. we pick
+ `adjusted_slice_sizes`[`k`] where `adjusted_slice_sizes` is `slice_sizes`
+ with the bounds at indices `collapsed_slice_dims` removed).
+
+Formally, the operand index `In` corresponding to an output index `Out` is
+computed as follows:
+
+ 1. Let `G` = { `Out`[`k`] for `k` in `batch_dims` }. Use `G` to slice out
+ vector `S` such that `S`[`i`] = `start_indices`[Combine(`G`, `i`)] where
+ Combine(A, b) inserts b at position `index_vector_dim` into A. Note that
+ this is well defined even if `G` is empty -- if `G` is empty then `S` =
+ `start_indices`.
+
+ 2. Create a starting index, `S`<sub>`in`</sub>, into `operand` using `S` by
+ scattering `S` using `start_index_map`. More precisely:
+ 1. `S`<sub>`in`</sub>[`start_index_map`[`k`]] = `S`[`k`] if `k` <
+ `start_index_map.size`.
2. `S`<sub>`in`</sub>[`_`] = `0` otherwise.
- 3. Create an index `W`<sub>`in`</sub> into `operand` by scattering the indices
- at the output window dimensions in `Out` according to
- the `elided_window_dims` set (`W`<sub>`in`</sub> is the _window index_
- mentioned above). More precisely:
- 1. `W`<sub>`in`</sub>[`window_dims_to_operand_dims`(`k`)] = `Out`[`k`] if
- `k` < `output_window_dims.size` (`window_dims_to_operand_dims` is
- defined below).
- 2. `W`<sub>`in`</sub>[`_`] = `0` otherwise.
- 4. `In` is `W`<sub>`in`</sub> + `S`<sub>`in`</sub> where + is element-wise
+
+ 3. Create an index `O`<sub>`in`</sub> into `operand` by scattering the indices
+ at the offset dimensions in `Out` according to the `collapsed_slice_dims`
+ set. More precisely:
+ 1. `O`<sub>`in`</sub>[`expand_offset_dims`(`k`)] =
+ `Out`[`offset_dims`[`k`]] if `k` < `offset_dims.size`
+ (`expand_offset_dims` is defined below).
+ 2. `O`<sub>`in`</sub>[`_`] = `0` otherwise.
+ 4. `In` is `O`<sub>`in`</sub> + `S`<sub>`in`</sub> where + is element-wise
addition.
-`window_dims_to_operand_dims` is the monotonic function with domain [`0`,
-`output_window_dims.size`) and range [`0`, `operand.rank`) \
-`elided_window_dims`. So if, e.g., `output_window_dims.size` is `4`,
-`operand.rank` is `6` and `elided_window_dims` is {`0`, `2`} then
-`window_dims_to_operand_dims` is {`0`→`1`, `1`→`3`, `2`→`4`, `3`→`5`}.
+`expand_offset_dims` is the monotonic function with domain [`0`, `offset.size`)
+and range [`0`, `operand.rank`) \ `collapsed_slice_dims`. So if, e.g.,
+`offset.size` is `4`, `operand.rank` is `6` and `collapsed_slice_dims` is {`0`,
+`2`} then `expand_offset_dims` is {`0`→`1`, `1`→`3`, `2`→`4`, `3`→`5`}.
### Informal Description and Examples
-`index_vector_dim` is set to `gather_indices.rank` - `1` in all of the
-examples that follow. More interesting values for `index_vector_dim`
-does not change the operation fundamentally, but makes the visual representation
-more cumbersome.
+Informally, every index `Out` in the output array corresponds to an element `E`
+in the operand array, computed as follows:
+
+ - We use the batch dimensions in `Out` to look up a starting index from
+ `start_indices`.
+
+ - We use `start_index_map` to map the starting index (which may have size less
+ than operand.rank) to a "full" starting index into operand.
+
+ - We dynamic-slice out a slice with size `slice_sizes` using the full starting
+ index.
+
+ - We reshape the slice by collapsing the `collapsed_slice_dims` dimensions.
+ Since all collapsed slice dimensions have to have bound 1 this reshape is
+ always legal.
+
+ - We use the offset dimensions in `Out` to index into this slice to get the
+ input element, `E`, corresponding to output index `Out`.
+
+`index_vector_dim` is set to `start_indices.rank` - `1` in all of the
+examples that follow. More interesting values for `index_vector_dim` does not
+change the operation fundamentally, but makes the visual representation more
+cumbersome.
To get an intuition on how all of the above fits together, let's look at an
-example that gathers 5 slices of shape `[8,6]` from a `[16,11]` tensor. The
-position of a slice into the `[16,11]` tensor can be represented as an index
+example that gathers 5 slices of shape `[8,6]` from a `[16,11]` array. The
+position of a slice into the `[16,11]` array can be represented as an index
vector of shape `S64[2]`, so the set of 5 positions can be represented as a
-`S64[5,2]` tensor.
+`S64[5,2]` array.
The behavior of the gather operation can then be depicted as an index
-transformation that takes [`G`,`W`<sub>`0`</sub>,`W`<sub>`1`</sub>], an index in
-the output shape, and maps it to an element in the input tensor in the following
+transformation that takes [`G`,`O`<sub>`0`</sub>,`O`<sub>`1`</sub>], an index in
+the output shape, and maps it to an element in the input array in the following
way:
<div style="width:95%; margin:auto; margin-bottom:10px; margin-top:20px;">
<img style="width:100%" src="../../images/ops_xla_gather_0.svg">
</div>
-We first select an (`X`,`Y`) vector from the gather indices tensor using `G`.
-The element in the output tensor at index
-[`G`,`W`<sub>`0`</sub>,`W`<sub>`1`</sub>] is then the element in the input
-tensor at index [`X`+`W`<sub>`0`</sub>,`Y`+`W`<sub>`1`</sub>].
+We first select an (`X`,`Y`) vector from the gather indices array using `G`.
+The element in the output array at index
+[`G`,`O`<sub>`0`</sub>,`O`<sub>`1`</sub>] is then the element in the input
+array at index [`X`+`O`<sub>`0`</sub>,`Y`+`O`<sub>`1`</sub>].
-`window_bounds` is `[8,6]`, which decides the range of W<sub>`0`</sub> and
+`slice_sizes` is `[8,6]`, which decides the range of W<sub>`0`</sub> and
W<sub>`1`</sub>, and this in turn decides the bounds of the slice.
This gather operation acts as a batch dynamic slice with `G` as the batch
dimension.
The gather indices may be multidimensional. For instance, a more general
-version of the example above using a "gather indices" tensor of shape `[4,5,2]`
+version of the example above using a "gather indices" array of shape `[4,5,2]`
would translate indices like this:
<div style="width:95%; margin:auto; margin-bottom:10px; margin-top:20px;">
@@ -1279,25 +1288,25 @@ would translate indices like this:
</div>
Again, this acts as a batch dynamic slice `G`<sub>`0`</sub> and
-`G`<sub>`1`</sub> as the batch dimensions. The window bounds are still `[8,6]`.
+`G`<sub>`1`</sub> as the batch dimensions. The slice size is still `[8,6]`.
The gather operation in XLA generalizes the informal semantics outlined above in
the following ways:
- 1. We can configure which dimensions in the output shape are the window
- dimensions (dimensions containing `W`<sub>`0`</sub>, `W`<sub>`1`</sub> in
- the last example). The output gather dimensions (dimensions containing
+ 1. We can configure which dimensions in the output shape are the offset
+ dimensions (dimensions containing `O`<sub>`0`</sub>, `O`<sub>`1`</sub> in
+ the last example). The output batch dimensions (dimensions containing
`G`<sub>`0`</sub>, `G`<sub>`1`</sub> in the last example) are defined to be
- the output dimensions that are not window dimensions.
+ the output dimensions that are not offset dimensions.
- 2. The number of output window dimensions explicitly present in the output
+ 2. The number of output offset dimensions explicitly present in the output
shape may be smaller than the input rank. These "missing" dimensions, which
- are listed explicitly as `elided_window_dims`, must have a window bound of
- `1`. Since they have a window bound of `1` the only valid index for them is
+ are listed explicitly as `collapsed_slice_dims`, must have a slice size of
+ `1`. Since they have a slice size of `1` the only valid index for them is
`0` and eliding them does not introduce ambiguity.
- 3. The slice extracted from the "Gather Indices" tensor ((`X`, `Y`) in the last
- example) may have fewer elements than the input tensor rank, and an explicit
+ 3. The slice extracted from the "Gather Indices" array ((`X`, `Y`) in the last
+ example) may have fewer elements than the input array rank, and an explicit
mapping dictates how the index should be expanded to have the same rank as
the input.
@@ -1308,20 +1317,19 @@ As a final example, we use (2) and (3) to implement `tf.gather_nd`:
</div>
`G`<sub>`0`</sub> and `G`<sub>`1`</sub> are used to slice out a starting index
-from the gather indices tensor as usual, except the starting index has only one
-element, `X`. Similarly, there is only one output window index with the value
-`W`<sub>`0`</sub>. However, before being used as indices into the input tensor,
-these are expanded in accordance to "Gather Index Mapping"
-(`gather_dims_to_operand_dims` in the formal description) and "Window Mapping"
-(`window_dims_to_operand_dims` in the formal description) into
-[`0`,`W`<sub>`0`</sub>] and [`X`,`0`] respectively, adding up to
-[`X`,`W`<sub>`0`</sub>]. In other words, the output index
-[`G`<sub>`0`</sub>,`G`<sub>`1`</sub>,`W`<sub>`0`</sub>] maps to the input index
+from the gather indices array as usual, except the starting index has only one
+element, `X`. Similarly, there is only one output offset index with the value
+`O`<sub>`0`</sub>. However, before being used as indices into the input array,
+these are expanded in accordance to "Gather Index Mapping" (`start_index_map` in
+the formal description) and "Offset Mapping" (`expand_offset_dims` in the formal
+description) into [`0`,`O`<sub>`0`</sub>] and [`X`,`0`] respectively, adding up
+to [`X`,`O`<sub>`0`</sub>]. In other words, the output index
+[`G`<sub>`0`</sub>,`G`<sub>`1`</sub>,`O`<sub>`0`</sub>] maps to the input index
[`GatherIndices`[`G`<sub>`0`</sub>,`G`<sub>`1`</sub>,`0`],`X`] which gives us
the semantics for `tf.gather_nd`.
-`window_bounds` for this case is `[1,11]`. Intuitively this means that every
-index `X` in the gather indices tensor picks an entire row and the result is the
+`slice_sizes` for this case is `[1,11]`. Intuitively this means that every
+index `X` in the gather indices array picks an entire row and the result is the
concatenation of all these rows.
## GetTupleElement
@@ -1877,19 +1885,19 @@ See also
[`XlaBuilder::RngNormal`](https://www.tensorflow.org/code/tensorflow/compiler/xla/client/xla_builder.h).
Constructs an output of a given shape with random numbers generated following
-the $$N(\mu, \sigma)$$ normal distribution. The parameters `mu` and `sigma`, and
-output shape have to have elemental type F32. The parameters furthermore have to
-be scalar valued.
+the $$N(\mu, \sigma)$$ normal distribution. The parameters $$\mu$$ and
+$$\sigma$$, and output shape have to have a floating point elemental type. The
+parameters furthermore have to be scalar valued.
-<b>`RngNormal(mean, sigma, shape)`</b>
+<b>`RngNormal(mu, sigma, shape)`</b>
| Arguments | Type | Semantics |
| --------- | ------- | --------------------------------------------------- |
-| `mu` | `XlaOp` | Scalar of type F32 specifying mean of generated |
-: : : numbers :
-| `sigma` | `XlaOp` | Scalar of type F32 specifying standard deviation of |
+| `mu` | `XlaOp` | Scalar of type T specifying mean of generated |
+: : : numbers :
+| `sigma` | `XlaOp` | Scalar of type T specifying standard deviation of |
: : : generated numbers :
-| `shape` | `Shape` | Output shape of type F32 |
+| `shape` | `Shape` | Output shape of type T |
## RngUniform
@@ -1898,9 +1906,11 @@ See also
Constructs an output of a given shape with random numbers generated following
the uniform distribution over the interval $$[a,b)$$. The parameters and output
-shape may be either F32, S32 or U32, but the types have to be consistent.
-Furthermore, the parameters need to be scalar valued. If $$b <= a$$ the result
-is implementation-defined.
+element type have to be a boolean type, an integral type or a floating point
+types, and the types have to be consistent. The CPU and GPU backends currently
+only support F64, F32, F16, BF16, S64, U64, S32 and U32. Furthermore, the
+parameters need to be scalar valued. If $$b <= a$$ the result is
+implementation-defined.
<b>`RngUniform(a, b, shape)`</b>
@@ -2383,8 +2393,6 @@ restrictions listed below.
last execution of the `body`.
* The shape of the type `T` is statically determined and must be the same
across all iterations.
-* `While` nodes are not allowed to be nested. (This restriction may be lifted
- in the future on some targets.)
The T parameters of the computations are initialized with the `init` value in
the first iteration and are automatically updated to the new result from `body`
diff --git a/tensorflow/docs_src/performance/xla/tfcompile.md b/tensorflow/docs_src/performance/xla/tfcompile.md
index e4b803164f..2e0f3774c4 100644
--- a/tensorflow/docs_src/performance/xla/tfcompile.md
+++ b/tensorflow/docs_src/performance/xla/tfcompile.md
@@ -17,7 +17,7 @@ kernels that are actually used in the computation.
The compiler is built on top of the XLA framework. The code bridging TensorFlow
to the XLA framework resides under
[tensorflow/compiler](https://www.tensorflow.org/code/tensorflow/compiler/),
-which also includes support for @{$jit$just-in-time (JIT) compilation} of
+which also includes support for [just-in-time (JIT) compilation](../../performance/xla/jit.md) of
TensorFlow graphs.
## What does tfcompile do?
@@ -116,7 +116,7 @@ tf_library(
> [make_test_graphs.py]("https://www.tensorflow.org/code/tensorflow/compiler/aot/tests/make_test_graphs.py")
> and specify the output location with the --out_dir flag.
-Typical graphs contain @{$python/state_ops$`Variables`}
+Typical graphs contain [`Variables`](../../api_guides/python/state_ops.md)
representing the weights that are learned via training, but `tfcompile` cannot
compile a subgraph that contain `Variables`. The
[freeze_graph.py](https://www.tensorflow.org/code/tensorflow/python/tools/freeze_graph.py)
diff --git a/tensorflow/docs_src/tutorials/_toc.yaml b/tensorflow/docs_src/tutorials/_toc.yaml
index d33869af6e..c0b85497e0 100644
--- a/tensorflow/docs_src/tutorials/_toc.yaml
+++ b/tensorflow/docs_src/tutorials/_toc.yaml
@@ -37,9 +37,6 @@ toc:
status: external
- title: "Custom training: walkthrough"
path: /tutorials/eager/custom_training_walkthrough
- - title: Translation with attention
- path: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb
- status: external
- title: ML at production scale
style: accordion
@@ -57,9 +54,37 @@ toc:
- title: Build a CNN using Estimators
path: /tutorials/estimators/cnn
+- title: Generative models
+ style: accordion
+ section:
+ - title: Text generation
+ path: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/text_generation.ipynb
+ status: external
+ - title: Translation with attention
+ path: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb
+ status: external
+ - title: Image captioning
+ path: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/image_captioning_with_attention.ipynb
+ status: external
+ - title: DCGAN
+ path: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb
+ status: external
+ - title: VAE
+ path: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/generative_examples/cvae.ipynb
+ status: external
+
- title: Images
style: accordion
section:
+ - title: Pix2Pix
+ path: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/pix2pix/pix2pix_eager.ipynb
+ status: external
+ - title: Neural Style Transfer
+ path: https://github.com/tensorflow/models/blob/master/research/nst_blogpost/4_Neural_Style_Transfer_with_Eager_Execution.ipynb
+ status: external
+ - title: Image Segmentation
+ path: https://github.com/tensorflow/models/blob/master/samples/outreach/blogs/segmentation_blogpost/image_segmentation.ipynb
+ status: external
- title: Image recognition
path: /tutorials/images/image_recognition
- title: Image retraining
diff --git a/tensorflow/docs_src/tutorials/eager/index.md b/tensorflow/docs_src/tutorials/eager/index.md
index a13b396094..887c820b85 100644
--- a/tensorflow/docs_src/tutorials/eager/index.md
+++ b/tensorflow/docs_src/tutorials/eager/index.md
@@ -10,4 +10,3 @@ auto&nbsp;differentiation. Start with these notebooks, then read the
3. <span>[Custom training: basics](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/custom_training.ipynb){:.external}</span>
4. <span>[Custom layers](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/custom_layers.ipynb){:.external}</span>
5. [Custom training: walkthrough](/tutorials/eager/custom_training_walkthrough)
-6. <span>[Advanced example: Neural machine translation with attention](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/nmt_with_attention/nmt_with_attention.ipynb){:.external}</span>
diff --git a/tensorflow/docs_src/tutorials/estimators/cnn.md b/tensorflow/docs_src/tutorials/estimators/cnn.md
index 100f501cc2..2fd69f50a0 100644
--- a/tensorflow/docs_src/tutorials/estimators/cnn.md
+++ b/tensorflow/docs_src/tutorials/estimators/cnn.md
@@ -190,7 +190,7 @@ def cnn_model_fn(features, labels, mode):
The following sections (with headings corresponding to each code block above)
dive deeper into the `tf.layers` code used to create each layer, as well as how
to calculate loss, configure the training op, and generate predictions. If
-you're already experienced with CNNs and @{$custom_estimators$TensorFlow `Estimator`s},
+you're already experienced with CNNs and [TensorFlow `Estimator`s](../../guide/custom_estimators.md),
and find the above code intuitive, you may want to skim these sections or just
skip ahead to ["Training and Evaluating the CNN MNIST Classifier"](#train_eval_mnist).
@@ -501,8 +501,8 @@ if mode == tf.estimator.ModeKeys.TRAIN:
```
> Note: For a more in-depth look at configuring training ops for Estimator model
-> functions, see @{$custom_estimators#defining-the-training-op-for-the-model$"Defining the training op for the model"}
-> in the @{$custom_estimators$"Creating Estimations in tf.estimator"} tutorial.
+> functions, see ["Defining the training op for the model"](../../guide/custom_estimators.md#defining-the-training-op-for-the-model)
+> in the ["Creating Estimations in tf.estimator"](../../guide/custom_estimators.md) tutorial.
### Add evaluation metrics
@@ -567,7 +567,7 @@ be saved (here, we specify the temp directory `/tmp/mnist_convnet_model`, but
feel free to change to another directory of your choice).
> Note: For an in-depth walkthrough of the TensorFlow `Estimator` API, see the
-> tutorial @{$custom_estimators$"Creating Estimators in tf.estimator."}
+> tutorial ["Creating Estimators in tf.estimator."](../../guide/custom_estimators.md)
### Set Up a Logging Hook {#set_up_a_logging_hook}
@@ -593,8 +593,8 @@ operation earlier when we generated the probabilities in `cnn_model_fn`.
> Note: If you don't explicitly assign a name to an operation via the `name`
> 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
-> @{$guide/debugger$TensorFlow Debugger (tfdbg)}.
+> [TensorBoard](../../guide/graph_viz.md)) or to enable the
+> [TensorFlow Debugger (tfdbg)](../../guide/debugger.md).
Next, we create the `LoggingTensorHook`, passing `tensors_to_log` to the
`tensors` argument. We set `every_n_iter=50`, which specifies that probabilities
@@ -686,9 +686,9 @@ Here, we've achieved an accuracy of 97.3% on our test data set.
To learn more about TensorFlow Estimators and CNNs in TensorFlow, see the
following resources:
-* @{$custom_estimators$Creating Estimators in tf.estimator}
+* [Creating Estimators in tf.estimator](../../guide/custom_estimators.md)
provides an introduction to the TensorFlow Estimator API. It walks through
configuring an Estimator, writing a model function, calculating loss, and
defining a training op.
-* @{$deep_cnn} walks through how to build a MNIST CNN classification model
+* [Advanced Convolutional Neural Networks](../../tutorials/images/deep_cnn.md) walks through how to build a MNIST CNN classification model
*without estimators* using lower-level TensorFlow operations.
diff --git a/tensorflow/docs_src/tutorials/images/deep_cnn.md b/tensorflow/docs_src/tutorials/images/deep_cnn.md
index 42ad484bbf..00996b82e6 100644
--- a/tensorflow/docs_src/tutorials/images/deep_cnn.md
+++ b/tensorflow/docs_src/tutorials/images/deep_cnn.md
@@ -40,7 +40,7 @@ designing larger and more sophisticated models in TensorFlow:
and `tf.nn.local_response_normalization`
(Chapter 3.3 in
[AlexNet paper](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)).
-* @{$summaries_and_tensorboard$Visualization}
+* [Visualization](../../guide/summaries_and_tensorboard.md)
of network activities during training, including input images,
losses and distributions of activations and gradients.
* Routines for calculating the
@@ -114,7 +114,7 @@ The input part of the model is built by the functions `inputs()` and
`distorted_inputs()` which read images from the CIFAR-10 binary data files.
These files contain fixed byte length records, so we use
`tf.FixedLengthRecordReader`.
-See @{$reading_data#reading-from-files$Reading Data} to
+See [Reading Data](../../api_guides/python/reading_data.md#reading-from-files) to
learn more about how the `Reader` class works.
The images are processed as follows:
@@ -131,10 +131,10 @@ artificially increase the data set size:
* Randomly distort the `tf.image.random_brightness`.
* Randomly distort the `tf.image.random_contrast`.
-Please see the @{$python/image$Images} page for the list of
+Please see the [Images](../../api_guides/python/image.md) page for the list of
available distortions. We also attach an
`tf.summary.image` to the images
-so that we may visualize them in @{$summaries_and_tensorboard$TensorBoard}.
+so that we may visualize them in [TensorBoard](../../guide/summaries_and_tensorboard.md).
This is a good practice to verify that inputs are built correctly.
<div style="width:50%; margin:auto; margin-bottom:10px; margin-top:20px;">
@@ -160,8 +160,8 @@ Layer Name | Description
`conv2` | `tf.nn.conv2d` and `tf.nn.relu` activation.
`norm2` | `tf.nn.local_response_normalization`.
`pool2` | `tf.nn.max_pool`.
-`local3` | @{$python/nn$fully connected layer with rectified linear activation}.
-`local4` | @{$python/nn$fully connected layer with rectified linear activation}.
+`local3` | [fully connected layer with rectified linear activation](../../api_guides/python/nn.md).
+`local4` | [fully connected layer with rectified linear activation](../../api_guides/python/nn.md).
`softmax_linear` | linear transformation to produce logits.
Here is a graph generated from TensorBoard describing the inference operation:
@@ -205,7 +205,7 @@ We visualize it in TensorBoard with a `tf.summary.scalar`:
We train the model using standard
[gradient descent](https://en.wikipedia.org/wiki/Gradient_descent)
-algorithm (see @{$python/train$Training} for other methods)
+algorithm (see [Training](../../api_guides/python/train.md) for other methods)
with a learning rate that
`tf.train.exponential_decay`
over time.
@@ -265,7 +265,7 @@ in `cifar10_input.py`.
`cifar10_train.py` periodically uses a `tf.train.Saver` to save
all model parameters in
-@{$guide/saved_model$checkpoint files}
+[checkpoint files](../../guide/saved_model.md)
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).
@@ -282,7 +282,7 @@ how the model is training. We want more insight into the model during training:
* Are the gradients, activations and weights reasonable?
* What is the learning rate currently at?
-@{$summaries_and_tensorboard$TensorBoard} provides this
+[TensorBoard](../../guide/summaries_and_tensorboard.md) provides this
functionality, displaying data exported periodically from `cifar10_train.py` via
a
`tf.summary.FileWriter`.
@@ -413,7 +413,7 @@ scope indicating that they should be run on the first GPU.
All variables are pinned to the CPU and accessed via
`tf.get_variable`
in order to share them in a multi-GPU version.
-See how-to on @{$variables$Sharing Variables}.
+See how-to on [Sharing Variables](../../guide/variables.md).
### Launching and Training the Model on Multiple GPU cards
diff --git a/tensorflow/docs_src/tutorials/images/image_recognition.md b/tensorflow/docs_src/tutorials/images/image_recognition.md
index 83a8d97cf0..52913b2082 100644
--- a/tensorflow/docs_src/tutorials/images/image_recognition.md
+++ b/tensorflow/docs_src/tutorials/images/image_recognition.md
@@ -106,7 +106,7 @@ curl -L "https://storage.googleapis.com/download.tensorflow.org/models/inception
Next, we need to compile the C++ binary that includes the code to load and run the graph.
If you've followed
-@{$install_sources$the instructions to download the source installation of TensorFlow}
+[the instructions to download the source installation of TensorFlow](../../install/install_sources.md)
for your platform, you should be able to build the example by
running this command from your shell terminal:
@@ -448,7 +448,7 @@ and Michael Nielsen's book has a
covering them.
To find out more about implementing convolutional neural networks, you can jump
-to the TensorFlow @{$deep_cnn$deep convolutional networks tutorial},
+to the TensorFlow [deep convolutional networks tutorial](../../tutorials/images/deep_cnn.md),
or start a bit more gently with our [Estimator MNIST tutorial](../estimators/cnn.md).
Finally, if you want to get up to speed on research in this area, you can
read the recent work of all the papers referenced in this tutorial.
diff --git a/tensorflow/docs_src/tutorials/representation/kernel_methods.md b/tensorflow/docs_src/tutorials/representation/kernel_methods.md
index 71e87f4d3e..67adc4951c 100644
--- a/tensorflow/docs_src/tutorials/representation/kernel_methods.md
+++ b/tensorflow/docs_src/tutorials/representation/kernel_methods.md
@@ -2,7 +2,7 @@
Note: This document uses a deprecated version of `tf.estimator`,
`tf.contrib.learn.Estimator`, which has a different interface. It also uses
-other `contrib` methods whose @{$version_compat#not_covered$API may not be stable}.
+other `contrib` methods whose [API may not be stable](../../guide/version_compat.md#not_covered).
In this tutorial, we demonstrate how combining (explicit) kernel methods with
linear models can drastically increase the latters' quality of predictions
@@ -52,7 +52,7 @@ In order to feed data to a `tf.contrib.learn Estimator`, it is helpful to conver
it to Tensors. For this, we will use an `input function` which adds Ops to the
TensorFlow graph that, when executed, create mini-batches of Tensors to be used
downstream. For more background on input functions, check
-@{$premade_estimators#create_input_functions$this section on input functions}.
+[this section on input functions](../../guide/premade_estimators.md#create_input_functions).
In this example, we will use the `tf.train.shuffle_batch` Op which, besides
converting numpy arrays to Tensors, allows us to specify the batch_size and
whether to randomize the input every time the input_fn Ops are executed
diff --git a/tensorflow/docs_src/tutorials/representation/linear.md b/tensorflow/docs_src/tutorials/representation/linear.md
index 014409c617..4f0e67f08e 100644
--- a/tensorflow/docs_src/tutorials/representation/linear.md
+++ b/tensorflow/docs_src/tutorials/representation/linear.md
@@ -18,7 +18,7 @@ tutorial walks through the code in greater detail.
To understand this overview it will help to have some familiarity
with basic machine learning concepts, and also with
-@{$premade_estimators$Estimators}.
+[Estimators](../../guide/premade_estimators.md).
[TOC]
@@ -175,7 +175,7 @@ the data itself. You provide the data through an input function.
The input function must return a dictionary of tensors. Each key corresponds to
the name of a `FeatureColumn`. Each key's value is a tensor containing the
values of that feature for all data instances. See
-@{$premade_estimators#input_fn} for a
+[Premade Estimators](../../guide/premade_estimators.md#input_fn) for a
more comprehensive look at input functions, and `input_fn` in the
[wide and deep learning tutorial](https://github.com/tensorflow/models/tree/master/official/wide_deep)
for an example implementation of an input function.
diff --git a/tensorflow/docs_src/tutorials/representation/word2vec.md b/tensorflow/docs_src/tutorials/representation/word2vec.md
index 7964650e19..df0d3176b6 100644
--- a/tensorflow/docs_src/tutorials/representation/word2vec.md
+++ b/tensorflow/docs_src/tutorials/representation/word2vec.md
@@ -383,13 +383,13 @@ compromised speed because we use Python for reading and feeding data items --
each of which require very little work on the TensorFlow back-end. If you find
your model is seriously bottlenecked on input data, you may want to implement a
custom data reader for your problem, as described in
-@{$new_data_formats$New Data Formats}. For the case of Skip-Gram
+[New Data Formats](../../extend/new_data_formats.md). For the case of Skip-Gram
modeling, we've actually already done this for you as an example in
[models/tutorials/embedding/word2vec.py](https://github.com/tensorflow/models/tree/master/tutorials/embedding/word2vec.py).
If your model is no longer I/O bound but you want still more performance, you
can take things further by writing your own TensorFlow Ops, as described in
-@{$adding_an_op$Adding a New Op}. Again we've provided an
+[Adding a New Op](../../extend/adding_an_op.md). Again we've provided an
example of this for the Skip-Gram case
[models/tutorials/embedding/word2vec_optimized.py](https://github.com/tensorflow/models/tree/master/tutorials/embedding/word2vec_optimized.py).
Feel free to benchmark these against each other to measure performance
diff --git a/tensorflow/docs_src/tutorials/sequences/recurrent.md b/tensorflow/docs_src/tutorials/sequences/recurrent.md
index 715cc7856a..39ad441381 100644
--- a/tensorflow/docs_src/tutorials/sequences/recurrent.md
+++ b/tensorflow/docs_src/tutorials/sequences/recurrent.md
@@ -77,9 +77,7 @@ The basic pseudocode is as follows:
words_in_dataset = tf.placeholder(tf.float32, [time_steps, batch_size, num_features])
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
# Initial state of the LSTM memory.
-hidden_state = tf.zeros([batch_size, lstm.state_size])
-current_state = tf.zeros([batch_size, lstm.state_size])
-state = hidden_state, current_state
+state = lstm.zero_state(batch_size, dtype=tf.float32)
probabilities = []
loss = 0.0
for current_batch_of_words in words_in_dataset:
@@ -112,7 +110,7 @@ words = tf.placeholder(tf.int32, [batch_size, num_steps])
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
# Initial state of the LSTM memory.
-initial_state = state = tf.zeros([batch_size, lstm.state_size])
+initial_state = state = lstm.zero_state(batch_size, dtype=tf.float32)
for i in range(num_steps):
# The value of state is updated after processing each batch of words.
@@ -140,7 +138,7 @@ for current_batch_of_words in words_in_dataset:
### Inputs
The word IDs will be embedded into a dense representation (see the
-@{$word2vec$Vector Representations Tutorial}) before feeding to
+[Vector Representations Tutorial](../../tutorials/representation/word2vec.md)) before feeding to
the LSTM. This allows the model to efficiently represent the knowledge about
particular words. It is also easy to write:
diff --git a/tensorflow/docs_src/tutorials/sequences/recurrent_quickdraw.md b/tensorflow/docs_src/tutorials/sequences/recurrent_quickdraw.md
index 37bce5b76d..657fab8a53 100644
--- a/tensorflow/docs_src/tutorials/sequences/recurrent_quickdraw.md
+++ b/tensorflow/docs_src/tutorials/sequences/recurrent_quickdraw.md
@@ -32,7 +32,7 @@ drawings in 345 categories.
To try the code for this tutorial:
-1. @{$install$Install TensorFlow} if you haven't already.
+1. [Install TensorFlow](../../install/index.md) if you haven't already.
1. Download the [tutorial code]
(https://github.com/tensorflow/models/tree/master/tutorials/rnn/quickdraw/train_model.py).
1. [Download the data](#download-the-data) in `TFRecord` format from
@@ -58,8 +58,7 @@ To try the code for this tutorial:
We make the data that we use in this tutorial available as `TFRecord` files
containing `TFExamples`. You can download the data from here:
-
-http://download.tensorflow.org/data/quickdraw_tutorial_dataset_v1.tar.gz
+<a rel="nofollow" href="http://download.tensorflow.org/data/quickdraw_tutorial_dataset_v1.tar.gz">http://download.tensorflow.org/data/quickdraw_tutorial_dataset_v1.tar.gz</a> (~1GB).
Alternatively you can download the original data in `ndjson` format from the
Google cloud and convert it to the `TFRecord` files containing `TFExamples`
@@ -108,7 +107,7 @@ This download will take a while and download a bit more than 23GB of data.
### Optional: Converting the data
To convert the `ndjson` files to
-@{$python/python_io#TFRecords_Format_Details$TFRecord} files containing
+[TFRecord](../../api_guides/python/python_io.md#TFRecords_Format_Details) files containing
[`tf.train.Example`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto)
protos run the following command.
@@ -118,7 +117,7 @@ protos run the following command.
```
This will store the data in 10 shards of
-@{$python/python_io#TFRecords_Format_Details$TFRecord} files with 10000 items
+[TFRecord](../../api_guides/python/python_io.md#TFRecords_Format_Details) files with 10000 items
per class for the training data and 1000 items per class as eval data.
This conversion process is described in more detail in the following.
@@ -220,7 +219,7 @@ length 2.
### Defining the model
To define the model we create a new `Estimator`. If you want to read more about
-estimators, we recommend @{$custom_estimators$this tutorial}.
+estimators, we recommend [this tutorial](../../guide/custom_estimators.md).
To build the model, we:
diff --git a/tensorflow/examples/android/.gitignore b/tensorflow/examples/android/.gitignore
new file mode 100644
index 0000000000..d245ab6109
--- /dev/null
+++ b/tensorflow/examples/android/.gitignore
@@ -0,0 +1,29 @@
+# This file is based on https://github.com/github/gitignore/blob/master/Android.gitignore
+*.iml
+.idea/compiler.xml
+.idea/copyright
+.idea/dictionaries
+.idea/gradle.xml
+.idea/libraries
+.idea/inspectionProfiles
+.idea/misc.xml
+.idea/modules.xml
+.idea/runConfigurations.xml
+.idea/tasks.xml
+.idea/workspace.xml
+.gradle
+local.properties
+.DS_Store
+build/
+gradleBuild/
+*.apk
+*.ap_
+*.dex
+*.class
+bin/
+gen/
+out/
+*.log
+.navigation/
+/captures
+.externalNativeBuild
diff --git a/tensorflow/examples/android/README.md b/tensorflow/examples/android/README.md
index 30a26d13c5..dac9b7ab82 100644
--- a/tensorflow/examples/android/README.md
+++ b/tensorflow/examples/android/README.md
@@ -45,11 +45,7 @@ on API >= 14 devices.
## Prebuilt Components:
-If you just want the fastest path to trying the demo, you may download the
-nightly build
-[here](https://ci.tensorflow.org/view/Nightly/job/nightly-android/). Expand the
-"View" and then the "out" folders under "Last Successful Artifacts" to find
-tensorflow_demo.apk.
+The fastest path to trying the demo is to download the [prebuilt demo APK](http://download.tensorflow.org/deps/tflite/TfLiteCameraDemo.apk).
Also available are precompiled native libraries, and a jcenter package that you
may simply drop into your own applications. See
@@ -113,8 +109,7 @@ protobuf compilation.
NOTE: Bazel does not currently support building for Android on Windows. Full
support for gradle/cmake builds is coming soon, but in the meantime we suggest
-that Windows users download the [prebuilt
-binaries](https://ci.tensorflow.org/view/Nightly/job/nightly-android/) instead.
+that Windows users download the [prebuilt demo APK](http://download.tensorflow.org/deps/tflite/TfLiteCameraDemo.apk) instead.
##### Install Bazel and Android Prerequisites
diff --git a/tensorflow/examples/ios/README.md b/tensorflow/examples/ios/README.md
index 5d7bd36837..64412d25a0 100644
--- a/tensorflow/examples/ios/README.md
+++ b/tensorflow/examples/ios/README.md
@@ -190,8 +190,5 @@ increase you see in your own app is similar, and if it's larger, look at the
"Other Linker Flags" used in the Simple Xcode project settings to strip the
executable.
-After that, you can manually look at modifying the list of kernels
-included in tensorflow/contrib/makefile/tf_op_files.txt to reduce the number of
-implementations to the ones you're actually using in your own model. We're
-hoping to automate this step in the future, but for now manually removing them
-is the best approach.
+For further optimization, please refer to the ["Optimization" section](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/makefile#optimization)
+of the makefile instructions.
diff --git a/tensorflow/examples/ios/benchmark/ios_image_load.h b/tensorflow/examples/ios/benchmark/ios_image_load.h
index 78eaded8d7..3f94984692 100644
--- a/tensorflow/examples/ios/benchmark/ios_image_load.h
+++ b/tensorflow/examples/ios/benchmark/ios_image_load.h
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#ifndef TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
-#define TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
+#ifndef TENSORFLOW_EXAMPLES_IOS_BENCHMARK_IOS_IMAGE_LOAD_H_
+#define TENSORFLOW_EXAMPLES_IOS_BENCHMARK_IOS_IMAGE_LOAD_H_
#include <vector>
@@ -24,4 +24,4 @@ std::vector<tensorflow::uint8> LoadImageFromFile(const char* file_name,
int* out_height,
int* out_channels);
-#endif // TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
+#endif // TENSORFLOW_EXAMPLES_IOS_BENCHMARK_IOS_IMAGE_LOAD_H_
diff --git a/tensorflow/examples/ios/camera/ios_image_load.h b/tensorflow/examples/ios/camera/ios_image_load.h
index 87a847e145..f10b0b983a 100644
--- a/tensorflow/examples/ios/camera/ios_image_load.h
+++ b/tensorflow/examples/ios/camera/ios_image_load.h
@@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#ifndef TENSORFLOW_CONTRIB_IOS_EXAMPLES_CAMERA_IMAGE_LOAD_H_
-#define TENSORFLOW_CONTRIB_IOS_EXAMPLES_CAMERA_IMAGE_LOAD_H_
+#ifndef TENSORFLOW_EXAMPLES_IOS_CAMERA_IOS_IMAGE_LOAD_H_
+#define TENSORFLOW_EXAMPLES_IOS_CAMERA_IOS_IMAGE_LOAD_H_
#include <vector>
@@ -24,4 +24,4 @@ std::vector<tensorflow::uint8> LoadImageFromFile(const char* file_name,
int* out_height,
int* out_channels);
-#endif // TENSORFLOW_CONTRIB_IOS_EXAMPLES_CAMERA_IMAGE_LOAD_H_
+#endif // TENSORFLOW_EXAMPLES_IOS_CAMERA_IOS_IMAGE_LOAD_H_
diff --git a/tensorflow/g3doc/README.txt b/tensorflow/g3doc/README.txt
index ed648f8b6b..515a9e9a02 100644
--- a/tensorflow/g3doc/README.txt
+++ b/tensorflow/g3doc/README.txt
@@ -22,12 +22,12 @@ When authoring docs, note that we have some new syntax for references --
at least for docs coming from Python docstrings or
tensorflow/docs_src/. Use:
-* @{tf.symbol} to make a link to the reference page for a Python
+* `tf.symbol` to make a link to the reference page for a Python
symbol. Note that class members don't get their own page, but the
- syntax still works, since @{tf.MyClass.method} links to the right
+ syntax still works, since `tf.MyClass.method` links to the right
part of the tf.MyClass page.
-* @{tensorflow::symbol} to make a link to the reference page for a C++
+* `tensorflow::symbol` to make a link to the reference page for a C++
symbol. (This only works for a few symbols but will work for more soon.)
* @{$doc_page} to make a link to another (not an API reference) doc
diff --git a/tensorflow/go/op/wrappers.go b/tensorflow/go/op/wrappers.go
index 9015cd616c..de096acc4d 100644
--- a/tensorflow/go/op/wrappers.go
+++ b/tensorflow/go/op/wrappers.go
@@ -3355,6 +3355,28 @@ func BitwiseXor(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {
return op.Output(0)
}
+// Computes element-wise population count (a.k.a. popcount, bitsum, bitcount).
+//
+// For each entry in `x`, calculates the number of `1` (on) bits in the binary
+// representation of that entry.
+//
+// **NOTE**: It is more efficient to first `tf.bitcast` your tensors into
+// `int32` or `int64` and perform the bitcount on the result, than to feed in
+// 8- or 16-bit inputs and then aggregate the resulting counts.
+func PopulationCount(scope *Scope, x tf.Output) (y tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "PopulationCount",
+ Input: []tf.Input{
+ x,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
// Computes the mean along sparse segments of a tensor.
//
// Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
@@ -4037,66 +4059,6 @@ func SlideDataset(scope *Scope, input_dataset tf.Output, window_size tf.Output,
return op.Output(0)
}
-// Computes the sum along sparse segments of a tensor divided by the sqrt of N.
-//
-// N is the size of the segment being reduced.
-//
-// Like `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is
-// misisng, the `output` tensor at that position will be zeroed.
-//
-// Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-// segments.
-//
-// Arguments:
-//
-// indices: A 1-D tensor. Has same rank as `segment_ids`.
-// segment_ids: A 1-D tensor. Values should be sorted and can be repeated.
-// num_segments: Should equal the number of distinct segment IDs.
-//
-// Returns Has same shape as data, except for dimension 0 which
-// has size `k`, the number of segments.
-func SparseSegmentSqrtNWithNumSegments(scope *Scope, data tf.Output, indices tf.Output, segment_ids tf.Output, num_segments tf.Output) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "SparseSegmentSqrtNWithNumSegments",
- Input: []tf.Input{
- data, indices, segment_ids, num_segments,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
-// Compute the upper regularized incomplete Gamma function `Q(a, x)`.
-//
-// The upper regularized incomplete Gamma function is defined as:
-//
-// \\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\)
-//
-// where
-//
-// \\(Gamma(a, x) = int_{x}^{\infty} t^{a-1} exp(-t) dt\\)
-//
-// is the upper incomplete Gama function.
-//
-// Note, above `P(a, x)` (`Igamma`) is the lower regularized complete
-// Gamma function.
-func Igammac(scope *Scope, a tf.Output, x tf.Output) (z tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "Igammac",
- Input: []tf.Input{
- a, x,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// ApproximateEqualAttr is an optional argument to ApproximateEqual.
type ApproximateEqualAttr func(optionalAttr)
@@ -8407,139 +8369,6 @@ func OrderedMapIncompleteSize(scope *Scope, dtypes []tf.DataType, optional ...Or
return op.Output(0)
}
-// DepthwiseConv2dNativeBackpropFilterAttr is an optional argument to DepthwiseConv2dNativeBackpropFilter.
-type DepthwiseConv2dNativeBackpropFilterAttr func(optionalAttr)
-
-// DepthwiseConv2dNativeBackpropFilterDataFormat sets the optional data_format attribute to value.
-//
-// value: Specify the data format of the input and output data. With the
-// default format "NHWC", the data is stored in the order of:
-// [batch, height, width, channels].
-// Alternatively, the format could be "NCHW", the data storage order of:
-// [batch, channels, height, width].
-// If not specified, defaults to "NHWC"
-func DepthwiseConv2dNativeBackpropFilterDataFormat(value string) DepthwiseConv2dNativeBackpropFilterAttr {
- return func(m optionalAttr) {
- m["data_format"] = value
- }
-}
-
-// DepthwiseConv2dNativeBackpropFilterDilations sets the optional dilations attribute to value.
-//
-// value: 1-D tensor of length 4. The dilation factor for each dimension of
-// `input`. If set to k > 1, there will be k-1 skipped cells between each filter
-// element on that dimension. The dimension order is determined by the value of
-// `data_format`, see above for details. Dilations in the batch and depth
-// dimensions must be 1.
-// If not specified, defaults to <i:1 i:1 i:1 i:1 >
-func DepthwiseConv2dNativeBackpropFilterDilations(value []int64) DepthwiseConv2dNativeBackpropFilterAttr {
- return func(m optionalAttr) {
- m["dilations"] = value
- }
-}
-
-// Computes the gradients of depthwise convolution with respect to the filter.
-//
-// Arguments:
-// input: 4-D with shape based on `data_format`. For example, if
-// `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height,
-// in_width, in_channels]` tensor.
-// filter_sizes: An integer vector representing the tensor shape of `filter`,
-// where `filter` is a 4-D
-// `[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor.
-// out_backprop: 4-D with shape based on `data_format`.
-// For example, if `data_format` is 'NHWC' then
-// out_backprop shape is `[batch, out_height, out_width, out_channels]`.
-// Gradients w.r.t. the output of the convolution.
-// strides: The stride of the sliding window for each dimension of the input
-// of the convolution.
-// padding: The type of padding algorithm to use.
-//
-// Returns 4-D with shape
-// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t.
-// the `filter` input of the convolution.
-func DepthwiseConv2dNativeBackpropFilter(scope *Scope, input tf.Output, filter_sizes tf.Output, out_backprop tf.Output, strides []int64, padding string, optional ...DepthwiseConv2dNativeBackpropFilterAttr) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{"strides": strides, "padding": padding}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "DepthwiseConv2dNativeBackpropFilter",
- Input: []tf.Input{
- input, filter_sizes, out_backprop,
- },
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
-// Returns immutable tensor from memory region.
-//
-// The current implementation memmaps the tensor from a file.
-//
-// Arguments:
-// dtype: Type of the returned tensor.
-// shape: Shape of the returned tensor.
-// memory_region_name: Name of readonly memory region used by the tensor, see
-// NewReadOnlyMemoryRegionFromFile in tensorflow::Env.
-func ImmutableConst(scope *Scope, dtype tf.DataType, shape tf.Shape, memory_region_name string) (tensor tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{"dtype": dtype, "shape": shape, "memory_region_name": memory_region_name}
- opspec := tf.OpSpec{
- Type: "ImmutableConst",
-
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
-// StringJoinAttr is an optional argument to StringJoin.
-type StringJoinAttr func(optionalAttr)
-
-// StringJoinSeparator sets the optional separator attribute to value.
-//
-// value: string, an optional join separator.
-// If not specified, defaults to ""
-func StringJoinSeparator(value string) StringJoinAttr {
- return func(m optionalAttr) {
- m["separator"] = value
- }
-}
-
-// Joins the strings in the given list of string tensors into one tensor;
-//
-// with the given separator (default is an empty separator).
-//
-// Arguments:
-// inputs: A list of string tensors. The tensors must all have the same shape,
-// or be scalars. Scalars may be mixed in; these will be broadcast to the shape
-// of non-scalar inputs.
-func StringJoin(scope *Scope, inputs []tf.Output, optional ...StringJoinAttr) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "StringJoin",
- Input: []tf.Input{
- tf.OutputList(inputs),
- },
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// ResourceApplyFtrlAttr is an optional argument to ResourceApplyFtrl.
type ResourceApplyFtrlAttr func(optionalAttr)
@@ -8782,28 +8611,6 @@ func Assert(scope *Scope, condition tf.Output, data []tf.Output, optional ...Ass
return scope.AddOperation(opspec)
}
-// Computes element-wise population count (a.k.a. popcount, bitsum, bitcount).
-//
-// For each entry in `x`, calculates the number of `1` (on) bits in the binary
-// representation of that entry.
-//
-// **NOTE**: It is more efficient to first `tf.bitcast` your tensors into
-// `int32` or `int64` and perform the bitcount on the result, than to feed in
-// 8- or 16-bit inputs and then aggregate the resulting counts.
-func PopulationCount(scope *Scope, x tf.Output) (y tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "PopulationCount",
- Input: []tf.Input{
- x,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// Broadcasts a tensor value to one or more other devices.
func CollectiveBcastSend(scope *Scope, input tf.Output, group_size int64, group_key int64, instance_key int64, shape tf.Shape) (data tf.Output) {
if scope.Err() != nil {
@@ -9484,34 +9291,216 @@ func IsInf(scope *Scope, x tf.Output) (y tf.Output) {
return op.Output(0)
}
-// Computes the sum along sparse segments of a tensor divided by the sqrt of N.
+// TruncatedNormalAttr is an optional argument to TruncatedNormal.
+type TruncatedNormalAttr func(optionalAttr)
+
+// TruncatedNormalSeed sets the optional seed attribute to value.
//
-// N is the size of the segment being reduced.
+// value: If either `seed` or `seed2` are set to be non-zero, the random number
+// generator is seeded by the given seed. Otherwise, it is seeded by a
+// random seed.
+// If not specified, defaults to 0
+func TruncatedNormalSeed(value int64) TruncatedNormalAttr {
+ return func(m optionalAttr) {
+ m["seed"] = value
+ }
+}
+
+// TruncatedNormalSeed2 sets the optional seed2 attribute to value.
//
-// Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
-// segments.
+// value: A second seed to avoid seed collision.
+// If not specified, defaults to 0
+func TruncatedNormalSeed2(value int64) TruncatedNormalAttr {
+ return func(m optionalAttr) {
+ m["seed2"] = value
+ }
+}
+
+// Outputs random values from a truncated normal distribution.
+//
+// The generated values follow a normal distribution with mean 0 and standard
+// deviation 1, except that values whose magnitude is more than 2 standard
+// deviations from the mean are dropped and re-picked.
//
// Arguments:
+// shape: The shape of the output tensor.
+// dtype: The type of the output.
//
-// indices: A 1-D tensor. Has same rank as `segment_ids`.
-// segment_ids: A 1-D tensor. Values should be sorted and can be repeated.
+// Returns A tensor of the specified shape filled with random truncated normal
+// values.
+func TruncatedNormal(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...TruncatedNormalAttr) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{"dtype": dtype}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "TruncatedNormal",
+ Input: []tf.Input{
+ shape,
+ },
+ Attrs: attrs,
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// SkipgramAttr is an optional argument to Skipgram.
+type SkipgramAttr func(optionalAttr)
+
+// SkipgramWindowSize sets the optional window_size attribute to value.
//
-// Returns Has same shape as data, except for dimension 0 which
-// has size `k`, the number of segments.
-func SparseSegmentSqrtN(scope *Scope, data tf.Output, indices tf.Output, segment_ids tf.Output) (output tf.Output) {
+// value: The number of words to predict to the left and right of the target.
+// If not specified, defaults to 5
+func SkipgramWindowSize(value int64) SkipgramAttr {
+ return func(m optionalAttr) {
+ m["window_size"] = value
+ }
+}
+
+// SkipgramMinCount sets the optional min_count attribute to value.
+//
+// value: The minimum number of word occurrences for it to be included in the
+// vocabulary.
+// If not specified, defaults to 5
+func SkipgramMinCount(value int64) SkipgramAttr {
+ return func(m optionalAttr) {
+ m["min_count"] = value
+ }
+}
+
+// SkipgramSubsample sets the optional subsample attribute to value.
+//
+// value: Threshold for word occurrence. Words that appear with higher
+// frequency will be randomly down-sampled. Set to 0 to disable.
+// If not specified, defaults to 0.001
+func SkipgramSubsample(value float32) SkipgramAttr {
+ return func(m optionalAttr) {
+ m["subsample"] = value
+ }
+}
+
+// Parses a text file and creates a batch of examples.
+//
+// DEPRECATED at GraphDef version 19: Moving word2vec into tensorflow_models/tutorials and deprecating its ops here as a result
+//
+// Arguments:
+// filename: The corpus's text file name.
+// batch_size: The size of produced batch.
+//
+// Returns A vector of words in the corpus.Frequencies of words. Sorted in the non-ascending order.Number of words per epoch in the data file.The current epoch number.The total number of words processed so far.A vector of word ids.A vector of word ids.
+func Skipgram(scope *Scope, filename string, batch_size int64, optional ...SkipgramAttr) (vocab_word tf.Output, vocab_freq tf.Output, words_per_epoch tf.Output, current_epoch tf.Output, total_words_processed tf.Output, examples tf.Output, labels tf.Output) {
if scope.Err() != nil {
return
}
+ attrs := map[string]interface{}{"filename": filename, "batch_size": batch_size}
+ for _, a := range optional {
+ a(attrs)
+ }
opspec := tf.OpSpec{
- Type: "SparseSegmentSqrtN",
+ Type: "Skipgram",
+
+ Attrs: attrs,
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0), op.Output(1), op.Output(2), op.Output(3), op.Output(4), op.Output(5), op.Output(6)
+}
+
+// StringToNumberAttr is an optional argument to StringToNumber.
+type StringToNumberAttr func(optionalAttr)
+
+// StringToNumberOutType sets the optional out_type attribute to value.
+//
+// value: The numeric type to interpret each string in `string_tensor` as.
+// If not specified, defaults to DT_FLOAT
+func StringToNumberOutType(value tf.DataType) StringToNumberAttr {
+ return func(m optionalAttr) {
+ m["out_type"] = value
+ }
+}
+
+// Converts each string in the input Tensor to the specified numeric type.
+//
+// (Note that int32 overflow results in an error while float overflow
+// results in a rounded value.)
+//
+// Returns A Tensor of the same shape as the input `string_tensor`.
+func StringToNumber(scope *Scope, string_tensor tf.Output, optional ...StringToNumberAttr) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "StringToNumber",
Input: []tf.Input{
- data, indices, segment_ids,
+ string_tensor,
},
+ Attrs: attrs,
}
op := scope.AddOperation(opspec)
return op.Output(0)
}
+// ResourceApplyFtrlV2Attr is an optional argument to ResourceApplyFtrlV2.
+type ResourceApplyFtrlV2Attr func(optionalAttr)
+
+// ResourceApplyFtrlV2UseLocking sets the optional use_locking attribute to value.
+//
+// value: If `True`, updating of the var and accum tensors will be protected
+// by a lock; otherwise the behavior is undefined, but may exhibit less
+// contention.
+// If not specified, defaults to false
+func ResourceApplyFtrlV2UseLocking(value bool) ResourceApplyFtrlV2Attr {
+ return func(m optionalAttr) {
+ m["use_locking"] = value
+ }
+}
+
+// Update '*var' according to the Ftrl-proximal scheme.
+//
+// grad_with_shrinkage = grad + 2 * l2_shrinkage * var
+// accum_new = accum + grad_with_shrinkage * grad_with_shrinkage
+// linear += grad_with_shrinkage +
+// (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var
+// quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2
+// var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0
+// accum = accum_new
+//
+// Arguments:
+// var_: Should be from a Variable().
+// accum: Should be from a Variable().
+// linear: Should be from a Variable().
+// grad: The gradient.
+// lr: Scaling factor. Must be a scalar.
+// l1: L1 regulariation. Must be a scalar.
+// l2: L2 shrinkage regulariation. Must be a scalar.
+//
+// lr_power: Scaling factor. Must be a scalar.
+//
+// Returns the created operation.
+func ResourceApplyFtrlV2(scope *Scope, var_ tf.Output, accum tf.Output, linear tf.Output, grad tf.Output, lr tf.Output, l1 tf.Output, l2 tf.Output, l2_shrinkage tf.Output, lr_power tf.Output, optional ...ResourceApplyFtrlV2Attr) (o *tf.Operation) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "ResourceApplyFtrlV2",
+ Input: []tf.Input{
+ var_, accum, linear, grad, lr, l1, l2, l2_shrinkage, lr_power,
+ },
+ Attrs: attrs,
+ }
+ return scope.AddOperation(opspec)
+}
+
// Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`.
//
// This Op does not require `a_indices` be sorted in standard lexicographic order.
@@ -9812,6 +9801,139 @@ func StatelessRandomNormal(scope *Scope, shape tf.Output, seed tf.Output, option
return op.Output(0)
}
+// DepthwiseConv2dNativeBackpropFilterAttr is an optional argument to DepthwiseConv2dNativeBackpropFilter.
+type DepthwiseConv2dNativeBackpropFilterAttr func(optionalAttr)
+
+// DepthwiseConv2dNativeBackpropFilterDataFormat sets the optional data_format attribute to value.
+//
+// value: Specify the data format of the input and output data. With the
+// default format "NHWC", the data is stored in the order of:
+// [batch, height, width, channels].
+// Alternatively, the format could be "NCHW", the data storage order of:
+// [batch, channels, height, width].
+// If not specified, defaults to "NHWC"
+func DepthwiseConv2dNativeBackpropFilterDataFormat(value string) DepthwiseConv2dNativeBackpropFilterAttr {
+ return func(m optionalAttr) {
+ m["data_format"] = value
+ }
+}
+
+// DepthwiseConv2dNativeBackpropFilterDilations sets the optional dilations attribute to value.
+//
+// value: 1-D tensor of length 4. The dilation factor for each dimension of
+// `input`. If set to k > 1, there will be k-1 skipped cells between each filter
+// element on that dimension. The dimension order is determined by the value of
+// `data_format`, see above for details. Dilations in the batch and depth
+// dimensions must be 1.
+// If not specified, defaults to <i:1 i:1 i:1 i:1 >
+func DepthwiseConv2dNativeBackpropFilterDilations(value []int64) DepthwiseConv2dNativeBackpropFilterAttr {
+ return func(m optionalAttr) {
+ m["dilations"] = value
+ }
+}
+
+// Computes the gradients of depthwise convolution with respect to the filter.
+//
+// Arguments:
+// input: 4-D with shape based on `data_format`. For example, if
+// `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height,
+// in_width, in_channels]` tensor.
+// filter_sizes: An integer vector representing the tensor shape of `filter`,
+// where `filter` is a 4-D
+// `[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor.
+// out_backprop: 4-D with shape based on `data_format`.
+// For example, if `data_format` is 'NHWC' then
+// out_backprop shape is `[batch, out_height, out_width, out_channels]`.
+// Gradients w.r.t. the output of the convolution.
+// strides: The stride of the sliding window for each dimension of the input
+// of the convolution.
+// padding: The type of padding algorithm to use.
+//
+// Returns 4-D with shape
+// `[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t.
+// the `filter` input of the convolution.
+func DepthwiseConv2dNativeBackpropFilter(scope *Scope, input tf.Output, filter_sizes tf.Output, out_backprop tf.Output, strides []int64, padding string, optional ...DepthwiseConv2dNativeBackpropFilterAttr) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{"strides": strides, "padding": padding}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "DepthwiseConv2dNativeBackpropFilter",
+ Input: []tf.Input{
+ input, filter_sizes, out_backprop,
+ },
+ Attrs: attrs,
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// Returns immutable tensor from memory region.
+//
+// The current implementation memmaps the tensor from a file.
+//
+// Arguments:
+// dtype: Type of the returned tensor.
+// shape: Shape of the returned tensor.
+// memory_region_name: Name of readonly memory region used by the tensor, see
+// NewReadOnlyMemoryRegionFromFile in tensorflow::Env.
+func ImmutableConst(scope *Scope, dtype tf.DataType, shape tf.Shape, memory_region_name string) (tensor tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{"dtype": dtype, "shape": shape, "memory_region_name": memory_region_name}
+ opspec := tf.OpSpec{
+ Type: "ImmutableConst",
+
+ Attrs: attrs,
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// StringJoinAttr is an optional argument to StringJoin.
+type StringJoinAttr func(optionalAttr)
+
+// StringJoinSeparator sets the optional separator attribute to value.
+//
+// value: string, an optional join separator.
+// If not specified, defaults to ""
+func StringJoinSeparator(value string) StringJoinAttr {
+ return func(m optionalAttr) {
+ m["separator"] = value
+ }
+}
+
+// Joins the strings in the given list of string tensors into one tensor;
+//
+// with the given separator (default is an empty separator).
+//
+// Arguments:
+// inputs: A list of string tensors. The tensors must all have the same shape,
+// or be scalars. Scalars may be mixed in; these will be broadcast to the shape
+// of non-scalar inputs.
+func StringJoin(scope *Scope, inputs []tf.Output, optional ...StringJoinAttr) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "StringJoin",
+ Input: []tf.Input{
+ tf.OutputList(inputs),
+ },
+ Attrs: attrs,
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
// StringSplitV2Attr is an optional argument to StringSplitV2.
type StringSplitV2Attr func(optionalAttr)
@@ -9985,6 +10107,24 @@ func SparseMatMul(scope *Scope, a tf.Output, b tf.Output, optional ...SparseMatM
return op.Output(0)
}
+// Elementwise computes the bitwise AND of `x` and `y`.
+//
+// The result will have those bits set, that are set in both `x` and `y`. The
+// computation is performed on the underlying representations of `x` and `y`.
+func BitwiseAnd(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "BitwiseAnd",
+ Input: []tf.Input{
+ x, y,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
// Concatenates quantized tensors along one dimension.
//
// Arguments:
@@ -11215,6 +11355,85 @@ func FakeQuantWithMinMaxVars(scope *Scope, inputs tf.Output, min tf.Output, max
return op.Output(0)
}
+// ResourceScatterNdUpdateAttr is an optional argument to ResourceScatterNdUpdate.
+type ResourceScatterNdUpdateAttr func(optionalAttr)
+
+// ResourceScatterNdUpdateUseLocking sets the optional use_locking attribute to value.
+//
+// value: An optional bool. Defaults to True. If True, the assignment will
+// be protected by a lock; otherwise the behavior is undefined,
+// but may exhibit less contention.
+// If not specified, defaults to true
+func ResourceScatterNdUpdateUseLocking(value bool) ResourceScatterNdUpdateAttr {
+ return func(m optionalAttr) {
+ m["use_locking"] = value
+ }
+}
+
+// Applies sparse `updates` to individual values or slices within a given
+//
+// variable according to `indices`.
+//
+// `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
+//
+// `indices` must be integer tensor, containing indices into `ref`.
+// It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
+//
+// The innermost dimension of `indices` (with length `K`) corresponds to
+// indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
+// dimension of `ref`.
+//
+// `updates` is `Tensor` of rank `Q-1+P-K` with shape:
+//
+// ```
+// [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
+// ```
+//
+// For example, say we want to update 4 scattered elements to a rank-1 tensor to
+// 8 elements. In Python, that update would look like this:
+//
+// ```python
+// ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
+// indices = tf.constant([[4], [3], [1] ,[7]])
+// updates = tf.constant([9, 10, 11, 12])
+// update = tf.scatter_nd_update(ref, indices, updates)
+// with tf.Session() as sess:
+// print sess.run(update)
+// ```
+//
+// The resulting update to ref would look like this:
+//
+// [1, 11, 3, 10, 9, 6, 7, 12]
+//
+// See @{tf.scatter_nd} for more details about how to make updates to
+// slices.
+//
+// Arguments:
+// ref: A resource handle. Must be from a VarHandleOp.
+// indices: A Tensor. Must be one of the following types: int32, int64.
+// A tensor of indices into ref.
+// updates: A Tensor. Must have the same type as ref. A tensor of updated
+// values to add to ref.
+//
+// Returns the created operation.
+func ResourceScatterNdUpdate(scope *Scope, ref tf.Output, indices tf.Output, updates tf.Output, optional ...ResourceScatterNdUpdateAttr) (o *tf.Operation) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "ResourceScatterNdUpdate",
+ Input: []tf.Input{
+ ref, indices, updates,
+ },
+ Attrs: attrs,
+ }
+ return scope.AddOperation(opspec)
+}
+
// Applies softmax to a batched N-D `SparseTensor`.
//
// The inputs represent an N-D SparseTensor with logical shape `[..., B, C]`
@@ -12159,34 +12378,6 @@ func OrderedMapPeek(scope *Scope, key tf.Output, indices tf.Output, dtypes []tf.
return values
}
-// Inverse fast Fourier transform.
-//
-// Computes the inverse 1-dimensional discrete Fourier transform over the
-// inner-most dimension of `input`.
-//
-// Arguments:
-// input: A complex64 tensor.
-//
-// Returns A complex64 tensor of the same shape as `input`. The inner-most
-// dimension of `input` is replaced with its inverse 1D Fourier transform.
-//
-// @compatibility(numpy)
-// Equivalent to np.fft.ifft
-// @end_compatibility
-func IFFT(scope *Scope, input tf.Output) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "IFFT",
- Input: []tf.Input{
- input,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// ResourceSparseApplyRMSPropAttr is an optional argument to ResourceSparseApplyRMSProp.
type ResourceSparseApplyRMSPropAttr func(optionalAttr)
@@ -12765,85 +12956,6 @@ func DeserializeSparse(scope *Scope, serialized_sparse tf.Output, dtype tf.DataT
return op.Output(0), op.Output(1), op.Output(2)
}
-// ResourceScatterNdUpdateAttr is an optional argument to ResourceScatterNdUpdate.
-type ResourceScatterNdUpdateAttr func(optionalAttr)
-
-// ResourceScatterNdUpdateUseLocking sets the optional use_locking attribute to value.
-//
-// value: An optional bool. Defaults to True. If True, the assignment will
-// be protected by a lock; otherwise the behavior is undefined,
-// but may exhibit less contention.
-// If not specified, defaults to true
-func ResourceScatterNdUpdateUseLocking(value bool) ResourceScatterNdUpdateAttr {
- return func(m optionalAttr) {
- m["use_locking"] = value
- }
-}
-
-// Applies sparse `updates` to individual values or slices within a given
-//
-// variable according to `indices`.
-//
-// `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
-//
-// `indices` must be integer tensor, containing indices into `ref`.
-// It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
-//
-// The innermost dimension of `indices` (with length `K`) corresponds to
-// indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
-// dimension of `ref`.
-//
-// `updates` is `Tensor` of rank `Q-1+P-K` with shape:
-//
-// ```
-// [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
-// ```
-//
-// For example, say we want to update 4 scattered elements to a rank-1 tensor to
-// 8 elements. In Python, that update would look like this:
-//
-// ```python
-// ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
-// indices = tf.constant([[4], [3], [1] ,[7]])
-// updates = tf.constant([9, 10, 11, 12])
-// update = tf.scatter_nd_update(ref, indices, updates)
-// with tf.Session() as sess:
-// print sess.run(update)
-// ```
-//
-// The resulting update to ref would look like this:
-//
-// [1, 11, 3, 10, 9, 6, 7, 12]
-//
-// See @{tf.scatter_nd} for more details about how to make updates to
-// slices.
-//
-// Arguments:
-// ref: A resource handle. Must be from a VarHandleOp.
-// indices: A Tensor. Must be one of the following types: int32, int64.
-// A tensor of indices into ref.
-// updates: A Tensor. Must have the same type as ref. A tensor of updated
-// values to add to ref.
-//
-// Returns the created operation.
-func ResourceScatterNdUpdate(scope *Scope, ref tf.Output, indices tf.Output, updates tf.Output, optional ...ResourceScatterNdUpdateAttr) (o *tf.Operation) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "ResourceScatterNdUpdate",
- Input: []tf.Input{
- ref, indices, updates,
- },
- Attrs: attrs,
- }
- return scope.AddOperation(opspec)
-}
-
// SqueezeAttr is an optional argument to Squeeze.
type SqueezeAttr func(optionalAttr)
@@ -13975,6 +14087,24 @@ func BoostedTreesPredict(scope *Scope, tree_ensemble_handle tf.Output, bucketize
return op.Output(0)
}
+// Elementwise computes the bitwise OR of `x` and `y`.
+//
+// The result will have those bits set, that are set in `x`, `y` or both. The
+// computation is performed on the underlying representations of `x` and `y`.
+func BitwiseOr(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "BitwiseOr",
+ Input: []tf.Input{
+ x, y,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
// MatrixSolveLsAttr is an optional argument to MatrixSolveLs.
type MatrixSolveLsAttr func(optionalAttr)
@@ -14052,24 +14182,6 @@ func MatrixSolveLs(scope *Scope, matrix tf.Output, rhs tf.Output, l2_regularizer
return op.Output(0)
}
-// Elementwise computes the bitwise OR of `x` and `y`.
-//
-// The result will have those bits set, that are set in `x`, `y` or both. The
-// computation is performed on the underlying representations of `x` and `y`.
-func BitwiseOr(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "BitwiseOr",
- Input: []tf.Input{
- x, y,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// MaxPool3DAttr is an optional argument to MaxPool3D.
type MaxPool3DAttr func(optionalAttr)
@@ -16942,216 +17054,6 @@ func MaxPoolV2(scope *Scope, input tf.Output, ksize tf.Output, strides tf.Output
return op.Output(0)
}
-// SkipgramAttr is an optional argument to Skipgram.
-type SkipgramAttr func(optionalAttr)
-
-// SkipgramWindowSize sets the optional window_size attribute to value.
-//
-// value: The number of words to predict to the left and right of the target.
-// If not specified, defaults to 5
-func SkipgramWindowSize(value int64) SkipgramAttr {
- return func(m optionalAttr) {
- m["window_size"] = value
- }
-}
-
-// SkipgramMinCount sets the optional min_count attribute to value.
-//
-// value: The minimum number of word occurrences for it to be included in the
-// vocabulary.
-// If not specified, defaults to 5
-func SkipgramMinCount(value int64) SkipgramAttr {
- return func(m optionalAttr) {
- m["min_count"] = value
- }
-}
-
-// SkipgramSubsample sets the optional subsample attribute to value.
-//
-// value: Threshold for word occurrence. Words that appear with higher
-// frequency will be randomly down-sampled. Set to 0 to disable.
-// If not specified, defaults to 0.001
-func SkipgramSubsample(value float32) SkipgramAttr {
- return func(m optionalAttr) {
- m["subsample"] = value
- }
-}
-
-// Parses a text file and creates a batch of examples.
-//
-// DEPRECATED at GraphDef version 19: Moving word2vec into tensorflow_models/tutorials and deprecating its ops here as a result
-//
-// Arguments:
-// filename: The corpus's text file name.
-// batch_size: The size of produced batch.
-//
-// Returns A vector of words in the corpus.Frequencies of words. Sorted in the non-ascending order.Number of words per epoch in the data file.The current epoch number.The total number of words processed so far.A vector of word ids.A vector of word ids.
-func Skipgram(scope *Scope, filename string, batch_size int64, optional ...SkipgramAttr) (vocab_word tf.Output, vocab_freq tf.Output, words_per_epoch tf.Output, current_epoch tf.Output, total_words_processed tf.Output, examples tf.Output, labels tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{"filename": filename, "batch_size": batch_size}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "Skipgram",
-
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0), op.Output(1), op.Output(2), op.Output(3), op.Output(4), op.Output(5), op.Output(6)
-}
-
-// StringToNumberAttr is an optional argument to StringToNumber.
-type StringToNumberAttr func(optionalAttr)
-
-// StringToNumberOutType sets the optional out_type attribute to value.
-//
-// value: The numeric type to interpret each string in `string_tensor` as.
-// If not specified, defaults to DT_FLOAT
-func StringToNumberOutType(value tf.DataType) StringToNumberAttr {
- return func(m optionalAttr) {
- m["out_type"] = value
- }
-}
-
-// Converts each string in the input Tensor to the specified numeric type.
-//
-// (Note that int32 overflow results in an error while float overflow
-// results in a rounded value.)
-//
-// Returns A Tensor of the same shape as the input `string_tensor`.
-func StringToNumber(scope *Scope, string_tensor tf.Output, optional ...StringToNumberAttr) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "StringToNumber",
- Input: []tf.Input{
- string_tensor,
- },
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
-// ResourceApplyFtrlV2Attr is an optional argument to ResourceApplyFtrlV2.
-type ResourceApplyFtrlV2Attr func(optionalAttr)
-
-// ResourceApplyFtrlV2UseLocking sets the optional use_locking attribute to value.
-//
-// value: If `True`, updating of the var and accum tensors will be protected
-// by a lock; otherwise the behavior is undefined, but may exhibit less
-// contention.
-// If not specified, defaults to false
-func ResourceApplyFtrlV2UseLocking(value bool) ResourceApplyFtrlV2Attr {
- return func(m optionalAttr) {
- m["use_locking"] = value
- }
-}
-
-// Update '*var' according to the Ftrl-proximal scheme.
-//
-// grad_with_shrinkage = grad + 2 * l2_shrinkage * var
-// accum_new = accum + grad_with_shrinkage * grad_with_shrinkage
-// linear += grad_with_shrinkage +
-// (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var
-// quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2
-// var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0
-// accum = accum_new
-//
-// Arguments:
-// var_: Should be from a Variable().
-// accum: Should be from a Variable().
-// linear: Should be from a Variable().
-// grad: The gradient.
-// lr: Scaling factor. Must be a scalar.
-// l1: L1 regulariation. Must be a scalar.
-// l2: L2 shrinkage regulariation. Must be a scalar.
-//
-// lr_power: Scaling factor. Must be a scalar.
-//
-// Returns the created operation.
-func ResourceApplyFtrlV2(scope *Scope, var_ tf.Output, accum tf.Output, linear tf.Output, grad tf.Output, lr tf.Output, l1 tf.Output, l2 tf.Output, l2_shrinkage tf.Output, lr_power tf.Output, optional ...ResourceApplyFtrlV2Attr) (o *tf.Operation) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "ResourceApplyFtrlV2",
- Input: []tf.Input{
- var_, accum, linear, grad, lr, l1, l2, l2_shrinkage, lr_power,
- },
- Attrs: attrs,
- }
- return scope.AddOperation(opspec)
-}
-
-// TruncatedNormalAttr is an optional argument to TruncatedNormal.
-type TruncatedNormalAttr func(optionalAttr)
-
-// TruncatedNormalSeed sets the optional seed attribute to value.
-//
-// value: If either `seed` or `seed2` are set to be non-zero, the random number
-// generator is seeded by the given seed. Otherwise, it is seeded by a
-// random seed.
-// If not specified, defaults to 0
-func TruncatedNormalSeed(value int64) TruncatedNormalAttr {
- return func(m optionalAttr) {
- m["seed"] = value
- }
-}
-
-// TruncatedNormalSeed2 sets the optional seed2 attribute to value.
-//
-// value: A second seed to avoid seed collision.
-// If not specified, defaults to 0
-func TruncatedNormalSeed2(value int64) TruncatedNormalAttr {
- return func(m optionalAttr) {
- m["seed2"] = value
- }
-}
-
-// Outputs random values from a truncated normal distribution.
-//
-// The generated values follow a normal distribution with mean 0 and standard
-// deviation 1, except that values whose magnitude is more than 2 standard
-// deviations from the mean are dropped and re-picked.
-//
-// Arguments:
-// shape: The shape of the output tensor.
-// dtype: The type of the output.
-//
-// Returns A tensor of the specified shape filled with random truncated normal
-// values.
-func TruncatedNormal(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...TruncatedNormalAttr) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{"dtype": dtype}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "TruncatedNormal",
- Input: []tf.Input{
- shape,
- },
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// MutableDenseHashTableV2Attr is an optional argument to MutableDenseHashTableV2.
type MutableDenseHashTableV2Attr func(optionalAttr)
@@ -17251,6 +17153,34 @@ func MutableDenseHashTableV2(scope *Scope, empty_key tf.Output, value_dtype tf.D
return op.Output(0)
}
+// Inverse fast Fourier transform.
+//
+// Computes the inverse 1-dimensional discrete Fourier transform over the
+// inner-most dimension of `input`.
+//
+// Arguments:
+// input: A complex64 tensor.
+//
+// Returns A complex64 tensor of the same shape as `input`. The inner-most
+// dimension of `input` is replaced with its inverse 1D Fourier transform.
+//
+// @compatibility(numpy)
+// Equivalent to np.fft.ifft
+// @end_compatibility
+func IFFT(scope *Scope, input tf.Output) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "IFFT",
+ Input: []tf.Input{
+ input,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
// 2D fast Fourier transform.
//
// Computes the 2-dimensional discrete Fourier transform over the inner-most
@@ -17759,123 +17689,6 @@ func TextLineDataset(scope *Scope, filenames tf.Output, compression_type tf.Outp
return op.Output(0)
}
-// CudnnRNNParamsSizeAttr is an optional argument to CudnnRNNParamsSize.
-type CudnnRNNParamsSizeAttr func(optionalAttr)
-
-// CudnnRNNParamsSizeRnnMode sets the optional rnn_mode attribute to value.
-// If not specified, defaults to "lstm"
-func CudnnRNNParamsSizeRnnMode(value string) CudnnRNNParamsSizeAttr {
- return func(m optionalAttr) {
- m["rnn_mode"] = value
- }
-}
-
-// CudnnRNNParamsSizeInputMode sets the optional input_mode attribute to value.
-// If not specified, defaults to "linear_input"
-func CudnnRNNParamsSizeInputMode(value string) CudnnRNNParamsSizeAttr {
- return func(m optionalAttr) {
- m["input_mode"] = value
- }
-}
-
-// CudnnRNNParamsSizeDirection sets the optional direction attribute to value.
-// If not specified, defaults to "unidirectional"
-func CudnnRNNParamsSizeDirection(value string) CudnnRNNParamsSizeAttr {
- return func(m optionalAttr) {
- m["direction"] = value
- }
-}
-
-// CudnnRNNParamsSizeDropout sets the optional dropout attribute to value.
-// If not specified, defaults to 0
-func CudnnRNNParamsSizeDropout(value float32) CudnnRNNParamsSizeAttr {
- return func(m optionalAttr) {
- m["dropout"] = value
- }
-}
-
-// CudnnRNNParamsSizeSeed sets the optional seed attribute to value.
-// If not specified, defaults to 0
-func CudnnRNNParamsSizeSeed(value int64) CudnnRNNParamsSizeAttr {
- return func(m optionalAttr) {
- m["seed"] = value
- }
-}
-
-// CudnnRNNParamsSizeSeed2 sets the optional seed2 attribute to value.
-// If not specified, defaults to 0
-func CudnnRNNParamsSizeSeed2(value int64) CudnnRNNParamsSizeAttr {
- return func(m optionalAttr) {
- m["seed2"] = value
- }
-}
-
-// Computes size of weights that can be used by a Cudnn RNN model.
-//
-// Return the params size that can be used by the Cudnn RNN model. Subsequent
-// weight allocation and initialization should use this size.
-//
-// num_layers: Specifies the number of layers in the RNN model.
-// num_units: Specifies the size of the hidden state.
-// input_size: Specifies the size of the input state.
-// rnn_mode: Indicates the type of the RNN model.
-// input_mode: Indicate whether there is a linear projection between the input and
-// The actual computation before the first layer. 'skip_input' is only allowed
-// when input_size == num_units; 'auto_select' implies 'skip_input' when
-// input_size == num_units; otherwise, it implies 'linear_input'.
-// direction: Indicates whether a bidirectional model will be used.
-// dir = (direction == bidirectional) ? 2 : 1
-// dropout: dropout probability. When set to 0., dropout is disabled.
-// seed: the 1st part of a seed to initialize dropout.
-// seed2: the 2nd part of a seed to initialize dropout.
-// params_size: The size of the params buffer that should be allocated and
-// initialized for this RNN model. Note that this params buffer may not be
-// compatible across GPUs. Please use CudnnRNNParamsWeights and
-// CudnnRNNParamsBiases to save and restore them in a way that is compatible
-// across different runs.
-func CudnnRNNParamsSize(scope *Scope, num_layers tf.Output, num_units tf.Output, input_size tf.Output, T tf.DataType, S tf.DataType, optional ...CudnnRNNParamsSizeAttr) (params_size tf.Output) {
- if scope.Err() != nil {
- return
- }
- attrs := map[string]interface{}{"T": T, "S": S}
- for _, a := range optional {
- a(attrs)
- }
- opspec := tf.OpSpec{
- Type: "CudnnRNNParamsSize",
- Input: []tf.Input{
- num_layers, num_units, input_size,
- },
- Attrs: attrs,
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
-// Computes gradients for SparseSegmentMean.
-//
-// Returns tensor "output" with same shape as grad, except for dimension 0 whose
-// value is output_dim0.
-//
-// Arguments:
-// grad: gradient propagated to the SparseSegmentMean op.
-// indices: indices passed to the corresponding SparseSegmentMean op.
-// segment_ids: segment_ids passed to the corresponding SparseSegmentMean op.
-// output_dim0: dimension 0 of "data" passed to SparseSegmentMean op.
-func SparseSegmentMeanGrad(scope *Scope, grad tf.Output, indices tf.Output, segment_ids tf.Output, output_dim0 tf.Output) (output tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "SparseSegmentMeanGrad",
- Input: []tf.Input{
- grad, indices, segment_ids, output_dim0,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
-
// Returns the set of files matching one or more glob patterns.
//
// Note that this routine only supports wildcard characters in the
@@ -20608,6 +20421,211 @@ func RandomUniformInt(scope *Scope, shape tf.Output, minval tf.Output, maxval tf
return op.Output(0)
}
+// CudnnRNNParamsSizeAttr is an optional argument to CudnnRNNParamsSize.
+type CudnnRNNParamsSizeAttr func(optionalAttr)
+
+// CudnnRNNParamsSizeRnnMode sets the optional rnn_mode attribute to value.
+// If not specified, defaults to "lstm"
+func CudnnRNNParamsSizeRnnMode(value string) CudnnRNNParamsSizeAttr {
+ return func(m optionalAttr) {
+ m["rnn_mode"] = value
+ }
+}
+
+// CudnnRNNParamsSizeInputMode sets the optional input_mode attribute to value.
+// If not specified, defaults to "linear_input"
+func CudnnRNNParamsSizeInputMode(value string) CudnnRNNParamsSizeAttr {
+ return func(m optionalAttr) {
+ m["input_mode"] = value
+ }
+}
+
+// CudnnRNNParamsSizeDirection sets the optional direction attribute to value.
+// If not specified, defaults to "unidirectional"
+func CudnnRNNParamsSizeDirection(value string) CudnnRNNParamsSizeAttr {
+ return func(m optionalAttr) {
+ m["direction"] = value
+ }
+}
+
+// CudnnRNNParamsSizeDropout sets the optional dropout attribute to value.
+// If not specified, defaults to 0
+func CudnnRNNParamsSizeDropout(value float32) CudnnRNNParamsSizeAttr {
+ return func(m optionalAttr) {
+ m["dropout"] = value
+ }
+}
+
+// CudnnRNNParamsSizeSeed sets the optional seed attribute to value.
+// If not specified, defaults to 0
+func CudnnRNNParamsSizeSeed(value int64) CudnnRNNParamsSizeAttr {
+ return func(m optionalAttr) {
+ m["seed"] = value
+ }
+}
+
+// CudnnRNNParamsSizeSeed2 sets the optional seed2 attribute to value.
+// If not specified, defaults to 0
+func CudnnRNNParamsSizeSeed2(value int64) CudnnRNNParamsSizeAttr {
+ return func(m optionalAttr) {
+ m["seed2"] = value
+ }
+}
+
+// Computes size of weights that can be used by a Cudnn RNN model.
+//
+// Return the params size that can be used by the Cudnn RNN model. Subsequent
+// weight allocation and initialization should use this size.
+//
+// num_layers: Specifies the number of layers in the RNN model.
+// num_units: Specifies the size of the hidden state.
+// input_size: Specifies the size of the input state.
+// rnn_mode: Indicates the type of the RNN model.
+// input_mode: Indicate whether there is a linear projection between the input and
+// The actual computation before the first layer. 'skip_input' is only allowed
+// when input_size == num_units; 'auto_select' implies 'skip_input' when
+// input_size == num_units; otherwise, it implies 'linear_input'.
+// direction: Indicates whether a bidirectional model will be used.
+// dir = (direction == bidirectional) ? 2 : 1
+// dropout: dropout probability. When set to 0., dropout is disabled.
+// seed: the 1st part of a seed to initialize dropout.
+// seed2: the 2nd part of a seed to initialize dropout.
+// params_size: The size of the params buffer that should be allocated and
+// initialized for this RNN model. Note that this params buffer may not be
+// compatible across GPUs. Please use CudnnRNNParamsWeights and
+// CudnnRNNParamsBiases to save and restore them in a way that is compatible
+// across different runs.
+func CudnnRNNParamsSize(scope *Scope, num_layers tf.Output, num_units tf.Output, input_size tf.Output, T tf.DataType, S tf.DataType, optional ...CudnnRNNParamsSizeAttr) (params_size tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ attrs := map[string]interface{}{"T": T, "S": S}
+ for _, a := range optional {
+ a(attrs)
+ }
+ opspec := tf.OpSpec{
+ Type: "CudnnRNNParamsSize",
+ Input: []tf.Input{
+ num_layers, num_units, input_size,
+ },
+ Attrs: attrs,
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// Computes gradients for SparseSegmentMean.
+//
+// Returns tensor "output" with same shape as grad, except for dimension 0 whose
+// value is output_dim0.
+//
+// Arguments:
+// grad: gradient propagated to the SparseSegmentMean op.
+// indices: indices passed to the corresponding SparseSegmentMean op.
+// segment_ids: segment_ids passed to the corresponding SparseSegmentMean op.
+// output_dim0: dimension 0 of "data" passed to SparseSegmentMean op.
+func SparseSegmentMeanGrad(scope *Scope, grad tf.Output, indices tf.Output, segment_ids tf.Output, output_dim0 tf.Output) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "SparseSegmentMeanGrad",
+ Input: []tf.Input{
+ grad, indices, segment_ids, output_dim0,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// Computes the sum along sparse segments of a tensor divided by the sqrt of N.
+//
+// N is the size of the segment being reduced.
+//
+// Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
+// segments.
+//
+// Arguments:
+//
+// indices: A 1-D tensor. Has same rank as `segment_ids`.
+// segment_ids: A 1-D tensor. Values should be sorted and can be repeated.
+//
+// Returns Has same shape as data, except for dimension 0 which
+// has size `k`, the number of segments.
+func SparseSegmentSqrtN(scope *Scope, data tf.Output, indices tf.Output, segment_ids tf.Output) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "SparseSegmentSqrtN",
+ Input: []tf.Input{
+ data, indices, segment_ids,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// Compute the upper regularized incomplete Gamma function `Q(a, x)`.
+//
+// The upper regularized incomplete Gamma function is defined as:
+//
+// \\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\)
+//
+// where
+//
+// \\(Gamma(a, x) = int_{x}^{\infty} t^{a-1} exp(-t) dt\\)
+//
+// is the upper incomplete Gama function.
+//
+// Note, above `P(a, x)` (`Igamma`) is the lower regularized complete
+// Gamma function.
+func Igammac(scope *Scope, a tf.Output, x tf.Output) (z tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "Igammac",
+ Input: []tf.Input{
+ a, x,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
+// Computes the sum along sparse segments of a tensor divided by the sqrt of N.
+//
+// N is the size of the segment being reduced.
+//
+// Like `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is
+// misisng, the `output` tensor at that position will be zeroed.
+//
+// Read @{$math_ops#Segmentation$the section on segmentation} for an explanation of
+// segments.
+//
+// Arguments:
+//
+// indices: A 1-D tensor. Has same rank as `segment_ids`.
+// segment_ids: A 1-D tensor. Values should be sorted and can be repeated.
+// num_segments: Should equal the number of distinct segment IDs.
+//
+// Returns Has same shape as data, except for dimension 0 which
+// has size `k`, the number of segments.
+func SparseSegmentSqrtNWithNumSegments(scope *Scope, data tf.Output, indices tf.Output, segment_ids tf.Output, num_segments tf.Output) (output tf.Output) {
+ if scope.Err() != nil {
+ return
+ }
+ opspec := tf.OpSpec{
+ Type: "SparseSegmentSqrtNWithNumSegments",
+ Input: []tf.Input{
+ data, indices, segment_ids, num_segments,
+ },
+ }
+ op := scope.AddOperation(opspec)
+ return op.Output(0)
+}
+
// Computes gradients for SparseSegmentSqrtN.
//
// Returns tensor "output" with same shape as grad, except for dimension 0 whose
@@ -31898,21 +31916,3 @@ func BoostedTreesDeserializeEnsemble(scope *Scope, tree_ensemble_handle tf.Outpu
}
return scope.AddOperation(opspec)
}
-
-// Elementwise computes the bitwise AND of `x` and `y`.
-//
-// The result will have those bits set, that are set in both `x` and `y`. The
-// computation is performed on the underlying representations of `x` and `y`.
-func BitwiseAnd(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {
- if scope.Err() != nil {
- return
- }
- opspec := tf.OpSpec{
- Type: "BitwiseAnd",
- Input: []tf.Input{
- x, y,
- },
- }
- op := scope.AddOperation(opspec)
- return op.Output(0)
-}
diff --git a/tensorflow/java/BUILD b/tensorflow/java/BUILD
index 87e6107c2d..9dce78b9a3 100644
--- a/tensorflow/java/BUILD
+++ b/tensorflow/java/BUILD
@@ -86,7 +86,10 @@ tf_cc_binary(
"src/gen/cc/op_gen_main.cc",
],
copts = tf_copts(),
- linkopts = ["-lm"],
+ linkopts = select({
+ "//tensorflow:windows": [],
+ "//conditions:default": ["-lm"],
+ }),
linkstatic = 1,
deps = [
":java_op_gen_lib",
@@ -368,7 +371,6 @@ tf_cc_binary(
"$(location {})".format(LINKER_EXPORTED_SYMBOLS),
],
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//conditions:default": [
"-z defs",
"-s",
diff --git a/tensorflow/java/maven/hadoop/pom.xml b/tensorflow/java/maven/hadoop/pom.xml
index 7fa751a46a..e0409fa41b 100644
--- a/tensorflow/java/maven/hadoop/pom.xml
+++ b/tensorflow/java/maven/hadoop/pom.xml
@@ -5,7 +5,7 @@
<groupId>org.tensorflow</groupId>
<artifactId>hadoop</artifactId>
<packaging>jar</packaging>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<name>tensorflow-hadoop</name>
<url>https://www.tensorflow.org</url>
<description>TensorFlow TFRecord InputFormat/OutputFormat for Apache Hadoop</description>
diff --git a/tensorflow/java/maven/libtensorflow/pom.xml b/tensorflow/java/maven/libtensorflow/pom.xml
index 8ecabfd399..f9093ce385 100644
--- a/tensorflow/java/maven/libtensorflow/pom.xml
+++ b/tensorflow/java/maven/libtensorflow/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.tensorflow</groupId>
<artifactId>parentpom</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<relativePath>../</relativePath>
</parent>
<artifactId>libtensorflow</artifactId>
diff --git a/tensorflow/java/maven/libtensorflow_jni/pom.xml b/tensorflow/java/maven/libtensorflow_jni/pom.xml
index e03ce32216..1208956dec 100644
--- a/tensorflow/java/maven/libtensorflow_jni/pom.xml
+++ b/tensorflow/java/maven/libtensorflow_jni/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.tensorflow</groupId>
<artifactId>parentpom</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<relativePath>../</relativePath>
</parent>
<artifactId>libtensorflow_jni</artifactId>
diff --git a/tensorflow/java/maven/libtensorflow_jni_gpu/pom.xml b/tensorflow/java/maven/libtensorflow_jni_gpu/pom.xml
index fee840f547..755449cb3c 100644
--- a/tensorflow/java/maven/libtensorflow_jni_gpu/pom.xml
+++ b/tensorflow/java/maven/libtensorflow_jni_gpu/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.tensorflow</groupId>
<artifactId>parentpom</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<relativePath>../</relativePath>
</parent>
<artifactId>libtensorflow_jni_gpu</artifactId>
diff --git a/tensorflow/java/maven/pom.xml b/tensorflow/java/maven/pom.xml
index 0c33819b2b..035077e1e0 100644
--- a/tensorflow/java/maven/pom.xml
+++ b/tensorflow/java/maven/pom.xml
@@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.tensorflow</groupId>
<artifactId>parentpom</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<packaging>pom</packaging>
<url>https://www.tensorflow.org</url>
diff --git a/tensorflow/java/maven/proto/pom.xml b/tensorflow/java/maven/proto/pom.xml
index 2af7a5cd2e..b89f042567 100644
--- a/tensorflow/java/maven/proto/pom.xml
+++ b/tensorflow/java/maven/proto/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.tensorflow</groupId>
<artifactId>parentpom</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<relativePath>../</relativePath>
</parent>
<artifactId>proto</artifactId>
diff --git a/tensorflow/java/maven/run_inside_container.sh b/tensorflow/java/maven/run_inside_container.sh
index f4794d68a9..8c4c9d498c 100644
--- a/tensorflow/java/maven/run_inside_container.sh
+++ b/tensorflow/java/maven/run_inside_container.sh
@@ -110,11 +110,17 @@ download_libtensorflow_jni_gpu() {
cd "${NATIVE_DIR}"
mkdir linux-x86_64
+ mkdir windows-x86_64
curl -L "${RELEASE_URL_PREFIX}/libtensorflow_jni-gpu-linux-x86_64-${TF_VERSION}.tar.gz" | tar -xvz -C linux-x86_64
+ curl -L "${RELEASE_URL_PREFIX}/libtensorflow_jni-gpu-windows-x86_64-${TF_VERSION}.zip" -o /tmp/windows.zip
+
+ unzip /tmp/windows.zip -d windows-x86_64
+ rm -f /tmp/windows.zip
# Updated timestamps seem to be required to get Maven to pick up the file.
touch linux-x86_64/*
+ touch windows-x86_64/*
cd "${DIR}"
}
diff --git a/tensorflow/java/maven/spark-connector/pom.xml b/tensorflow/java/maven/spark-connector/pom.xml
index 27d9b54c6c..31e39c588a 100644
--- a/tensorflow/java/maven/spark-connector/pom.xml
+++ b/tensorflow/java/maven/spark-connector/pom.xml
@@ -6,7 +6,7 @@
<groupId>org.tensorflow</groupId>
<artifactId>spark-connector_2.11</artifactId>
<packaging>jar</packaging>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<name>spark-tensorflow-connector</name>
<url>https://www.tensorflow.org</url>
<description>TensorFlow TFRecord connector for Apache Spark DataFrames</description>
diff --git a/tensorflow/java/maven/tensorflow/pom.xml b/tensorflow/java/maven/tensorflow/pom.xml
index c952545bc6..0de90244b1 100644
--- a/tensorflow/java/maven/tensorflow/pom.xml
+++ b/tensorflow/java/maven/tensorflow/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>org.tensorflow</groupId>
<artifactId>parentpom</artifactId>
- <version>1.10.0-rc1</version>
+ <version>1.10.0</version>
<relativePath>../</relativePath>
</parent>
<artifactId>tensorflow</artifactId>
diff --git a/tensorflow/java/src/main/java/org/tensorflow/types/UInt8.java b/tensorflow/java/src/main/java/org/tensorflow/types/UInt8.java
index 0c751aed9f..824f7fbe32 100644
--- a/tensorflow/java/src/main/java/org/tensorflow/types/UInt8.java
+++ b/tensorflow/java/src/main/java/org/tensorflow/types/UInt8.java
@@ -16,6 +16,33 @@ limitations under the License.
package org.tensorflow.types;
/** Represents an 8-bit unsigned integer. */
-public class UInt8 {
+public class UInt8 extends Number {
+
+ private static final long serialVersionUID = 1L;
+
+ // This class is only used for generic parameterization and is not instantiable. Thus,
+ // it is safe to implement the Number abstract methods with all zeros, as they will
+ // never be invoked.
+
+ @Override
+ public double doubleValue() {
+ return 0.0;
+ }
+
+ @Override
+ public float floatValue() {
+ return 0.0f;
+ }
+
+ @Override
+ public int intValue() {
+ return 0;
+ }
+
+ @Override
+ public long longValue() {
+ return 0L;
+ }
+
private UInt8() {}
}
diff --git a/tensorflow/python/BUILD b/tensorflow/python/BUILD
index 2e6fb11655..68b3722326 100644
--- a/tensorflow/python/BUILD
+++ b/tensorflow/python/BUILD
@@ -138,6 +138,7 @@ py_library(
"//tensorflow/python/ops/parallel_for",
"//tensorflow/python/profiler",
"//tensorflow/python/saved_model",
+ "//tensorflow/python/tools:component_api_helper",
"//third_party/py/numpy",
],
)
@@ -1870,6 +1871,7 @@ py_library(
":framework_for_generated_wrappers",
":math_ops",
":nn_ops_gen",
+ ":numerics",
"@six_archive//:six",
],
)
@@ -1883,7 +1885,6 @@ py_test(
":client_testlib",
":clip_ops",
":framework_for_generated_wrappers",
- ":numerics",
"//third_party/py/numpy",
],
)
@@ -3265,6 +3266,7 @@ py_library(
"@six_archive//:six",
"//tensorflow/core:protos_all_py",
"//tensorflow/python/data/ops:dataset_ops",
+ "//tensorflow/python/distribute:distribute_coordinator_context",
"//tensorflow/python/eager:backprop",
"//tensorflow/python/eager:context",
# `layers` dependency only exists due to the use of a small utility.
@@ -3340,7 +3342,10 @@ py_library(
py_library(
name = "distribute",
- srcs = ["training/distribute.py"],
+ srcs = [
+ "training/distribute.py",
+ "training/distribution_strategy_context.py",
+ ],
srcs_version = "PY2AND3",
deps = [
":array_ops",
@@ -4205,7 +4210,6 @@ cuda_py_test(
":math_ops",
"//tensorflow/core:protos_all_py",
],
- tags = ["no_windows"],
)
cuda_py_test(
@@ -4499,7 +4503,6 @@ py_test(
srcs = ["training/saver_large_partitioned_variable_test.py"],
srcs_version = "PY2AND3",
tags = [
- "no_windows",
"noasan", # http://b/30782289
"notsan", # http://b/30782289
],
@@ -4657,7 +4660,10 @@ py_test(
size = "medium",
srcs = ["training/monitored_session_test.py"],
srcs_version = "PY2AND3",
- tags = ["notsan"], # b/67945581
+ tags = [
+ "no_pip",
+ "notsan", # b/67945581
+ ],
deps = [
":array_ops",
":checkpoint_management",
@@ -4675,6 +4681,7 @@ py_test(
"//tensorflow/contrib/framework:framework_py",
"//tensorflow/contrib/testing:testing_py",
"//tensorflow/core:protos_all_py",
+ "//tensorflow/python/distribute:distribute_coordinator",
],
)
diff --git a/tensorflow/python/client/client_lib.py b/tensorflow/python/client/client_lib.py
index c94767a03c..80a256bf7a 100644
--- a/tensorflow/python/client/client_lib.py
+++ b/tensorflow/python/client/client_lib.py
@@ -15,7 +15,7 @@
"""Support for launching graphs and executing operations.
-See the @{$python/client} guide.
+See the [Client](https://tensorflow.org/api_guides/python/client) guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/client/session.py b/tensorflow/python/client/session.py
index 58a002c776..1841dd998b 100644
--- a/tensorflow/python/client/session.py
+++ b/tensorflow/python/client/session.py
@@ -724,7 +724,7 @@ class BaseSession(SessionInterface):
"""Returns a context manager that makes this object the default session.
Use with the `with` keyword to specify that calls to
- @{tf.Operation.run} or @{tf.Tensor.eval} should be executed in
+ `tf.Operation.run` or `tf.Tensor.eval` should be executed in
this session.
```python
@@ -736,7 +736,7 @@ class BaseSession(SessionInterface):
print(c.eval())
```
- To get the current default session, use @{tf.get_default_session}.
+ To get the current default session, use `tf.get_default_session`.
*N.B.* The `as_default` context manager *does not* close the
session when you exit the context, and you must close the session
@@ -765,7 +765,7 @@ class BaseSession(SessionInterface):
*N.B.* Entering a `with sess.as_default():` block does not affect
the current default graph. If you are using multiple graphs, and
- `sess.graph` is different from the value of @{tf.get_default_graph},
+ `sess.graph` is different from the value of `tf.get_default_graph`,
you must explicitly enter a `with sess.graph.as_default():` block
to make `sess.graph` the default graph.
@@ -786,14 +786,14 @@ class BaseSession(SessionInterface):
nested list, tuple, namedtuple, dict, or OrderedDict containing graph
elements at its leaves. A graph element can be one of the following types:
- * An @{tf.Operation}.
+ * An `tf.Operation`.
The corresponding fetched value will be `None`.
- * A @{tf.Tensor}.
+ * A `tf.Tensor`.
The corresponding fetched value will be a numpy ndarray containing the
value of that tensor.
- * A @{tf.SparseTensor}.
+ * A `tf.SparseTensor`.
The corresponding fetched value will be a
- @{tf.SparseTensorValue}
+ `tf.SparseTensorValue`
containing the value of that sparse tensor.
* A `get_tensor_handle` op. The corresponding fetched value will be a
numpy ndarray containing the handle of that tensor.
@@ -829,16 +829,16 @@ class BaseSession(SessionInterface):
the value of tensors in the graph. Each key in `feed_dict` can be
one of the following types:
- * If the key is a @{tf.Tensor}, the
+ * If the key is a `tf.Tensor`, the
value may be a Python scalar, string, list, or numpy ndarray
that can be converted to the same `dtype` as that
tensor. Additionally, if the key is a
- @{tf.placeholder}, the shape of
+ `tf.placeholder`, the shape of
the value will be checked for compatibility with the placeholder.
* If the key is a
- @{tf.SparseTensor},
+ `tf.SparseTensor`,
the value should be a
- @{tf.SparseTensorValue}.
+ `tf.SparseTensorValue`.
* If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value
should be a nested tuple with the same structure that maps to their
corresponding values as above.
@@ -1120,7 +1120,7 @@ class BaseSession(SessionInterface):
For example, if element `i` of `feed_list` is a `tf.Tensor`, the `i`th
argument to the returned callable must be a numpy ndarray (or something
convertible to an ndarray) with matching element type and shape. See
- @{tf.Session.run} for details of the allowable feed key and value types.
+ `tf.Session.run` for details of the allowable feed key and value types.
The returned callable will have the same return type as
`tf.Session.run(fetches, ...)`. For example, if `fetches` is a `tf.Tensor`,
@@ -1128,14 +1128,14 @@ class BaseSession(SessionInterface):
it will return `None`.
Args:
- fetches: A value or list of values to fetch. See @{tf.Session.run}
+ fetches: A value or list of values to fetch. See `tf.Session.run`
for details of the allowable fetch types.
feed_list: (Optional.) A list of `feed_dict` keys. See
- @{tf.Session.run} for details of the allowable feed key types.
+ `tf.Session.run` for details of the allowable feed key types.
accept_options: (Optional.) Iff `True`, the returned `Callable` will be
- able to accept @{tf.RunOptions} and @{tf.RunMetadata} as optional
+ able to accept `tf.RunOptions` and `tf.RunMetadata` as optional
keyword arguments `options` and `run_metadata`, respectively, with
- the same syntax and semantics as @{tf.Session.run}, which is useful
+ the same syntax and semantics as `tf.Session.run`, which is useful
for certain use cases (profiling and debugging) but will result in
measurable slowdown of the `Callable`'s performance. Default: `False`.
@@ -1145,7 +1145,7 @@ class BaseSession(SessionInterface):
Raises:
TypeError: If `fetches` or `feed_list` cannot be interpreted
- as arguments to @{tf.Session.run}.
+ as arguments to `tf.Session.run`.
"""
if feed_list is not None:
if not isinstance(feed_list, (list, tuple)):
@@ -1453,10 +1453,10 @@ class Session(BaseSession):
```
A session may own resources, such as
- @{tf.Variable}, @{tf.QueueBase},
- and @{tf.ReaderBase}. It is important to release
+ `tf.Variable`, `tf.QueueBase`,
+ and `tf.ReaderBase`. It is important to release
these resources when they are no longer required. To do this, either
- invoke the @{tf.Session.close} method on the session, or use
+ invoke the `tf.Session.close` method on the session, or use
the session as a context manager. The following two examples are
equivalent:
@@ -1500,7 +1500,7 @@ class Session(BaseSession):
Args:
target: (Optional.) The execution engine to connect to.
Defaults to using an in-process engine. See
- @{$distributed$Distributed TensorFlow}
+ [Distributed TensorFlow](https://tensorflow.org/deploy/distributed)
for more examples.
graph: (Optional.) The `Graph` to be launched (described above).
config: (Optional.) A
@@ -1592,8 +1592,8 @@ class InteractiveSession(BaseSession):
The only difference with a regular `Session` is that an `InteractiveSession`
installs itself as the default session on construction.
- The methods @{tf.Tensor.eval}
- and @{tf.Operation.run}
+ The methods `tf.Tensor.eval`
+ and `tf.Operation.run`
will use that session to run ops.
This is convenient in interactive shells and [IPython
diff --git a/tensorflow/python/compat/compat.py b/tensorflow/python/compat/compat.py
index 4921f8b8b2..572e6e34c8 100644
--- a/tensorflow/python/compat/compat.py
+++ b/tensorflow/python/compat/compat.py
@@ -14,8 +14,8 @@
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.
-See
-@{$guide/version_compat#backward_and_partial_forward_compatibility}
+See [Version
+Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""
from __future__ import absolute_import
@@ -26,14 +26,15 @@ import datetime
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export
-_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2018, 8, 8)
+_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2018, 8, 20)
@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
"""Return true if the forward compatibility window has expired.
- See @{$guide/version_compat#backward_and_partial_forward_compatibility}.
+ See [Version
+ compatibility](https://tensorflow.org/guide/version_compat#backward_forward).
Forward-compatibility refers to scenarios where the producer of a TensorFlow
model (a GraphDef or SavedModel) is compiled against a version of the
@@ -91,7 +92,8 @@ def forward_compatible(year, month, day):
def forward_compatibility_horizon(year, month, day):
"""Context manager for testing forward compatibility of generated graphs.
- See @{$guide/version_compat#backward_and_partial_forward_compatibility}.
+ See [Version
+ compatibility](https://tensorflow.org/guide/version_compat#backward_forward).
To ensure forward compatibility of generated graphs (see `forward_compatible`)
with older binaries, new features can be gated with:
diff --git a/tensorflow/python/data/__init__.py b/tensorflow/python/data/__init__.py
index 3b9bf2469e..f8b561205e 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 @{$guide/datasets$Importing Data} for an overview.
+See [Importing Data](https://tensorflow.org/guide/datasets) for an overview.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/data/ops/BUILD b/tensorflow/python/data/ops/BUILD
index 50ba5f403e..57517afae8 100644
--- a/tensorflow/python/data/ops/BUILD
+++ b/tensorflow/python/data/ops/BUILD
@@ -27,6 +27,7 @@ py_library(
"//tensorflow/python/data/util:nest",
"//tensorflow/python/data/util:random_seed",
"//tensorflow/python/data/util:sparse",
+ "//tensorflow/python/data/util:structure",
"//third_party/py/numpy",
],
)
diff --git a/tensorflow/python/data/ops/dataset_ops.py b/tensorflow/python/data/ops/dataset_ops.py
index 6cda2a77cc..fdab8abfae 100644
--- a/tensorflow/python/data/ops/dataset_ops.py
+++ b/tensorflow/python/data/ops/dataset_ops.py
@@ -222,10 +222,10 @@ class Dataset(object):
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
+ `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}.
+ [this guide](https://tensorflow.org/guide/datasets#consuming_numpy_arrays).
Args:
tensors: A nested structure of tensors.
@@ -241,10 +241,10 @@ class Dataset(object):
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
+ `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}.
+ [this guide](https://tensorflow.org/guide/datasets#consuming_numpy_arrays).
Args:
tensors: A nested structure of tensors, each having the same size in the
@@ -331,7 +331,7 @@ class Dataset(object):
```
NOTE: The current implementation of `Dataset.from_generator()` uses
- @{tf.py_func} and inherits the same constraints. In particular, it
+ `tf.py_func` and inherits the same constraints. In particular, it
requires the `Dataset`- and `Iterator`-related operations to be placed
on a device in the same process as the Python program that called
`Dataset.from_generator()`. The body of `generator` will not be
@@ -641,7 +641,7 @@ class Dataset(object):
Defaults to `True`.
seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
random seed that will be used to create the distribution. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
Returns:
Dataset: A `Dataset` of strings corresponding to file names.
@@ -706,7 +706,7 @@ class Dataset(object):
dataset will sample.
seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
random seed that will be used to create the distribution. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
reshuffle_each_iteration: (Optional.) A boolean, which if true indicates
that the dataset should be pseudorandomly reshuffled each time it is
iterated over. (Defaults to `True`.)
@@ -863,7 +863,7 @@ class Dataset(object):
This transformation combines multiple consecutive elements of the input
dataset into a single element.
- Like @{tf.data.Dataset.batch}, the tensors in the resulting element will
+ Like `tf.data.Dataset.batch`, the tensors in the resulting element will
have an additional outer dimension, which will be `batch_size` (or
`N % batch_size` for the last element if `batch_size` does not divide the
number of input elements `N` evenly and `drop_remainder` is `False`). If
@@ -871,7 +871,7 @@ class Dataset(object):
should set the `drop_remainder` argument to `True` to prevent the smaller
batch from being produced.
- Unlike @{tf.data.Dataset.batch}, the input elements to be batched may have
+ Unlike `tf.data.Dataset.batch`, the input elements to be batched may have
different shapes, and this transformation will pad each component to the
respective shape in `padding_shapes`. The `padding_shapes` argument
determines the resulting shape for each dimension of each component in an
@@ -883,8 +883,8 @@ class Dataset(object):
will be padded out to the maximum length of all elements in that
dimension.
- See also @{tf.contrib.data.dense_to_sparse_batch}, which combines elements
- that may have different shapes into a @{tf.SparseTensor}.
+ See also `tf.contrib.data.dense_to_sparse_batch`, which combines elements
+ that may have different shapes into a `tf.SparseTensor`.
Args:
batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of
@@ -1039,7 +1039,7 @@ class Dataset(object):
elements are produced. `cycle_length` controls the number of input elements
that are processed concurrently. If you set `cycle_length` to 1, this
transformation will handle one input element at a time, and will produce
- identical results = to @{tf.data.Dataset.flat_map}. In general,
+ identical results = to `tf.data.Dataset.flat_map`. In general,
this transformation will apply `map_func` to `cycle_length` input elements,
open iterators on the returned `Dataset` objects, and cycle through them
producing `block_length` consecutive elements from each iterator, and
@@ -1306,7 +1306,7 @@ class _NestedDatasetComponent(object):
class _VariantDataset(Dataset):
- """A Dataset wrapper around a @{tf.variant}-typed function argument."""
+ """A Dataset wrapper around a `tf.variant`-typed function argument."""
def __init__(self, dataset_variant, structure):
super(_VariantDataset, self).__init__()
@@ -1342,20 +1342,20 @@ class StructuredFunctionWrapper(object):
func: A function from a nested structure to another nested structure.
transformation_name: Human-readable name of the transformation in which
this function is being instantiated, for error messages.
- dataset: (Optional.) A @{tf.data.Dataset}. If given, the structure of this
+ dataset: (Optional.) A `tf.data.Dataset`. If given, the structure of this
dataset will be assumed as the structure for `func` arguments; otherwise
`input_classes`, `input_shapes`, and `input_types` must be defined.
input_classes: (Optional.) A nested structure of `type`. If given, this
argument defines the Python types for `func` arguments.
- input_shapes: (Optional.) A nested structure of @{tf.TensorShape}. If
+ input_shapes: (Optional.) A nested structure of `tf.TensorShape`. If
given, this argument defines the shapes and structure for `func`
arguments.
- input_types: (Optional.) A nested structure of @{tf.DType}. If given, this
+ input_types: (Optional.) A nested structure of `tf.DType`. If given, this
argument defines the element types and structure for `func` arguments.
add_to_graph: (Optional.) If `True`, the function will be added to the
default graph.
experimental_nested_dataset_support: (Optional.) If `True`, the function
- will support @{tf.data.Dataset} objects as arguments and return values.
+ will support `tf.data.Dataset` objects as arguments and return values.
Raises:
ValueError: If an invalid combination of `dataset`, `input_classes`,
@@ -1478,7 +1478,7 @@ class StructuredFunctionWrapper(object):
self._function._create_definition_if_needed() # pylint: disable=protected-access
def _defun_args(self):
- """Returns a flat list of @{tf.DType} for the input element structure."""
+ """Returns a flat list of `tf.DType` for the input element structure."""
ret = []
for input_type, input_class in zip(nest.flatten(self._input_types),
nest.flatten(self._input_classes)):
@@ -1523,7 +1523,7 @@ def flat_structure(dataset):
`**flat_structure(self)` to the op constructor.
Args:
- dataset: A @{tf.data.Dataset}.
+ dataset: A `tf.data.Dataset`.
Returns:
A dictionary of keyword arguments that can be passed to many Dataset op
@@ -1846,7 +1846,7 @@ class ShuffleDataset(Dataset):
dataset will sample.
seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the
random seed that will be used to create the distribution. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
reshuffle_each_iteration: (Optional.) A boolean, which if true indicates
that the dataset should be pseudorandomly reshuffled each time it is
iterated over. (Defaults to `True`.)
diff --git a/tensorflow/python/data/ops/iterator_ops.py b/tensorflow/python/data/ops/iterator_ops.py
index 83c541c2f7..8f8e026df9 100644
--- a/tensorflow/python/data/ops/iterator_ops.py
+++ b/tensorflow/python/data/ops/iterator_ops.py
@@ -220,9 +220,9 @@ class Iterator(checkpointable.CheckpointableBase):
"""Creates a new, uninitialized `Iterator` based on the given handle.
This method allows you to define a "feedable" iterator where you can choose
- between concrete iterators by feeding a value in a @{tf.Session.run} call.
- In that case, `string_handle` would a @{tf.placeholder}, and you would feed
- it with the value of @{tf.data.Iterator.string_handle} in each step.
+ between concrete iterators by feeding a value in a `tf.Session.run` call.
+ In that case, `string_handle` would be a `tf.placeholder`, and you would
+ feed it with the value of `tf.data.Iterator.string_handle` in each step.
For example, if you had two iterators that marked the current position in
a training dataset and a test dataset, you could choose which to use in
@@ -362,9 +362,9 @@ class Iterator(checkpointable.CheckpointableBase):
In graph mode, you should typically call this method *once* and use its
result as the input to another computation. A typical loop will then call
- @{tf.Session.run} on the result of that computation. The loop will terminate
+ `tf.Session.run` on the result of that computation. The loop will terminate
when the `Iterator.get_next()` operation raises
- @{tf.errors.OutOfRangeError}. The following skeleton shows how to use
+ `tf.errors.OutOfRangeError`. The following skeleton shows how to use
this method when building a training loop:
```python
diff --git a/tensorflow/python/data/ops/optional_ops.py b/tensorflow/python/data/ops/optional_ops.py
index 1d3007ef76..b75b98dc72 100644
--- a/tensorflow/python/data/ops/optional_ops.py
+++ b/tensorflow/python/data/ops/optional_ops.py
@@ -33,8 +33,8 @@ class Optional(object):
An `Optional` can represent the result of an operation that may fail as a
value, rather than raising an exception and halting execution. For example,
- @{tf.contrib.data.get_next_as_optional} returns an `Optional` that either
- contains the next value from a @{tf.data.Iterator} if one exists, or a "none"
+ `tf.contrib.data.get_next_as_optional` returns an `Optional` that either
+ contains the next value from a `tf.data.Iterator` if one exists, or a "none"
value that indicates the end of the sequence has been reached.
"""
@@ -55,7 +55,7 @@ class Optional(object):
"""Returns a nested structure of values wrapped by this optional.
If this optional does not have a value (i.e. `self.has_value()` evaluates
- to `False`), this operation will raise @{tf.errors.InvalidArgumentError}
+ to `False`), this operation will raise `tf.errors.InvalidArgumentError`
at runtime.
Args:
diff --git a/tensorflow/python/data/util/BUILD b/tensorflow/python/data/util/BUILD
index 5fcc62b60b..39082ce370 100644
--- a/tensorflow/python/data/util/BUILD
+++ b/tensorflow/python/data/util/BUILD
@@ -63,6 +63,41 @@ py_test(
)
py_library(
+ name = "structure",
+ srcs = ["structure.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":nest",
+ "//tensorflow/python:dtypes",
+ "//tensorflow/python:framework_ops",
+ "//tensorflow/python:ops",
+ "//tensorflow/python:sparse_ops",
+ "//tensorflow/python:sparse_tensor",
+ "//tensorflow/python:tensor_shape",
+ "//tensorflow/python:tensor_util",
+ "//tensorflow/python:util",
+ ],
+)
+
+py_test(
+ name = "structure_test",
+ size = "small",
+ srcs = ["structure_test.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":nest",
+ ":structure",
+ "//tensorflow/python:array_ops",
+ "//tensorflow/python:client_testlib",
+ "//tensorflow/python:dtypes",
+ "//tensorflow/python:sparse_tensor",
+ "//tensorflow/python:tensor_shape",
+ "//tensorflow/python:variables",
+ "@absl_py//absl/testing:parameterized",
+ ],
+)
+
+py_library(
name = "convert",
srcs = ["convert.py"],
srcs_version = "PY2AND3",
diff --git a/tensorflow/python/data/util/convert.py b/tensorflow/python/data/util/convert.py
index 746b3d66de..ba297900b0 100644
--- a/tensorflow/python/data/util/convert.py
+++ b/tensorflow/python/data/util/convert.py
@@ -36,11 +36,11 @@ def optional_param_to_tensor(argument_name,
def partial_shape_to_tensor(shape_like):
- """Returns a @{tf.Tensor} that represents the given shape.
+ """Returns a `tf.Tensor` that represents the given shape.
Args:
- shape_like: A value that can be converted to a @{tf.TensorShape} or a
- @{tf.Tensor}.
+ shape_like: A value that can be converted to a `tf.TensorShape` or a
+ `tf.Tensor`.
Returns:
A 1-D `tf.Tensor` of `tf.int64` elements representing the given shape, where
diff --git a/tensorflow/python/data/util/random_seed.py b/tensorflow/python/data/util/random_seed.py
index e2c9d8672f..d5169f7a53 100644
--- a/tensorflow/python/data/util/random_seed.py
+++ b/tensorflow/python/data/util/random_seed.py
@@ -29,14 +29,14 @@ from tensorflow.python.ops import math_ops
def get_seed(seed):
"""Returns the local seeds an operation should use given an op-specific seed.
- See @{tf.get_seed} for more details. This wrapper adds support for the case
+ See `tf.get_seed` for more details. This wrapper adds support for the case
where `seed` may be a tensor.
Args:
- seed: An integer or a @{tf.int64} scalar tensor.
+ seed: An integer or a `tf.int64` scalar tensor.
Returns:
- A tuple of two @{tf.int64} scalar tensors that should be used for the local
+ A tuple of two `tf.int64` scalar tensors that should be used for the local
seed of the calling dataset.
"""
seed, seed2 = random_seed.get_seed(seed)
diff --git a/tensorflow/python/data/util/structure.py b/tensorflow/python/data/util/structure.py
new file mode 100644
index 0000000000..c5764b8dfe
--- /dev/null
+++ b/tensorflow/python/data/util/structure.py
@@ -0,0 +1,315 @@
+# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ==============================================================================
+"""Utilities for describing the structure of a `tf.data` type."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import abc
+
+from tensorflow.python.data.util import nest
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import ops
+from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib
+from tensorflow.python.framework import tensor_shape
+from tensorflow.python.framework import tensor_util
+from tensorflow.python.ops import sparse_ops
+
+
+class Structure(object):
+ """Represents structural information, such as type and shape, about a value.
+
+ A `Structure` generalizes the `tf.Tensor.dtype` and `tf.Tensor.shape`
+ properties, so that we can define generic containers of objects including:
+
+ * `tf.Tensor`
+ * `tf.SparseTensor`
+ * Nested structures of the above.
+
+ TODO(b/110122868): In the future, a single `Structure` will replace the
+ `tf.data.Dataset.output_types`, `tf.data.Dataset.output_shapes`,
+ and `tf.data.Dataset.output_classes`, and similar properties and arguments in
+ the `tf.data.Iterator` and `Optional` classes.
+ """
+ __metaclass__ = abc.ABCMeta
+
+ @abc.abstractproperty
+ def _flat_shapes(self):
+ """A list of shapes matching the shapes of `self._to_tensor_list()`.
+
+ Returns:
+ A list of `tf.TensorShape` objects.
+ """
+ raise NotImplementedError("Structure._flat_shapes")
+
+ @abc.abstractproperty
+ def _flat_types(self):
+ """A list of types matching the types of `self._to_tensor_list()`.
+
+ Returns:
+ A list of `tf.DType` objects.
+ """
+ raise NotImplementedError("Structure._flat_shapes")
+
+ @abc.abstractmethod
+ def is_compatible_with(self, value):
+ """Returns `True` if `value` is compatible with this structure.
+
+ A value `value` is compatible with a structure `s` if
+ `Structure.from_value(value)` would return a structure `t` that is a
+ "subtype" of `s`. A structure `t` is a "subtype" of `s` if:
+
+ * `s` and `t` are instances of the same `Structure` subclass.
+ * The nested structures (if any) of `s` and `t` are the same, according to
+ `tf.contrib.framework.nest.assert_same_structure`, and each nested
+ structure of `t` is a "subtype" of the corresponding nested structure of
+ `s`.
+ * Any `tf.DType` components of `t` are the same as the corresponding
+ components in `s`.
+ * Any `tf.TensorShape` components of `t` are compatible with the
+ corresponding components in `s`, according to
+ `tf.TensorShape.is_compatible_with`.
+
+ Args:
+ value: A potentially structured value.
+
+ Returns:
+ `True` if `value` matches this structure, otherwise `False`.
+ """
+ raise NotImplementedError("Structure.is_compatible_with()")
+
+ @abc.abstractmethod
+ def _to_tensor_list(self, value):
+ """Returns a flat list of `tf.Tensor` representing `value`.
+
+ This method can be used, along with `self._flat_shapes` and
+ `self._flat_types` to represent structured values in lower level APIs
+ (such as plain TensorFlow operations) that do not understand structure.
+
+ Requires: `self.is_compatible_with(value)`.
+
+ Args:
+ value: A value with compatible structure.
+
+ Returns:
+ A flat list of `tf.Tensor` representing `value`.
+ """
+ raise NotImplementedError("Structure._to_tensor_list()")
+
+ @abc.abstractmethod
+ def _from_tensor_list(self, flat_value):
+ """Builds a flat list of `tf.Tensor` into a value matching this structure.
+
+ Requires: The shapes and types of the tensors in `flat_value` must be
+ compatible with `self._flat_shapes` and `self._flat_types` respectively.
+
+ Args:
+ flat_value: A list of `tf.Tensor` with compatible flat structure.
+
+ Returns:
+ A structured object matching this structure.
+ """
+ raise NotImplementedError("Structure._from_tensor_list()")
+
+ @staticmethod
+ def from_value(value):
+ """Returns a `Structure` that represents the given `value`.
+
+ Args:
+ value: A potentially structured value.
+
+ Returns:
+ A `Structure` that is compatible with `value`.
+
+ Raises:
+ TypeError: If a structure cannot be built for `value`, because its type
+ or one of its component types is not supported.
+ """
+
+ # TODO(b/110122868): Add support for custom types, Dataset, and Optional
+ # to this method.
+ if isinstance(
+ value,
+ (sparse_tensor_lib.SparseTensor, sparse_tensor_lib.SparseTensorValue)):
+ return SparseTensorStructure.from_value(value)
+ elif isinstance(value, (tuple, dict)):
+ return NestedStructure.from_value(value)
+ else:
+ try:
+ tensor = ops.convert_to_tensor(value)
+ except (ValueError, TypeError):
+ raise TypeError("Could not build a structure for %r" % value)
+ return TensorStructure.from_value(tensor)
+
+
+# NOTE(mrry): The following classes make extensive use of non-public methods of
+# their base class, so we disable the protected-access lint warning once here.
+# pylint: disable=protected-access
+class NestedStructure(Structure):
+ """Represents a nested structure in which each leaf is a `Structure`."""
+
+ def __init__(self, nested_structure):
+ self._nested_structure = nested_structure
+ self._flat_shapes_list = []
+ self._flat_types_list = []
+ for s in nest.flatten(nested_structure):
+ if not isinstance(s, Structure):
+ raise TypeError("nested_structure must be a (potentially nested) tuple "
+ "or dictionary of Structure objects.")
+ self._flat_shapes_list.extend(s._flat_shapes)
+ self._flat_types_list.extend(s._flat_types)
+
+ @property
+ def _flat_shapes(self):
+ return self._flat_shapes_list
+
+ @property
+ def _flat_types(self):
+ return self._flat_types_list
+
+ def is_compatible_with(self, value):
+ try:
+ nest.assert_shallow_structure(self._nested_structure, value)
+ except (ValueError, TypeError):
+ return False
+
+ return all(
+ s.is_compatible_with(v) for s, v in zip(
+ nest.flatten(self._nested_structure),
+ nest.flatten_up_to(self._nested_structure, value)))
+
+ def _to_tensor_list(self, value):
+ ret = []
+
+ try:
+ flat_value = nest.flatten_up_to(self._nested_structure, value)
+ except (ValueError, TypeError):
+ raise ValueError("The value %r is not compatible with the nested "
+ "structure %r." % (value, self._nested_structure))
+
+ for sub_value, structure in zip(flat_value,
+ nest.flatten(self._nested_structure)):
+ if not structure.is_compatible_with(sub_value):
+ raise ValueError("Component value %r is not compatible with the nested "
+ "structure %r." % (sub_value, structure))
+ ret.extend(structure._to_tensor_list(sub_value))
+ return ret
+
+ def _from_tensor_list(self, flat_value):
+ if len(flat_value) != len(self._flat_types):
+ raise ValueError("Expected %d flat values in NestedStructure but got %d."
+ % (len(self._flat_types), len(flat_value)))
+
+ flat_ret = []
+ for sub_value, structure in zip(flat_value,
+ nest.flatten(self._nested_structure)):
+ flat_ret.append(structure._from_tensor_list([sub_value]))
+
+ return nest.pack_sequence_as(self._nested_structure, flat_ret)
+
+ @staticmethod
+ def from_value(value):
+ flat_nested_structure = [
+ Structure.from_value(sub_value) for sub_value in nest.flatten(value)
+ ]
+ return NestedStructure(nest.pack_sequence_as(value, flat_nested_structure))
+
+
+class TensorStructure(Structure):
+ """Represents structural information about a `tf.Tensor`."""
+
+ def __init__(self, dtype, shape):
+ self._dtype = dtypes.as_dtype(dtype)
+ self._shape = tensor_shape.as_shape(shape)
+
+ @property
+ def _flat_shapes(self):
+ return [self._shape]
+
+ @property
+ def _flat_types(self):
+ return [self._dtype]
+
+ def is_compatible_with(self, value):
+ try:
+ value = ops.convert_to_tensor(value, dtype=self._dtype)
+ except (ValueError, TypeError):
+ return False
+
+ return (self._dtype.is_compatible_with(value.dtype) and
+ self._shape.is_compatible_with(value.shape))
+
+ def _to_tensor_list(self, value):
+ if not self.is_compatible_with(value):
+ raise ValueError("Value %r is not convertible to a tensor with dtype %s "
+ "and shape %s." % (value, self._dtype, self._shape))
+ return [value]
+
+ def _from_tensor_list(self, flat_value):
+ if len(flat_value) != 1:
+ raise ValueError("TensorStructure corresponds to a single tf.Tensor.")
+ if not self.is_compatible_with(flat_value[0]):
+ raise ValueError("Cannot convert %r to a tensor with dtype %s and shape "
+ "%s." % (flat_value[0], self._dtype, self._shape))
+ return flat_value[0]
+
+ @staticmethod
+ def from_value(value):
+ return TensorStructure(value.dtype, value.shape)
+
+
+class SparseTensorStructure(Structure):
+ """Represents structural information about a `tf.SparseTensor`."""
+
+ def __init__(self, dtype, dense_shape):
+ self._dtype = dtypes.as_dtype(dtype)
+ self._dense_shape = tensor_shape.as_shape(dense_shape)
+
+ @property
+ def _flat_shapes(self):
+ return [tensor_shape.vector(3)]
+
+ @property
+ def _flat_types(self):
+ return [dtypes.variant]
+
+ def is_compatible_with(self, value):
+ try:
+ value = sparse_tensor_lib.SparseTensor.from_value(value)
+ except TypeError:
+ return False
+ return (isinstance(value, (sparse_tensor_lib.SparseTensor,
+ sparse_tensor_lib.SparseTensorValue)) and
+ self._dtype.is_compatible_with(value.dtype) and
+ self._dense_shape.is_compatible_with(
+ tensor_util.constant_value_as_shape(value.dense_shape)))
+
+ def _to_tensor_list(self, value):
+ return [sparse_ops.serialize_sparse(value, out_type=dtypes.variant)]
+
+ def _from_tensor_list(self, flat_value):
+ if (len(flat_value) != 1 or flat_value[0].dtype != dtypes.variant or
+ not flat_value[0].shape.is_compatible_with(tensor_shape.vector(3))):
+ raise ValueError("SparseTensorStructure corresponds to a single "
+ "tf.variant vector of length 3.")
+ return sparse_ops.deserialize_sparse(
+ flat_value[0], dtype=self._dtype, rank=self._dense_shape.ndims)
+
+ @staticmethod
+ def from_value(value):
+ sparse_tensor = sparse_tensor_lib.SparseTensor.from_value(value)
+ return SparseTensorStructure(
+ sparse_tensor.dtype,
+ tensor_util.constant_value_as_shape(sparse_tensor.dense_shape))
diff --git a/tensorflow/python/data/util/structure_test.py b/tensorflow/python/data/util/structure_test.py
new file mode 100644
index 0000000000..d0c7df67ae
--- /dev/null
+++ b/tensorflow/python/data/util/structure_test.py
@@ -0,0 +1,327 @@
+# 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 utilities working with arbitrarily nested structures."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from absl.testing import parameterized
+import numpy as np
+
+from tensorflow.python.data.util import nest
+from tensorflow.python.data.util import structure
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import sparse_tensor
+from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import variables
+from tensorflow.python.platform import test
+
+
+class StructureTest(test.TestCase, parameterized.TestCase):
+ # pylint disable=protected-access
+
+ @parameterized.parameters(
+ (constant_op.constant(37.0), structure.TensorStructure, [dtypes.float32],
+ [[]]), (sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[4, 5]),
+ structure.SparseTensorStructure, [dtypes.variant], [[3]]),
+ ((constant_op.constant(37.0), constant_op.constant([1, 2, 3])),
+ structure.NestedStructure, [dtypes.float32, dtypes.int32], [[], [3]]), ({
+ "a": constant_op.constant(37.0),
+ "b": constant_op.constant([1, 2, 3])
+ }, structure.NestedStructure, [dtypes.float32, dtypes.int32], [[], [3]]),
+ ({
+ "a":
+ constant_op.constant(37.0),
+ "b": (sparse_tensor.SparseTensor(
+ indices=[[0, 0]], values=[1], dense_shape=[1, 1]),
+ sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[4, 5]))
+ }, structure.NestedStructure,
+ [dtypes.float32, dtypes.variant, dtypes.variant], [[], [3], [3]]))
+ def testFlatStructure(self, value, expected_structure, expected_types,
+ expected_shapes):
+ s = structure.Structure.from_value(value)
+ self.assertIsInstance(s, expected_structure)
+ self.assertEqual(expected_types, s._flat_types)
+ self.assertEqual(expected_shapes, s._flat_shapes)
+
+ @parameterized.parameters(
+ (constant_op.constant(37.0), [
+ constant_op.constant(38.0),
+ array_ops.placeholder(dtypes.float32),
+ variables.Variable(100.0), 42.0,
+ np.array(42.0, dtype=np.float32)
+ ], [constant_op.constant([1.0, 2.0]),
+ constant_op.constant(37)]),
+ (sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[4, 5]),
+ [
+ sparse_tensor.SparseTensor(
+ indices=[[1, 1], [3, 4]], values=[10, -1], dense_shape=[4, 5]),
+ sparse_tensor.SparseTensorValue(
+ indices=[[1, 1], [3, 4]], values=[10, -1], dense_shape=[4, 5]),
+ array_ops.sparse_placeholder(dtype=dtypes.int32),
+ array_ops.sparse_placeholder(dtype=dtypes.int32, shape=[None, None])
+ ], [
+ constant_op.constant(37, shape=[4, 5]),
+ sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[5, 6]),
+ array_ops.sparse_placeholder(
+ dtype=dtypes.int32, shape=[None, None, None]),
+ sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1.0], dense_shape=[4, 5])
+ ]),
+ ({
+ "a": constant_op.constant(37.0),
+ "b": constant_op.constant([1, 2, 3])
+ }, [{
+ "a": constant_op.constant(15.0),
+ "b": constant_op.constant([4, 5, 6])
+ }], [{
+ "a": constant_op.constant(15.0),
+ "b": constant_op.constant([4, 5, 6, 7])
+ }, {
+ "a": constant_op.constant(15),
+ "b": constant_op.constant([4, 5, 6])
+ }, {
+ "a":
+ constant_op.constant(15),
+ "b":
+ sparse_tensor.SparseTensor(
+ indices=[[0], [1], [2]], values=[4, 5, 6], dense_shape=[3])
+ }, (constant_op.constant(15.0), constant_op.constant([4, 5, 6]))]),
+ )
+ def testIsCompatibleWith(self, original_value, compatible_values,
+ incompatible_values):
+ s = structure.Structure.from_value(original_value)
+ for compatible_value in compatible_values:
+ self.assertTrue(s.is_compatible_with(compatible_value))
+ for incompatible_value in incompatible_values:
+ self.assertFalse(s.is_compatible_with(incompatible_value))
+
+ # NOTE(mrry): The arguments must be lifted into lambdas because otherwise they
+ # will be executed before the (eager- or graph-mode) test environment has been
+ # set up.
+ # pylint: disable=g-long-lambda
+ @parameterized.parameters(
+ (lambda: constant_op.constant(37.0),),
+ (lambda: sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[4, 5]),),
+ (lambda: {"a": constant_op.constant(37.0),
+ "b": constant_op.constant([1, 2, 3])},),
+ (lambda: {"a": constant_op.constant(37.0),
+ "b": (sparse_tensor.SparseTensor(
+ indices=[[0, 0]], values=[1], dense_shape=[1, 1]),
+ sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[4, 5]))
+ },),
+ )
+ def testRoundTripConversion(self, value_fn):
+ value = value_fn()
+ s = structure.Structure.from_value(value)
+ before = self.evaluate(value)
+ after = self.evaluate(s._from_tensor_list(s._to_tensor_list(value)))
+
+ flat_before = nest.flatten(before)
+ flat_after = nest.flatten(after)
+ for b, a in zip(flat_before, flat_after):
+ if isinstance(b, sparse_tensor.SparseTensorValue):
+ self.assertAllEqual(b.indices, a.indices)
+ self.assertAllEqual(b.values, a.values)
+ self.assertAllEqual(b.dense_shape, a.dense_shape)
+ else:
+ self.assertAllEqual(b, a)
+ # pylint: enable=g-long-lambda
+
+ def testIncompatibleStructure(self):
+ # Define three mutually incompatible values/structures, and assert that:
+ # 1. Using one structure to flatten a value with an incompatible structure
+ # fails.
+ # 2. Using one structure to restructre a flattened value with an
+ # incompatible structure fails.
+ value_tensor = constant_op.constant(42.0)
+ s_tensor = structure.Structure.from_value(value_tensor)
+ flat_tensor = s_tensor._to_tensor_list(value_tensor)
+
+ value_sparse_tensor = sparse_tensor.SparseTensor(
+ indices=[[0, 0]], values=[1], dense_shape=[1, 1])
+ s_sparse_tensor = structure.Structure.from_value(value_sparse_tensor)
+ flat_sparse_tensor = s_sparse_tensor._to_tensor_list(value_sparse_tensor)
+
+ value_nest = {
+ "a": constant_op.constant(37.0),
+ "b": constant_op.constant([1, 2, 3])
+ }
+ s_nest = structure.Structure.from_value(value_nest)
+ flat_nest = s_nest._to_tensor_list(value_nest)
+
+ with self.assertRaisesRegexp(
+ ValueError, r"SparseTensor.* is not convertible to a tensor with "
+ r"dtype.*float32.* and shape \(\)"):
+ s_tensor._to_tensor_list(value_sparse_tensor)
+ with self.assertRaisesRegexp(
+ ValueError, r"Value \{.*\} is not convertible to a tensor with "
+ r"dtype.*float32.* and shape \(\)"):
+ s_tensor._to_tensor_list(value_nest)
+
+ with self.assertRaisesRegexp(TypeError, "Input must be a SparseTensor"):
+ s_sparse_tensor._to_tensor_list(value_tensor)
+
+ with self.assertRaisesRegexp(TypeError, "Input must be a SparseTensor"):
+ s_sparse_tensor._to_tensor_list(value_nest)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Tensor.* not compatible with the nested structure "
+ ".*TensorStructure.*TensorStructure"):
+ s_nest._to_tensor_list(value_tensor)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensor.* not compatible with the nested structure "
+ ".*TensorStructure.*TensorStructure"):
+ s_nest._to_tensor_list(value_sparse_tensor)
+
+ with self.assertRaisesRegexp(
+ ValueError, r"Cannot convert.*with dtype.*float32.* and shape \(\)"):
+ s_tensor._from_tensor_list(flat_sparse_tensor)
+
+ with self.assertRaisesRegexp(
+ ValueError, "TensorStructure corresponds to a single tf.Tensor."):
+ s_tensor._from_tensor_list(flat_nest)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensorStructure corresponds to a single tf.variant "
+ "vector of length 3."):
+ s_sparse_tensor._from_tensor_list(flat_tensor)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensorStructure corresponds to a single tf.variant "
+ "vector of length 3."):
+ s_sparse_tensor._from_tensor_list(flat_nest)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Expected 2 flat values in NestedStructure but got 1."):
+ s_nest._from_tensor_list(flat_tensor)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Expected 2 flat values in NestedStructure but got 1."):
+ s_nest._from_tensor_list(flat_sparse_tensor)
+
+ def testIncompatibleNestedStructure(self):
+ # Define three mutually incompatible nested values/structures, and assert
+ # that:
+ # 1. Using one structure to flatten a value with an incompatible structure
+ # fails.
+ # 2. Using one structure to restructre a flattened value with an
+ # incompatible structure fails.
+
+ value_0 = {
+ "a": constant_op.constant(37.0),
+ "b": constant_op.constant([1, 2, 3])
+ }
+ s_0 = structure.Structure.from_value(value_0)
+ flat_s_0 = s_0._to_tensor_list(value_0)
+
+ # `value_1` has compatible nested structure with `value_0`, but different
+ # classes.
+ value_1 = {
+ "a":
+ constant_op.constant(37.0),
+ "b":
+ sparse_tensor.SparseTensor(
+ indices=[[0, 0]], values=[1], dense_shape=[1, 1])
+ }
+ s_1 = structure.Structure.from_value(value_1)
+ flat_s_1 = s_1._to_tensor_list(value_1)
+
+ # `value_2` has incompatible nested structure with `value_0` and `value_1`.
+ value_2 = {
+ "a":
+ constant_op.constant(37.0),
+ "b": (sparse_tensor.SparseTensor(
+ indices=[[0, 0]], values=[1], dense_shape=[1, 1]),
+ sparse_tensor.SparseTensor(
+ indices=[[3, 4]], values=[-1], dense_shape=[4, 5]))
+ }
+ s_2 = structure.Structure.from_value(value_2)
+ flat_s_2 = s_2._to_tensor_list(value_2)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensor.* not compatible with the nested structure "
+ ".*TensorStructure"):
+ s_0._to_tensor_list(value_1)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensor.*SparseTensor.* not compatible with the "
+ "nested structure .*TensorStructure"):
+ s_0._to_tensor_list(value_2)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Tensor.* not compatible with the nested structure "
+ ".*SparseTensorStructure"):
+ s_1._to_tensor_list(value_0)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensor.*SparseTensor.* not compatible with the "
+ "nested structure .*TensorStructure"):
+ s_0._to_tensor_list(value_2)
+
+ # NOTE(mrry): The repr of the dictionaries is not sorted, so the regexp
+ # needs to account for "a" coming before or after "b". It might be worth
+ # adding a deterministic repr for these error messages (among other
+ # improvements).
+ with self.assertRaisesRegexp(
+ ValueError, "Tensor.*Tensor.* not compatible with the nested structure "
+ ".*(TensorStructure.*SparseTensorStructure.*SparseTensorStructure|"
+ "SparseTensorStructure.*SparseTensorStructure.*TensorStructure)"):
+ s_2._to_tensor_list(value_0)
+
+ with self.assertRaisesRegexp(
+ ValueError, "(Tensor.*SparseTensor|SparseTensor.*Tensor).* "
+ "not compatible with the nested structure .*"
+ "(TensorStructure.*SparseTensorStructure.*SparseTensorStructure|"
+ "SparseTensorStructure.*SparseTensorStructure.*TensorStructure)"):
+ s_2._to_tensor_list(value_1)
+
+ with self.assertRaisesRegexp(
+ ValueError, r"Cannot convert.*with dtype.*int32.* and shape \(3,\)"):
+ s_0._from_tensor_list(flat_s_1)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Expected 2 flat values in NestedStructure but got 3."):
+ s_0._from_tensor_list(flat_s_2)
+
+ with self.assertRaisesRegexp(
+ ValueError, "SparseTensorStructure corresponds to a single tf.variant "
+ "vector of length 3."):
+ s_1._from_tensor_list(flat_s_0)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Expected 2 flat values in NestedStructure but got 3."):
+ s_1._from_tensor_list(flat_s_2)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Expected 3 flat values in NestedStructure but got 2."):
+ s_2._from_tensor_list(flat_s_0)
+
+ with self.assertRaisesRegexp(
+ ValueError, "Expected 3 flat values in NestedStructure but got 2."):
+ s_2._from_tensor_list(flat_s_1)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/python/debug/BUILD b/tensorflow/python/debug/BUILD
index 27b8ebd362..8a4ac6aaef 100644
--- a/tensorflow/python/debug/BUILD
+++ b/tensorflow/python/debug/BUILD
@@ -936,7 +936,6 @@ py_test(
size = "small",
srcs = ["cli/profile_analyzer_cli_test.py"],
srcs_version = "PY2AND3",
- tags = ["no_windows"],
deps = [
":debugger_cli_common",
":profile_analyzer_cli",
diff --git a/tensorflow/python/debug/__init__.py b/tensorflow/python/debug/__init__.py
index 34da44b60d..242215dccb 100644
--- a/tensorflow/python/debug/__init__.py
+++ b/tensorflow/python/debug/__init__.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""Public Python API of TensorFlow Debugger (tfdbg).
-See the @{$python/tfdbg} guide.
+See the [TFDBG](https://tensorflow.org/api_guides/python/tfdbg) guide.
@@add_debug_tensor_watch
@@watch_graph
diff --git a/tensorflow/python/debug/lib/debug_gradients.py b/tensorflow/python/debug/lib/debug_gradients.py
index 589a13db7f..5e95bcba47 100644
--- a/tensorflow/python/debug/lib/debug_gradients.py
+++ b/tensorflow/python/debug/lib/debug_gradients.py
@@ -69,7 +69,7 @@ class GradientsDebugger(object):
"""Gradients Debugger.
Allows retrieval of gradient tensors created by TensorFlow's automatic
- differentiation algorithm, i.e., @{tf.gradients} and optimizer classes that
+ differentiation algorithm, i.e., `tf.gradients` and optimizer classes that
use it.
"""
# TODO(cais): Add examples code in the doc string?
@@ -142,8 +142,8 @@ class GradientsDebugger(object):
Args:
input_tensor: the input `tf.Tensor` object whose related gradient tensors
are to be reigstered with this `GradientsDebugger` instance when they
- are created, e.g., during @{tf.gradients} calls or the construction
- of optimization (training) op that uses @{tf.gradients}.
+ are created, e.g., during `tf.gradients` calls or the construction
+ of optimization (training) op that uses `tf.gradients`.
Returns:
A forwarded identity of `input_tensor`, as a `tf.Tensor`.
diff --git a/tensorflow/python/debug/wrappers/dumping_wrapper.py b/tensorflow/python/debug/wrappers/dumping_wrapper.py
index 3fac2e5971..c02d5f66ec 100644
--- a/tensorflow/python/debug/wrappers/dumping_wrapper.py
+++ b/tensorflow/python/debug/wrappers/dumping_wrapper.py
@@ -45,7 +45,7 @@ class DumpingDebugWrapperSession(framework.NonInteractiveDebugWrapperSession):
session_root: (`str`) Path to the session root directory. Must be a
directory that does not exist or an empty directory. If the directory
does not exist, it will be created by the debugger core during debug
- @{tf.Session.run}
+ `tf.Session.run`
calls.
As the `run()` calls occur, subdirectories will be added to
`session_root`. The subdirectories' names has the following pattern:
diff --git a/tensorflow/python/distribute/BUILD b/tensorflow/python/distribute/BUILD
index 68d8b8d13b..98ef9bf492 100644
--- a/tensorflow/python/distribute/BUILD
+++ b/tensorflow/python/distribute/BUILD
@@ -41,3 +41,43 @@ py_test(
"//tensorflow/python:variables",
],
)
+
+py_library(
+ name = "distribute_coordinator_context",
+ srcs = [
+ "distribute_coordinator_context.py",
+ ],
+ srcs_version = "PY2AND3",
+ deps = [],
+)
+
+py_library(
+ name = "multi_worker_util",
+ srcs = [
+ "multi_worker_util.py",
+ ],
+ srcs_version = "PY2AND3",
+ deps = [
+ "//tensorflow/core:protos_all_py",
+ "//tensorflow/python:training",
+ ],
+)
+
+py_test(
+ name = "multi_worker_util_test",
+ srcs = ["multi_worker_util_test.py"],
+ srcs_version = "PY2AND3",
+ tags = ["no_pip"],
+ deps = [
+ ":multi_worker_util",
+ "//tensorflow/core:protos_all_py",
+ "//tensorflow/python:constant_op",
+ "//tensorflow/python:framework_ops",
+ "//tensorflow/python:framework_test_lib",
+ "//tensorflow/python:math_ops",
+ "//tensorflow/python:training",
+ "//tensorflow/python/eager:test",
+ "//third_party/py/numpy",
+ "@absl_py//absl/testing:parameterized",
+ ],
+)
diff --git a/tensorflow/python/distribute/distribute_coordinator.py b/tensorflow/python/distribute/distribute_coordinator.py
index fc9ca4ac4a..eb081b65fc 100644
--- a/tensorflow/python/distribute/distribute_coordinator.py
+++ b/tensorflow/python/distribute/distribute_coordinator.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
-"""A unified and split coordinator for distributed TensorFlow."""
+"""A component for running distributed TensorFlow."""
from __future__ import absolute_import
from __future__ import division
@@ -24,6 +24,8 @@ import os
import threading
from tensorflow.core.protobuf import cluster_pb2
+from tensorflow.python.distribute import distribute_coordinator_context
+from tensorflow.python.training import monitored_session
from tensorflow.python.training import server_lib
@@ -43,23 +45,12 @@ class CoordinatorMode(object):
# client and connects to remote servers for training. Each remote server can
# use the distribute coordinator binary with task_type set correctly which
# will then turn into standard servers.
- SPLIT_CLIENT = 0
+ STANDALONE_CLIENT = "standalone_client"
# The distribute coordinator runs on each worker. It will run a standard
# server on each worker and optionally run the `worker_fn` that is configured
# to talk to its standard server.
- INDEPENDENT_WORKER = 1
-
-
-_worker_context = threading.local()
-
-
-def get_current_worker_context():
- """Returns the current task context."""
- try:
- return _worker_context.current
- except AttributeError:
- return None
+ INDEPENDENT_WORKER = "independent_worker"
class _Barrier(object):
@@ -113,14 +104,17 @@ class _WorkerContext(object):
"""
def __init__(self,
+ strategy,
cluster_spec,
task_type,
task_id,
+ session_config=None,
rpc_layer="grpc",
worker_barrier=None):
"""Initialize the worker context object.
Args:
+ strategy: a `DistributionStrategy` object.
cluster_spec: a ClusterSpec object. It can be empty or None in the local
training case.
task_type: a string indicating the role of the corresponding task, such as
@@ -128,14 +122,17 @@ class _WorkerContext(object):
replicated training.
task_id: an integer indicating id of the corresponding task. It can be
None if it is local training or in-graph replicated training.
+ session_config: an optional @{tf.ConfigProto} object.
rpc_layer: optional string specifying the RPC protocol for communication
with worker masters. If None or empty, hosts in the `cluster_spec` will
be used directly.
worker_barrier: optional, the barrier object for worker synchronization.
"""
+ self._strategy = strategy
self._cluster_spec = cluster_spec
self._task_type = task_type
self._task_id = task_id
+ self._session_config = session_config
self._worker_barrier = worker_barrier
self._rpc_layer = rpc_layer
self._master_target = self._get_master_target()
@@ -143,26 +140,31 @@ class _WorkerContext(object):
self._is_chief_node = self._is_chief()
def _debug_message(self):
- return "[cluster_spec: %r, task_type: %r, task_id: %r]" % (
- self._cluster_spec, self.task_type, self.task_id)
+ if self._cluster_spec:
+ return "[cluster_spec: %r, task_type: %r, task_id: %r]" % (
+ self._cluster_spec, self.task_type, self.task_id)
+ else:
+ return "[local]"
def __enter__(self):
- old_context = get_current_worker_context()
+ old_context = distribute_coordinator_context.get_current_worker_context()
if old_context:
raise ValueError(
"You cannot run distribute coordinator in a `worker_fn`.\t" +
self._debug_message())
- _worker_context.current = self
+ # pylint: disable=protected-access
+ distribute_coordinator_context._worker_context.current = self
def __exit__(self, unused_exception_type, unused_exception_value,
unused_traceback):
- _worker_context.current = None
+ # pylint: disable=protected-access
+ distribute_coordinator_context._worker_context.current = None
def _get_master_target(self):
"""Return the master target for a task."""
# If cluster_spec is None or empty, we use local master.
if not self._cluster_spec:
- return "local"
+ return ""
# If task_type is None, then it is in-graph replicated training. In this
# case we use the chief or first worker's master target.
@@ -207,6 +209,47 @@ class _WorkerContext(object):
self._debug_message())
self._worker_barrier.wait()
+ def session_creator(self,
+ scaffold=None,
+ config=None,
+ checkpoint_dir=None,
+ checkpoint_filename_with_path=None,
+ max_wait_secs=7200):
+ """Returns a session creator.
+
+ The returned session creator will be configured with the correct master
+ target and session configs. It will also run either init ops or ready ops
+ by querying the `strategy` object when `create_session` is called on it.
+
+ Args:
+ scaffold: A `Scaffold` used for gathering or building supportive ops. If
+ not specified a default one is created. It's used to finalize the graph.
+ config: `ConfigProto` proto used to configure the session.
+ checkpoint_dir: A string. Optional path to a directory where to restore
+ variables.
+ checkpoint_filename_with_path: Full file name path to the checkpoint file.
+ Only one of `checkpoint_dir` or `checkpoint_filename_with_path` can be
+ specified.
+ max_wait_secs: Maximum time to wait for the session to become available.
+
+ Returns:
+ a descendant of SessionCreator.
+ """
+ # TODO(yuefengz): merge session config.
+ if self._strategy.should_init:
+ return monitored_session.ChiefSessionCreator(
+ scaffold,
+ master=self.master_target,
+ config=config or self._session_config,
+ checkpoint_dir=checkpoint_dir,
+ checkpoint_filename_with_path=checkpoint_filename_with_path)
+ else:
+ return monitored_session.WorkerSessionCreator(
+ scaffold,
+ master=self.master_target,
+ config=config or self._session_config,
+ max_wait_secs=max_wait_secs)
+
@property
def has_barrier(self):
"""Whether the barrier is set or not."""
@@ -247,21 +290,38 @@ class _WorkerContext(object):
"""Returns number of workers in the cluster, including chief."""
return self._num_workers
+ @property
+ def should_checkpoint(self):
+ """Whether to save checkpoint."""
+ return self._strategy.should_checkpoint
+
+ @property
+ def should_save_summary(self):
+ """Whether to save summaries."""
+ return self._strategy.should_save_summary
+
def _run_single_worker(worker_fn,
+ strategy,
cluster_spec,
task_type,
task_id,
- rpc_layer,
+ session_config,
+ rpc_layer="",
worker_barrier=None):
"""Runs a single worker by calling `worker_fn` under context."""
- with _WorkerContext(
+ strategy = copy.deepcopy(strategy)
+ strategy.configure(session_config, cluster_spec, task_type, task_id)
+ context = _WorkerContext(
+ strategy,
cluster_spec,
task_type,
task_id,
+ session_config=session_config,
rpc_layer=rpc_layer,
- worker_barrier=worker_barrier):
- worker_fn()
+ worker_barrier=worker_barrier)
+ with context:
+ worker_fn(strategy)
def _run_std_server(cluster_spec=None,
@@ -280,13 +340,15 @@ def _run_std_server(cluster_spec=None,
return server
-def _run_between_graph_client(worker_fn, cluster_spec, rpc_layer):
+def _run_between_graph_client(worker_fn, strategy, cluster_spec, session_config,
+ rpc_layer):
"""Runs a standalone client for between-graph replication."""
eval_thread = None
if _TaskType.EVALUATOR in cluster_spec.jobs:
eval_thread = threading.Thread(
target=_run_single_worker,
- args=(worker_fn, cluster_spec, _TaskType.EVALUATOR, 0),
+ args=(worker_fn, strategy, cluster_spec, _TaskType.EVALUATOR, 0,
+ session_config),
kwargs={
"rpc_layer": rpc_layer,
})
@@ -298,7 +360,8 @@ def _run_between_graph_client(worker_fn, cluster_spec, rpc_layer):
for task_id in range(len(cluster_spec.as_dict().get(task_type, []))):
t = threading.Thread(
target=_run_single_worker,
- args=(worker_fn, cluster_spec, task_type, task_id),
+ args=(worker_fn, strategy, cluster_spec, task_type, task_id,
+ session_config),
kwargs={
"rpc_layer": rpc_layer,
"worker_barrier": worker_barrier
@@ -315,43 +378,53 @@ def _run_between_graph_client(worker_fn, cluster_spec, rpc_layer):
eval_thread.join()
-def _run_in_graph_client(worker_fn, cluster_spec, rpc_layer):
+def _run_in_graph_client(worker_fn, strategy, cluster_spec, session_config,
+ rpc_layer):
"""Runs a standalone client for in-graph replication."""
eval_thread = None
if _TaskType.EVALUATOR in cluster_spec.jobs:
eval_thread = threading.Thread(
target=_run_single_worker,
- args=(worker_fn, cluster_spec, _TaskType.EVALUATOR, 0),
+ args=(worker_fn, strategy, cluster_spec, _TaskType.EVALUATOR, 0,
+ session_config),
kwargs={
"rpc_layer": rpc_layer,
})
eval_thread.start()
- _run_single_worker(worker_fn, cluster_spec, None, None, rpc_layer)
+ _run_single_worker(
+ worker_fn,
+ strategy,
+ cluster_spec,
+ None,
+ None,
+ session_config,
+ rpc_layer=rpc_layer)
if eval_thread:
eval_thread.join()
-
-# TODO(yuefengz): propagate cluster_spec in the SPLIT_CLIENT mode.
+# TODO(yuefengz): propagate cluster_spec in the STANDALONE_CLIENT mode.
# TODO(yuefengz): we may need a smart way to figure out whether the current task
# is the special task when we support cluster_spec propagation.
def run_distribute_coordinator(worker_fn,
- mode=CoordinatorMode.SPLIT_CLIENT,
+ strategy,
+ mode=CoordinatorMode.STANDALONE_CLIENT,
cluster_spec=None,
task_type=None,
task_id=None,
- between_graph=False,
+ session_config=None,
rpc_layer="grpc"):
"""Runs the coordinator for distributed TensorFlow.
This function runs a split coordinator for distributed TensorFlow in its
- default mode, i.e the SPLIT_CLIENT mode. Given a `cluster_spec` specifying
- server addresses and their roles in a cluster, this coordinator will figure
- out how to set them up, give the underlying function the right targets for
- master sessions via a scope object and coordinate their training. The cluster
- consisting of standard servers needs to be brought up either with the standard
- server binary or with a binary running distribute coordinator with `task_type`
- set to non-client type which will then turn into standard servers.
+ default mode, i.e the STANDALONE_CLIENT mode. Given a `cluster_spec`
+ specifying server addresses and their roles in a cluster, this coordinator
+ will figure out how to set them up, give the underlying function the right
+ targets for master sessions via a scope object and coordinate their training.
+ The cluster consisting of standard servers needs to be brought up either with
+ the standard server binary or with a binary running distribute coordinator
+ with `task_type` set to non-client type which will then turn into standard
+ servers.
In addition to be the distribute coordinator, this is also the source of
configurations for each job in the distributed training. As there are multiple
@@ -370,6 +443,14 @@ def run_distribute_coordinator(worker_fn,
`worker_fn` depending whether it is between-graph training or in-graph
replicated training.
+ The `strategy` object is expected to be a DistributionStrategy object which
+ has implemented methods needed by distributed coordinator such as
+ `configure(session_config, cluster_spec, task_type, task_id)` which configures
+ the strategy object for a specific task and `should_init` property which
+ instructs the distribute coordinator whether to run init ops for a task. The
+ distribute coordinator will make a copy of the `strategy` object, call its
+ `configure` method and pass it to `worker_fn` as an argument.
+
The `worker_fn` defines the training logic and is called under a its own
worker context which can be accessed to via `get_current_worker_context`. A
worker context provides access to configurations for each task, e.g. the
@@ -413,16 +494,20 @@ def run_distribute_coordinator(worker_fn,
evaluation.
Args:
- worker_fn: the function to be called and given the access to a coordinator
- context object.
+ worker_fn: the function to be called. The function should accept a
+ `strategy` object and will be given access to a context object via a
+ context manager scope.
+ strategy: a DistributionStrategy object which specifying whether it should
+ run between-graph replicated training or not, whether to run init ops,
+ etc. This object will also be configured given `session_config`,
+ `cluster_spc`, `task_type` and `task_id`.
mode: in which mode this distribute coordinator runs.
cluster_spec: a dict, ClusterDef or ClusterSpec specifying servers and roles
in a cluster. If not set or empty, fall back to local training.
task_type: the current task type, optional if this is a client.
task_id: the current task id, optional if this is a client.
- between_graph: a boolean. It is only useful when `cluster_spec` is set and
- not empty. If true, it will use between-graph replicated training;
- otherwise it will use in-graph replicated training.
+ session_config: an optional @{tf.ConfigProto} object which will be passed
+ to `strategy`'s `configure` method and used to create a session.
rpc_layer: optional string, the protocol for RPC, e.g. "grpc".
Raises:
@@ -448,15 +533,18 @@ def run_distribute_coordinator(worker_fn,
if not cluster_spec:
# `mode` is ignored in the local case.
- _run_single_worker(worker_fn, None, None, None, rpc_layer)
- elif mode == CoordinatorMode.SPLIT_CLIENT:
+ _run_single_worker(worker_fn, strategy, None, None, None, session_config,
+ rpc_layer)
+ elif mode == CoordinatorMode.STANDALONE_CLIENT:
# The client must know the cluster but servers in the cluster don't have to
# know the client.
if task_type in [_TaskType.CLIENT, None]:
- if between_graph:
- _run_between_graph_client(worker_fn, cluster_spec, rpc_layer)
+ if strategy.between_graph:
+ _run_between_graph_client(worker_fn, strategy, cluster_spec,
+ session_config, rpc_layer)
else:
- _run_in_graph_client(worker_fn, cluster_spec, rpc_layer)
+ _run_in_graph_client(worker_fn, strategy, cluster_spec, session_config,
+ rpc_layer)
else:
# If not a client job, run the standard server.
server = _run_std_server(
@@ -471,19 +559,21 @@ def run_distribute_coordinator(worker_fn,
cluster_spec=cluster_spec, task_type=task_type, task_id=task_id)
if task_type in [_TaskType.CHIEF, _TaskType.WORKER]:
- if between_graph:
+ if strategy.between_graph:
# All jobs run `worker_fn` if between-graph.
- _run_single_worker(worker_fn, cluster_spec, task_type, task_id,
- rpc_layer)
+ _run_single_worker(worker_fn, strategy, cluster_spec, task_type,
+ task_id, session_config, rpc_layer)
else:
# Only one node runs `worker_fn` if in-graph.
- context = _WorkerContext(cluster_spec, task_type, task_id, rpc_layer)
+ context = _WorkerContext(strategy, cluster_spec, task_type, task_id)
if context.is_chief:
- _run_single_worker(worker_fn, cluster_spec, None, None, rpc_layer)
+ _run_single_worker(worker_fn, strategy, cluster_spec, None, None,
+ session_config, rpc_layer)
else:
server.join()
elif task_type == _TaskType.EVALUATOR:
- _run_single_worker(worker_fn, cluster_spec, task_type, task_id, rpc_layer)
+ _run_single_worker(worker_fn, strategy, cluster_spec, task_type, task_id,
+ session_config, rpc_layer)
else:
if task_type != _TaskType.PS:
raise ValueError("Unexpected task_type: %r" % task_type)
diff --git a/tensorflow/python/distribute/distribute_coordinator_context.py b/tensorflow/python/distribute/distribute_coordinator_context.py
new file mode 100644
index 0000000000..dee65ce883
--- /dev/null
+++ b/tensorflow/python/distribute/distribute_coordinator_context.py
@@ -0,0 +1,31 @@
+# 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.
+# ==============================================================================
+"""The context retrieval method for distribute coordinator."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import threading
+
+_worker_context = threading.local()
+
+
+def get_current_worker_context():
+ """Returns the current task context."""
+ try:
+ return _worker_context.current
+ except AttributeError:
+ return None
diff --git a/tensorflow/python/distribute/distribute_coordinator_test.py b/tensorflow/python/distribute/distribute_coordinator_test.py
index 319c29ba2f..97c6bdd15a 100644
--- a/tensorflow/python/distribute/distribute_coordinator_test.py
+++ b/tensorflow/python/distribute/distribute_coordinator_test.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
-"""Tests for distribute coordinator."""
+"""Tests for Distribute Coordinator."""
from __future__ import absolute_import
from __future__ import division
@@ -37,6 +37,7 @@ except ImportError as _error:
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.distribute import distribute_coordinator
+from tensorflow.python.distribute import distribute_coordinator_context
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
@@ -44,17 +45,17 @@ from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
+from tensorflow.python.training import monitored_session
+
CHIEF = distribute_coordinator._TaskType.CHIEF
WORKER = distribute_coordinator._TaskType.WORKER
PS = distribute_coordinator._TaskType.PS
EVALUATOR = distribute_coordinator._TaskType.EVALUATOR
-SPLIT_CLIENT = distribute_coordinator.CoordinatorMode.SPLIT_CLIENT
+STANDALONE_CLIENT = distribute_coordinator.CoordinatorMode.STANDALONE_CLIENT
INDEPENDENT_WORKER = distribute_coordinator.CoordinatorMode.INDEPENDENT_WORKER
-RUN_STD_SERVER_METHOD = "tensorflow.python.distribute.distribute_coordinator._run_std_server"
-
NUM_WORKERS = 3
NUM_PS = 2
@@ -74,6 +75,57 @@ def _strip_protocol(target):
return target
+class MockStrategy(object):
+
+ def __init__(self,
+ between_graph=False,
+ should_init=None,
+ should_checkpoint=None,
+ should_save_summary=None):
+ self._between_graph = between_graph
+ self._should_init = should_init
+ self._should_checkpoint = should_checkpoint
+ self._should_save_summary = should_save_summary
+
+ @property
+ def between_graph(self):
+ return self._between_graph
+
+ def configure(self,
+ session_options=None,
+ cluster_spec=None,
+ task_type=None,
+ task_id=None):
+ del session_options, cluster_spec, task_type
+ if self._should_init is None:
+ if task_id == 0:
+ self._should_init = True
+ else:
+ self._should_init = False
+ if self._should_checkpoint is None:
+ if task_id == 0:
+ self._should_checkpoint = True
+ else:
+ self._should_checkpoint = False
+ if self._should_save_summary is None:
+ if task_id == 0:
+ self._should_save_summary = True
+ else:
+ self._should_save_summary = False
+
+ @property
+ def should_init(self):
+ return self._should_init
+
+ @property
+ def should_checkpoint(self):
+ return self._should_checkpoint
+
+ @property
+ def should_save_summary(self):
+ return self._should_save_summary
+
+
class MockServer(object):
def __init__(self):
@@ -108,6 +160,7 @@ class DistributeCoordinatorTestBase(test.TestCase):
self._result_correct = 0
self._lock = threading.Lock()
self._worker_context = {}
+ self._strategy_property = {}
self._std_servers = {}
self._barrier = distribute_coordinator._Barrier(NUM_WORKERS)
@@ -142,8 +195,8 @@ class DistributeCoordinatorTestBase(test.TestCase):
cluster_spec[EVALUATOR] = ["localhost:%s" % portpicker.pick_unused_port()]
return cluster_spec
- def _in_graph_worker_fn(self):
- context = distribute_coordinator.get_current_worker_context()
+ def _in_graph_worker_fn(self, strategy):
+ context = distribute_coordinator_context.get_current_worker_context()
self.assertTrue(context is not None)
with self._test_session(target=context.master_target) as sess:
xs = []
@@ -164,22 +217,23 @@ class DistributeCoordinatorTestBase(test.TestCase):
if result_value == expected:
self._result_correct += 1
- def _run_coordinator_in_thread(self, worker_fn, **kwargs):
+ def _run_coordinator_in_thread(self, worker_fn, strategy, **kwargs):
t = threading.Thread(
target=distribute_coordinator.run_distribute_coordinator,
- args=(worker_fn,),
+ args=(worker_fn, strategy),
kwargs=kwargs)
t.start()
return t
- def _run_multiple_coordinator_in_threads(self, worker_fn, cluster_spec,
- **kwargs):
+ def _run_multiple_coordinator_in_threads(self, worker_fn, strategy,
+ cluster_spec, **kwargs):
threads = {}
for task_type in cluster_spec.keys():
threads[task_type] = []
for task_id in range(len(cluster_spec[task_type])):
t = self._run_coordinator_in_thread(
worker_fn,
+ strategy,
cluster_spec=cluster_spec,
task_type=task_type,
task_id=task_id,
@@ -187,8 +241,8 @@ class DistributeCoordinatorTestBase(test.TestCase):
threads[task_type].append(t)
return threads
- def _between_graph_worker_fn(self):
- context = distribute_coordinator.get_current_worker_context()
+ def _between_graph_worker_fn(self, strategy):
+ context = distribute_coordinator_context.get_current_worker_context()
self.assertTrue(context is not None)
with self._test_session(target=context.master_target) as sess:
with ops.device("/job:ps/task:0"):
@@ -234,14 +288,50 @@ class DistributeCoordinatorTestBase(test.TestCase):
with self._lock:
self._result_correct += 1
- def _dump_worker_context(self):
+ def _between_graph_with_monitored_session(self, strategy):
+ context = distribute_coordinator_context.get_current_worker_context()
+ self.assertTrue(context is not None)
+ with ops.device("/job:ps/task:0"):
+ # TODO(yuefengz): investigate why not using resource variable will make
+ # the test flaky.
+ x = variable_scope.get_variable("x", initializer=10.0, use_resource=True)
+ with ops.device("/job:ps/task:1"):
+ y = variable_scope.get_variable("y", initializer=20.0, use_resource=True)
+
+ x_add = x.assign_add(2.0)
+ y_sub = y.assign_sub(2.0)
+ train_op = control_flow_ops.group([x_add, y_sub])
+
+ # The monitored session will run init or ready ops.
+ with monitored_session.MonitoredSession() as sess:
+ sess.run(train_op)
+
+ # Synchronize workers after one step to make sure they all have finished
+ # training.
+ if context.has_barrier:
+ context.wait_for_other_workers()
+ else:
+ self._barrier.wait()
+
+ x_val, y_val = sess.run([x, y])
+
+ self.assertEqual(x_val, 16.0)
+ self.assertEqual(y_val, 14.0)
+ if x_val == 16.0 and y_val == 14.0:
+ with self._lock:
+ self._result_correct += 1
+
+ def _dump_worker_context(self, strategy):
"""Dumps the propoerties of each worker context.
It dumps the context properties to a dict mapping from task_type to a list
of tuples of master_target, num_workers, is_chief and distribute_mode, where
the list is indexed by the task_id.
+
+ Args:
+ strategy: a `DistributionStrategy` object.
"""
- context = distribute_coordinator.get_current_worker_context()
+ context = distribute_coordinator_context.get_current_worker_context()
self.assertTrue(context is not None)
task_type = str(context.task_type)
task_id = context.task_id or 0
@@ -255,6 +345,25 @@ class DistributeCoordinatorTestBase(test.TestCase):
context.is_chief,
context.distributed_mode)
+ def _dump_strategy_property(self, strategy):
+ context = distribute_coordinator_context.get_current_worker_context()
+ self.assertTrue(context is not None)
+
+ self.assertEqual(context._strategy.should_init, strategy.should_init)
+ self.assertEqual(context.should_checkpoint, strategy.should_checkpoint)
+ self.assertEqual(context.should_save_summary, strategy.should_save_summary)
+
+ task_type = str(context.task_type)
+ task_id = context.task_id or 0
+ with self._lock:
+ if task_type not in self._strategy_property:
+ self._strategy_property[task_type] = []
+ while len(self._strategy_property[task_type]) <= task_id:
+ self._strategy_property[task_type].append(None)
+ self._strategy_property[task_type][task_id] = (
+ context._strategy.should_init, context.should_checkpoint,
+ context.should_save_summary)
+
def _run_mock_std_server(self,
session_config=None,
cluster_spec=None,
@@ -274,22 +383,32 @@ class DistributeCoordinatorTestBase(test.TestCase):
return server
-class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
+class DistributeCoordinatorTestStandaloneMode(DistributeCoordinatorTestBase):
- def testInGraphSplitMode(self):
- """Test it runs in-graph replication in split client mode."""
+ def testInGraphStandaloneMode(self):
+ """Test it runs in-graph replication in standalone client mode."""
distribute_coordinator.run_distribute_coordinator(
self._in_graph_worker_fn,
- cluster_spec=self._cluster_spec,
- between_graph=False)
+ MockStrategy(between_graph=False),
+ cluster_spec=self._cluster_spec)
self.assertEqual(self._result_correct, 1)
def testBetweenGraph(self):
- """Test it runs between-graph replication in split client mode."""
+ """Test it runs between-graph replication in standalone client mode."""
distribute_coordinator.run_distribute_coordinator(
self._between_graph_worker_fn,
- cluster_spec=self._cluster_spec,
- between_graph=True)
+ MockStrategy(between_graph=True),
+ cluster_spec=self._cluster_spec)
+
+ # Each finished worker will increment self._result_correct.
+ self.assertEqual(self._result_correct, NUM_WORKERS)
+
+ def testBetweenGraphWithMonitoredSession(self):
+ """Test monitored session in standalone client mode."""
+ distribute_coordinator.run_distribute_coordinator(
+ self._between_graph_with_monitored_session,
+ MockStrategy(between_graph=True),
+ cluster_spec=self._cluster_spec)
# Each finished worker will increment self._result_correct.
self.assertEqual(self._result_correct, NUM_WORKERS)
@@ -298,8 +417,8 @@ class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
# Dumps the task contexts to the self._worker_context dict.
distribute_coordinator.run_distribute_coordinator(
self._dump_worker_context,
- cluster_spec=self._cluster_spec,
- between_graph=True)
+ MockStrategy(between_graph=True),
+ cluster_spec=self._cluster_spec)
# There is only one type of task and there three such tasks.
self.assertEqual(len(self._worker_context), 1)
@@ -318,12 +437,30 @@ class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
self._worker_context[WORKER][2],
(_bytes_to_str(self._workers[2].target), NUM_WORKERS, False, True))
+ def testBetweenGraphStrategyProperties(self):
+ # Dumps properties of the strategy objects.
+ distribute_coordinator.run_distribute_coordinator(
+ self._dump_strategy_property,
+ MockStrategy(between_graph=True, should_init=True),
+ cluster_spec=self._cluster_spec)
+
+ # There is only one type of task and there three such tasks.
+ self.assertEqual(len(self._strategy_property), 1)
+ self.assertTrue(WORKER in self._strategy_property)
+ self.assertEqual(len(self._strategy_property[WORKER]), NUM_WORKERS)
+
+ # Check whether each task has the right properties of should_init,
+ # should_checkpoint and should_save_summary.
+ self.assertEqual(self._strategy_property[WORKER][0], (True, True, True))
+ self.assertEqual(self._strategy_property[WORKER][1], (True, False, False))
+ self.assertEqual(self._strategy_property[WORKER][2], (True, False, False))
+
def testInGraphContext(self):
# Dumps the task contexts to the self._worker_context dict.
distribute_coordinator.run_distribute_coordinator(
self._dump_worker_context,
- cluster_spec=self._cluster_spec,
- between_graph=False)
+ MockStrategy(between_graph=False),
+ cluster_spec=self._cluster_spec)
# There is only a "None" task in the dumped task context.
self.assertEqual(len(self._worker_context), 1)
@@ -339,7 +476,9 @@ class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
def testLocalContext(self):
# Dumps the task contexts to the self._worker_context dict.
distribute_coordinator.run_distribute_coordinator(
- self._dump_worker_context, cluster_spec=None, between_graph=True)
+ self._dump_worker_context,
+ MockStrategy(between_graph=False),
+ cluster_spec=None)
# There is only a "None" task.
self.assertEqual(len(self._worker_context), 1)
@@ -348,7 +487,7 @@ class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
# Check whether each task has the right master_target, num_workers, is_chief
# and distributed_mode.
- self.assertEqual(self._worker_context["None"][0], ("local", 0, True, False))
+ self.assertEqual(self._worker_context["None"][0], ("", 0, True, False))
def testBetweenGraphContextWithChief(self):
# Adds a chief node, so there are NUM_WORKERS + 1 workers in total.
@@ -358,8 +497,8 @@ class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
# Dumps the task contexts to the self._worker_context dict.
distribute_coordinator.run_distribute_coordinator(
self._dump_worker_context,
+ MockStrategy(between_graph=True),
cluster_spec=cluster_spec,
- between_graph=True,
rpc_layer="grpc")
# There are one CHIEF and three workers.
@@ -391,8 +530,8 @@ class DistributeCoordinatorTestSplitMode(DistributeCoordinatorTestBase):
# Dumps the task contexts to the self._worker_context dict.
distribute_coordinator.run_distribute_coordinator(
self._dump_worker_context,
+ MockStrategy(between_graph=False),
cluster_spec=cluster_spec,
- between_graph=False,
rpc_layer=None)
# There are one "None" task and one EVALUATOR task.
@@ -417,8 +556,8 @@ class DistributeCoordinatorTestInpendentWorkerMode(
cluster_spec = self._create_cluster_spec(num_workers=NUM_WORKERS)
threads = self._run_multiple_coordinator_in_threads(
self._in_graph_worker_fn,
+ MockStrategy(between_graph=False),
cluster_spec,
- between_graph=False,
mode=INDEPENDENT_WORKER)
threads[WORKER][0].join()
self.assertEqual(self._result_correct, 1)
@@ -428,8 +567,22 @@ class DistributeCoordinatorTestInpendentWorkerMode(
num_workers=NUM_WORKERS, num_ps=NUM_PS)
threads = self._run_multiple_coordinator_in_threads(
self._between_graph_worker_fn,
+ MockStrategy(between_graph=True),
+ cluster_spec,
+ mode=INDEPENDENT_WORKER)
+ for task_id in range(NUM_WORKERS):
+ threads[WORKER][task_id].join()
+
+ # Each finished worker will increment self._result_correct.
+ self.assertEqual(self._result_correct, NUM_WORKERS)
+
+ def testBetweenGraphWithMonitoredSession(self):
+ cluster_spec = self._create_cluster_spec(
+ num_workers=NUM_WORKERS, num_ps=NUM_PS)
+ threads = self._run_multiple_coordinator_in_threads(
+ self._between_graph_with_monitored_session,
+ MockStrategy(between_graph=True),
cluster_spec,
- between_graph=True,
mode=INDEPENDENT_WORKER)
for task_id in range(NUM_WORKERS):
threads[WORKER][task_id].join()
@@ -444,9 +597,9 @@ class DistributeCoordinatorTestInpendentWorkerMode(
self._run_mock_std_server):
threads = self._run_multiple_coordinator_in_threads(
self._dump_worker_context,
+ MockStrategy(between_graph=True),
cluster_spec,
mode=INDEPENDENT_WORKER,
- between_graph=True,
rpc_layer=None)
for task_id in range(NUM_WORKERS):
threads[WORKER][task_id].join()
@@ -476,6 +629,31 @@ class DistributeCoordinatorTestInpendentWorkerMode(
self.assertFalse(self._std_servers[WORKER][1].joined)
self.assertFalse(self._std_servers[WORKER][2].joined)
+ def testBetweenGraphStrategyProperties(self):
+ cluster_spec = self._create_cluster_spec(num_workers=NUM_WORKERS)
+ # Dumps properties of the strategy objects.
+ with test.mock.patch.object(distribute_coordinator, "_run_std_server",
+ self._run_mock_std_server):
+ threads = self._run_multiple_coordinator_in_threads(
+ self._dump_strategy_property,
+ MockStrategy(between_graph=True, should_init=True),
+ cluster_spec,
+ mode=INDEPENDENT_WORKER,
+ rpc_layer=None)
+ for task_id in range(NUM_WORKERS):
+ threads[WORKER][task_id].join()
+
+ # There is only one type of task and there three such tasks.
+ self.assertEqual(len(self._strategy_property), 1)
+ self.assertTrue(WORKER in self._strategy_property)
+ self.assertEqual(len(self._strategy_property[WORKER]), NUM_WORKERS)
+
+ # Check whether each task has the right properties of should_init,
+ # should_checkpoint and should_save_summary.
+ self.assertEqual(self._strategy_property[WORKER][0], (True, True, True))
+ self.assertEqual(self._strategy_property[WORKER][1], (True, False, False))
+ self.assertEqual(self._strategy_property[WORKER][2], (True, False, False))
+
def testInGraphContext(self):
cluster_spec = self._create_cluster_spec(num_workers=NUM_WORKERS)
# Dumps the task contexts and std server arguments.
@@ -483,9 +661,9 @@ class DistributeCoordinatorTestInpendentWorkerMode(
self._run_mock_std_server):
threads = self._run_multiple_coordinator_in_threads(
self._dump_worker_context,
+ MockStrategy(between_graph=False),
cluster_spec,
mode=INDEPENDENT_WORKER,
- between_graph=False,
rpc_layer=None)
for task_id in range(NUM_WORKERS):
threads[WORKER][task_id].join()
@@ -519,9 +697,9 @@ class DistributeCoordinatorTestInpendentWorkerMode(
self._run_mock_std_server):
threads = self._run_multiple_coordinator_in_threads(
self._dump_worker_context,
+ MockStrategy(between_graph=False),
cluster_spec,
mode=INDEPENDENT_WORKER,
- between_graph=False,
rpc_layer=None)
for task_id in range(NUM_WORKERS):
threads[WORKER][task_id].join()
diff --git a/tensorflow/python/distribute/multi_worker_util.py b/tensorflow/python/distribute/multi_worker_util.py
new file mode 100644
index 0000000000..360733eff6
--- /dev/null
+++ b/tensorflow/python/distribute/multi_worker_util.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.
+# ==============================================================================
+"""Utilities for multi-worker distribution strategies."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.core.protobuf import cluster_pb2
+from tensorflow.python.training import server_lib
+
+
+def normalize_cluster_spec(cluster_spec):
+ """Makes `cluster_spec` into a `ClusterSpec` object.
+
+ Args:
+ cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the
+ cluster configurations.
+
+ Returns:
+ a `ClusterSpec` object.
+
+ Raises:
+ ValueError: if `cluster_spec` is not a dict or a `ClusterSpec` or a
+ `ClusterDef`.
+ """
+ if isinstance(cluster_spec, (dict, cluster_pb2.ClusterDef)):
+ return server_lib.ClusterSpec(cluster_spec)
+ elif not isinstance(cluster_spec, server_lib.ClusterSpec):
+ raise ValueError(
+ "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a "
+ "`tf.train.ClusterDef` object")
+ return cluster_spec
+
+
+def is_chief(cluster_spec, task_type, task_id):
+ """Returns whether the given task is chief in the cluster.
+
+ Args:
+ cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object specifying the
+ cluster configurations.
+ task_type: the task type in the cluster.
+ task_id: the task id in the cluster.
+
+ Returns:
+ a boolean indicating whether the given task is chief.
+
+ Raises:
+ ValueError: if `task_type` is not in the `cluster_spec` or `task_id` exceeds
+ the maximum id of the `task_type`.
+ """
+ cluster_spec = normalize_cluster_spec(cluster_spec)
+ if task_type not in cluster_spec.jobs:
+ raise ValueError(
+ "The task_type \"%s\" is not in the `cluster_spec`." % task_type)
+ if task_id >= cluster_spec.num_tasks(task_type):
+ raise ValueError("The `task_id` %d exceeds the maximum id of %s." % (
+ task_id, task_type))
+
+ if task_type == "chief":
+ return True
+
+ # If chief not in the cluster_spec, use the first worker as chief. This is
+ # common in CollectiveAllReduceStrategy.
+ if ("chief" not in cluster_spec.jobs and task_type == "worker" and
+ task_id == 0):
+ return True
+ return False
diff --git a/tensorflow/python/distribute/multi_worker_util_test.py b/tensorflow/python/distribute/multi_worker_util_test.py
new file mode 100644
index 0000000000..bdc49725c7
--- /dev/null
+++ b/tensorflow/python/distribute/multi_worker_util_test.py
@@ -0,0 +1,107 @@
+# 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 multi_worker_util."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.core.protobuf import cluster_pb2
+from tensorflow.python.distribute import multi_worker_util
+from tensorflow.python.eager import test
+from tensorflow.python.training import server_lib
+
+
+class NormalizeClusterSpecTest(test.TestCase):
+
+ def assert_same_cluster(self, lhs, rhs):
+ self.assertEqual(
+ server_lib.ClusterSpec(lhs).as_dict(),
+ server_lib.ClusterSpec(rhs).as_dict())
+
+ def testDictAsInput(self):
+ cluster_spec = {
+ "chief": ["127.0.0.1:1234"],
+ "worker": ["127.0.0.1:8964", "127.0.0.1:2333"],
+ "ps": ["127.0.0.1:1926", "127.0.0.1:3141"]
+ }
+ self.assert_same_cluster(
+ cluster_spec, multi_worker_util.normalize_cluster_spec(cluster_spec))
+
+ def testClusterDefAsInput(self):
+ cluster_def = cluster_pb2.ClusterDef()
+ job = cluster_def.job.add()
+ job.name = "chief"
+ job.tasks[0] = "127.0.0.1:1234"
+
+ job = cluster_def.job.add()
+ job.name = "worker"
+ job.tasks[0] = "127.0.0.1:8964"
+ job.tasks[1] = "127.0.0.1:2333"
+
+ job = cluster_def.job.add()
+ job.name = "ps"
+ job.tasks[0] = "127.0.0.1:1926"
+ job.tasks[1] = "127.0.0.1:3141"
+
+ self.assert_same_cluster(
+ cluster_def, multi_worker_util.normalize_cluster_spec(cluster_def))
+
+ def testClusterSpecAsInput(self):
+ cluster_spec = server_lib.ClusterSpec({
+ "chief": ["127.0.0.1:1234"],
+ "worker": ["127.0.0.1:8964", "127.0.0.1:2333"],
+ "ps": ["127.0.0.1:1926", "127.0.0.1:3141"]
+ })
+ self.assert_same_cluster(
+ cluster_spec, multi_worker_util.normalize_cluster_spec(cluster_spec))
+
+ def testUnexpectedInput(self):
+ cluster_spec = ["127.0.0.1:8964", "127.0.0.1:2333"]
+
+ with self.assertRaisesRegexp(
+ ValueError,
+ "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a "
+ "`tf.train.ClusterDef` object"):
+ multi_worker_util.normalize_cluster_spec(cluster_spec)
+
+
+class IsChiefTest(test.TestCase):
+
+ def testClusterWithChief(self):
+ cluster_spec = {
+ "chief": ["127.0.0.1:1234"],
+ "worker": ["127.0.0.1:8964", "127.0.0.1:2333"],
+ "ps": ["127.0.0.1:1926", "127.0.0.1:3141"]
+ }
+ self.assertTrue(multi_worker_util.is_chief(cluster_spec, "chief", 0))
+ self.assertFalse(multi_worker_util.is_chief(cluster_spec, "worker", 0))
+
+ def testClusterWithoutChief(self):
+ cluster_spec = {"worker": ["127.0.0.1:8964", "127.0.0.1:2333"]}
+ self.assertTrue(multi_worker_util.is_chief(cluster_spec, "worker", 0))
+ self.assertFalse(multi_worker_util.is_chief(cluster_spec, "worker", 1))
+
+ with self.assertRaisesRegexp(
+ ValueError, "The task_type \"chief\" is not in the `cluster_spec`."):
+ multi_worker_util.is_chief(cluster_spec, "chief", 0)
+
+ with self.assertRaisesRegexp(
+ ValueError, "The `task_id` 2 exceeds the maximum id of worker."):
+ multi_worker_util.is_chief(cluster_spec, "worker", 2)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/python/eager/BUILD b/tensorflow/python/eager/BUILD
index de93b1e2e1..bdabbf4ea3 100644
--- a/tensorflow/python/eager/BUILD
+++ b/tensorflow/python/eager/BUILD
@@ -47,7 +47,6 @@ py_library(
":core",
":execute",
":function",
- ":graph_callable",
":graph_only_ops",
":tape",
":test",
@@ -254,41 +253,6 @@ py_library(
)
py_library(
- name = "graph_callable",
- srcs = ["graph_callable.py"],
- srcs_version = "PY2AND3",
- visibility = ["//tensorflow:internal"],
- deps = [
- "//tensorflow/python:array_ops",
- "//tensorflow/python:dtypes",
- "//tensorflow/python:errors",
- "//tensorflow/python:framework_ops",
- "//tensorflow/python:resource_variable_ops",
- "//tensorflow/python:util",
- "//tensorflow/python:variable_scope",
- "//tensorflow/python/eager:context",
- "//tensorflow/python/eager:function",
- "//tensorflow/python/eager:tape",
- ],
-)
-
-py_test(
- name = "graph_callable_test",
- srcs = ["graph_callable_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":backprop",
- ":graph_callable",
- "//tensorflow/python:dtypes",
- "//tensorflow/python:function",
- "//tensorflow/python:init_ops",
- "//tensorflow/python:math_ops",
- "//tensorflow/python:variable_scope",
- "//tensorflow/python/eager:test",
- ],
-)
-
-py_library(
name = "backprop",
srcs = ["backprop.py"],
srcs_version = "PY2AND3",
diff --git a/tensorflow/python/eager/backprop.py b/tensorflow/python/eager/backprop.py
index 728b283695..7978383e55 100644
--- a/tensorflow/python/eager/backprop.py
+++ b/tensorflow/python/eager/backprop.py
@@ -34,6 +34,7 @@ from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
+from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.platform import tf_logging as logging
@@ -180,10 +181,10 @@ def implicit_val_and_grad(f):
```
Args:
- f: function to be differentiated. If `f` returns a scalar, this scalar will
- be differentiated. If `f` returns a tensor or list of tensors, by default
- a scalar will be computed by adding all their values to produce a single
- scalar.
+ f: function to be differentiated. If `f` returns a scalar, this scalar will
+ be differentiated. If `f` returns a tensor or list of tensors, by default
+ a scalar will be computed by adding all their values to produce a single
+ scalar.
Returns:
A function which, when called, returns a tuple pair.
@@ -255,10 +256,10 @@ def implicit_grad(f):
```
Args:
- f: function to be differentiated. If `f` returns a scalar, this scalar will
- be differentiated. If `f` returns a tensor or list of tensors, by default
- a scalar will be computed by adding all their values to produce a single
- scalar.
+ f: function to be differentiated. If `f` returns a scalar, this scalar will
+ be differentiated. If `f` returns a tensor or list of tensors, by default
+ a scalar will be computed by adding all their values to produce a single
+ scalar.
Returns:
A function which, when called, returns a list of (gradient, variable) pairs.
@@ -343,24 +344,24 @@ def gradients_function(f, params=None):
Note that only tensors with real or complex dtypes are differentiable.
Args:
- f: function to be differentiated. If `f` returns a scalar, this scalar will
- be differentiated. If `f` returns a tensor or list of tensors, by default
- a scalar will be computed by adding all their values to produce a single
- scalar. If desired, the tensors can be elementwise multiplied by the
- tensors passed as the `dy` keyword argument to the returned gradient
- function.
- params: list of parameter names of f or list of integers indexing the
- parameters with respect to which we'll differentiate. Passing None
- differentiates with respect to all parameters.
+ f: function to be differentiated. If `f` returns a scalar, this scalar will
+ be differentiated. If `f` returns a tensor or list of tensors, by default
+ a scalar will be computed by adding all their values to produce a single
+ scalar. If desired, the tensors can be elementwise multiplied by the
+ tensors passed as the `dy` keyword argument to the returned gradient
+ function.
+ params: list of parameter names of f or list of integers indexing the
+ parameters with respect to which we'll differentiate. Passing None
+ differentiates with respect to all parameters.
Returns:
function which, when called, returns the value of f and the gradient
- of f with respect to all of `params`. The function takes an extra optional
- keyword argument "dy". Setting it allows computation of vector jacobian
+ of `f` with respect to all of `params`. The function takes an extra optional
+ keyword argument `dy`. Setting it allows computation of vector jacobian
products for vectors other than the vector of ones.
Raises:
- ValueError: if the params are not all strings or all integers.
+ ValueError: if the params are not all strings or all integers.
"""
def decorated(*args, **kwds):
@@ -440,23 +441,24 @@ def val_and_grad_function(f, params=None):
```
Args:
- f: function to be differentiated. If `f` returns a scalar, this scalar will
- be differentiated. If `f` returns a tensor or list of tensors, by default
- a scalar will be computed by adding all their values to produce a single
- scalar. If desired, the tensors can be elementwise multiplied by the
- tensors passed as the `dy` keyword argument to the returned gradient
- function.
- params: list of parameter names of f or list of integers indexing the
- parameters with respect to which we'll differentiate. Passing `None`
- differentiates with respect to all parameters.
-
- Returns: function which, when called, returns the value of f and the gradient
- of f with respect to all of `params`. The function takes an extra optional
- keyword argument "dy". Setting it allows computation of vector jacobian
- products for vectors other than the vector of ones.
+ f: function to be differentiated. If `f` returns a scalar, this scalar will
+ be differentiated. If `f` returns a tensor or list of tensors, by default
+ a scalar will be computed by adding all their values to produce a single
+ scalar. If desired, the tensors can be elementwise multiplied by the
+ tensors passed as the `dy` keyword argument to the returned gradient
+ function.
+ params: list of parameter names of f or list of integers indexing the
+ parameters with respect to which we'll differentiate. Passing `None`
+ differentiates with respect to all parameters.
+
+ Returns:
+ function which, when called, returns the value of f and the gradient
+ of f with respect to all of `params`. The function takes an extra optional
+ keyword argument "dy". Setting it allows computation of vector jacobian
+ products for vectors other than the vector of ones.
Raises:
- ValueError: if the params are not all strings or all integers.
+ ValueError: if the params are not all strings or all integers.
"""
def decorated(*args, **kwds):
@@ -557,7 +559,7 @@ def _aggregate_grads(gradients):
if len(gradients) == 1:
return gradients[0]
if all([isinstance(g, ops.Tensor) for g in gradients]):
- return math_ops.add_n(gradients)
+ return gen_math_ops.add_n(gradients)
else:
assert all([isinstance(g, (ops.Tensor, ops.IndexedSlices))
for g in gradients])
@@ -592,7 +594,9 @@ def _num_elements(grad):
def _fast_fill(value, shape, dtype):
- return array_ops.fill(shape, constant_op.constant(value, dtype=dtype))
+ return array_ops.fill(
+ constant_op.constant(shape, dtype=dtypes.int32),
+ constant_op.constant(value, dtype=dtype))
def _zeros(shape, dtype):
@@ -646,7 +650,7 @@ class GradientTape(object):
Operations are recorded if they are executed within this context manager and
at least one of their inputs is being "watched".
- Trainable variables (created by `tf.Variable` or @{tf.get_variable},
+ Trainable variables (created by `tf.Variable` or `tf.get_variable`,
trainable=True is default in both cases) are automatically watched. Tensors
can be manually watched by invoking the `watch` method on this context
manager.
diff --git a/tensorflow/python/eager/benchmarks_test.py b/tensorflow/python/eager/benchmarks_test.py
index 1a78559ac0..a2e8422671 100644
--- a/tensorflow/python/eager/benchmarks_test.py
+++ b/tensorflow/python/eager/benchmarks_test.py
@@ -77,19 +77,54 @@ class SubclassedKerasModel(keras.Model):
def __init__(self):
super(SubclassedKerasModel, self).__init__()
- self.layer = keras.layers.Dense(
+ self.layer_a = keras.layers.Dense(
+ 64, kernel_initializer="ones", bias_initializer="zeros")
+ self.layer_b = keras.layers.Dense(
+ 128, kernel_initializer="ones", bias_initializer="zeros")
+ self.layer_c = keras.layers.Dense(
+ 256, kernel_initializer="ones", bias_initializer="zeros")
+ self.layer_d = keras.layers.Dense(
+ 256, kernel_initializer="ones", bias_initializer="zeros")
+ self.layer_e = keras.layers.Dense(
10, kernel_initializer="ones", bias_initializer="zeros")
def call(self, x):
- return self.layer(x)
+ x = self.layer_a(x)
+ x = self.layer_b(x)
+ x = self.layer_c(x)
+ x = self.layer_d(x)
+ return self.layer_e(x)
def make_keras_model():
- x = keras.Input(shape=(10,))
- y = keras.layers.Dense(
- 10, kernel_initializer="ones", bias_initializer="zeros")(
- x)
- return keras.Model(inputs=x, outputs=y)
+ model_input = keras.Input(shape=(10,))
+ x = keras.layers.Dense(
+ 64, kernel_initializer="ones", bias_initializer="zeros")(model_input)
+ x = keras.layers.Dense(
+ 128, kernel_initializer="ones", bias_initializer="zeros")(x)
+ x = keras.layers.Dense(
+ 256, kernel_initializer="ones", bias_initializer="zeros")(x)
+ x = keras.layers.Dense(
+ 256, kernel_initializer="ones", bias_initializer="zeros")(x)
+ x = keras.layers.Dense(
+ 10, kernel_initializer="ones", bias_initializer="zeros")(x)
+ return keras.Model(inputs=model_input, outputs=x)
+
+
+def make_sequential_keras_model():
+ model = keras.models.Sequential()
+ model.add(keras.layers.Dense(
+ 64, kernel_initializer="ones", bias_initializer="zeros",
+ input_shape=(10,)))
+ model.add(keras.layers.Dense(
+ 128, kernel_initializer="ones", bias_initializer="zeros"))
+ model.add(keras.layers.Dense(
+ 256, kernel_initializer="ones", bias_initializer="zeros"))
+ model.add(keras.layers.Dense(
+ 256, kernel_initializer="ones", bias_initializer="zeros"))
+ model.add(keras.layers.Dense(
+ 10, kernel_initializer="ones", bias_initializer="zeros"))
+ return model
class MicroBenchmarks(test.Benchmark):
@@ -315,6 +350,21 @@ class MicroBenchmarks(test.Benchmark):
func = lambda: f(m, m, transpose_b)
self._run(func, num_iters, execution_mode=execution_mode)
+ def _benchmark_defun_matmul_forward_backward(self,
+ m,
+ transpose_b,
+ num_iters,
+ execution_mode=None):
+ f = function.defun(math_ops.matmul)
+
+ def func():
+ with backprop.GradientTape() as gt:
+ gt.watch(m)
+ y = f(m, m, transpose_b)
+ _ = gt.gradient(y, m)
+
+ self._run(func, num_iters, execution_mode=execution_mode)
+
def _benchmark_read_variable(self, m, num_iters):
self._run(m.value, num_iters)
@@ -386,6 +436,21 @@ class MicroBenchmarks(test.Benchmark):
num_iters=self._num_iters_2_by_2,
execution_mode=context.ASYNC)
+ def benchmark_defun_matmul_forward_backward_2_by_2_CPU(self):
+ with context.device(CPU):
+ m = self._m_2_by_2.cpu()
+ self._benchmark_defun_matmul_forward_backward(
+ m, transpose_b=False, num_iters=self._num_iters_2_by_2)
+
+ def benchmark_defun_matmul_forward_backward_2_by_2_CPU_async(self):
+ with context.device(CPU):
+ m = self._m_2_by_2.cpu()
+ self._benchmark_defun_matmul_forward_backward(
+ m,
+ transpose_b=False,
+ num_iters=self._num_iters_2_by_2,
+ execution_mode=context.ASYNC)
+
def benchmark_tf_matmul_2_by_2_GPU(self):
if not context.num_gpus():
return
@@ -638,6 +703,15 @@ class MicroBenchmarks(test.Benchmark):
assert np.equal(func(), SubclassedKerasModel()(data)).all()
self._run(func, 30000)
+ def benchmark_keras_model_sequential(self):
+ model = make_sequential_keras_model()
+ data = random_ops.random_uniform((10, 10))
+ func = lambda: model(data)
+ # Symmetry with benchmark_keras_model_functional
+ func()
+ assert np.equal(func(), make_keras_model()(data)).all()
+ self._run(func, 30000)
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/eager/context.py b/tensorflow/python/eager/context.py
index aa57ca03e6..6a327bd010 100644
--- a/tensorflow/python/eager/context.py
+++ b/tensorflow/python/eager/context.py
@@ -663,7 +663,7 @@ def internal_operation_seed():
def executing_eagerly():
"""Returns True if the current thread has eager execution enabled.
- Eager execution is typically enabled via @{tf.enable_eager_execution},
+ Eager execution is typically enabled via `tf.enable_eager_execution`,
but may also be enabled within the context of a Python function via
tf.contrib.eager.py_func.
"""
diff --git a/tensorflow/python/eager/function.py b/tensorflow/python/eager/function.py
index adbf5605ed..3f8dac0bd4 100644
--- a/tensorflow/python/eager/function.py
+++ b/tensorflow/python/eager/function.py
@@ -26,7 +26,6 @@ import threading
import numpy as np
import six
-from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import function_pb2
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
@@ -42,7 +41,8 @@ from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import resource_variable_ops
-from tensorflow.python.training import distribute
+from tensorflow.python.ops import variable_scope
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.util import compat
from tensorflow.python.util import nest
from tensorflow.python.util import tf_decorator
@@ -101,7 +101,7 @@ class CapturingGraph(ops.Graph):
The entries are in the order they were captured.
"""
- def __init__(self):
+ def __init__(self, graph=None):
super(CapturingGraph, self).__init__()
self.captures = collections.OrderedDict()
@@ -184,7 +184,6 @@ class FuncGraph(CapturingGraph):
Attributes:
name: The name of the function.
-
inputs: Placeholder tensors representing the inputs to this function. The
tensors are in this FuncGraph. This represents "regular" inputs as well as
captured inputs (i.e. the values of self.captures), with the regular
@@ -206,7 +205,7 @@ class FuncGraph(CapturingGraph):
graph: if specified, this FuncGraph will inherit its graph key,
collections, and seed from `graph`.
"""
- super(FuncGraph, self).__init__()
+ super(FuncGraph, self).__init__(graph=graph)
self.name = name
self.inputs = []
@@ -227,10 +226,17 @@ class FuncGraph(CapturingGraph):
self.get_collection_ref(collection)[:] = graph.get_collection(
collection)
+ # Copy distribution strategy scope from the containing graph as well.
+ self._distribution_strategy_stack = graph._distribution_strategy_stack # pylint: disable=protected-access
+
if context.executing_eagerly():
self.seed = context.global_seed()
+ self._xla_compile = (context.context().device_spec.device_type == "TPU")
else:
self.seed = graph.seed
+ self._xla_compile = getattr(graph, "_xla_compile", False)
+ else:
+ self._xla_compile = False
def capture(self, tensor, name=None):
"""Calls CapturingGraph.capture and updates self.inputs if necessary."""
@@ -243,78 +249,6 @@ class FuncGraph(CapturingGraph):
return internal_tensor
-# pylint: disable=invalid-name
-class HelperContext(object):
- """ControlFlowContext with a customizable AddOp method."""
-
- def __init__(self, add_op_internal):
- self._add_op_internal = add_op_internal
- self._values = set() # control flow code sometimes updates this.
-
- def _AddOpInternal(self, op):
- self._add_op_internal(op)
-
- @property
- def outer_context(self):
- return self._outer_context
-
- def GetWhileContext(self):
- if self._outer_context:
- return self._outer_context.GetWhileContext()
-
- def IsWhileContext(self):
- return False
-
- def IsCondContext(self):
- return False
-
- def IsXLAContext(self):
- return False
-
- def AddOp(self, op): # pylint: disable=invalid-name
- self._AddOpInternal(op)
- if self._outer_context:
- self._outer_context.AddOp(op)
-
- def AddName(self, _):
- pass
-
- def AddInnerOp(self, op):
- self._AddOpInternal(op)
- if self._outer_context:
- self._outer_context.AddInnerOp(op)
-
- def AddValue(self, val):
- if self._outer_context:
- return self._outer_context.AddValue(val)
- else:
- return val
-
- def EnterGradientColocation(self, op, gradient_uid):
- """Start building a gradient colocated with an op."""
- if self._outer_context:
- self._outer_context.EnterGradientColocation(op, gradient_uid)
-
- def ExitGradientColocation(self, op, gradient_uid):
- """Start building a gradient colocated with an op."""
- if self._outer_context:
- self._outer_context.ExitGradientColocation(op, gradient_uid)
-
- def __enter__(self):
- # pylint: disable=protected-access
- self._g = ops.get_default_graph()
- self._outer_context = self._g._get_control_flow_context()
- self._g._set_control_flow_context(self)
- self._nested_contexts = (
- self._outer_context._nested_contexts
- if self._outer_context is not None else None)
- # pylint: enable=protected-access
-
- def __exit__(self, *_):
- self._g._set_control_flow_context(self._outer_context) # pylint: disable=protected-access
-# pylint: enable=invalid-name
-
-
def _forward_name(n):
"""The name of a generated forward defun named n."""
return "__forward_%s_%s" % (n, ops.uid())
@@ -335,9 +269,6 @@ def _register(fn):
context.context().add_function(fn)
-_xla_compile_attr = "_XlaCompile"
-
-
# TODO(apassos) get rid of this by splitting framework.function._DefinedFunction
# so it doesn't have the definition-generating logic and is just a container for
# an already-defined function.
@@ -350,18 +281,20 @@ class _EagerDefinedFunction(object):
class may be provided as the value of these `func` attributes.
"""
- def __init__(self, name, graph, operations, inputs, outputs, attrs):
+ def __init__(self, name, graph, inputs, outputs, attrs):
"""Initializes an eager defined function.
Args:
name: str, the name for the created function.
graph: Graph, the graph containing the operations in the function
- operations: list of Operation; the subset of operations in the graph
- which will be in the function
inputs: the tensors in the graph to be used as inputs to the function
outputs: the tensors in the graph which will be outputs to the function
attrs: dict mapping names of attributes to their AttrValue values
"""
+ operations = [
+ op for op in graph.get_operations()
+ if op not in set(arg.op for arg in inputs)
+ ]
fn = pywrap_tensorflow.TF_GraphToFunction_wrapper(
graph._c_graph, # pylint: disable=protected-access
compat.as_str(name),
@@ -379,7 +312,6 @@ class _EagerDefinedFunction(object):
# It might be worth creating a convenient way to re-use status.
pywrap_tensorflow.TF_FunctionSetAttrValueProto(
fn, compat.as_str(name), serialized)
- self._xla_compile = _xla_compile_attr in attrs
# TODO(apassos) avoid creating a FunctionDef (specially to grab the
# signature, but also in general it's nice not to depend on it.
@@ -395,6 +327,7 @@ class _EagerDefinedFunction(object):
self.signature = function_def.signature
self._num_outputs = len(self.signature.output_arg)
self._output_types = [o.type for o in self.signature.output_arg]
+ self._output_shapes = [o.shape for o in outputs]
self.grad_func_name = None
self.python_grad_func = None
self._c_func = c_api_util.ScopedTFFunction(fn)
@@ -415,7 +348,7 @@ class _EagerDefinedFunction(object):
def stateful_ops(self):
return self._stateful_ops
- def call(self, ctx, args, output_shapes):
+ def call(self, ctx, args):
"""Calls this function with `args` as inputs.
Function execution respects device annotations only if the function won't
@@ -424,8 +357,6 @@ class _EagerDefinedFunction(object):
Args:
ctx: a Context object
args: a list of arguments to supply this function with.
- output_shapes: shapes to which outputs should be set; ignored when
- executing eagerly.
Returns:
The outputs of the function call.
@@ -433,10 +364,7 @@ class _EagerDefinedFunction(object):
executing_eagerly = ctx.executing_eagerly()
- xla_compile = self._xla_compile or (executing_eagerly and
- ctx.device_spec.device_type == "TPU")
-
- if xla_compile:
+ if self._graph._xla_compile: # pylint: disable=protected-access
# XLA compilation relies upon a custom kernel creator to run functions.
signature = self.signature
if executing_eagerly:
@@ -474,16 +402,11 @@ class _EagerDefinedFunction(object):
if executing_eagerly:
return outputs
else:
- for i, shape in enumerate(output_shapes):
+ for i, shape in enumerate(self._output_shapes):
outputs[i].set_shape(shape)
return outputs
-def _map_sequence_obj_to_idx(sequence):
- """Maps objs in the sequence from id(obj) to sequence index."""
- return {id(x): i for i, x in enumerate(sequence)}
-
-
def _flatten(sequence):
"""A wrapper around `nest.flatten` that also unpacks `IndexedSlices`."""
# TODO(akshayka): Support `SparseTensor` in a similar fashion.
@@ -500,153 +423,106 @@ def _flatten(sequence):
return outputs
-# TODO(akshayka): Perhaps rename to something more appropriate.
-class GraphModeFunction(object):
+class GraphCallable(object):
"""Callable object encapsulating a function definition and its gradient.
- `GraphModeFunction` is a callable that encapsulates a function definition and
+ `GraphCallable` is a callable that encapsulates a function definition and
is differentiable under `tf.GradientTape` objects.
"""
- def __init__(self,
- name,
- input_placeholders,
- extra_inputs,
- graph,
- operations,
- outputs,
- python_func_outputs,
- output_shapes,
- variables=None,
- attrs=None):
- """Initialize a GraphModeFunction.
+ def __init__(self, func_graph, attrs=None):
+ """Initialize a GraphCallable.
Args:
- name: str the name of the created function
- input_placeholders: list of placeholder values (tensors) to feed when
- calling the wrapped function.
- extra_inputs: Tensor inputs this function definition closed over which
- are passed as arguments. Need to track so gradients are supported
- correctly.
- graph: the Graph from which the operations will be pulled. Used as
- a context when computing gradients.
- operations: the subset of Operations in the graph used in the function
- definition.
- outputs: a flat list of the Tensors in the graph used as outputs to the
- function
- python_func_outputs: a possibly nested python object which will be
- returned by this function. The Tensors in this structure will be
- replaced by their corresponding values in outputs. Note that this
- structure might contain Python `None`s.
- output_shapes: List of shapes of all tensors in outputs
- variables: (optional) List of variables to watch during function
- execution.
+ func_graph: An instance of FuncGraph: the function body to wrap.
attrs: (optional) dict mapping names of attributes to their AttrValue
values. Attributes in `attrs` will be included in this function's
definition.
+
+ Raises:
+ ValueError: If number of input_placeholders is not equal to the number
+ of function inputs.
"""
+ self._func_graph = func_graph
+ self._captured_inputs = list(self._func_graph.captures.keys())
+ self._num_outputs = len(self._func_graph.outputs)
+ self._output_shapes = tuple(
+ output.shape for output in self._func_graph.outputs)
self._attrs = attrs or {}
- defined_function = _EagerDefinedFunction(
- name, graph, operations, input_placeholders, outputs, self._attrs)
- if len(input_placeholders) != len(defined_function.signature.input_arg):
- raise ValueError("Internal error: invalid lengths. %s %s" % (
- len(input_placeholders), len(defined_function.signature.input_arg)))
- self._input_placeholders = input_placeholders
- self._extra_inputs = list(extra_inputs)
- self._graph = graph
- self._backward_function = None
- self._func_name = name
- self._function_def = defined_function
- self._num_outputs = len(defined_function.signature.output_arg)
- self._python_func_outputs = python_func_outputs
- self._python_returns = [python_func_outputs] if isinstance(
- python_func_outputs,
- (ops.Tensor, type(None))) else _flatten(python_func_outputs)
- self._output_shapes = output_shapes
- self._variables = variables if variables is not None else []
-
- # Find the variables that are components of something distributed and
- # put them into a {handle_tensor -> distributed variable object} map.
+
+ self._inference_function = _EagerDefinedFunction(
+ _inference_name(self._func_graph.name), self._func_graph,
+ self._func_graph.inputs, self._func_graph.outputs, self._attrs)
+ self._backward_graph_callable = None
+
+ # Map holding distributed variables, keyed by resource handle tensors.
self._distributed_variables = {}
- strategy = distribute.get_distribution_strategy()
- for variable in self._variables:
+ strategy = distribution_strategy_context.get_distribution_strategy()
+ for variable in self._func_graph.variables:
# If variable is not distributed, unwrap returns [variable].
component_variables = strategy.unwrap(variable)
- # Only add to the dictionary when the variable is actually distributed,
- # i.e. more than one component or the component is different from the
- # variable itself. component_variables cannot be empty.
+ # Only update the dictionary when the variable is actually distributed.
if (len(component_variables) > 1 or component_variables[0] != variable):
for component_variable in component_variables:
self._distributed_variables[component_variable.handle] = variable
@property
+ def graph(self):
+ return self._func_graph
+
+ @property
def variables(self):
- return self._variables
+ return self._func_graph.variables
def _construct_backprop_function(self):
"""Constructs the backprop function object for this function."""
- filtered_outputs = [x for x in self._python_returns if x is not None]
- # TODO(skyewm): use FuncGraph
- backwards_graph = CapturingGraph()
- backwards_graph._graph_key = self._graph._graph_key # pylint: disable=protected-access
- for collection in self._graph.collections:
- backwards_graph.get_collection_ref(
- collection)[:] = self._graph.get_collection(collection)
- backwards_graph.seed = self._graph.seed
+ backwards_graph = FuncGraph(
+ _backward_name(self._func_graph.name), self._func_graph)
with backwards_graph.as_default():
- self._out_grad_placeholders = [
- graph_placeholder(x.dtype, x.shape) for x in filtered_outputs]
- in_gradients = gradients_impl._GradientsHelper( # pylint: disable=protected-access
- filtered_outputs,
- self._input_placeholders,
- grad_ys=self._out_grad_placeholders,
- src_graph=self._graph)
-
- backward_outputs = tuple(
- grad for grad in _flatten(in_gradients) if grad is not None)
- output_shapes = tuple(grad.shape for grad in backward_outputs)
-
- extra_inputs = backwards_graph.captures.keys()
- extra_placeholders = backwards_graph.captures.values()
-
- forward_name = _forward_name(self._func_name)
- # Note: we cannot have placeholder ops in the graph or the TPU compilation
- # pass fails.
- placeholder_ops = set([y.op for y in self._input_placeholders])
- function_ops = [x for x in self._graph.get_operations()
- if x not in placeholder_ops]
- self._forward_fdef = _EagerDefinedFunction(
- forward_name, self._graph, function_ops,
- self._input_placeholders, filtered_outputs + list(extra_inputs),
+ gradients_wrt_outputs = [
+ graph_placeholder(x.dtype, x.shape) for x in self._func_graph.outputs
+ ]
+ gradients_wrt_inputs = gradients_impl._GradientsHelper( # pylint: disable=protected-access
+ self._func_graph.outputs,
+ self._func_graph.inputs,
+ grad_ys=gradients_wrt_outputs,
+ src_graph=self._func_graph)
+
+ self._forward_function = _EagerDefinedFunction(
+ _forward_name(
+ self._func_graph.name), self._func_graph, self._func_graph.inputs,
+ self._func_graph.outputs + list(backwards_graph.captures.keys()),
self._attrs)
- all_inputs = self._out_grad_placeholders + list(extra_placeholders)
- # Excluding input ops from the body as we do not intend to execute these
- # operations when the function is executed.
- all_ignored_ops = frozenset(x.op for x in all_inputs)
- # Enforce a deterministic order of operations in the generated graph. This
- # means rerunning the function-defining code will always define the same
- # function, which is useful if we serialize this etc.
- function_def_ops = tuple(x
- for x in sorted(backwards_graph.get_operations(),
- key=lambda x: x.name)
- if x not in all_ignored_ops)
- bname = _backward_name(self._func_name)
- self._backward_function = GraphModeFunction(
- bname, all_inputs, [], backwards_graph, function_def_ops,
- backward_outputs, in_gradients, output_shapes, attrs=self._attrs)
+
+ # The ordering of `backwards_graph.inputs` is important: inputs of
+ # `self._backward_graph_callable` correspond to outputs of
+ # `self._forward_function`.
+ backwards_graph.inputs = gradients_wrt_outputs + list(
+ backwards_graph.captures.values())
+ # Clear captures, since we pass them in as inputs.
+ backwards_graph.captures = {}
+ backwards_graph.outputs.extend(
+ grad for grad in _flatten(gradients_wrt_inputs) if grad is not None)
+ backwards_graph.structured_outputs = gradients_wrt_inputs
+ self._backward_graph_callable = GraphCallable(
+ backwards_graph, attrs=self._attrs)
def _backprop_call(self, args):
- """Calls the wrapped function and records the result on a tape.
+ """Calls the forward function and records the result on a tape.
(Only records results on a tape if the function has outputs)
Args:
- args: All inputs to the function, including resolved extra inputs
+ args: All inputs to the function, including resolved captured inputs
+
Returns:
The call output.
"""
+ if self._backward_graph_callable is None:
+ self._construct_backprop_function()
+
ctx = context.context()
- outputs = self._forward_fdef.call(ctx, args, self._output_shapes)
+ outputs = self._forward_function.call(ctx, args)
if isinstance(outputs, ops.Operation) or outputs is None:
return outputs
@@ -657,14 +533,10 @@ class GraphModeFunction(object):
side_outputs = outputs[self._num_outputs:]
def backward_function(*args):
- return self._backward_function(*(list(args) + side_outputs)) # pylint: disable=not-callable
-
- tape.record_operation(
- self._forward_fdef.signature.name,
- real_outputs,
- args,
- backward_function)
+ return self._backward_graph_callable(*(list(args) + side_outputs)) # pylint: disable=not-callable
+ tape.record_operation(self._forward_function.signature.name, real_outputs,
+ args, backward_function)
return self._build_call_outputs(real_outputs)
@property
@@ -672,7 +544,7 @@ class GraphModeFunction(object):
"""The function's output shapes."""
# TODO(ebrevdo): Should we only keep the output shapes associated
# with len(self._python_returns) outputs?
- outputs_list = nest.flatten(self._python_func_outputs)
+ outputs_list = nest.flatten(self._func_graph.structured_outputs)
j = 0
for i, o in enumerate(outputs_list):
if o is not None:
@@ -686,23 +558,25 @@ class GraphModeFunction(object):
else:
outputs_list[i] = self._output_shapes[j]
j += 1
- return nest.pack_sequence_as(self._python_func_outputs, outputs_list)
+ return nest.pack_sequence_as(self._func_graph.structured_outputs,
+ outputs_list)
@property
def output_dtypes(self):
- return nest.map_structure(
- lambda x: x.dtype if x is not None else None, self._python_func_outputs)
+ return nest.map_structure(lambda x: x.dtype if x is not None else None,
+ self._func_graph.structured_outputs)
@property
def captured_inputs(self):
- return self._extra_inputs
+ # TODO(akshayka): Should this return `_resolve_captured_inputs()`?
+ return self._captured_inputs
@property
def name(self):
"""Returns the name of the function in Eager-compatible format."""
- return self._function_def.name.encode("utf-8")
+ return self._inference_function.name.encode("utf-8")
- def _resolve_extra_inputs(self):
+ def _resolve_captured_inputs(self):
"""Resolve captured distributed variables to their current values.
Some inputs can be distributed variables. Such variables yield a different
@@ -710,43 +584,39 @@ class GraphModeFunction(object):
execution.
Returns:
- a list of resolved extra input tensors.
+ a list of resolved captured input tensors.
"""
if self._distributed_variables:
- # Loop over each extra_inputs and check if it corresponds to something
+ # Loop over each captured input and check if it corresponds to something
# distributed. If so, get its _distributed_container and fetch the
# component appropriate for the current execution context.
- resolved_extra_inputs = self._extra_inputs[:]
- for i, extra_input in enumerate(self._extra_inputs):
- distributed_var = self._distributed_variables.get(extra_input, None)
+ resolved_captured_inputs = self._captured_inputs[:]
+ for i, captured_input in enumerate(self._captured_inputs):
+ distributed_var = self._distributed_variables.get(captured_input, None)
if distributed_var is not None:
# distributed variables override __getattr__ and substitute the
# right component variable. In here, `distributed_var.handle`
# actually does the equivalent of
# distributed_var.get_current_component_var().handle.
- resolved_extra_inputs[i] = distributed_var.handle
- return resolved_extra_inputs
-
- return self._extra_inputs
+ resolved_captured_inputs[i] = distributed_var.handle
+ return resolved_captured_inputs
+ return self._captured_inputs
def __call__(self, *args):
"""Executes the passed function in eager mode."""
- for v in self._variables:
+ for v in self._func_graph.variables:
if v.trainable:
tape.watch_variable(v)
- resolved_extra_inputs = self._resolve_extra_inputs()
-
+ captures = self._resolve_captured_inputs()
tensor_inputs = [x for x in nest.flatten(args) if isinstance(x, ops.Tensor)]
- args = tensor_inputs + resolved_extra_inputs
- if tape.should_record(tensor_inputs) or tape.should_record(
- resolved_extra_inputs):
- if self._backward_function is None:
- self._construct_backprop_function()
+ args = tensor_inputs + captures
+
+ if tape.should_record(tensor_inputs) or tape.should_record(captures):
return self._backprop_call(args)
ctx = context.context()
- outputs = self._function_def.call(ctx, args, self._output_shapes)
+ outputs = self._inference_function.call(ctx, args)
return self._build_call_outputs(outputs)
def _build_call_outputs(self, result):
@@ -757,12 +627,12 @@ class GraphModeFunction(object):
Returns:
The actual call output.
"""
- if self._python_func_outputs is None:
+ if self._func_graph.structured_outputs is None:
return result
# Use `nest.flatten` instead of `_flatten` in order to preserve any
- # IndexedSlices in `self._python_func_outputs`.
- outputs_list = nest.flatten(self._python_func_outputs)
+ # IndexedSlices in `self._func_graph.structured_outputs`.
+ outputs_list = nest.flatten(self._func_graph.structured_outputs)
j = 0
for i, o in enumerate(outputs_list):
if o is not None:
@@ -776,13 +646,13 @@ class GraphModeFunction(object):
j += 3
else:
outputs_list[i] = ops.IndexedSlices(
- values=result[j],
- indices=result[j + 1])
+ values=result[j], indices=result[j + 1])
j += 2
else:
outputs_list[i] = result[j]
j += 1
- ret = nest.pack_sequence_as(self._python_func_outputs, outputs_list)
+ ret = nest.pack_sequence_as(self._func_graph.structured_outputs,
+ outputs_list)
return ret
@@ -798,20 +668,18 @@ def _get_defun_inputs_from_signature(signature):
def _get_defun_inputs_from_args(args):
"""Maps python function args to graph-construction inputs."""
function_inputs = [
- graph_placeholder(arg.dtype, arg.shape) if isinstance(arg, ops.Tensor)
- else arg for arg in nest.flatten(args)
+ graph_placeholder(arg.dtype, arg.shape)
+ if isinstance(arg, ops.Tensor) else arg for arg in nest.flatten(args)
]
return nest.pack_sequence_as(args, function_inputs)
-def _trace_and_define_function(name, python_func, compiled, args, kwds,
- signature=None):
- """Defines and returns graph-mode version of `python_func`.
+def _func_graph_from_py_func(name, python_func, args, kwds, signature=None):
+ """Returns a `FuncGraph` generated from `python_func`.
Args:
name: an identifier for the function.
python_func: the Python function to trace.
- compiled: whether the graph function should be compiled through XLA.
args: the positional args with which the Python function should be called;
ignored if a signature is provided.
kwds: the keyword args with which the Python function should be called;
@@ -823,15 +691,16 @@ def _trace_and_define_function(name, python_func, compiled, args, kwds,
inputs.
Returns:
- A GraphModeFunction.
+ A FuncGraph.
Raises:
TypeError: If any of `python_func`'s return values is neither `None` nor a
`Tensor`.
"""
- func_graph = FuncGraph(_inference_name(name), graph=ops.get_default_graph())
-
+ func_graph = FuncGraph(name, graph=ops.get_default_graph())
with func_graph.as_default(), AutomaticControlDependencies() as a:
+ variable_scope.get_variable_scope().set_use_resource(True)
+
if signature is None:
func_args = _get_defun_inputs_from_args(args)
func_kwds = _get_defun_inputs_from_args(kwds)
@@ -842,8 +711,7 @@ def _trace_and_define_function(name, python_func, compiled, args, kwds,
# Note: `nest.flatten` sorts by keys, as does `_deterministic_dict_values`.
func_graph.inputs.extend(
x for x in nest.flatten(func_args) + nest.flatten(func_kwds)
- if isinstance(x, ops.Tensor)
- )
+ if isinstance(x, ops.Tensor))
# Variables to help check whether mutation happens in calling the function
# Copy the recursive list, tuple and map structure, but not base objects
@@ -868,6 +736,7 @@ def _trace_and_define_function(name, python_func, compiled, args, kwds,
this_tape = tape.push_new_tape()
try:
func_outputs = python_func(*func_args, **func_kwds)
+ # invariant: `func_outputs` contains only Tensors and `None`s.
func_outputs = nest.map_structure(convert, func_outputs)
def check_mutation(n1, n2):
@@ -887,53 +756,34 @@ def _trace_and_define_function(name, python_func, compiled, args, kwds,
check_mutation(func_args_before, func_args)
check_mutation(func_kwds_before, func_kwds)
-
finally:
tape.pop_tape(this_tape)
+
func_graph.structured_outputs = func_outputs
+ # Returning a closed-over tensor does not trigger convert_to_tensor.
+ func_graph.outputs.extend(
+ func_graph.capture(x)
+ for x in _flatten(func_graph.structured_outputs)
+ if x is not None)
+
+ # Some captured variables might be components of DistributedValues.
+ # Instead of storing non-distributed component variables, we
+ # store their distributed containers so we can retrieve the correct
+ # component variables at call-time.
variables = list(this_tape.watched_variables())
-
- # Some variables captured by the tape can come from a DistributedValue.
- # At call time, DistributedValue can return another variable (e.g. if
- # the function is run on a different device). Thus, instead of storing
- # the specific captured variable, we replace it with its distributed
- # container.
- strategy = distribute.get_distribution_strategy()
+ strategy = distribution_strategy_context.get_distribution_strategy()
for i, variable in enumerate(variables):
# If variable is not distributed value_container returns itself.
variables[i] = strategy.value_container(variable)
-
func_graph.variables = variables
- # Returning a closed-over tensor as an output does not trigger a
- # call to convert_to_tensor, so we manually capture all such tensors.
- func_graph.outputs.extend(
- func_graph.capture(x) for x in _flatten(func_graph.structured_outputs)
- if x is not None
- )
-
- output_shapes = tuple(
- x.shape if isinstance(x, ops.Tensor) else None
- for x in func_graph.outputs)
-
- all_ignored_ops = frozenset(x.op for x in func_graph.inputs)
- operations = tuple(x for x in func_graph.get_operations()
- if x not in all_ignored_ops)
- # Register any other functions defined in the graph
- # TODO(ashankar): Oh lord, forgive me for this lint travesty.
+ # Register any other functions defined in the graph.
if context.executing_eagerly():
for f in func_graph._functions.values(): # pylint: disable=protected-access
# TODO(ashankar): What about the gradient registry?
_register(f._c_func.func) # pylint: disable=protected-access
- attrs = {}
- if compiled:
- attrs[_xla_compile_attr] = attr_value_pb2.AttrValue(b=True)
-
- return GraphModeFunction(
- func_graph.name, func_graph.inputs, func_graph.captures.keys(),
- func_graph, operations, func_graph.outputs, func_graph.structured_outputs,
- output_shapes, func_graph.variables, attrs)
+ return func_graph
_TensorType = collections.namedtuple("_TensorType", ["dtype", "shape"])
@@ -997,8 +847,7 @@ class _PolymorphicFunction(object):
def __init__(self,
python_function,
name,
- input_signature=None,
- compiled=False):
+ input_signature=None):
"""Initializes a polymorphic function.
Args:
@@ -1007,7 +856,6 @@ class _PolymorphicFunction(object):
input_signature: a possibly nested sequence of `TensorSpec` objects
specifying the input signature of this function. If `None`, a separate
function is instantiated for each inferred input signature.
- compiled: if True, the framework will attempt to compile func with XLA.
Raises:
ValueError: if `input_signature` is not None and the `python_function`'s
@@ -1026,7 +874,6 @@ class _PolymorphicFunction(object):
self._args_to_prepend = tuple()
self._kwds_to_include = {}
self._name = name
- self._compiled = compiled
self._arguments_to_functions = {}
self._variables = []
@@ -1156,8 +1003,9 @@ class _PolymorphicFunction(object):
if any(not isinstance(arg, ops.Tensor) for arg in flat_inputs):
raise ValueError("When input_signature is provided, all inputs to "
"the Python function must be Tensors.")
- tensor_specs = [tensor_spec.TensorSpec.from_tensor(tensor)
- for tensor in flat_inputs]
+ tensor_specs = [
+ tensor_spec.TensorSpec.from_tensor(tensor) for tensor in flat_inputs
+ ]
if any(not spec.is_compatible_with(other)
for spec, other in zip(self._flat_input_signature, tensor_specs)):
raise ValueError("Python inputs incompatible with input_signature: "
@@ -1191,9 +1039,9 @@ class _PolymorphicFunction(object):
"must be hashable.")
if graph_function is None:
- graph_function = _trace_and_define_function(
- self._name, self._python_function, self._compiled, args, kwds,
- self._input_signature)
+ graph_function = GraphCallable(
+ _func_graph_from_py_func(self._name, self._python_function, args,
+ kwds, self._input_signature))
self._variables.extend(
[v for v in graph_function.variables if v not in self._variables])
self._arguments_to_functions[cache_key] = graph_function
@@ -1214,14 +1062,11 @@ class _PolymorphicFunction(object):
return self._variables
-# TODO(akshayka): Remove the `compiled` flag and create a separate
-# API for xla compilation (`defun` is already complicated enough
-# as it is, and the keyword argument makes 'compiled' an overloaded concept)
-def defun(func=None, input_signature=None, compiled=False):
+def defun(func=None, input_signature=None):
"""Compiles a Python function into a callable TensorFlow graph.
`defun` (short for "define function") trace-compiles a Python function
- composed of TensorFlow operations into a callable that executes a @{tf.Graph}
+ composed of TensorFlow operations into a callable that executes a `tf.Graph`
containing those operations. The callable produced by `defun` contains only
the subgraph of TensorFlow operations that were executed when the Python
function was called with a particular input signature, defined as a list
@@ -1244,9 +1089,9 @@ def defun(func=None, input_signature=None, compiled=False):
For a Python function to be compatible with `defun`, all of its arguments must
be hashable Python objects or lists thereof. The function itself may not
modify the list/map structure of its arguments. Additionally, it must return
- zero or more @{tf.Tensor} objects. If the Python function returns
- a @{tf.Variable}, its compiled version will return the value of that variable
- as a @{tf.Tensor}.
+ zero or more `tf.Tensor` objects. If the Python function returns
+ a `tf.Variable`, its compiled version will return the value of that variable
+ as a `tf.Tensor`.
Executing a graph generated by `defun` respects device annotations (i.e.,
all `with tf.device` directives present in a Python function will also be
@@ -1315,25 +1160,67 @@ def defun(func=None, input_signature=None, compiled=False):
When using `defun`, there are subtleties regarding inputs, Python control
flow, and variable creation that one should be aware of. For concreteness, let
- `f` be a Python function that returns zero or more @{tf.Tensor} objects and
+ `f` be a Python function that returns zero or more `tf.Tensor` objects and
let `F = defun(f)`. `F` builds a graph for each unique input signature it
sees, Python control flow is baked into graphs, and operations related to
variable initialization are automatically lifted out of the graphs that `F`
generates and placed in the eager context if executing eagerly or into an
outer graph otherwise.
- _Tracing and Input Signatures_.
- The signature of inputs supplied to `F` is defined to be a tuple of the shapes
- and dtypes of Tensor-typed arguments and the values of non-Tensor arguments,
- where "arguments" includes both args and kwargs. Every time `F` is invoked,
- the signature of its inputs are inferred. The first time `F(*args, **kwargs)`
- is invoked with a particular signature, `f(*args, **kwargs)` is executed and
- all the TensorFlow operations that `f` executes, along with the Tensors that
- flow between them, are recorded in a TensorFlow graph. `F` caches this graph
- and binds it to the inputs' signature; every subsequent invocation of `F` with
- inputs conforming to this signature will immediately retrieve the cached graph
- and pass it to the TensorFlow runtime for execution.
+ _Input Signatures_
+ By default, `F = tf.contrib.eager.defun(f)` instantiates a separate graph
+ for every unique sequence of the shapes and dtypes of Tensor arguments and
+ the values of Python objects it is invoked with. For example, calling
+ `F(tf.random_uniform([2])` will execute a different graph than
+ `F(tf.random_uniform([3])` because the two inputs have different shapes.
+ The first time that `F(*args, **kwargs)` is called with a particular sequence
+ of Tensor shapes and dtypes and Python values, it constructs a graph by
+ tracing the execution of `f(*args, **kwargs)`; this graph is bound to an
+ input signature inferred from `(*args, **kwargs)` and cached for future reuse.
+
+ `tf.contrib.eager.defun` caches graphs for your convenience, letting you
+ define TensorFlow functions without explicitly specifying their signatures.
+ However, this policy is conservative and potentially expensive; for example,
+ when different invocations of your function have differently-shaped Tensor
+ inputs, this policy might generate more graph functions than necessary. To
+ eliminate such costs, `tf.contrib.eager.defun` allows you to supply an
+ optional `input_signature` argument specifying the shapes and dtypes of the
+ inputs. In particular, the shapes may be partially unspecified, with `None`s
+ in the unknown dimensions. When an input signature is provided,
+ `tf.contrib.eager.defun` will only instantiate a single graph for the
+ decorated Python function. The following is an example:
+
+ ```python
+ import tensorflow as tf
+ # The first `TensorSpec` below describes the shape and dtype of `words`,
+ # and the second describes the shape and dtype of `another_tensor`. Note that
+ # the last dimension of the `words` `TensorSpec` is left unspecified.
+ @tf.contrib.eager.defun(input_signature=[
+ tf.contrib.eager.TensorSpec(shape=[50, 300, None], dtype=tf.float32),
+ tf.contrib.eager.TensorSpec(shape=[300, 100], dtype=tf.float32)
+ ])
+ def my_sequence_model(words, another_tensor):
+ ...
+
+ # Note how the third dimension of the first input can vary freely.
+ words = tf.random_uniform(([50, 300, 10])
+ second_input = tf.random_uniform([300, 100])
+ my_sequence_model(words, second_input)
+
+ words = tf.random_uniform(([50, 300, 20])
+ my_sequence_model(words, second_input)
+
+ # Passing an input with an incompatible shape will raise an error.
+ words = tf.random_uniform(([50, 100, 20])
+ my_sequence_model(words, second_input) # <---- This will raise an error.
+
+ ```
+
+ Python functions that are compiled with an `input_signature` must only accept
+ Tensors as arguments and must not take unnamed keyword arguments (**kwargs).
+
+ _Tracing_
Be aware that because `F` only logs TensorFlow operations, all the other
Python code that `f` executes will only shape the _construction_ of the graphs
that `F` executes: the Python code won't be executed when the graphs
@@ -1398,10 +1285,10 @@ def defun(func=None, input_signature=None, compiled=False):
On the other hand, because `defun` generates graphs by tracing and not by
source code analysis, it fully unrolls Python `for` and `while` loops,
potentially creating large graphs. If your Python function has native loops
- that run for many iterations, consider replacing them with @{tf.while_loop}
+ that run for many iterations, consider replacing them with `tf.while_loop`
operations.
- When constructing graphs, @{tf.Tensor} objects cannot be used as Python
+ When constructing graphs, `tf.Tensor` objects cannot be used as Python
`bool` objects. This means, for example, that you should replace code in `f`
resembling
@@ -1420,7 +1307,7 @@ def defun(func=None, input_signature=None, compiled=False):
automatically lifted out of the graphs generated by `defun`. In practice, this
implies that variable creation and initialization only happen the first time
`F` is called, and that variables are reused every time thereafter. Many
- TensorFlow APIs, like @{tf.keras.layers.Layer} objects, create variables the
+ TensorFlow APIs, like `tf.keras.layers.Layer` objects, create variables the
first time they are called and reuse them thereafter. Automatic variable
lifting makes it possible to compile these APIs without extra effort, at the
cost of introducing a discrepancy between the semantics of executing Python
@@ -1459,16 +1346,17 @@ def defun(func=None, input_signature=None, compiled=False):
to reference the same set of variables, add logic to your Python function that
ensures that variables are only created the first time it is called and are
reused for every subsequent invocation; note that this is precisely what
- @{tf.keras.layers.Layer} objects do, so we recommend using them to represent
+ `tf.keras.layers.Layer` objects do, so we recommend using them to represent
variable-bearing computations whenever possible.
Args:
func: function to be compiled. If `func` is None, returns a
decorator that can be invoked with a single argument - `func`. The
end result is equivalent to providing all the arguments up front.
- In other words, defun(compiled=True)(func) is equivalent to
- defun(func, compiled=True). The former allows the following use case:
- @tf.contrib.eager.defun(compiled=True)
+ In other words, defun(input_signature=...)(func) is equivalent to
+ defun(func, input_signature=...). The former allows
+ the following use case:
+ @tf.contrib.eager.defun(input_signature=...)
def foo(...):
...
@@ -1479,11 +1367,6 @@ def defun(func=None, input_signature=None, compiled=False):
signature is specified, every input to `func` must be a `Tensor`, and
`func` cannot accept `**kwargs`.
- compiled: If True, an attempt to compile `func` with XLA will be made.
- If it fails, function will be run normally. Experimental. Currently
- supported only for execution on TPUs. For the vast majority of users,
- this argument should be False.
-
Returns:
If `func` is not None, returns a callable that will execute the compiled
function (and return zero or more `tf.Tensor` objects).
@@ -1499,7 +1382,7 @@ def defun(func=None, input_signature=None, compiled=False):
return tf_decorator.make_decorator(
function,
_PolymorphicFunction(
- function, name, input_signature=input_signature, compiled=compiled))
+ function, name, input_signature=input_signature))
# This code path is for the `foo = tfe.defun(foo, ...)` use case
if func is not None:
@@ -1557,7 +1440,8 @@ def make_defun_op(func, *args, **kwds):
and which can be called directly the way a `@defun` wrapped function
can.
"""
- return _trace_and_define_function(func.__name__, func, False, args, kwds)
+ return GraphCallable(
+ _func_graph_from_py_func(func.__name__, func, args, kwds))
class AutomaticControlDependencies(object):
diff --git a/tensorflow/python/eager/function_test.py b/tensorflow/python/eager/function_test.py
index 06b4e732a1..380bcf763f 100644
--- a/tensorflow/python/eager/function_test.py
+++ b/tensorflow/python/eager/function_test.py
@@ -19,6 +19,7 @@ from __future__ import print_function
import collections
import functools
+from multiprocessing.pool import ThreadPool
import sys
from tensorflow.core.protobuf import config_pb2
@@ -143,6 +144,61 @@ class FunctionTest(test.TestCase):
out = sq_op(t)
self.assertAllEqual(out, math_ops.matmul(t, t).numpy())
+ def testExecutingStatelessDefunConcurrently(self):
+
+ @function.defun
+ def stateless(x):
+ return math_ops.multiply(2.0, x)
+
+ pool = ThreadPool()
+ inputs = [constant_op.constant(1.0 * x) for x in range(100)]
+ outputs = [float(out) for out in pool.map(stateless, inputs)]
+ expected = [float(2.0 * x) for x in inputs]
+ self.assertSequenceEqual(outputs, expected)
+
+ def testExecutingManyStatelessDefunsConcurrently(self):
+
+ @function.defun
+ def stateless(x):
+ del x
+ return math_ops.multiply(2.0, 2.0)
+
+ pool = ThreadPool()
+ # `pool.map` below instantiates 100 functions, one for each object.
+ outputs = [
+ float(out)
+ for out in pool.map(stateless, [object() for _ in range(100)])
+ ]
+ expected = [4.0] * 100
+ self.assertSequenceEqual(outputs, expected)
+
+ def testExecutingStatefulDefunConcurrently(self):
+
+ v = resource_variable_ops.ResourceVariable(1.0)
+
+ @function.defun
+ def stateful(x):
+ v.assign(x)
+
+ pool = ThreadPool()
+ inputs = [constant_op.constant(0.0)] * 100
+ pool.map(stateful, inputs)
+ self.assertEqual(float(v.read_value()), 0.0)
+
+ def testExecutingManyStatefulDefunsConcurrently(self):
+
+ v = resource_variable_ops.ResourceVariable(1.0)
+
+ @function.defun
+ def stateful(x):
+ del x
+ return v.assign(0.0)
+
+ pool = ThreadPool()
+ # `pool.map` below instantiates 100 functions, one for each object.
+ pool.map(stateful, [object() for _ in range(100)])
+ self.assertEqual(float(v.read_value()), 0.0)
+
def disabled_testRandomSeed(self):
@function.defun
@@ -341,6 +397,18 @@ class FunctionTest(test.TestCase):
compiled = function.defun(f)
compiled()
+ @test_util.run_in_graph_and_eager_modes
+ def testDefunForcesResourceVariables(self):
+
+ def variable_creator():
+ return variables.Variable(0.0).read_value()
+
+ defined = function.defun(variable_creator)
+ defined() # Create the variable.
+ self.assertEqual(len(defined.variables), 1)
+ self.assertIsInstance(
+ defined.variables[0], resource_variable_ops.ResourceVariable)
+
def testDefunDifferentiable(self):
v = resource_variable_ops.ResourceVariable(1.0)
@@ -378,6 +446,22 @@ class FunctionTest(test.TestCase):
op = call()
self.assertAllEqual(sess.run(op), 2.0)
+ def testSymbolicGradientVariableZerosLike(self):
+ with ops.Graph().as_default():
+ v = resource_variable_ops.ResourceVariable(1.0)
+
+ @function.defun
+ def f(x, v):
+ v.read_value()
+ return x * x
+
+ x = constant_op.constant(1.0)
+ l = f(x, v)
+ _, dv = gradients_impl.gradients(l, [x, v])
+ with self.test_session():
+ v.initializer.run()
+ self.assertAllEqual(dv.eval(), 0.0)
+
def testGraphModeManyFunctions(self):
with context.graph_mode(), self.test_session():
@@ -876,9 +960,12 @@ class FunctionTest(test.TestCase):
y = model(x)
self.assertAllEqual([[[[4.0]]]], y.numpy())
+ # Note: The ConfigProto below unfortunately only configures graph
+ # construction. Eager's configuration is controlled in `__main__`.
@test_util.run_in_graph_and_eager_modes(
- config=config_pb2.ConfigProto(device_count={'CPU': 3}))
+ config=config_pb2.ConfigProto(device_count={'CPU': 4}))
def testDeviceAnnotationsRespected(self):
+
@function.defun
def multi_device_fn():
with ops.device('/cpu:0'):
@@ -890,12 +977,28 @@ class FunctionTest(test.TestCase):
with ops.device('/cpu:2'):
s3 = iterator_ops.Iterator.from_structure(
(dtypes.float32,)).string_handle()
- return s1, s2, s3
+ with ops.device(''):
+ # TODO(akshayka): This is unfortunate and brittle. It prevents
+ # `Iterator.from_structure` from assigning the iterator op to 'cpu:0'.
+ # Remove this hack once we have a way of obtaining metadata about
+ # function execution.
+ s4 = iterator_ops.Iterator.from_structure(
+ (dtypes.float32,)).string_handle()
+ return s1, s2, s3, s4
- outputs = multi_device_fn()
- self.assertTrue(compat.as_bytes('CPU:0') in self.evaluate(outputs[0]))
- self.assertTrue(compat.as_bytes('CPU:1') in self.evaluate(outputs[1]))
- self.assertTrue(compat.as_bytes('CPU:2') in self.evaluate(outputs[2]))
+ with ops.device('/cpu:3'):
+ outputs = self.evaluate(multi_device_fn())
+ self.assertIn(compat.as_bytes('CPU:0'), outputs[0])
+ self.assertIn(compat.as_bytes('CPU:1'), outputs[1])
+ self.assertIn(compat.as_bytes('CPU:2'), outputs[2])
+ self.assertIn(compat.as_bytes('CPU:3'), outputs[3])
+
+ with ops.device('/cpu:0'):
+ outputs = self.evaluate(multi_device_fn())
+ self.assertIn(compat.as_bytes('CPU:0'), outputs[0])
+ self.assertIn(compat.as_bytes('CPU:1'), outputs[1])
+ self.assertIn(compat.as_bytes('CPU:2'), outputs[2])
+ self.assertIn(compat.as_bytes('CPU:0'), outputs[3])
def testVariablesAreTracked(self):
v = resource_variable_ops.ResourceVariable(1.0)
@@ -1677,5 +1780,5 @@ class AutomaticControlDependenciesTest(test.TestCase):
if __name__ == '__main__':
ops.enable_eager_execution(
- config=config_pb2.ConfigProto(device_count={'CPU': 3}))
+ config=config_pb2.ConfigProto(device_count={'CPU': 4}))
test.main()
diff --git a/tensorflow/python/eager/graph_callable.py b/tensorflow/python/eager/graph_callable.py
deleted file mode 100644
index 7105d2e399..0000000000
--- a/tensorflow/python/eager/graph_callable.py
+++ /dev/null
@@ -1,435 +0,0 @@
-# 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.
-# 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.
-# ==============================================================================
-"""Decorator that produces a callable object that executes a TensorFlow graph.
-"""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import contextlib
-
-from tensorflow.python.eager import context
-from tensorflow.python.eager import function
-from tensorflow.python.eager import tape
-from tensorflow.python.framework import dtypes
-from tensorflow.python.framework import errors
-from tensorflow.python.framework import ops as tf_ops
-from tensorflow.python.framework import tensor_shape
-from tensorflow.python.ops import array_ops
-from tensorflow.python.ops import resource_variable_ops
-from tensorflow.python.ops import variable_scope
-from tensorflow.python.util import nest
-from tensorflow.python.util import tf_decorator
-from tensorflow.python.util import tf_inspect
-
-
-def _default_initializer(name, shape, dtype):
- """The default initializer for variables."""
- # pylint: disable=protected-access
- store = variable_scope._get_default_variable_store()
- initializer = store._get_default_initializer(name, shape=shape, dtype=dtype)
- # pylint: enable=protected-access
- return initializer[0]
-
-
-class _CapturedVariable(object):
- """Variable captured by graph_callable.
-
- Internal to the implementation of graph_callable. Created only by
- _VariableCapturingScope and used only to read the variable values when calling
- the function after the variables are initialized.
- """
-
- def __init__(self, name, initializer, shape, dtype, trainable):
- self.name = name
- if initializer is None:
- initializer = _default_initializer(name, shape, dtype)
- initial_value = lambda: initializer(shape, dtype=dtype)
-
- with context.eager_mode():
- self.variable = resource_variable_ops.ResourceVariable(
- initial_value=initial_value, name=name, dtype=dtype,
- trainable=trainable)
- self.shape = shape
- self.dtype = dtype
- self.placeholder = None
- self.trainable = trainable
-
- def read(self, want_gradients=True):
- if want_gradients and self.trainable:
- v = tape.watch_variable(self.variable)
- else:
- v = self.variable
- return v.read_value()
-
-
-class _VariableCapturingScope(object):
- """Variable-scope-like object which captures tf.get_variable calls.
-
- This is responsible for the main difference between the initialization version
- of a function object and the calling version of a function object.
-
- capturing_scope replaces calls to tf.get_variable with placeholder tensors to
- be fed the variable's current value. TODO(apassos): these placeholders should
- instead be objects implementing a similar API to tf.Variable, for full
- compatibility.
-
- initializing_scope replaces calls to tf.get_variable with creation of
- variables and initialization of their values. This allows eventual support of
- initialized_value and friends.
-
- TODO(apassos): once the eager mode layers API is implemented support eager
- func-to-object as well.
- """
-
- def __init__(self):
- self.variables = {}
- self.tf_variables = {}
-
- @contextlib.contextmanager
- def capturing_scope(self):
- """Context manager to capture variable creations.
-
- Replaces variable accesses with placeholders.
-
- Yields:
- nothing
- """
- # TODO(apassos) ignoring the regularizer and partitioner here; figure out
- # how to deal with these.
- def _custom_getter( # pylint: disable=missing-docstring
- getter=None,
- name=None,
- shape=None,
- dtype=dtypes.float32,
- initializer=None,
- regularizer=None,
- reuse=None,
- trainable=None,
- collections=None,
- caching_device=None, # pylint: disable=redefined-outer-name
- partitioner=None,
- validate_shape=True,
- use_resource=None,
- aggregation=variable_scope.VariableAggregation.NONE,
- synchronization=variable_scope.VariableSynchronization.AUTO):
- del getter, regularizer, partitioner, validate_shape, use_resource, dtype
- del collections, initializer, trainable, reuse, caching_device, shape
- del aggregation, synchronization
- assert name in self.variables
- v = self.variables[name]
- return v.variable
-
- scope = variable_scope.get_variable_scope()
- with variable_scope.variable_scope(scope, custom_getter=_custom_getter):
- yield
-
- @contextlib.contextmanager
- def initializing_scope(self):
- """Context manager to capture variable creations.
-
- Forcibly initializes all created variables.
-
- Yields:
- nothing
- """
- # TODO(apassos) ignoring the regularizer and partitioner here; figure out
- # how to deal with these.
- def _custom_getter( # pylint: disable=missing-docstring
- getter=None,
- name=None,
- shape=None,
- dtype=dtypes.float32,
- initializer=None,
- regularizer=None,
- reuse=None,
- trainable=None,
- collections=None,
- caching_device=None, # pylint: disable=redefined-outer-name
- partitioner=None,
- validate_shape=True,
- use_resource=None,
- aggregation=variable_scope.VariableAggregation.NONE,
- synchronization=variable_scope.VariableSynchronization.AUTO):
- del getter, regularizer, collections, caching_device, partitioner
- del use_resource, validate_shape, aggregation, synchronization
- if name in self.tf_variables:
- if reuse:
- return self.tf_variables[name].initialized_value()
- else:
- raise ValueError("Specified reuse=%s but tried to reuse variables."
- % reuse)
- # TODO(apassos): ensure this is on the same device as above
- v = _CapturedVariable(name, initializer, shape, dtype, trainable)
- self.variables[name] = v
-
- graph_mode_resource = v.variable.handle
- if initializer is None:
- initializer = _default_initializer(name, shape, dtype)
- resource_variable_ops.shape_safe_assign_variable_handle(
- graph_mode_resource, v.variable.shape, initializer(shape, dtype))
- return v.variable
-
- scope = variable_scope.get_variable_scope()
- with variable_scope.variable_scope(scope, custom_getter=_custom_getter):
- yield
-
-
-class _InitializingFunctionObject(object):
- """Responsible for deciding which version of func-to-object to call.
-
- call_fn is the version which calls the function with the current values of the
- variables and init_fn is the version which calls the function to initialize
- all variables.
-
- TODO(apassos): figure out a way to support initializing only _some_
- variables. This requires a way to pull out a variable's initialization code
- from the graph, which might not be possible in general.
- """
-
- def __init__(self, call_fn, init_fn, shape_and_dtypes):
- self._init_fn = init_fn
- self._call_fn = call_fn
- self.shape_and_dtypes = shape_and_dtypes
- self.flattened_shapes = [tensor_shape.as_shape(sd.shape) for sd in
- nest.flatten(self.shape_and_dtypes)]
-
- @property
- def variables(self):
- return self._call_fn.variables
-
- def __call__(self, *args):
- nest.assert_same_structure(self.shape_and_dtypes, args, check_types=False)
- if not all([
- shape.is_compatible_with(arg.shape)
- for shape, arg in zip(self.flattened_shapes, nest.flatten(args))
- ]):
- raise ValueError(
- "Declared shapes do not match argument shapes: Expected %s, found %s."
- % (self.flattened_shapes, [arg.shape for arg in nest.flatten(args)]))
-
- initialized = [resource_variable_ops.var_is_initialized_op(
- v.handle).numpy() for v in self._call_fn.variables]
- if all(x for x in initialized):
- for v in self._call_fn.variables:
- if v.trainable:
- tape.watch_variable(v)
- return self._call_fn(*args)
- elif all(not x for x in initialized):
- return self._init_fn(*args)
- else:
- raise ValueError("Some, but not all, variables are initialized.")
-
-
-def _get_graph_callable_inputs(shape_and_dtypes):
- """Maps specified shape_and_dtypes to graph inputs."""
- ret = []
- for x in shape_and_dtypes:
- if isinstance(x, ShapeAndDtype):
- ret.append(array_ops.placeholder(x.dtype, x.shape))
- elif isinstance(x, (tuple, list)):
- ret.append(_get_graph_callable_inputs(x))
- else:
- raise errors.InvalidArgumentError(
- None, None, "Expected the argument to @graph_callable to be a "
- "(possibly nested) list or tuple of ShapeAndDtype objects, "
- "but got an object of type: %s" % type(x))
-
- return tuple(ret) if isinstance(shape_and_dtypes, tuple) else ret
-
-
-def _graph_callable_internal(func, shape_and_dtypes):
- """Defines and returns a template version of func.
-
- Under the hood we make two function objects, each wrapping a different version
- of the graph-mode code. One version immediately runs variable initialization
- before making the variable's Tensors available for use, while the other
- version replaces the Variables with placeholders which become function
- arguments and get the current variable's value.
-
- Limitations in (2) and (4) are because this does not implement a graph-mode
- Variable class which has a convert_to_tensor(as_ref=True) method and a
- initialized_value method. This is fixable.
-
- Args:
- func: The tfe Python function to compile.
- shape_and_dtypes: A possibly nested list or tuple of ShapeAndDtype objects.
-
- Raises:
- ValueError: If any one of func's outputs is not a Tensor.
-
- Returns:
- Callable graph object.
- """
- container = tf_ops.get_default_graph()._container # pylint: disable=protected-access
- graph_key = tf_ops.get_default_graph()._graph_key # pylint: disable=protected-access
- with context.graph_mode():
- # This graph will store both the initialization and the call version of the
- # wrapped function. It will later be used by the backprop code to build the
- # backprop graph, if necessary.
- tmp_graph = function.CapturingGraph()
- # Inherit the graph key from the original graph to ensure optimizers don't
- # misbehave.
- tmp_graph._container = container # pylint: disable=protected-access
- tmp_graph._graph_key = graph_key # pylint: disable=protected-access
- with tmp_graph.as_default():
- # Placeholders for the non-variable inputs.
- func_inputs = _get_graph_callable_inputs(shape_and_dtypes)
- func_num_args = len(tf_inspect.getfullargspec(func).args)
- if len(func_inputs) != func_num_args:
- raise TypeError("The number of arguments accepted by the decorated "
- "function `%s` (%d) must match the number of "
- "ShapeAndDtype objects passed to the graph_callable() "
- "decorator (%d)." %
- (func.__name__, func_num_args, len(func_inputs)))
-
- # First call the function to generate a graph which can initialize all
- # variables. As a side-effect this will populate the variable capturing
- # scope's view of which variables exist.
- variable_captures = _VariableCapturingScope()
- with variable_captures.initializing_scope(
- ), function.AutomaticControlDependencies() as a:
- func_outputs = func(*func_inputs)
- outputs_list = nest.flatten(func_outputs)
- for i, x in enumerate(outputs_list):
- if x is not None:
- outputs_list[i] = a.mark_as_return(x)
- if len(outputs_list) == 1 and outputs_list[0] is None:
- outputs_list = []
- output_shapes = [x.shape for x in outputs_list]
- if not all(isinstance(x, tf_ops.Tensor) for x in outputs_list):
- raise ValueError("Found non-tensor output in %s" % str(outputs_list))
- initializing_operations = tmp_graph.get_operations()
-
- # Call the function again, now replacing usages of variables with
- # placeholders. This assumes the variable capturing scope created above
- # knows about all variables.
- tmp_graph.clear_resource_control_flow_state()
- with variable_captures.capturing_scope(
- ), function.AutomaticControlDependencies() as a:
- captured_outputs = func(*func_inputs)
- captured_outlist = nest.flatten(captured_outputs)
- for i, x in enumerate(captured_outlist):
- if x is not None:
- captured_outlist[i] = a.mark_as_return(x)
- capturing_operations = tmp_graph.get_operations()[
- len(initializing_operations):]
-
- sorted_variables = sorted(variable_captures.variables.values(),
- key=lambda x: x.name)
-
- extra_inputs = tmp_graph.captures.keys()
- extra_placeholders = tmp_graph.captures.values()
-
- flat_inputs = [x for x in nest.flatten(func_inputs)
- if isinstance(x, tf_ops.Tensor)]
- placeholder_inputs = flat_inputs+ list(extra_placeholders)
-
- func_def_outputs = [x for x in outputs_list if isinstance(x, tf_ops.Tensor)]
- initialization_name = function._inference_name(func.__name__) # pylint: disable=protected-access
- # TODO(ashankar): Oh lord, forgive me for this lint travesty.
- # Also, what about the gradient registry of these functions? Those need to be
- # addressed as well.
- for f in tmp_graph._functions.values(): # pylint: disable=protected-access
- function._register(f._c_func.func) # pylint: disable=protected-access
- initializer_function = function.GraphModeFunction(
- initialization_name,
- placeholder_inputs,
- extra_inputs,
- tmp_graph,
- initializing_operations,
- func_def_outputs,
- func_outputs,
- output_shapes)
-
- capture_func_def_outputs = [
- x for x in captured_outlist if isinstance(x, tf_ops.Tensor)]
- captured_function_name = function._inference_name(func.__name__) # pylint: disable=protected-access
- captured_function = function.GraphModeFunction(
- captured_function_name,
- placeholder_inputs,
- extra_inputs,
- tmp_graph,
- capturing_operations,
- capture_func_def_outputs,
- captured_outputs,
- output_shapes,
- variables=[x.variable for x in sorted_variables])
-
- return _InitializingFunctionObject(captured_function, initializer_function,
- shape_and_dtypes)
-
-
-class ShapeAndDtype(object):
- """Data type that packages together shape and type information.
-
- Used for arguments to graph callables. See graph_callable() for an example.
- """
-
- def __init__(self, shape, dtype):
- self.shape = shape
- self.dtype = dtype
-
-
-def graph_callable(shape_and_dtypes):
- """Decorator that produces a callable that executes a TensorFlow graph.
-
- When applied on a function that constructs a TensorFlow graph, this decorator
- produces a callable object that:
-
- 1. Executes the graph when invoked. The first call will initialize any
- variables defined in the graph.
-
- 2. Provides a .variables() method to return the list of TensorFlow variables
- defined in the graph.
-
- Note that the wrapped function is not allowed to change the values of the
- variables, just use them.
-
- The return value of the wrapped function must be one of the following:
- (1) None, (2) a Tensor, or (3) a possibly nested sequence of Tensors.
-
- Example:
-
- ```python
- @tfe.graph_callable([tfe.ShapeAndDtype(shape(), dtype=dtypes.float32)])
- def foo(x):
- v = tf.get_variable('v', initializer=tf.ones_initializer(), shape=())
- return v + x
-
- ret = foo(tfe.Tensor(2.0)) # `ret` here is a Tensor with value 3.0.
-
- foo.variables[0].assign(7.0) # Modify the value of variable `v`.
- ret = foo(tfe.Tensor(2.0)) # `ret` here now is a Tensor with value 9.0.
- ```
- Args:
- shape_and_dtypes: A possibly nested list or tuple of ShapeAndDtype objects
- that specifies shape and type information for each of the callable's
- arguments. The length of this list must be equal to the number of
- arguments accepted by the wrapped function.
-
- Returns:
- A callable graph object.
- """
- # TODO(alive,apassos): support initialized_value and friends from tf.Variable.
- assert context.executing_eagerly(), (
- "graph_callable can only be used when Eager execution is enabled.")
- def decorator(func):
- return tf_decorator.make_decorator(func,
- _graph_callable_internal(
- func, shape_and_dtypes))
-
- return decorator
diff --git a/tensorflow/python/eager/graph_callable_test.py b/tensorflow/python/eager/graph_callable_test.py
deleted file mode 100644
index b9e6ca2a93..0000000000
--- a/tensorflow/python/eager/graph_callable_test.py
+++ /dev/null
@@ -1,249 +0,0 @@
-# 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.
-# 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.
-# ==============================================================================
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.python.eager import backprop
-from tensorflow.python.eager import graph_callable
-from tensorflow.python.eager import test
-from tensorflow.python.framework import constant_op
-from tensorflow.python.framework import dtypes
-from tensorflow.python.framework import function
-from tensorflow.python.framework import tensor_shape
-from tensorflow.python.ops import init_ops
-from tensorflow.python.ops import math_ops
-from tensorflow.python.ops import variable_scope
-
-
-class GraphCallableTest(test.TestCase):
-
- def testBasic(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def my_function(x):
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- return v + x
-
- self.assertEqual(
- 2, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())
-
- my_function.variables[0].assign(1.)
- self.assertEqual(
- 3, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())
-
- def testFunctionWithoutReturnValue(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def my_function(x):
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- v.assign(x)
-
- my_function(constant_op.constant(4, dtype=dtypes.float32))
- self.assertAllEqual(4, my_function.variables[0].read_value())
-
- def testFunctionWithoutReturnValueAndArgs(self):
-
- @graph_callable.graph_callable([])
- def my_function():
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- v.assign(4)
-
- my_function()
- self.assertAllEqual(4, my_function.variables[0].read_value())
-
- def testVariableAPI(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def my_function(x):
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- return v.read_value() + x
-
- self.assertEqual(
- 2, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())
-
- my_function.variables[0].assign(1.)
- self.assertEqual(
- 3, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())
-
- def testTensorShape(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(1), dtype=dtypes.float32)])
- def my_function(x):
- _ = x.get_shape()
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=[x.shape[0]])
- self.assertEqual(v.shape[0], x.shape[0])
- return v + x
-
- self.assertEqual([2.],
- my_function(
- constant_op.constant([2.],
- dtype=dtypes.float32)).numpy())
-
- def testUpdatesAreOrdered(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def my_function(x):
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- v.assign(x + 1)
- v.assign(v * x)
- return v.read_value()
-
- self.assertAllEqual(my_function(constant_op.constant(2.0)), 6.0)
-
- def testEmptyInitializer(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(1), dtype=dtypes.float32)])
- def my_function(x):
- v = variable_scope.get_variable("v", shape=[1])
- return x + 0 * v
-
- self.assertEqual([2.],
- my_function(
- constant_op.constant([2.],
- dtype=dtypes.float32)).numpy())
-
- def testMismatchingNumArgs(self):
- # pylint: disable=anomalous-backslash-in-string
- with self.assertRaisesRegexp(TypeError,
- "The number of arguments accepted by the "
- "decorated function `my_function` \(2\) must "
- "match the number of ShapeAndDtype objects "
- "passed to the graph_callable\(\) decorator "
- "\(1\)."):
- @graph_callable.graph_callable([
- graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])
- def my_function(x, y): # pylint: disable=unused-variable
- return x + y
- # pylint: enable=anomalous-backslash-in-string
-
- def testPureFunction(self):
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])
- def f(x):
- return math_ops.add(x, constant_op.constant(3))
-
- self.assertAllEqual(5, f(constant_op.constant(2)))
-
- def testNestedFunction(self):
- # TensorFlow function (which is what would be used in TensorFlow graph
- # construction).
- @function.Defun(dtypes.int32, dtypes.int32)
- def add(a, b):
- return math_ops.add(a, b)
-
- # A graph_callable that will invoke the TensorFlow function.
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])
- def add_one(x):
- return add(x, 1)
-
- self.assertAllEqual(3, add_one(constant_op.constant(2)))
-
- # TODO(ashankar): Make this work.
- # The problem is that the two graph_callables (for add_one and add_two)
- # are both trying to register the FunctionDef corresponding to "add".
- def DISABLED_testRepeatedUseOfSubFunction(self):
-
- @function.Defun(dtypes.int32, dtypes.int32)
- def add(a, b):
- return math_ops.add(a, b)
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])
- def add_one(x):
- return add(x, 1)
-
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])
- def add_two(x):
- return add(x, 2)
-
- two = constant_op.constant(2)
- self.assertAllEqual(3, add_one(two))
- self.assertAllEqual(4, add_two(two))
-
- def testNestedSequenceInputs(self):
- sd = graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)
- @graph_callable.graph_callable([[sd, tuple([sd, sd]), sd]])
- def my_op(inputs):
- a, b, c = inputs
- e, f = b
- v = variable_scope.get_variable(
- "my_v", initializer=init_ops.zeros_initializer(), shape=())
- return [a + a + v, tuple([e + e, f + f]), c + c], a + e + f + c + v
-
- inputs = [constant_op.constant(1.),
- [constant_op.constant(2.), constant_op.constant(3.)],
- constant_op.constant(4.)]
- ret = my_op(inputs)
- self.assertEqual(len(ret), 2.)
- self.assertAllEqual(ret[1], 10.)
-
- my_op.variables[0].assign(1.)
- ret = my_op(inputs)
- self.assertAllEqual(ret[1], 11.)
-
- def testVariableShapeIsTensorShape(self):
- @graph_callable.graph_callable([])
- def my_function():
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- self.assertIsInstance(v.get_shape(), tensor_shape.TensorShape)
-
- my_function()
-
- def testIncorrectlyShapedInputs(self):
- @graph_callable.graph_callable(
- [graph_callable.ShapeAndDtype(shape=(3), dtype=dtypes.float32)])
- def my_function(x):
- v = variable_scope.get_variable(
- "v", initializer=init_ops.zeros_initializer(), shape=())
- return v + x
-
- with self.assertRaises(ValueError):
- my_function([1, 2])
-
- self.assertTrue(([1, 2, 3] == my_function(
- constant_op.constant([1, 2, 3], dtype=dtypes.float32)).numpy()).all())
-
- def testGradients(self):
- @graph_callable.graph_callable([])
- def my_function():
- v = variable_scope.get_variable(
- "v", initializer=init_ops.constant_initializer(3.), shape=())
- return v * v
-
- grad_fn = backprop.implicit_grad(my_function)
- grads_and_vars = list(zip(*grad_fn()))
- self.assertAllEqual(6., grads_and_vars[0][0])
-
-
-if __name__ == "__main__":
- test.main()
diff --git a/tensorflow/python/eager/pywrap_tensor.cc b/tensorflow/python/eager/pywrap_tensor.cc
index 15d2ccf9d2..c12bf89f8f 100644
--- a/tensorflow/python/eager/pywrap_tensor.cc
+++ b/tensorflow/python/eager/pywrap_tensor.cc
@@ -800,9 +800,6 @@ PyObject* TFE_Py_InitEagerTensor(PyObject* base_class) {
EagerTensorType = &_EagerTensorType;
Py_INCREF(EagerTensorType);
#endif
- // We disable instance based attribute lookup. Its not clear if these
- // dictionaries are correctly initialized in the first place.
- EagerTensorType->tp_dictoffset = 0;
return reinterpret_cast<PyObject*>(EagerTensorType);
}
diff --git a/tensorflow/python/estimator/canned/boosted_trees.py b/tensorflow/python/estimator/canned/boosted_trees.py
index 8b423f76de..16928ca4b7 100644
--- a/tensorflow/python/estimator/canned/boosted_trees.py
+++ b/tensorflow/python/estimator/canned/boosted_trees.py
@@ -703,9 +703,30 @@ def _bt_model_fn(
global_step = training_util.get_or_create_global_step()
bucket_size_list, feature_ids_list = _group_features_by_num_buckets(
sorted_feature_columns)
+ # Create Ensemble resources.
+ tree_ensemble = boosted_trees_ops.TreeEnsemble(name=name)
+
+ # Create logits.
+ if mode != model_fn.ModeKeys.TRAIN:
+ input_feature_list = _get_transformed_features(features,
+ sorted_feature_columns)
+ logits = boosted_trees_ops.predict(
+ # For non-TRAIN mode, ensemble doesn't change after initialization,
+ # so no local copy is needed; using tree_ensemble directly.
+ tree_ensemble_handle=tree_ensemble.resource_handle,
+ bucketized_features=input_feature_list,
+ logits_dimension=head.logits_dimension)
+ return head.create_estimator_spec(
+ features=features,
+ mode=mode,
+ labels=labels,
+ train_op_fn=control_flow_ops.no_op,
+ logits=logits)
+
+ # ============== Training graph ==============
# Extract input features and set up cache for training.
training_state_cache = None
- if mode == model_fn.ModeKeys.TRAIN and train_in_memory:
+ if train_in_memory:
# cache transformed features as well for in-memory training.
batch_size = array_ops.shape(labels)[0]
input_feature_list, input_cache_op = (
@@ -717,63 +738,51 @@ def _bt_model_fn(
else:
input_feature_list = _get_transformed_features(features,
sorted_feature_columns)
- if mode == model_fn.ModeKeys.TRAIN and example_id_column_name:
+ if example_id_column_name:
example_ids = features[example_id_column_name]
training_state_cache = _CacheTrainingStatesUsingHashTable(
example_ids, head.logits_dimension)
- # Create Ensemble resources.
- tree_ensemble = boosted_trees_ops.TreeEnsemble(name=name)
# Variable that determines whether bias centering is needed.
center_bias_var = variable_scope.variable(
initial_value=center_bias, name='center_bias_needed', trainable=False)
- # Create logits.
- if mode != model_fn.ModeKeys.TRAIN:
- logits = boosted_trees_ops.predict(
- # For non-TRAIN mode, ensemble doesn't change after initialization,
- # so no local copy is needed; using tree_ensemble directly.
- tree_ensemble_handle=tree_ensemble.resource_handle,
+ if is_single_machine:
+ local_tree_ensemble = tree_ensemble
+ ensemble_reload = control_flow_ops.no_op()
+ else:
+ # Have a local copy of ensemble for the distributed setting.
+ with ops.device(worker_device):
+ local_tree_ensemble = boosted_trees_ops.TreeEnsemble(
+ name=name + '_local', is_local=True)
+ # TODO(soroush): Do partial updates if this becomes a bottleneck.
+ ensemble_reload = local_tree_ensemble.deserialize(
+ *tree_ensemble.serialize())
+
+ if training_state_cache:
+ cached_tree_ids, cached_node_ids, cached_logits = (
+ training_state_cache.lookup())
+ else:
+ # Always start from the beginning when no cache is set up.
+ batch_size = array_ops.shape(labels)[0]
+ cached_tree_ids, cached_node_ids, cached_logits = (
+ array_ops.zeros([batch_size], dtype=dtypes.int32),
+ _DUMMY_NODE_ID * array_ops.ones([batch_size], dtype=dtypes.int32),
+ array_ops.zeros(
+ [batch_size, head.logits_dimension], dtype=dtypes.float32))
+
+ with ops.control_dependencies([ensemble_reload]):
+ (stamp_token, num_trees, num_finalized_trees, num_attempted_layers,
+ last_layer_nodes_range) = local_tree_ensemble.get_states()
+ summary.scalar('ensemble/num_trees', num_trees)
+ summary.scalar('ensemble/num_finalized_trees', num_finalized_trees)
+ summary.scalar('ensemble/num_attempted_layers', num_attempted_layers)
+
+ partial_logits, tree_ids, node_ids = boosted_trees_ops.training_predict(
+ tree_ensemble_handle=local_tree_ensemble.resource_handle,
+ cached_tree_ids=cached_tree_ids,
+ cached_node_ids=cached_node_ids,
bucketized_features=input_feature_list,
logits_dimension=head.logits_dimension)
- else:
- if is_single_machine:
- local_tree_ensemble = tree_ensemble
- ensemble_reload = control_flow_ops.no_op()
- else:
- # Have a local copy of ensemble for the distributed setting.
- with ops.device(worker_device):
- local_tree_ensemble = boosted_trees_ops.TreeEnsemble(
- name=name + '_local', is_local=True)
- # TODO(soroush): Do partial updates if this becomes a bottleneck.
- ensemble_reload = local_tree_ensemble.deserialize(
- *tree_ensemble.serialize())
-
- if training_state_cache:
- cached_tree_ids, cached_node_ids, cached_logits = (
- training_state_cache.lookup())
- else:
- # Always start from the beginning when no cache is set up.
- batch_size = array_ops.shape(labels)[0]
- cached_tree_ids, cached_node_ids, cached_logits = (
- array_ops.zeros([batch_size], dtype=dtypes.int32),
- _DUMMY_NODE_ID * array_ops.ones([batch_size], dtype=dtypes.int32),
- array_ops.zeros(
- [batch_size, head.logits_dimension], dtype=dtypes.float32))
-
- with ops.control_dependencies([ensemble_reload]):
- (stamp_token, num_trees, num_finalized_trees, num_attempted_layers,
- last_layer_nodes_range) = local_tree_ensemble.get_states()
- summary.scalar('ensemble/num_trees', num_trees)
- summary.scalar('ensemble/num_finalized_trees', num_finalized_trees)
- summary.scalar('ensemble/num_attempted_layers', num_attempted_layers)
-
- partial_logits, tree_ids, node_ids = boosted_trees_ops.training_predict(
- tree_ensemble_handle=local_tree_ensemble.resource_handle,
- cached_tree_ids=cached_tree_ids,
- cached_node_ids=cached_node_ids,
- bucketized_features=input_feature_list,
- logits_dimension=head.logits_dimension)
-
logits = cached_logits + partial_logits
# Create training graph.
@@ -846,12 +855,11 @@ def _bt_model_fn(
labels=labels,
train_op_fn=_train_op_fn,
logits=logits)
- if mode == model_fn.ModeKeys.TRAIN:
- # Add an early stop hook.
- estimator_spec = estimator_spec._replace(
- training_hooks=estimator_spec.training_hooks +
- (_StopAtAttemptsHook(num_finalized_trees, num_attempted_layers,
- tree_hparams.n_trees, tree_hparams.max_depth),))
+ # Add an early stop hook.
+ estimator_spec = estimator_spec._replace(
+ training_hooks=estimator_spec.training_hooks +
+ (_StopAtAttemptsHook(num_finalized_trees, num_attempted_layers,
+ tree_hparams.n_trees, tree_hparams.max_depth),))
return estimator_spec
diff --git a/tensorflow/python/estimator/canned/dnn_linear_combined.py b/tensorflow/python/estimator/canned/dnn_linear_combined.py
index efa7812452..4945c3ba11 100644
--- a/tensorflow/python/estimator/canned/dnn_linear_combined.py
+++ b/tensorflow/python/estimator/canned/dnn_linear_combined.py
@@ -388,7 +388,7 @@ class DNNLinearCombinedClassifier(estimator.Estimator):
if a categorical column is multivalent. One of "mean", "sqrtn", and
"sum" -- these are effectively different ways to do example-level
normalization, which can be useful for bag-of-words features. For more
- details, see @{tf.feature_column.linear_model$linear_model}.
+ details, see `tf.feature_column.linear_model`.
Raises:
ValueError: If both linear_feature_columns and dnn_features_columns are
@@ -586,7 +586,7 @@ class DNNLinearCombinedRegressor(estimator.Estimator):
if a categorical column is multivalent. One of "mean", "sqrtn", and
"sum" -- these are effectively different ways to do example-level
normalization, which can be useful for bag-of-words features. For more
- details, see @{tf.feature_column.linear_model$linear_model}.
+ details, see `tf.feature_column.linear_model`.
Raises:
ValueError: If both linear_feature_columns and dnn_features_columns are
diff --git a/tensorflow/python/estimator/canned/linear.py b/tensorflow/python/estimator/canned/linear.py
index 58a7160348..115dd18518 100644
--- a/tensorflow/python/estimator/canned/linear.py
+++ b/tensorflow/python/estimator/canned/linear.py
@@ -306,7 +306,7 @@ class LinearClassifier(estimator.Estimator):
is multivalent. One of "mean", "sqrtn", and "sum" -- these are
effectively different ways to do example-level normalization, which can
be useful for bag-of-words features. for more details, see
- @{tf.feature_column.linear_model$linear_model}.
+ `tf.feature_column.linear_model`.
Returns:
A `LinearClassifier` estimator.
@@ -472,7 +472,7 @@ class LinearRegressor(estimator.Estimator):
is multivalent. One of "mean", "sqrtn", and "sum" -- these are
effectively different ways to do example-level normalization, which can
be useful for bag-of-words features. for more details, see
- @{tf.feature_column.linear_model$linear_model}.
+ `tf.feature_column.linear_model`.
"""
head = head_lib._regression_head( # pylint: disable=protected-access
label_dimension=label_dimension, weight_column=weight_column,
diff --git a/tensorflow/python/estimator/canned/prediction_keys.py b/tensorflow/python/estimator/canned/prediction_keys.py
index 16890ec09a..daa275b46b 100644
--- a/tensorflow/python/estimator/canned/prediction_keys.py
+++ b/tensorflow/python/estimator/canned/prediction_keys.py
@@ -32,3 +32,4 @@ class PredictionKeys(object):
LOGITS = 'logits'
PREDICTIONS = 'predictions'
PROBABILITIES = 'probabilities'
+ TOP_K = 'top_k'
diff --git a/tensorflow/python/estimator/estimator.py b/tensorflow/python/estimator/estimator.py
index 3b6b180b25..f7ee42c7f6 100644
--- a/tensorflow/python/estimator/estimator.py
+++ b/tensorflow/python/estimator/estimator.py
@@ -50,9 +50,10 @@ from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.saved_model import builder as saved_model_builder
-from tensorflow.python.saved_model import constants
+from tensorflow.python.saved_model import utils_impl as saved_model_utils
from tensorflow.python.summary import summary
from tensorflow.python.summary.writer import writer_cache
+from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import device_setter
from tensorflow.python.training import distribute as distribute_lib
@@ -85,14 +86,15 @@ class Estimator(object):
subdirectory thereof. If `model_dir` is not set, a temporary directory is
used.
- The `config` argument can be passed `RunConfig` object containing information
- about the execution environment. It is passed on to the `model_fn`, if the
- `model_fn` has a parameter named "config" (and input functions in the same
- manner). If the `config` parameter is not passed, it is instantiated by the
- `Estimator`. Not passing config means that defaults useful for local execution
- are used. `Estimator` makes config available to the model (for instance, to
- allow specialization based on the number of workers available), and also uses
- some of its fields to control internals, especially regarding checkpointing.
+ The `config` argument can be passed `tf.estimator.RunConfig` object containing
+ information about the execution environment. It is passed on to the
+ `model_fn`, if the `model_fn` has a parameter named "config" (and input
+ functions in the same manner). If the `config` parameter is not passed, it is
+ instantiated by the `Estimator`. Not passing config means that defaults useful
+ for local execution are used. `Estimator` makes config available to the model
+ (for instance, to allow specialization based on the number of workers
+ available), and also uses some of its fields to control internals, especially
+ regarding checkpointing.
The `params` argument contains hyperparameters. It is passed to the
`model_fn`, if the `model_fn` has a parameter named "params", and to the input
@@ -118,7 +120,8 @@ class Estimator(object):
warm_start_from=None):
"""Constructs an `Estimator` instance.
- See @{$estimators} for more information. To warm-start an `Estimator`:
+ See [estimators](https://tensorflow.org/guide/estimators) for more information.
+ To warm-start an `Estimator`:
```python
estimator = tf.estimator.DNNClassifier(
@@ -128,7 +131,7 @@ class Estimator(object):
```
For more details on warm-start configuration, see
- @{tf.estimator.WarmStartSettings$WarmStartSettings}.
+ `tf.estimator.WarmStartSettings`.
Args:
model_fn: Model function. Follows the signature:
@@ -137,41 +140,43 @@ class Estimator(object):
* `features`: This is the first item returned from the `input_fn`
passed to `train`, `evaluate`, and `predict`. This should be a
- single `Tensor` or `dict` of same.
+ single `tf.Tensor` or `dict` of same.
* `labels`: This is the second item returned from the `input_fn`
passed to `train`, `evaluate`, and `predict`. This should be a
- single `Tensor` or `dict` of same (for multi-head models). If
- mode is `ModeKeys.PREDICT`, `labels=None` will be passed. If
- the `model_fn`'s signature does not accept `mode`, the
- `model_fn` must still be able to handle `labels=None`.
+ single `tf.Tensor` or `dict` of same (for multi-head models).
+ If mode is @{tf.estimator.ModeKeys.PREDICT}, `labels=None` will
+ be passed. If the `model_fn`'s signature does not accept
+ `mode`, the `model_fn` must still be able to handle
+ `labels=None`.
* `mode`: Optional. Specifies if this training, evaluation or
- prediction. See `ModeKeys`.
+ prediction. See `tf.estimator.ModeKeys`.
* `params`: Optional `dict` of hyperparameters. Will receive what
is passed to Estimator in `params` parameter. This allows
to configure Estimators from hyper parameter tuning.
- * `config`: Optional configuration object. Will receive what is passed
- to Estimator in `config` parameter, or the default `config`.
- Allows updating things in your `model_fn` based on
+ * `config`: Optional `estimator.RunConfig` object. Will receive what
+ is passed to Estimator as its `config` parameter, or a default
+ value. Allows setting up things in your `model_fn` based on
configuration such as `num_ps_replicas`, or `model_dir`.
* Returns:
- `EstimatorSpec`
+ `tf.estimator.EstimatorSpec`
model_dir: Directory to save model parameters, graph and etc. This can
- also be used to load checkpoints from the directory into a estimator to
+ also be used to load checkpoints from the directory into an estimator to
continue training a previously saved model. If `PathLike` object, the
path will be resolved. If `None`, the model_dir in `config` will be used
if set. If both are set, they must be same. If both are `None`, a
temporary directory will be used.
- config: Configuration object.
+ config: `estimator.RunConfig` configuration object.
params: `dict` of hyper parameters that will be passed into `model_fn`.
Keys are names of parameters, values are basic python types.
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
- filepath is provided instead of a `WarmStartSettings`,
- then all variables are warm-started, and it is assumed
- that vocabularies and Tensor names are unchanged.
+ filepath is provided instead of a
+ `tf.estimator.WarmStartSettings`, then all variables are
+ warm-started, and it is assumed that vocabularies
+ and `tf.Tensor` names are unchanged.
Raises:
ValueError: parameters of `model_fn` don't match `params`.
@@ -180,8 +185,8 @@ class Estimator(object):
"""
Estimator._assert_members_are_not_overridden(self)
- config = maybe_overwrite_model_dir_and_session_config(config, model_dir)
- self._config = config
+ self._config = maybe_overwrite_model_dir_and_session_config(config,
+ model_dir)
# The distribute field contains an instance of DistributionStrategy.
self._train_distribution = self._config.train_distribute
@@ -219,10 +224,10 @@ class Estimator(object):
@property
def model_fn(self):
- """Returns the model_fn which is bound to self.params.
+ """Returns the `model_fn` which is bound to `self.params`.
Returns:
- The model_fn with following signature:
+ The `model_fn` with following signature:
`def model_fn(features, labels, mode, config)`
"""
@@ -242,7 +247,7 @@ class Estimator(object):
Numpy array - value of the tensor.
Raises:
- ValueError: If the Estimator has not produced a checkpoint yet.
+ ValueError: If the `Estimator` has not produced a checkpoint yet.
"""
_check_checkpoint_available(self.model_dir)
with context.graph_mode():
@@ -255,14 +260,14 @@ class Estimator(object):
List of names.
Raises:
- ValueError: If the Estimator has not produced a checkpoint yet.
+ ValueError: If the `Estimator` has not produced a checkpoint yet.
"""
_check_checkpoint_available(self.model_dir)
with context.graph_mode():
return [name for name, _ in training.list_variables(self.model_dir)]
def latest_checkpoint(self):
- """Finds the filename of latest saved checkpoint file in `model_dir`.
+ """Finds the filename of the latest saved checkpoint file in `model_dir`.
Returns:
The full path to the latest checkpoint or `None` if no checkpoint was
@@ -277,40 +282,38 @@ class Estimator(object):
steps=None,
max_steps=None,
saving_listeners=None):
- """Trains a model given training data input_fn.
+ """Trains a model given training data `input_fn`.
Args:
input_fn: A function that provides input data for training as minibatches.
- See @{$premade_estimators#create_input_functions} for more
- information. The function should construct and return one of
- the following:
-
- * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
- tuple (features, labels) with same constraints as below.
- * A tuple (features, labels): Where `features` is a `Tensor` or a
- dictionary of string feature name to `Tensor` and `labels` is a
- `Tensor` or a dictionary of string label name to `Tensor`. Both
- `features` and `labels` are consumed by `model_fn`. They should
- satisfy the expectation of `model_fn` from inputs.
-
- hooks: List of `SessionRunHook` subclass instances. Used for callbacks
- inside the training loop.
- steps: Number of steps for which to train model. If `None`, train forever
- or train until input_fn generates the `OutOfRange` error or
- `StopIteration` exception. 'steps' works incrementally. If you call two
- times train(steps=10) then training occurs in total 20 steps. If
- `OutOfRange` or `StopIteration` occurs in the middle, training stops
+ See [Premade
+ Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions)
+ for more information. The function should construct and return one of
+ the following: * A
+ `tf.data.Dataset` object: Outputs of `Dataset` object must be a tuple
+ `(features, labels)` with same constraints as below. * A tuple
+ `(features, labels)`: Where `features` is a `tf.Tensor` or a dictionary
+ of string feature name to `Tensor` and `labels` is a `Tensor` or a
+ dictionary of string label name to `Tensor`. Both `features` and
+ `labels` are consumed by `model_fn`. They should satisfy the expectation
+ of `model_fn` from inputs.
+ hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
+ callbacks inside the training loop.
+ steps: Number of steps for which to train the model. If `None`, train
+ forever or train until `input_fn` generates the `tf.errors.OutOfRange`
+ error or `StopIteration` exception. `steps` works incrementally. If you
+ call two times `train(steps=10)` then training occurs in total 20 steps.
+ If `OutOfRange` or `StopIteration` occurs in the middle, training stops
before 20 steps. If you don't want to have incremental behavior please
set `max_steps` instead. If set, `max_steps` must be `None`.
max_steps: Number of total steps for which to train model. If `None`,
- train forever or train until input_fn generates the `OutOfRange` error
- or `StopIteration` exception. If set, `steps` must be `None`. If
- `OutOfRange` or `StopIteration` occurs in the middle, training stops
- before `max_steps` steps.
- Two calls to `train(steps=100)` means 200 training
- iterations. On the other hand, two calls to `train(max_steps=100)` means
- that the second call will not do any iteration since first call did
- all 100 steps.
+ train forever or train until `input_fn` generates the
+ `tf.errors.OutOfRange` error or `StopIteration` exception. If set,
+ `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the
+ middle, training stops before `max_steps` steps. Two calls to
+ `train(steps=100)` means 200 training iterations. On the other hand, two
+ calls to `train(max_steps=100)` means that the second call will not do
+ any iteration since first call did all 100 steps.
saving_listeners: list of `CheckpointSaverListener` objects. Used for
callbacks that run immediately before or after checkpoint savings.
@@ -319,8 +322,16 @@ class Estimator(object):
Raises:
ValueError: If both `steps` and `max_steps` are not `None`.
- ValueError: If either `steps` or `max_steps` is <= 0.
+ ValueError: If either `steps` or `max_steps <= 0`.
"""
+ if self.config.task_type in (run_config.TaskType.EVALUATOR,
+ run_config.TaskType.PS):
+ raise ValueError(
+ 'Train has been called wrong configuration. Please use '
+ 'tf.estimator.train_and_evaluate which calls propper API according '
+ 'to given configuration. Current configuration: {}.'.format(
+ self.config))
+
with context.graph_mode():
if (steps is not None) and (max_steps is not None):
raise ValueError('Can not provide both steps and max_steps.')
@@ -345,13 +356,29 @@ class Estimator(object):
return self
def _convert_train_steps_to_hooks(self, steps, max_steps):
+ """Create hooks to run correct number of steps in training.
+
+ Args:
+ steps: number of steps to run during training.
+ max_steps: maximum number of steps to be run during training. It'll be
+ the maximum number of steps the model will train to after restoring
+ from checkpoint even across multiple estimator.train calls.
+
+ Returns:
+ List of hooks to be passed to the estimator.
+ """
if steps is not None or max_steps is not None:
+ if self._train_distribution:
+ steps_per_run = getattr(self._train_distribution, 'steps_per_run', 1)
+ if steps_per_run > 1:
+ return [basic_session_run_hooks._MultiStepStopAtStepHook( # pylint: disable=protected-access
+ steps, max_steps, steps_per_run)]
return [training.StopAtStepHook(steps, max_steps)]
else:
return []
def eval_dir(self, name=None):
- """Shows directory name where evaluation metrics are dumped.
+ """Shows the directory name where evaluation metrics are dumped.
Args:
name: Name of the evaluation if user needs to run multiple evaluations on
@@ -367,36 +394,35 @@ class Estimator(object):
def evaluate(self, input_fn, steps=None, hooks=None, checkpoint_path=None,
name=None):
- """Evaluates the model given evaluation data input_fn.
+ """Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data.
Evaluates until:
- `steps` batches are processed, or
- - `input_fn` raises an end-of-input exception (`OutOfRangeError` or
+ - `input_fn` raises an end-of-input exception (`tf.errors.OutOfRangeError`
+ or
`StopIteration`).
Args:
- input_fn: A function that constructs the input data for evaluation.
- See @{$premade_estimators#create_input_functions} for more
- information. The function should construct and return one of
- the following:
-
- * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
- tuple (features, labels) with same constraints as below.
- * A tuple (features, labels): Where `features` is a `Tensor` or a
- dictionary of string feature name to `Tensor` and `labels` is a
- `Tensor` or a dictionary of string label name to `Tensor`. Both
- `features` and `labels` are consumed by `model_fn`. They should
- satisfy the expectation of `model_fn` from inputs.
-
+ input_fn: A function that constructs the input data for evaluation. See
+ [Premade Estimators](https://tensorflow.org/guide/premade#create_input_functions}
+ for more information. The
+ function should construct and return one of the following: * A
+ `tf.data.Dataset` object: Outputs of `Dataset` object must be a tuple
+ `(features, labels)` with same constraints as below. * A tuple
+ `(features, labels)`: Where `features` is a `tf.Tensor` or a dictionary
+ of string feature name to `Tensor` and `labels` is a `Tensor` or a
+ dictionary of string label name to `Tensor`. Both `features` and
+ `labels` are consumed by `model_fn`. They should satisfy the expectation
+ of `model_fn` from inputs.
steps: Number of steps for which to evaluate model. If `None`, evaluates
until `input_fn` raises an end-of-input exception.
- hooks: List of `SessionRunHook` subclass instances. Used for callbacks
- inside the evaluation call.
+ hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
+ callbacks inside the evaluation call.
checkpoint_path: Path of a specific checkpoint to evaluate. If `None`, the
latest checkpoint in `model_dir` is used. If there are no checkpoints
in `model_dir`, evaluation is run with newly initialized `Variables`
- instead of restored from checkpoint.
+ instead of ones restored from checkpoint.
name: Name of the evaluation if user needs to run multiple evaluations on
different data sets, such as on training data vs test data. Metrics for
different evaluations are saved in separate folders, and appear
@@ -436,9 +462,7 @@ class Estimator(object):
output_dir=self.eval_dir(name))
with ops.Graph().as_default():
- # TODO(priyag): Support distributed eval on TPUs.
- if (self._eval_distribution
- and self._eval_distribution.__class__.__name__ != 'TPUStrategy'):
+ if self._eval_distribution:
with self._eval_distribution.scope():
return _evaluate()
else:
@@ -462,33 +486,34 @@ class Estimator(object):
Args:
input_fn: A function that constructs the features. Prediction continues
- until `input_fn` raises an end-of-input exception (`OutOfRangeError` or
- `StopIteration`).
- See @{$premade_estimators#create_input_functions} for more
- information. The function should construct and return one of
+ until `input_fn` raises an end-of-input exception
+ (`tf.errors.OutOfRangeError` or `StopIteration`).
+ See [Premade
+ Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions)
+ for more information. The function should construct and return one of
the following:
- * A 'tf.data.Dataset' object: Outputs of `Dataset` object must have
+ * A `tf.data.Dataset` object: Outputs of `Dataset` object must have
same constraints as below.
- * features: A `Tensor` or a dictionary of string feature name to
+ * features: A `tf.Tensor` or a dictionary of string feature name to
`Tensor`. features are consumed by `model_fn`. They should satisfy
the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
predict_keys: list of `str`, name of the keys to predict. It is used if
- the `EstimatorSpec.predictions` is a `dict`. If `predict_keys` is used
- then rest of the predictions will be filtered from the dictionary. If
- `None`, returns all.
- hooks: List of `SessionRunHook` subclass instances. Used for callbacks
- inside the prediction call.
+ the `tf.estimator.EstimatorSpec.predictions` is a `dict`. If
+ `predict_keys` is used then rest of the predictions will be filtered
+ from the dictionary. If `None`, returns all.
+ hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
+ callbacks inside the prediction call.
checkpoint_path: Path of a specific checkpoint to predict. If `None`, the
latest checkpoint in `model_dir` is used. If there are no checkpoints
in `model_dir`, prediction is run with newly initialized `Variables`
- instead of restored from checkpoint.
- yield_single_examples: If False, yield the whole batch as returned by the
- `model_fn` instead of decomposing the batch into individual elements.
- This is useful if `model_fn` returns some tensors whose first dimension
- is not equal to the batch size.
+ instead of ones restored from checkpoint.
+ yield_single_examples: If `False`, yields the whole batch as returned by
+ the `model_fn` instead of decomposing the batch into individual
+ elements. This is useful if `model_fn` returns some tensors whose first
+ dimension is not equal to the batch size.
Yields:
Evaluated values of `predictions` tensors.
@@ -496,10 +521,10 @@ class Estimator(object):
Raises:
ValueError: Could not find a trained model in `model_dir`.
ValueError: If batch length of predictions is not the same and
- `yield_single_examples` is True.
+ `yield_single_examples` is `True`.
ValueError: If there is a conflict between `predict_keys` and
`predictions`. For example if `predict_keys` is not `None` but
- `EstimatorSpec.predictions` is not a `dict`.
+ `tf.estimator.EstimatorSpec.predictions` is not a `dict`.
"""
with context.graph_mode():
hooks = _check_hooks_type(hooks)
@@ -554,14 +579,10 @@ class Estimator(object):
return
allowed_overrides = set([
- '_call_input_fn', '_call_model_fn',
- '_convert_train_steps_to_hooks', '_convert_eval_steps_to_hooks',
- '_create_global_step', '_create_and_assert_global_step',
+ '_create_and_assert_global_step',
'_tf_api_names', '_tf_api_names_v1', '_estimator_api_names',
'_estimator_api_names_v1', '_estimator_api_constants',
'_estimator_api_constants_v1',
- '_validate_features_in_predict_input',
- '_add_meta_graph_for_mode'
])
estimator_members = set([m for m in Estimator.__dict__.keys()
if not m.startswith('__')])
@@ -582,30 +603,33 @@ class Estimator(object):
checkpoint_path=None,
strip_default_attrs=False):
# pylint: disable=line-too-long
- """Exports inference graph as a SavedModel into given dir.
+ """Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide, see
- @{$saved_model#using_savedmodel_with_estimators$Using SavedModel with Estimators}.
+ [Using SavedModel with Estimators](https://tensorflow.org/guide/saved_model#using_savedmodel_with_estimators).
This method builds a new graph by first calling the
- serving_input_receiver_fn to obtain feature `Tensor`s, and then calling
- this `Estimator`'s model_fn to generate the model graph based on those
+ `serving_input_receiver_fn` to obtain feature `Tensor`s, and then calling
+ this `Estimator`'s `model_fn` to generate the model graph based on those
features. It restores the given checkpoint (or, lacking that, the most
recent checkpoint) into this graph in a fresh session. Finally it creates
- a timestamped export directory below the given export_dir_base, and writes
- a `SavedModel` into it containing a single `MetaGraphDef` saved from this
+ a timestamped export directory below the given `export_dir_base`, and writes
+ a `SavedModel` into it containing a single `tf.MetaGraphDef` saved from this
session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each
- element of the export_outputs dict returned from the model_fn, named using
+ element of the `export_outputs` dict returned from the `model_fn`, named
+ using
the same keys. One of these keys is always
- signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which
+ `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`,
+ indicating which
signature will be served when a serving request does not specify one.
For each signature, the outputs are provided by the corresponding
- `ExportOutput`s, and the inputs are always the input receivers provided by
- the serving_input_receiver_fn.
+ `tf.estimator.export.ExportOutput`s, and the inputs are always the input
+ receivers provided by
+ the `serving_input_receiver_fn`.
- Extra assets may be written into the SavedModel via the assets_extra
+ Extra assets may be written into the `SavedModel` via the `assets_extra`
argument. This should be a dict, where each key gives a destination path
(including the filename) relative to the assets.extra directory. The
corresponding value gives the full path of the source file to be copied.
@@ -614,23 +638,27 @@ class Estimator(object):
Args:
export_dir_base: A string containing a directory in which to create
- timestamped subdirectories containing exported SavedModels.
- serving_input_receiver_fn: A function that takes no argument and
- returns a `ServingInputReceiver` or `TensorServingInputReceiver`.
+ timestamped subdirectories containing exported `SavedModel`s.
+ serving_input_receiver_fn: A function that takes no argument and returns a
+ `tf.estimator.export.ServingInputReceiver` or
+ `tf.estimator.export.TensorServingInputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
- within the exported SavedModel, or `None` if no extra assets are needed.
- as_text: whether to write the SavedModel proto in text format.
+ within the exported `SavedModel`, or `None` if no extra assets are
+ needed.
+ as_text: whether to write the `SavedModel` proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
- removed from the NodeDefs. For a detailed guide, see
- [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
+ removed from the `NodeDef`s. For a detailed guide, see [Stripping
+ Default-Valued
+ Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
Returns:
The string path to the exported directory.
Raises:
- ValueError: if no serving_input_receiver_fn is provided, no export_outputs
+ ValueError: if no `serving_input_receiver_fn` is provided, no
+ `export_outputs`
are provided, or no checkpoint can be found.
"""
# pylint: enable=line-too-long
@@ -651,35 +679,37 @@ class Estimator(object):
strip_default_attrs=False,
mode=model_fn_lib.ModeKeys.PREDICT):
# pylint: disable=line-too-long
- """Exports a single train/eval/predict graph as a SavedModel.
+ """Exports a single train/eval/predict graph as a `SavedModel`.
- This method is a wrapper for _export_all_saved_models, and wraps a raw
- input_receiver_fn in a dictionary to pass in to that function.
- See _export_all_saved_models for full docs.
+ This method is a wrapper for `_export_all_saved_models`, and wraps a raw
+ `input_receiver_fn` in a dictionary to pass in to that function.
+ See `_export_all_saved_models` for full docs.
- See tf.contrib.estimator.export_saved_model_for_mode for the currently
+ See `tf.contrib.estimator.export_saved_model_for_mode` for the currently
exposed version of this function.
Args:
export_dir_base: A string containing a directory in which to create
- timestamped subdirectories containing exported SavedModels.
- input_receiver_fn: a function that takes no argument and
- returns the appropriate subclass of `InputReceiver`.
+ timestamped subdirectories containing exported `SavedModel`s.
+ input_receiver_fn: a function that takes no argument and returns the
+ appropriate subclass of `InputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
- within the exported SavedModel, or `None` if no extra assets are needed.
- as_text: whether to write the SavedModel proto in text format.
+ within the exported `SavedModel`, or `None` if no extra assets are
+ needed.
+ as_text: whether to write the `SavedModel` proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
- removed from the NodeDefs. For a detailed guide, see
- [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
- mode: tf.estimator.ModeKeys value indicating with mode will be exported.
+ removed from the `NodeDef`s. For a detailed guide, see [Stripping
+ Default-Valued
+ Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
+ mode: `tf.estimator.ModeKeys` value indicating with mode will be exported.
Returns:
The string path to the exported directory.
Raises:
- ValueError: if input_receiver_fn is None, no export_outputs
+ ValueError: if `input_receiver_fn` is `None`, no `export_outputs`
are provided, or no checkpoint can be found.
"""
# pylint: enable=line-too-long
@@ -703,40 +733,46 @@ class Estimator(object):
checkpoint_path=None,
strip_default_attrs=False):
# pylint: disable=line-too-long
- """Exports a SavedModel containing MetaGraphDefs for each requested mode.
+ """Exports a `SavedModel` containing `tf.MetaGraphDefs` for each requested mode.
- See tf.contrib.estimator.export_all_saved_models for the currently
+ See `tf.contrib.estimator.export_all_saved_models` for the currently
exposed version of this function.
- For each mode passed in via the input_receiver_fn_map,
- this method builds a new graph by calling the input_receiver_fn to obtain
+ For each mode passed in via the `input_receiver_fn_map`,
+ this method builds a new graph by calling the `input_receiver_fn` to obtain
feature and label `Tensor`s. Next, this method calls the `Estimator`'s
- model_fn in the passed mode to generate the model graph based on
+ `model_fn` in the passed mode to generate the model graph based on
those features and labels, and restores the given checkpoint
(or, lacking that, the most recent checkpoint) into the graph.
- Only one of the modes is used for saving variables to the SavedModel
- (order of preference: TRAIN, EVAL, then PREDICT), such that up to three
- MetaGraphDefs are saved with a single set of variables in a single
- SavedModel directory.
-
- For the variables and MetaGraphDefs, a timestamped export directory below
- export_dir_base, and writes a `SavedModel` into it containing
- the `MetaGraphDef` for the given mode and its associated signatures.
+ Only one of the modes is used for saving variables to the `SavedModel`
+ (order of preference: @{tf.estimator.ModeKeys#TRAIN$TRAIN},
+ @{tf.estimator.ModeKeys#EVAL$EVAL}, then
+ @{tf.estimator.ModeKeys#PREDICT$PREDICT}), such that up to three
+ `tf.MetaGraphDefs` are saved with a single set of variables in a single
+ `SavedModel` directory.
+
+ For the variables and `tf.MetaGraphDefs`, a timestamped export directory
+ below
+ `export_dir_base`, and writes a `SavedModel` into it containing
+ the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef`
- for each element of the export_outputs dict returned from the model_fn,
+ for each element of the `export_outputs` dict returned from the `model_fn`,
named using the same keys. One of these keys is always
- signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which
+ `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`,
+ indicating which
signature will be served when a serving request does not specify one.
For each signature, the outputs are provided by the corresponding
- `ExportOutput`s, and the inputs are always the input receivers provided by
- the serving_input_receiver_fn.
+ `tf.estimator.export.ExportOutput`s, and the inputs are always the input
+ receivers provided by
+ the `serving_input_receiver_fn`.
- For training and evaluation, the train_op is stored in an extra collection,
- and loss, metrics, and predictions are included in a SignatureDef for the
+ For training and evaluation, the `train_op` is stored in an extra
+ collection,
+ and loss, metrics, and predictions are included in a `SignatureDef` for the
mode in question.
- Extra assets may be written into the SavedModel via the assets_extra
+ Extra assets may be written into the `SavedModel` via the `assets_extra`
argument. This should be a dict, where each key gives a destination path
(including the filename) relative to the assets.extra directory. The
corresponding value gives the full path of the source file to be copied.
@@ -745,25 +781,28 @@ class Estimator(object):
Args:
export_dir_base: A string containing a directory in which to create
- timestamped subdirectories containing exported SavedModels.
- input_receiver_fn_map: dict of tf.estimator.ModeKeys to input_receiver_fn
- mappings, where the input_receiver_fn is a function that takes no
- argument and returns the appropriate subclass of `InputReceiver`.
+ timestamped subdirectories containing exported `SavedModel`s.
+ input_receiver_fn_map: dict of `tf.estimator.ModeKeys` to
+ `input_receiver_fn` mappings, where the `input_receiver_fn` is a
+ function that takes no arguments and returns the appropriate subclass of
+ `InputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
- within the exported SavedModel, or `None` if no extra assets are needed.
- as_text: whether to write the SavedModel proto in text format.
+ within the exported `SavedModel`, or `None` if no extra assets are
+ needed.
+ as_text: whether to write the `SavedModel` proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
- removed from the NodeDefs. For a detailed guide, see
- [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
+ removed from the `NodeDef`s. For a detailed guide, see [Stripping
+ Default-Valued
+ Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
Returns:
- A dict of tf.estimator.ModeKeys value to string path for each exported
+ A dict of `tf.estimator.ModeKeys` value to string path for each exported
directory.
Raises:
- ValueError: if any input_receiver_fn is None, no export_outputs
+ ValueError: if any `input_receiver_fn` is `None`, no `export_outputs`
are provided, or no checkpoint can be found.
"""
# pylint: enable=line-too-long
@@ -836,25 +875,29 @@ class Estimator(object):
export_tags=None,
check_variables=True):
# pylint: disable=line-too-long
- """Loads variables and adds them along with a MetaGraphDef for saving.
+ """Loads variables and adds them along with a `tf.MetaGraphDef` for saving.
Args:
- builder: instance of SavedModelBuilder that will be used for saving.
- input_receiver_fn_map: dict of tf.estimator.ModeKeys to input_receiver_fn
- mappings, where the input_receiver_fn is a function that takes no
- argument and returns the appropriate subclass of `InputReceiver`.
+ builder: instance of `tf.saved_modle.builder.SavedModelBuilder` that will
+ be used for saving.
+ input_receiver_fn_map: dict of `tf.estimator.ModeKeys` to
+ `input_receiver_fn` mappings, where the `input_receiver_fn` is a
+ function that takes no argument and returns the appropriate subclass of
+ `InputReceiver`.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
- removed from the NodeDefs. For a detailed guide, see
- [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
- save_variables: bool, whether variables should be saved. If False, just
- the MetaGraphDef will be saved. Note that save_variables should only be
- True for the first call to this function, and the SavedModelBuilder will
- raise an error if that is not the case.
- mode: tf.estimator.ModeKeys value indicating which mode will be exported.
- export_tags: The set of tags with which to save `MetaGraphDef`. If None,
- a default set will be selected to matched the passed mode.
+ removed from the `NodeDef`s. For a detailed guide, see [Stripping
+ Default-Valued
+ Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
+ save_variables: bool, whether variables should be saved. If `False`, just
+ the `tf.MetaGraphDef` will be saved. Note that `save_variables` should
+ only be `True` for the first call to this function, and the
+ `SavedModelBuilder` will raise an error if that is not the case.
+ mode: `tf.estimator.ModeKeys` value indicating which mode will be
+ exported.
+ export_tags: The set of tags with which to save `tf.MetaGraphDef`. If
+ `None`, a default set will be selected to matched the passed mode.
check_variables: bool, whether to check the checkpoint has all variables.
Raises:
@@ -936,21 +979,23 @@ class Estimator(object):
builder.add_meta_graph(**meta_graph_kwargs)
def _get_export_outputs_for_spec(self, estimator_spec):
- """Given an EstimatorSpec, determine what our export outputs should be.
+ """Given an `EstimatorSpec`, determine what our export outputs should be.
- EstimatorSpecs contain export_outputs that are used for serving, but for
+ `EstimatorSpecs` contains `export_outputs` that are used for serving, but
+ for
training and eval graphs, we must wrap the tensors of interest in
- appropriate ExportOutput objects.
+ appropriate `tf.estimator.export.ExportOutput` objects.
Args:
- estimator_spec: EstimatorSpec object that will be exported.
+ estimator_spec: `tf.estimator.EstimatorSpec` object that will be exported.
Returns:
- a dict mapping export_output_name to ExportOutput object.
+ a dict mapping `export_output_name` to `tf.estimator.export.ExportOutput`
+ object.
Raises:
- ValueError: if an appropriate ExportOutput cannot be found for the
- passed EstimatorSpec.mode
+ ValueError: if an appropriate `ExportOutput` cannot be found for the
+ passed `EstimatorSpec.mode`
"""
mode = estimator_spec.mode
if mode == model_fn_lib.ModeKeys.PREDICT:
@@ -985,16 +1030,21 @@ class Estimator(object):
'QueueRunner. That means predict yields forever. '
'This is probably a mistake.')
- def _get_features_and_labels_from_input_fn(self, input_fn, mode,
- distribution=None):
- """Extracts the `features` and labels from return values of `input_fn`."""
- if distribution is not None and mode == model_fn_lib.ModeKeys.TRAIN:
+ def _get_iterator_from_input_fn(self, input_fn, mode, distribution=None):
+ if distribution is not None:
result = distribution.distribute_dataset(
lambda: self._call_input_fn(input_fn, mode))
else:
result = self._call_input_fn(input_fn, mode)
- return estimator_util.parse_input_fn_result(result)
+ iterator = result.make_initializable_iterator()
+ input_hooks = [estimator_util._DatasetInitializerHook(iterator)] # pylint: disable=protected-access
+ return iterator, input_hooks
+
+ def _get_features_and_labels_from_input_fn(self, input_fn, mode):
+ """Extracts the `features` and labels from return values of `input_fn`."""
+ return estimator_util.parse_input_fn_result(
+ self._call_input_fn(input_fn, mode))
def _extract_batch_length(self, preds_evaluated):
"""Extracts batch length of predictions."""
@@ -1027,13 +1077,13 @@ class Estimator(object):
"""Creates the global step tensor in graph.
The global step tensor must be an integer type with name 'global_step' and
- be added to the collection @{tf.GraphKeys.GLOBAL_STEP}.
+ be added to the collection @{tf.GraphKeys#GLOBAL_STEP$GLOBAL_STEP}.
Args:
graph: The graph in which to create the global step tensor.
Returns:
- The global step `Tensor`.
+ The global step `tf.Tensor`.
"""
return training.create_global_step(graph)
@@ -1044,7 +1094,7 @@ class Estimator(object):
graph: The graph in which to create the global step tensor.
Returns:
- The global step `Tensor`.
+ The global step `tf.Tensor`.
"""
step = self._create_global_step(graph)
assert step == training.get_global_step()
@@ -1056,21 +1106,21 @@ class Estimator(object):
Args:
input_fn: The input function.
- mode: ModeKeys
+ mode: `tf.estimator.ModeKeys`
Returns:
- The return value of the passed input_fn, which should be one of:
+ The return value of the passed `input_fn`, which should be one of:
* A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
- tuple (features, labels) with same constraints as below.
- * A tuple (features, labels): Where `features` is a `Tensor` or a
+ tuple `(features, labels)` with same constraints as below.
+ * A tuple `(features, labels)`: Where `features` is a `Tensor` or a
dictionary of string feature name to `Tensor` and `labels` is a
`Tensor` or a dictionary of string label name to `Tensor`. Both
`features` and `labels` are consumed by `model_fn`. They should
satisfy the expectation of `model_fn` from inputs.
Raises:
- ValueError: if input_fn takes invalid arguments.
+ ValueError: if `input_fn` takes invalid arguments.
"""
input_fn_args = function_utils.fn_args(input_fn)
kwargs = {}
@@ -1089,14 +1139,14 @@ class Estimator(object):
Args:
features: features dict.
labels: labels dict.
- mode: ModeKeys
- config: RunConfig
+ mode: `tf.estimator.ModeKeys`
+ config: `tf.estimator.RunConfig`
Returns:
- An `EstimatorSpec` object.
+ An `tf.estimator.EstimatorSpec` object.
Raises:
- ValueError: if model_fn returns invalid objects.
+ ValueError: if `model_fn` returns invalid objects.
"""
model_fn_args = function_utils.fn_args(self._model_fn)
kwargs = {}
@@ -1129,14 +1179,14 @@ class Estimator(object):
return self._train_model_default(input_fn, hooks, saving_listeners)
def _train_model_default(self, input_fn, hooks, saving_listeners):
- """Initiate training with input_fn, without DistributionStrategies.
+ """Initiate training with `input_fn`, without `DistributionStrategies`.
Args:
input_fn: A function that provides input data for training as minibatches.
- hooks: List of `SessionRunHook` subclass instances. Used for callbacks
- inside the training loop.
- saving_listeners: list of `CheckpointSaverListener` objects. Used for
- callbacks that run immediately before or after checkpoint savings.
+ hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
+ callbacks inside the training loop.
+ saving_listeners: list of `tf.train.CheckpointSaverListener` objects. Used
+ for callbacks that run immediately before or after checkpoint savings.
Returns:
Loss from training
@@ -1163,14 +1213,14 @@ class Estimator(object):
saving_listeners)
def _train_model_distributed(self, input_fn, hooks, saving_listeners):
- """Initiate training with input_fn, using DistributionStrategies.
+ """Initiate training with `input_fn`, using `DistributionStrategies`.
Args:
input_fn: A function that provides input data for training as minibatches.
- hooks: List of `SessionRunHook` subclass instances. Used for callbacks
- inside the training loop.
- saving_listeners: list of `CheckpointSaverListener` objects. Used for
- callbacks that run immediately before or after checkpoint savings.
+ hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
+ callbacks inside the training loop.
+ saving_listeners: list of `tf.train.CheckpointSaverListener` objects. Used
+ for callbacks that run immediately before or after checkpoint savings.
Returns:
Loss from training
@@ -1184,31 +1234,26 @@ class Estimator(object):
worker_hooks = []
with ops.Graph().as_default() as g:
+ # We want to create the iterations variable outside the distribution scope
+ # as that is just stored on the host and mainly used to drive the loop
+ # and doesn't need to be a Mirrored/Device variable.
+ steps_per_run_variable = training.get_or_create_steps_per_run_variable()
with self._train_distribution.scope():
random_seed.set_random_seed(self._config.tf_random_seed)
+ iterator, input_hooks = self._get_iterator_from_input_fn(
+ input_fn, model_fn_lib.ModeKeys.TRAIN, self._train_distribution)
+ worker_hooks.extend(input_hooks)
+ global_step_tensor = self._create_and_assert_global_step(g)
+ # we want to add to the global collection in the main thread not the
+ # tower threads.
+ ops.add_to_collection(
+ training_util.GLOBAL_STEP_READ_KEY,
+ self._train_distribution.read_var(global_step_tensor))
if is_tpu_strategy:
- # Create the iterator for run_on_dataset function
- # TODO(sourabhbajaj): refactor this out to call a function on the
- # strategy
- dataset = self._train_distribution.distribute_dataset(
- lambda: self._call_input_fn(input_fn, # pylint: disable=g-long-lambda
- model_fn_lib.ModeKeys.TRAIN))
- iterator = dataset.make_initializable_iterator()
- worker_hooks.append(
- estimator_util._DatasetInitializerHook(iterator)) # pylint: disable=protected-access
-
- global_step_tensor = self._create_and_assert_global_step(g)
- # we want to add to the global collection in the main thread not the
- # tower threads.
- ops.add_to_collection(
- training_util.GLOBAL_STEP_READ_KEY,
- self._train_distribution.read_var(global_step_tensor))
-
# Create a step_fn from the train_op of grouped_estimator_spec
- def step_fn(ctx, inputs):
+ def step_fn(ctx, features, labels):
"""A single step that is passed to run_on_dataset."""
- features, labels = inputs
estimator_spec = self._train_distribution.call_for_each_tower(
self._call_model_fn,
features,
@@ -1224,33 +1269,27 @@ class Estimator(object):
return estimator_spec.train_op
# Create new train_op post graph rewrites
- # TODO(sourabhbajaj): Make sure train_steps and tpu_iterations
- # work correctly. Currently hardcoded at 2
initial_training_loss = constant_op.constant(1e7)
ctx = self._train_distribution.run_steps_on_dataset(
- step_fn, iterator, iterations=2,
+ step_fn, iterator, iterations=steps_per_run_variable,
initial_loop_values={'loss': initial_training_loss})
distributed_train_op = ctx.run_op
- tpu_result = ctx.last_step_outputs
+ loss = ctx.last_step_outputs['loss']
grouped_estimator_spec = ctx.non_tensor_outputs['estimator_spec']
else:
- features, labels, input_hooks = (
- self._get_features_and_labels_from_input_fn(
- input_fn, model_fn_lib.ModeKeys.TRAIN,
- self._train_distribution))
- worker_hooks.extend(input_hooks)
- global_step_tensor = self._create_and_assert_global_step(g)
- # we want to add to the global collection in the main thread not the
- # tower threads.
- ops.add_to_collection(
- training_util.GLOBAL_STEP_READ_KEY,
- self._train_distribution.read_var(global_step_tensor))
+ features, labels = iterator.get_next()
grouped_estimator_spec = self._train_distribution.call_for_each_tower(
self._call_model_fn,
features,
labels, # although this will be None it seems
model_fn_lib.ModeKeys.TRAIN,
self.config)
+ loss = self._train_distribution.unwrap(
+ self._train_distribution.reduce(
+ distribute_lib.get_loss_reduction(),
+ grouped_estimator_spec.loss,
+ destinations='/device:CPU:0'))[0]
+ distributed_train_op = grouped_estimator_spec.train_op
scaffold = _combine_distributed_scaffold(
grouped_estimator_spec.scaffold, self._train_distribution)
@@ -1264,21 +1303,10 @@ class Estimator(object):
grouped_estimator_spec.training_hooks)
training_chief_hooks = get_hooks_from_the_first_device(
grouped_estimator_spec.training_chief_hooks)
-
- # TODO(sourabhbajaj): Merge the two code paths and clean up the code
- if is_tpu_strategy:
- loss = tpu_result['loss']
- worker_hooks.append(
- estimator_util.StrategyInitFinalizeHook(
- self._train_distribution.initialize,
- self._train_distribution.finalize))
- else:
- loss = self._train_distribution.unwrap(
- self._train_distribution.reduce(
- distribute_lib.get_loss_reduction(),
- grouped_estimator_spec.loss,
- destinations='/device:CPU:0'))[0]
- distributed_train_op = grouped_estimator_spec.train_op
+ worker_hooks.append(
+ estimator_util.StrategyInitFinalizeHook(
+ self._train_distribution.initialize,
+ self._train_distribution.finalize))
estimator_spec = model_fn_lib.EstimatorSpec(
mode=grouped_estimator_spec.mode,
@@ -1379,31 +1407,18 @@ class Estimator(object):
"""Builds the graph and related hooks to run evaluation."""
random_seed.set_random_seed(self._config.tf_random_seed)
self._create_and_assert_global_step(ops.get_default_graph())
- features, labels, input_hooks = (
- self._get_features_and_labels_from_input_fn(
- input_fn, model_fn_lib.ModeKeys.EVAL, self._eval_distribution))
if self._eval_distribution:
- (loss_metric, scaffold, evaluation_hooks, eval_metric_ops) = (
- self._call_model_fn_eval_distributed(features, labels, self.config))
+ (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) = (
+ self._call_model_fn_eval_distributed(input_fn, self.config))
else:
- (loss_metric, scaffold, evaluation_hooks, eval_metric_ops) = (
- self._call_model_fn_eval(features, labels, self.config))
+ (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) = (
+ self._call_model_fn_eval(input_fn, self.config))
global_step_tensor = training_util.get_global_step(ops.get_default_graph())
# Call to warm_start has to be after model_fn is called.
self._maybe_warm_start(checkpoint_path)
- if model_fn_lib.LOSS_METRIC_KEY in eval_metric_ops:
- raise ValueError(
- 'Metric with name "%s" is not allowed, because Estimator ' %
- (model_fn_lib.LOSS_METRIC_KEY) +
- 'already defines a default metric with the same name.')
- eval_metric_ops[model_fn_lib.LOSS_METRIC_KEY] = loss_metric
-
- update_op, eval_dict = _extract_metric_update_ops(eval_metric_ops,
- self._eval_distribution)
-
if ops.GraphKeys.GLOBAL_STEP in eval_dict:
raise ValueError(
'Metric with name `global_step` is not allowed, because Estimator '
@@ -1428,26 +1443,70 @@ class Estimator(object):
return scaffold, update_op, eval_dict, all_hooks
- def _call_model_fn_eval(self, features, labels, config):
+ def _call_model_fn_eval(self, input_fn, config):
+ """Call model_fn for evaluation and handle return values."""
+ features, labels, input_hooks = self._get_features_and_labels_from_input_fn(
+ input_fn, model_fn_lib.ModeKeys.EVAL)
+
estimator_spec = self._call_model_fn(
features, labels, model_fn_lib.ModeKeys.EVAL, config)
- loss_metric = metrics_lib.mean(estimator_spec.loss)
- return (loss_metric, estimator_spec.scaffold,
- estimator_spec.evaluation_hooks, estimator_spec.eval_metric_ops)
+ eval_metric_ops = _verify_and_create_loss_metric(
+ estimator_spec.eval_metric_ops, estimator_spec.loss)
+ update_op, eval_dict = _extract_metric_update_ops(eval_metric_ops)
+ return (estimator_spec.scaffold, estimator_spec.evaluation_hooks,
+ input_hooks, update_op, eval_dict)
- def _call_model_fn_eval_distributed(self, features, labels, config):
+ def _call_model_fn_eval_distributed(self, input_fn, config):
"""Call model_fn in distribution mode and handle return values."""
- grouped_estimator_spec = self._eval_distribution.call_for_each_tower(
- self._call_model_fn, features, labels,
- model_fn_lib.ModeKeys.EVAL, config)
+
+ iterator, input_hooks = self._get_iterator_from_input_fn(
+ input_fn, model_fn_lib.ModeKeys.EVAL, self._eval_distribution)
+
+ is_tpu_strategy = (
+ self._eval_distribution.__class__.__name__ == 'TPUStrategy')
+
+ if is_tpu_strategy:
+ def step_fn(ctx, features, labels):
+ """Runs one step of the eval computation and captures outputs."""
+ estimator_spec = self._eval_distribution.call_for_each_tower(
+ self._call_model_fn, features, labels, model_fn_lib.ModeKeys.EVAL,
+ config)
+ eval_metric_ops = _verify_and_create_loss_metric(
+ estimator_spec.eval_metric_ops, estimator_spec.loss,
+ self._eval_distribution)
+ update_op, eval_dict = _extract_metric_update_ops(
+ eval_metric_ops, self._eval_distribution)
+ ctx.set_non_tensor_output(name='estimator_spec', output=estimator_spec)
+ ctx.set_non_tensor_output(name='eval_dict', output=eval_dict)
+ return update_op
+
+ # TODO(priyag): Fix eval step hook to account for steps_per_run.
+ ctx = self._eval_distribution.run_steps_on_dataset(
+ step_fn, iterator, iterations=self._eval_distribution.steps_per_run)
+ update_op = ctx.run_op
+ eval_dict = ctx.non_tensor_outputs['eval_dict']
+ grouped_estimator_spec = ctx.non_tensor_outputs['estimator_spec']
+ else:
+ features, labels = iterator.get_next()
+ grouped_estimator_spec = self._eval_distribution.call_for_each_tower(
+ self._call_model_fn, features, labels,
+ model_fn_lib.ModeKeys.EVAL, config)
+ eval_metric_ops = _verify_and_create_loss_metric(
+ grouped_estimator_spec.eval_metric_ops, grouped_estimator_spec.loss,
+ self._eval_distribution)
+ update_op, eval_dict = _extract_metric_update_ops(
+ eval_metric_ops, self._eval_distribution)
+
scaffold = _combine_distributed_scaffold(
grouped_estimator_spec.scaffold, self._eval_distribution)
evaluation_hooks = self._eval_distribution.unwrap(
grouped_estimator_spec.evaluation_hooks)[0]
- loss_metric = self._eval_distribution.call_for_each_tower(
- metrics_lib.mean, grouped_estimator_spec.loss)
- return (loss_metric, scaffold,
- evaluation_hooks, grouped_estimator_spec.eval_metric_ops)
+ evaluation_hooks = evaluation_hooks + (
+ estimator_util.StrategyInitFinalizeHook(
+ self._eval_distribution.initialize,
+ self._eval_distribution.finalize),)
+
+ return (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict)
def _evaluate_run(self, checkpoint_path, scaffold, update_op, eval_dict,
all_hooks, output_dir):
@@ -1483,6 +1542,23 @@ class Estimator(object):
warm_starting_util.warm_start(*self._warm_start_settings)
+def _verify_and_create_loss_metric(eval_metric_ops, loss, distribution=None):
+ """Creates a metric for loss and throws an error if one already exists."""
+ if model_fn_lib.LOSS_METRIC_KEY in eval_metric_ops:
+ raise ValueError(
+ 'Metric with name "%s" is not allowed, because Estimator ' %
+ (model_fn_lib.LOSS_METRIC_KEY) +
+ 'already defines a default metric with the same name.')
+
+ if distribution is None:
+ loss_metric = metrics_lib.mean(loss)
+ else:
+ loss_metric = distribution.call_for_each_tower(
+ metrics_lib.mean, loss)
+ eval_metric_ops[model_fn_lib.LOSS_METRIC_KEY] = loss_metric
+ return eval_metric_ops
+
+
def maybe_overwrite_model_dir_and_session_config(config, model_dir):
"""Overwrite estimator config by `model_dir` and `session_config` if needed.
@@ -1516,9 +1592,9 @@ def maybe_overwrite_model_dir_and_session_config(config, model_dir):
"`model_dir` are set both in constructor and `RunConfig`, but with "
"different values. In constructor: '{}', in `RunConfig`: "
"'{}' ".format(model_dir, config.model_dir))
- if model_dir:
- config = run_config.RunConfig.replace(config, model_dir=model_dir)
- if getattr(config, 'model_dir', None) is None:
+ if model_dir:
+ config = run_config.RunConfig.replace(config, model_dir=model_dir)
+ elif getattr(config, 'model_dir', None) is None:
model_dir = tempfile.mkdtemp()
logging.warning('Using temporary folder as model directory: %s', model_dir)
config = run_config.RunConfig.replace(config, model_dir=model_dir)
@@ -1527,7 +1603,7 @@ def maybe_overwrite_model_dir_and_session_config(config, model_dir):
def create_per_tower_ready_op(scaffold):
- """Create a Scaffold.ready_op inside a tower."""
+ """Create a `tf.train.Scaffold.ready_op` inside a tower."""
if scaffold.ready_op:
return scaffold.ready_op
@@ -1542,7 +1618,7 @@ def create_per_tower_ready_op(scaffold):
def create_per_tower_ready_for_local_init_op(scaffold):
- """Create a Scaffold.ready_for_local_init_op inside a tower."""
+ """Create a `tf.train.Scaffold.ready_for_local_init_op` inside a tower."""
if scaffold.ready_for_local_init_op:
return scaffold.ready_for_local_init_op
@@ -1640,7 +1716,7 @@ def _check_checkpoint_available(model_dir):
def _check_hooks_type(hooks):
- """Returns hooks if all are SessionRunHook, raises TypeError otherwise."""
+ """Returns hooks if all are `SessionRunHook`, raises TypeError otherwise."""
hooks = list(hooks or [])
for h in hooks:
if not isinstance(h, training.SessionRunHook):
@@ -1660,17 +1736,18 @@ def _check_listeners_type(saving_listeners):
def _get_replica_device_setter(config):
- """Creates a replica device setter if required as a default device_fn.
+ """Creates a replica device setter if required as a default `device_fn`.
- `Estimator` uses ReplicaDeviceSetter as a default device placer. It sets the
- distributed related arguments such as number of ps_replicas based on given
- config.
+ `Estimator` uses `tf.train.ReplicaDeviceSetter` as a default device placer. It
+ sets the
+ distributed related arguments such as number of `ps_replicas` based on given
+ `config`.
Args:
- config: A `RunConfig` instance.
+ config: A `tf.estimator.RunConfig` instance.
Returns:
- A replica device setter, or None.
+ A replica device setter, or `None`.
"""
if config.task_type:
worker_device = '/job:%s/task:%d' % (config.task_type, config.task_id)
@@ -1689,7 +1766,7 @@ def _get_replica_device_setter(config):
def _verify_model_fn_args(model_fn, params):
- """Verifies model fn arguments."""
+ """Verifies `model_fn` arguments."""
args = set(function_utils.fn_args(model_fn))
if 'features' not in args:
raise ValueError('model_fn (%s) must include features argument.' % model_fn)
@@ -1787,10 +1864,24 @@ def _write_dict_to_summary(output_dir,
logging.warn('Skipping summary for %s, cannot parse string to Summary.',
key)
continue
+ elif isinstance(dictionary[key], np.ndarray):
+ value = summary_proto.value.add()
+ value.tag = key
+ value.node_name = key
+ tensor_proto = tensor_util.make_tensor_proto(dictionary[key])
+ value.tensor.CopyFrom(tensor_proto)
+ # pylint: disable=line-too-long
+ logging.info(
+ 'Summary for np.ndarray is not visible in Tensorboard by default. '
+ 'Consider using a Tensorboard plugin for visualization (see '
+ 'https://github.com/tensorflow/tensorboard-plugin-example/blob/master/README.md'
+ ' for more information).')
+ # pylint: enable=line-too-long
else:
logging.warn(
'Skipping summary for %s, must be a float, np.float32, np.int64, '
- 'np.int32 or int or a serialized string of Summary.', key)
+ 'np.int32 or int or np.ndarray or a serialized string of Summary.',
+ key)
summary_writer.add_summary(summary_proto, current_global_step)
summary_writer.flush()
@@ -1820,7 +1911,7 @@ def _write_checkpoint_path_to_summary(output_dir, checkpoint_path,
def _has_dataset_or_queue_runner(maybe_tensor):
- """Returns True if TF dataset or QueueRunner has been used."""
+ """Returns `True` if `Dataset` or `QueueRunner` has been used."""
# Check TF dataset first. Here, we use a simple algorithm to check the top
# level Tensors only, which should be sufficient for most users.
tensors = [x for x in nest.flatten(maybe_tensor) if isinstance(x, ops.Tensor)]
@@ -1843,9 +1934,9 @@ class WarmStartSettings(
'var_name_to_vocab_info',
'var_name_to_prev_var_name',
])):
- """Settings for warm-starting in Estimators.
+ """Settings for warm-starting in `tf.estimator.Estimators`.
- Example Use with canned `DNNEstimator`:
+ Example Use with canned `tf.estimator.DNNEstimator`:
```
emb_vocab_file = tf.feature_column.embedding_column(
@@ -1962,23 +2053,19 @@ class WarmStartSettings(
ckpt_to_initialize_from: [Required] A string specifying the directory with
checkpoint file(s) or path to checkpoint from which to warm-start the
model parameters.
- vars_to_warm_start: [Optional] One of the following:
-
- - A regular expression (string) that captures which variables to
- warm-start (see tf.get_collection). This expression will only consider
- variables in the TRAINABLE_VARIABLES collection.
- - A list of Variables to warm-start.
- - A list of strings, each representing a full variable name to warm-start.
- - `None`, in which case only variables specified in
- `var_name_to_vocab_info` will be warm-started.
-
- Defaults to `'.*'`, which warm-starts all variables in the
- TRAINABLE_VARIABLES collection. Note that this excludes variables such as
- accumulators and moving statistics from batch norm.
+ vars_to_warm_start: [Optional] One of the following: - A regular expression
+ (string) that captures which variables to warm-start (see
+ `tf.get_collection`). This expression will only consider variables in the
+ `TRAINABLE_VARIABLES` collection. - A list of Variables to warm-start. - A
+ list of strings, each representing a full variable name to warm-start. -
+ `None`, in which case only variables specified in `var_name_to_vocab_info`
+ will be warm-started. Defaults to `'.*'`, which warm-starts all variables
+ in the `TRAINABLE_VARIABLES` collection. Note that this excludes
+ variables such as accumulators and moving statistics from batch norm.
var_name_to_vocab_info: [Optional] Dict of variable names (strings) to
- VocabInfo. The variable names should be "full" variables, not the names
- of the partitions. If not explicitly provided, the variable is assumed to
- have no vocabulary.
+ `tf.estimator.VocabInfo`. The variable names should be "full" variables,
+ not the names of the partitions. If not explicitly provided, the variable
+ is assumed to have no vocabulary.
var_name_to_prev_var_name: [Optional] Dict of variable names (strings) to
name of the previously-trained variable in `ckpt_to_initialize_from`. If
not explicitly provided, the name of the variable is assumed to be same
@@ -2003,43 +2090,45 @@ class WarmStartSettings(
def _get_saved_model_ckpt(saved_model_dir):
- """Return path to variables checkpoint in a SavedModel directory."""
+ """Return path to variables checkpoint in a `SavedModel` directory."""
if not gfile.Exists(
- os.path.join(compat.as_bytes(saved_model_dir),
- compat.as_bytes('variables/variables.index'))):
+ os.path.join(saved_model_utils.get_variables_dir(saved_model_dir),
+ compat.as_text('variables.index'))):
raise ValueError('Directory provided has an invalid SavedModel format: %s'
% saved_model_dir)
- return os.path.join(
- compat.as_bytes(saved_model_dir),
- compat.as_bytes('{}/{}'.format(constants.VARIABLES_DIRECTORY,
- constants.VARIABLES_FILENAME)))
+ return saved_model_utils.get_variables_path(saved_model_dir)
def _get_default_warm_start_settings(warm_start_from):
- """Returns default WarmStartSettings.
+ """Returns default `tf.estimator.WarmStartSettings`.
Args:
warm_start_from: Either a string representing the filepath of a checkpoint
- or SavedModel to initialize from, or an instance of WarmStartSettings.
+ or `SavedModel` to initialize from, or an instance of
+ `tf.estimator.WarmStartSettings`.
Returns:
- Either None or an instance of WarmStartSettings.
+ Either None or an instance of `WarmStartSettings`.
Raises:
- ValueError: If warm_start_from is not None but is neither a string nor an
- instance of WarmStartSettings.
+ ValueError: If `warm_start_from` is not `None` but is neither a string nor
+ an
+ instance of `WarmStartSettings`.
"""
if warm_start_from is None:
return None
if isinstance(warm_start_from, (six.string_types, six.binary_type)):
# Infer that this is a SavedModel if export_path +
# 'variables/variables.index' exists, and if so, construct the
- # WarmStartSettings pointing to export_path + 'variables/variables'.
- if gfile.Exists(os.path.join(compat.as_bytes(warm_start_from),
- compat.as_bytes('variables/variables.index'))):
+ # WarmStartSettings pointing to the variables path
+ # (export_path + 'variables/variables').
+ if gfile.Exists(os.path.join(
+ saved_model_utils.get_variables_dir(warm_start_from),
+ compat.as_text('variables.index'))):
logging.info('Warm-starting from a SavedModel')
return WarmStartSettings(
- ckpt_to_initialize_from=_get_saved_model_ckpt(warm_start_from))
+ ckpt_to_initialize_from=saved_model_utils.get_variables_path(
+ warm_start_from))
return WarmStartSettings(ckpt_to_initialize_from=warm_start_from)
elif isinstance(warm_start_from, WarmStartSettings):
return warm_start_from
diff --git a/tensorflow/python/estimator/estimator_test.py b/tensorflow/python/estimator/estimator_test.py
index e8552092e0..d316742a83 100644
--- a/tensorflow/python/estimator/estimator_test.py
+++ b/tensorflow/python/estimator/estimator_test.py
@@ -58,6 +58,7 @@ from tensorflow.python.ops import string_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops.losses import losses
+from tensorflow.python.ops.random_ops import random_uniform
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
@@ -158,16 +159,7 @@ class EstimatorInheritanceConstraintTest(test.TestCase):
def __init__(self):
super(_Estimator, self).__init__(model_fn=dummy_model_fn)
- def _call_input_fn(self, input_fn, mode):
- return input_fn()
-
- def _create_global_step(self, graph):
- pass
-
- def _convert_train_steps_to_hooks(self, steps, max_steps):
- pass
-
- def _convert_eval_steps_to_hooks(self, steps):
+ def _tf_api_names(self):
pass
_Estimator()
@@ -473,6 +465,29 @@ class EstimatorTrainTest(test.TestCase):
est.train(InputFn(), steps=1)
self.assertEqual(1, input_fn_call_count[0])
+ def test_nested_input_fn(self):
+ expected_params = {'batch_size': 10}
+
+ def _input_fn():
+ dataset_features = dataset_ops.Dataset.from_tensor_slices(
+ (random_uniform([4]),
+ random_uniform([4, 100], maxval=100, dtype=dtypes.int32)))
+ dataset_labels = dataset_ops.Dataset.from_tensor_slices(
+ random_uniform([4, 10]))
+ dataset = dataset_ops.Dataset.zip((dataset_features, dataset_labels))
+ dataset = dataset.repeat(-1)
+ iterator = dataset.make_initializable_iterator()
+ return iterator.get_next()
+
+ def _model_fn(features, labels, mode, params, config):
+ del params, config
+ return model_fn_global_step_incrementer(features, labels, mode)
+
+ expected_config = run_config.RunConfig().replace(tf_random_seed=4321)
+ est = estimator.Estimator(
+ model_fn=_model_fn, params=expected_params, config=expected_config)
+ est.train(_input_fn, steps=4)
+
def test_input_fn_args(self):
expected_mode = model_fn_lib.ModeKeys.TRAIN
expected_params = {'batch_size': 10}
@@ -940,6 +955,19 @@ class EstimatorTrainTest(test.TestCase):
est = estimator.Estimator(model_fn=_model_fn)
est.train(dummy_input_fn, steps=1)
+ def test_config_should_not_be_evaluator_or_ps(self):
+
+ class FakeEvaluatorConfig(run_config.RunConfig):
+
+ @property
+ def task_type(self):
+ return run_config.TaskType.EVALUATOR
+
+ est = estimator.Estimator(
+ model_fn=dummy_model_fn, config=FakeEvaluatorConfig())
+ with self.assertRaisesRegexp(ValueError, 'train_and_evaluate'):
+ est.train(dummy_input_fn, steps=1)
+
def _model_fn_with_eval_metric_ops(features, labels, mode, params):
_, _ = features, labels
@@ -1458,6 +1486,48 @@ class EstimatorEvaluateTest(test.TestCase):
self.assertProtoEquals(expected_tensor_proto,
next(summaries).value[0].tensor)
+ def test_summary_writing_with_tensor(self):
+
+ def model_fn_with_prediction_mean_tensor_eval_metric_ops(
+ features, labels, mode, params):
+ _, _ = features, labels
+ global_step = training.get_global_step()
+
+ metric_name = params.get('metric_name') or 'metric'
+ predictions = constant_op.constant([1., .5, 0.])
+ eval_metric_ops = {metric_name: metrics_lib.mean_tensor(predictions)}
+ return model_fn_lib.EstimatorSpec(
+ mode,
+ loss=constant_op.constant(1.),
+ predictions={'predictions': predictions},
+ train_op=state_ops.assign_add(global_step, 1),
+ eval_metric_ops=eval_metric_ops)
+
+ metric_key = 'PMT'
+ params = {
+ 'metric_name': metric_key,
+ }
+ est = estimator.Estimator(
+ model_fn=model_fn_with_prediction_mean_tensor_eval_metric_ops,
+ params=params,
+ config=run_config.RunConfig(save_summary_steps=1))
+ est.train(input_fn=dummy_input_fn, steps=10)
+ est.evaluate(
+ input_fn=dummy_input_fn,
+ steps=10,
+ )
+
+ writer_cache.FileWriterCache.clear()
+
+ self.assertTrue(
+ check_eventfile_for_keyword(metric_key, est.eval_dir()),
+ '{} should be part of reported summaries.'.format(metric_key))
+
+ summaries = summaries_with_matching_keyword(metric_key, est.eval_dir())
+ for value in next(summaries).value:
+ if value.tag == metric_key:
+ self.assertTrue(value.HasField('tensor'))
+
class EstimatorPredictTest(test.TestCase):
@@ -2641,6 +2711,7 @@ class EstimatorExportTest(test.TestCase):
_, _ = features, labels
my_int = variables.Variable(1, name='my_int',
collections=[ops.GraphKeys.LOCAL_VARIABLES])
+ _ = training.get_or_create_steps_per_run_variable()
scores = constant_op.constant([3.])
with ops.control_dependencies([
variables.local_variables_initializer(),
diff --git a/tensorflow/python/estimator/export/export.py b/tensorflow/python/estimator/export/export.py
index 529e7a8b87..3d171f7811 100644
--- a/tensorflow/python/estimator/export/export.py
+++ b/tensorflow/python/estimator/export/export.py
@@ -288,9 +288,8 @@ def build_parsing_serving_input_receiver_fn(feature_spec,
def _placeholder_from_tensor(t, default_batch_size=None):
- shape_list = t.get_shape().as_list()
- shape_list[0] = default_batch_size
- shape = tensor_shape.TensorShape(shape_list)
+ batch_shape = tensor_shape.TensorShape([default_batch_size])
+ shape = batch_shape.concatenate(t.get_shape()[1:])
# Reuse the feature tensor's op name (t.op.name) for the placeholder,
# excluding the index from the tensor's name (t.name):
diff --git a/tensorflow/python/estimator/export/export_test.py b/tensorflow/python/estimator/export/export_test.py
index d2ac7f0b3b..1d475adb43 100644
--- a/tensorflow/python/estimator/export/export_test.py
+++ b/tensorflow/python/estimator/export/export_test.py
@@ -31,6 +31,7 @@ from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
+from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import parsing_ops
@@ -378,6 +379,20 @@ class ExportTest(test_util.TensorFlowTestCase):
v = serving_input_receiver_fn()
self.assertTrue(isinstance(v, export.ServingInputReceiver))
+ def test_build_raw_serving_input_receiver_fn_without_shape(self):
+ """Test case for issue #21178."""
+ f = {"feature_1": array_ops.placeholder(dtypes.float32),
+ "feature_2": array_ops.placeholder(dtypes.int32)}
+ serving_input_receiver_fn = export.build_raw_serving_input_receiver_fn(f)
+ v = serving_input_receiver_fn()
+ self.assertTrue(isinstance(v, export.ServingInputReceiver))
+ self.assertEqual(
+ tensor_shape.unknown_shape(),
+ v.receiver_tensors["feature_1"].shape)
+ self.assertEqual(
+ tensor_shape.unknown_shape(),
+ v.receiver_tensors["feature_2"].shape)
+
def test_build_raw_serving_input_receiver_fn(self):
features = {"feature_1": constant_op.constant(["hello"]),
"feature_2": constant_op.constant([42])}
diff --git a/tensorflow/python/estimator/exporter_test.py b/tensorflow/python/estimator/exporter_test.py
index c4b006955c..fcccfbde7a 100644
--- a/tensorflow/python/estimator/exporter_test.py
+++ b/tensorflow/python/estimator/exporter_test.py
@@ -323,6 +323,43 @@ class LatestExporterTest(test.TestCase):
self.assertTrue(gfile.Exists(export_dir_3))
self.assertTrue(gfile.Exists(export_dir_4))
+ def test_garbage_collect_exports_with_trailing_delimiter(self):
+ export_dir_base = tempfile.mkdtemp() + "export/"
+ gfile.MkDir(export_dir_base)
+ export_dir_1 = _create_test_export_dir(export_dir_base)
+ export_dir_2 = _create_test_export_dir(export_dir_base)
+ export_dir_3 = _create_test_export_dir(export_dir_base)
+ export_dir_4 = _create_test_export_dir(export_dir_base)
+
+ self.assertTrue(gfile.Exists(export_dir_1))
+ self.assertTrue(gfile.Exists(export_dir_2))
+ self.assertTrue(gfile.Exists(export_dir_3))
+ self.assertTrue(gfile.Exists(export_dir_4))
+
+ def _serving_input_receiver_fn():
+ return array_ops.constant([1]), None
+
+ exporter = exporter_lib.LatestExporter(
+ name="latest_exporter",
+ serving_input_receiver_fn=_serving_input_receiver_fn,
+ exports_to_keep=1)
+ estimator = test.mock.Mock(spec=estimator_lib.Estimator)
+ # Garbage collect all but the most recent 2 exports,
+ # where recency is determined based on the timestamp directory names.
+ with test.mock.patch.object(gfile, "ListDirectory") as mock_list_directory:
+ mock_list_directory.return_value = [
+ os.path.basename(export_dir_1) + b"/",
+ os.path.basename(export_dir_2) + b"/",
+ os.path.basename(export_dir_3) + b"/",
+ os.path.basename(export_dir_4) + b"/",
+ ]
+ exporter.export(estimator, export_dir_base, None, None, False)
+
+ self.assertFalse(gfile.Exists(export_dir_1))
+ self.assertFalse(gfile.Exists(export_dir_2))
+ self.assertFalse(gfile.Exists(export_dir_3))
+ self.assertTrue(gfile.Exists(export_dir_4))
+
def _create_test_export_dir(export_dir_base):
export_dir = _get_timestamped_export_dir(export_dir_base)
diff --git a/tensorflow/python/estimator/gc.py b/tensorflow/python/estimator/gc.py
index 9f8a463ec1..03ad33dd6b 100644
--- a/tensorflow/python/estimator/gc.py
+++ b/tensorflow/python/estimator/gc.py
@@ -201,9 +201,11 @@ def _get_paths(base_dir, parser):
raw_paths = gfile.ListDirectory(base_dir)
paths = []
for r in raw_paths:
- p = parser(Path(os.path.join(compat.as_str_any(base_dir),
- compat.as_str_any(r)),
- None))
+ # ListDirectory() return paths with "/" at the last if base_dir was GCS URL
+ r = compat.as_str_any(r)
+ if r[-1] == '/':
+ r = r[0:len(r)-1]
+ p = parser(Path(os.path.join(compat.as_str_any(base_dir), r), None))
if p:
paths.append(p)
return sorted(paths)
diff --git a/tensorflow/python/estimator/gc_test.py b/tensorflow/python/estimator/gc_test.py
index 2cbdd511d1..53c3d4ca2a 100644
--- a/tensorflow/python/estimator/gc_test.py
+++ b/tensorflow/python/estimator/gc_test.py
@@ -140,6 +140,17 @@ class GcTest(test_util.TensorFlowTestCase):
gfile.MakeDirs(os.path.join(compat.as_str_any(base_dir), "42"))
gc._get_paths(base_dir, _create_parser(base_dir))
+ def testGcsDirWithSeparator(self):
+ base_dir = "gs://bucket/foo"
+ with test.mock.patch.object(gfile, "ListDirectory") as mock_list_directory:
+ # gfile.ListDirectory returns directory names with separator '/'
+ mock_list_directory.return_value = ["0/", "1/"]
+ self.assertEqual(
+ gc._get_paths(base_dir, _create_parser(base_dir)),
+ [
+ gc.Path(os.path.join(base_dir, "0"), 0),
+ gc.Path(os.path.join(base_dir, "1"), 1)
+ ])
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/estimator/inputs/numpy_io_test.py b/tensorflow/python/estimator/inputs/numpy_io_test.py
index 81b201cc5c..4e7b00b307 100644
--- a/tensorflow/python/estimator/inputs/numpy_io_test.py
+++ b/tensorflow/python/estimator/inputs/numpy_io_test.py
@@ -19,9 +19,15 @@ from __future__ import division
from __future__ import print_function
import numpy as np
-
+from tensorflow.python.client import session as session_lib
from tensorflow.python.estimator.inputs import numpy_io
+from tensorflow.python.feature_column import feature_column_lib as fc
+from tensorflow.python.feature_column.feature_column import _LinearModel
from tensorflow.python.framework import errors
+from tensorflow.python.framework import ops
+from tensorflow.python.ops import lookup_ops
+from tensorflow.python.ops import variable_scope
+from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.platform import test
from tensorflow.python.training import coordinator
from tensorflow.python.training import monitored_session
@@ -456,5 +462,159 @@ class NumpyIoTest(test.TestCase):
self.assertAllEqual(res_arr[1], res_dict[1])
+class FeatureColumnIntegrationTest(test.TestCase):
+
+ def _initialized_session(self, config=None):
+ sess = session_lib.Session(config=config)
+ sess.run(variables_lib.global_variables_initializer())
+ sess.run(lookup_ops.tables_initializer())
+ return sess
+
+ def _get_linear_model_bias(self, name='linear_model'):
+ with variable_scope.variable_scope(name, reuse=True):
+ return variable_scope.get_variable('bias_weights')
+
+ def _get_linear_model_column_var(self, column, name='linear_model'):
+ return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES,
+ name + '/' + column.name)[0]
+
+ def _get_keras_linear_model_predictions(
+ self,
+ features,
+ feature_columns,
+ units=1,
+ sparse_combiner='sum',
+ weight_collections=None,
+ trainable=True,
+ cols_to_vars=None):
+ keras_linear_model = _LinearModel(
+ feature_columns,
+ units,
+ sparse_combiner,
+ weight_collections,
+ trainable,
+ name='linear_model')
+ retval = keras_linear_model(features) # pylint: disable=not-callable
+ if cols_to_vars is not None:
+ cols_to_vars.update(keras_linear_model.cols_to_vars())
+ return retval
+
+ def test_linear_model_numpy_input_fn(self):
+ price = fc.numeric_column('price')
+ price_buckets = fc.bucketized_column(price, boundaries=[0., 10., 100.,])
+ body_style = fc.categorical_column_with_vocabulary_list(
+ 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
+
+ input_fn = numpy_io.numpy_input_fn(
+ x={
+ 'price': np.array([-1., 2., 13., 104.]),
+ 'body-style': np.array(['sedan', 'hardtop', 'wagon', 'sedan']),
+ },
+ batch_size=2,
+ shuffle=False)
+ features = input_fn()
+ net = fc.linear_model(features, [price_buckets, body_style])
+ # self.assertEqual(1 + 3 + 5, net.shape[1])
+ with self._initialized_session() as sess:
+ coord = coordinator.Coordinator()
+ threads = queue_runner_impl.start_queue_runners(sess, coord=coord)
+
+ bias = self._get_linear_model_bias()
+ price_buckets_var = self._get_linear_model_column_var(price_buckets)
+ body_style_var = self._get_linear_model_column_var(body_style)
+
+ sess.run(price_buckets_var.assign([[10.], [100.], [1000.], [10000.]]))
+ sess.run(body_style_var.assign([[-10.], [-100.], [-1000.]]))
+ sess.run(bias.assign([5.]))
+
+ self.assertAllClose([[10 - 1000 + 5.], [100 - 10 + 5.]], sess.run(net))
+
+ coord.request_stop()
+ coord.join(threads)
+
+ def test_linear_model_impl_numpy_input_fn(self):
+ price = fc.numeric_column('price')
+ price_buckets = fc.bucketized_column(
+ price, boundaries=[
+ 0.,
+ 10.,
+ 100.,
+ ])
+ body_style = fc.categorical_column_with_vocabulary_list(
+ 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
+
+ input_fn = numpy_io.numpy_input_fn(
+ x={
+ 'price': np.array([-1., 2., 13., 104.]),
+ 'body-style': np.array(['sedan', 'hardtop', 'wagon', 'sedan']),
+ },
+ batch_size=2,
+ shuffle=False)
+ features = input_fn()
+ net = self._get_keras_linear_model_predictions(
+ features, [price_buckets, body_style])
+ # self.assertEqual(1 + 3 + 5, net.shape[1])
+ with self._initialized_session() as sess:
+ coord = coordinator.Coordinator()
+ threads = queue_runner_impl.start_queue_runners(sess, coord=coord)
+
+ bias = self._get_linear_model_bias()
+ price_buckets_var = self._get_linear_model_column_var(price_buckets)
+ body_style_var = self._get_linear_model_column_var(body_style)
+
+ sess.run(price_buckets_var.assign([[10.], [100.], [1000.], [10000.]]))
+ sess.run(body_style_var.assign([[-10.], [-100.], [-1000.]]))
+ sess.run(bias.assign([5.]))
+
+ self.assertAllClose([[10 - 1000 + 5.], [100 - 10 + 5.]], sess.run(net))
+
+ coord.request_stop()
+ coord.join(threads)
+
+ def test_functional_input_layer_with_numpy_input_fn(self):
+ embedding_values = (
+ (1., 2., 3., 4., 5.), # id 0
+ (6., 7., 8., 9., 10.), # id 1
+ (11., 12., 13., 14., 15.) # id 2
+ )
+ def _initializer(shape, dtype, partition_info):
+ del shape, dtype, partition_info
+ return embedding_values
+
+ # price has 1 dimension in input_layer
+ price = fc.numeric_column('price')
+ body_style = fc.categorical_column_with_vocabulary_list(
+ 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
+ # one_hot_body_style has 3 dims in input_layer.
+ one_hot_body_style = fc.indicator_column(body_style)
+ # embedded_body_style has 5 dims in input_layer.
+ embedded_body_style = fc.embedding_column(body_style, dimension=5,
+ initializer=_initializer)
+
+ input_fn = numpy_io.numpy_input_fn(
+ x={
+ 'price': np.array([11., 12., 13., 14.]),
+ 'body-style': np.array(['sedan', 'hardtop', 'wagon', 'sedan']),
+ },
+ batch_size=2,
+ shuffle=False)
+ features = input_fn()
+ net = fc.input_layer(features,
+ [price, one_hot_body_style, embedded_body_style])
+ self.assertEqual(1 + 3 + 5, net.shape[1])
+ with self._initialized_session() as sess:
+ coord = coordinator.Coordinator()
+ threads = queue_runner_impl.start_queue_runners(sess, coord=coord)
+
+ # Each row is formed by concatenating `embedded_body_style`,
+ # `one_hot_body_style`, and `price` in order.
+ self.assertAllEqual(
+ [[11., 12., 13., 14., 15., 0., 0., 1., 11.],
+ [1., 2., 3., 4., 5., 1., 0., 0., 12]],
+ sess.run(net))
+
+ coord.request_stop()
+ coord.join(threads)
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/python/estimator/keras.py b/tensorflow/python/estimator/keras.py
index c91204a35f..6361c6acc1 100644
--- a/tensorflow/python/estimator/keras.py
+++ b/tensorflow/python/estimator/keras.py
@@ -33,9 +33,6 @@ from tensorflow.python.framework import tensor_util
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import models
from tensorflow.python.keras import optimizers
-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 CustomObjectScope
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import metrics as metrics_module
@@ -43,12 +40,10 @@ from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.training import checkpoint_management
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import optimizer as tf_optimizer_module
from tensorflow.python.training import saver as saver_lib
from tensorflow.python.training import training_util
-from tensorflow.python.training.checkpointable import base as checkpointable
-from tensorflow.python.training.checkpointable import data_structures
_DEFAULT_SERVING_KEY = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
@@ -92,184 +87,78 @@ def _any_weight_initialized(keras_model):
return False
-def _create_ordered_io(keras_model, estimator_io, is_input=True):
- """Create a list of tensors from IO dictionary based on Keras IO order.
+def _convert_estimator_io_to_keras(keras_model, features, labels):
+ """Converts estimator features and labels to keras input and target tensors.
Args:
- keras_model: An instance of compiled keras model.
- estimator_io: The features or labels (dict or plain array) from model_fn.
- is_input: True if dictionary is for inputs.
+ keras_model: a compiled `tf.keras.Model` instance, used to determine the
+ order of the returned lists.
+ features: Dict of tensors or `None`.
+ labels: Dict of tensors, a single tensor, or `None`.
Returns:
- A list of tensors based on Keras IO order.
-
- Raises:
- ValueError: if dictionary keys cannot be found in Keras model input_names
- or output_names.
- """
- if isinstance(estimator_io, (list, tuple)):
- # Case currently not supported by most built-in input_fn,
- # but it's good to have for sanity
- return [_convert_tensor(x) for x in estimator_io]
- elif isinstance(estimator_io, dict):
- if is_input:
- if keras_model._is_graph_network:
- keras_io_names = keras_model.input_names
- else:
- keras_io_names = [
- 'input_%d' % i for i in range(1, len(estimator_io) + 1)]
- else:
- if keras_model._is_graph_network:
- keras_io_names = keras_model.output_names
- else:
- keras_io_names = [
- 'output_%d' % i for i in range(1, len(estimator_io) + 1)]
-
- for key in estimator_io:
- if key not in keras_io_names:
- raise ValueError(
- 'Cannot find %s with name "%s" in Keras Model. '
- 'It needs to match one '
- 'of the following: %s' % ('input' if is_input else 'output', key,
- ', '.join(keras_io_names)))
- tensors = [_convert_tensor(estimator_io[io_name])
- for io_name in keras_io_names]
- return tensors
- else:
- # Plain array.
- return _convert_tensor(estimator_io)
-
-
-def _in_place_subclassed_model_reset(model):
- """Substitute for model cloning that works for subclassed models.
-
- Subclassed models cannot be cloned because their topology is not serializable.
- To "instantiate" an identical model in a new TF graph, we reuse the original
- model object, but we clear its state.
-
- After calling this function on a model instance, you can use the model
- instance as if it were a model clone (in particular you can use it in a new
- graph).
-
- This method clears the state of the input model. It is thus destructive.
- However the original state can be restored fully by calling
- `_in_place_subclassed_model_state_restoration`.
-
- Args:
- model: Instance of a Keras model created via subclassing.
-
- Raises:
- ValueError: In case the model uses a subclassed model as inner layer.
+ Tuple of (
+ list of input tensors or `None`,
+ list of target tensors or `None`)
+ The order of tensors is determined by the order set in the keras model.
"""
- assert not model._is_graph_network # Only makes sense for subclassed networks
- # Retrieve all layers tracked by the model as well as their attribute names
- attributes_cache = {}
- for name in dir(model):
- try:
- value = getattr(model, name)
- except (AttributeError, ValueError, TypeError):
- continue
- if isinstance(value, Layer):
- attributes_cache[name] = value
- assert value in model._layers
- elif isinstance(value, (list, tuple)) and name not in ('layers', '_layers'):
- # Handle case: list/tuple of layers (also tracked by the Network API).
- if value and all(isinstance(val, Layer) for val in value):
- raise ValueError('We do not support the use of list-of-layers '
- 'attributes in subclassed models used with '
- '`model_to_estimator` at this time. Found list '
- 'model: %s' % name)
-
- # Replace layers on the model with fresh layers
- layers_to_names = {value: key for key, value in attributes_cache.items()}
- original_layers = model._layers[:]
- model._layers = data_structures.NoDependency([])
- for layer in original_layers: # We preserve layer order.
- config = layer.get_config()
- # This will not work for nested subclassed models used as layers.
- # This would be theoretically possible to support, but would add complexity.
- # Only do it if users complain.
- if isinstance(layer, Network) and not layer._is_graph_network:
- raise ValueError('We do not support the use of nested subclassed models '
- 'in `model_to_estimator` at this time. Found nested '
- 'model: %s' % layer)
- fresh_layer = layer.__class__.from_config(config)
- name = layers_to_names[layer]
- setattr(model, name, fresh_layer)
-
- # Cache original model build attributes (in addition to layers)
- if (not hasattr(model, '_original_attributes_cache') or
- model._original_attributes_cache is None):
- if model.built:
- attributes_to_cache = [
- 'inputs',
- 'outputs',
- '_feed_outputs',
- '_feed_output_names',
- '_feed_output_shapes',
- '_feed_loss_fns',
- 'loss_weights_list',
- 'targets',
- '_feed_targets',
- 'sample_weight_modes',
- 'weighted_metrics',
- 'metrics_names',
- 'metrics_tensors',
- 'metrics_updates',
- 'stateful_metric_names',
- 'total_loss',
- 'sample_weights',
- '_feed_sample_weights',
- 'train_function',
- 'test_function',
- 'predict_function',
- '_collected_trainable_weights',
- '_feed_inputs',
- '_feed_input_names',
- '_feed_input_shapes',
- 'optimizer',
- ]
- for name in attributes_to_cache:
- attributes_cache[name] = getattr(model, name)
- model._original_attributes_cache = data_structures.NoDependency(
- attributes_cache)
- # Reset built state
- model.built = False
- model.inputs = None
- model.outputs = None
-
-
-def _in_place_subclassed_model_state_restoration(model):
- """Restores the original state of a model after it was "reset".
-
- This undoes this action of `_in_place_subclassed_model_reset`.
- Args:
- model: Instance of a Keras model created via subclassing, on which
- `_in_place_subclassed_model_reset` was previously called.
- """
- assert not model._is_graph_network
- # Restore layers and build attributes
- if (hasattr(model, '_original_attributes_cache') and
- model._original_attributes_cache is not None):
- # Models have sticky attribute assignment, so we want to be careful to add
- # back the previous attributes and track Layers by their original names
- # without adding dependencies on "utility" attributes which Models exempt
- # when they're constructed.
- model._layers = data_structures.NoDependency([])
- for name, value in model._original_attributes_cache.items():
- if not isinstance(value, checkpointable.CheckpointableBase):
- # If this value is not already checkpointable, it's probably that way
- # for a reason; we don't want to start tracking data structures that the
- # original Model didn't.
- value = data_structures.NoDependency(value)
- setattr(model, name, value)
- model._original_attributes_cache = None
- else:
- # Restore to the state of a never-called model.
- model.built = False
- model.inputs = None
- model.outputs = None
+ def _to_ordered_tensor_list(obj, key_order, obj_name, order_name):
+ """Convert obj to an ordered list of tensors.
+
+ Args:
+ obj: List, dict, or single tensor. May be `None`.
+ key_order: List of strings with the order to return (used if obj is a
+ dict).
+ obj_name: String name of object (e.g. "features" or "labels")
+ order_name: String name of the key order (e.g. "inputs" or "outputs")
+
+ Returns:
+ List of tensors, or `None`
+
+ Raises:
+ KeyError: If obj has invalid keys.
+ """
+ if obj is None:
+ return None
+ elif isinstance(obj, (list, tuple)):
+ return [_convert_tensor(x) for x in obj]
+ elif isinstance(obj, dict):
+ # Ensure that the obj keys and keys in key_order are exactly the same.
+ different_keys = set(obj.keys()) ^ set(key_order)
+
+ if different_keys:
+ raise KeyError(
+ 'The dictionary passed into {obj_name} does not have the expected '
+ '{order_name} keys defined in the keras model.'
+ '\n\tExpected keys: {order_keys}'
+ '\n\t{obj_name} keys: {obj_keys}'
+ '\n\tDifference: {different_keys}'.format(
+ order_name=order_name, order_keys=set(key_order),
+ obj_name=obj_name, obj_keys=set(obj.keys()),
+ different_keys=different_keys))
+
+ return [_convert_tensor(obj[key]) for key in key_order]
+ else: # Assume obj is a tensor.
+ return [_convert_tensor(obj)]
+
+ input_names = None
+ output_names = None
+ if isinstance(features, dict):
+ input_names = (
+ keras_model.input_names if keras_model._is_graph_network else
+ ['input_%d' % i for i in range(1, len(features) + 1)])
+ if isinstance(labels, dict):
+ output_names = (
+ keras_model.output_names if keras_model._is_graph_network else
+ ['output_%d' % i for i in range(1, len(labels) + 1)])
+
+ input_tensors = _to_ordered_tensor_list(
+ features, input_names, 'features', 'inputs')
+ target_tensors = _to_ordered_tensor_list(
+ labels, output_names, 'labels', 'outputs')
+
+ return input_tensors, target_tensors
def _clone_and_build_model(mode,
@@ -289,61 +178,14 @@ def _clone_and_build_model(mode,
Returns:
The newly built model.
"""
- # Set to True during training, False for inference.
+ # Set to True during training, False for inference or testing.
K.set_learning_phase(mode == model_fn_lib.ModeKeys.TRAIN)
-
- # Get list of inputs.
- if features is None:
- input_tensors = None
- else:
- input_tensors = _create_ordered_io(keras_model,
- estimator_io=features,
- is_input=True)
- # Get list of outputs.
- if labels is None:
- target_tensors = None
- elif isinstance(labels, dict):
- target_tensors = _create_ordered_io(keras_model,
- estimator_io=labels,
- is_input=False)
- else:
- target_tensors = [
- _convert_tensor(labels)
- ]
-
- if keras_model._is_graph_network:
- if custom_objects:
- with CustomObjectScope(custom_objects):
- model = models.clone_model(keras_model, input_tensors=input_tensors)
- else:
- model = models.clone_model(keras_model, input_tensors=input_tensors)
- else:
- model = keras_model
- _in_place_subclassed_model_reset(model)
- if input_tensors is not None:
- model._set_inputs(input_tensors)
-
- # Compile/Build model
- if mode is model_fn_lib.ModeKeys.PREDICT:
- if isinstance(model, models.Sequential):
- model.build()
- else:
- if isinstance(keras_model.optimizer, optimizers.TFOptimizer):
- optimizer = keras_model.optimizer
- else:
- optimizer_config = keras_model.optimizer.get_config()
- optimizer = keras_model.optimizer.__class__.from_config(optimizer_config)
- optimizer.iterations = training_util.get_or_create_global_step()
-
- model.compile(
- optimizer,
- keras_model.loss,
- metrics=keras_model.metrics,
- loss_weights=keras_model.loss_weights,
- sample_weight_mode=keras_model.sample_weight_mode,
- weighted_metrics=keras_model.weighted_metrics,
- target_tensors=target_tensors)
- return model
+ input_tensors, target_tensors = _convert_estimator_io_to_keras(
+ keras_model, features, labels)
+ return models.clone_and_build_model(
+ keras_model, input_tensors, target_tensors, custom_objects,
+ compile_clone=(mode != model_fn_lib.ModeKeys.PREDICT),
+ in_place_reset=(not keras_model._is_graph_network))
def _create_keras_model_fn(keras_model, custom_objects=None):
@@ -361,7 +203,7 @@ def _create_keras_model_fn(keras_model, custom_objects=None):
"""model_fn for keras Estimator."""
# Raise an error when users use DistributionStrategy with native Keras
# optimizers. Currently we only support native TensorFlow optimizers.
- if distribute_lib.has_distribution_strategy() and \
+ if distribution_strategy_context.has_distribution_strategy() and \
not isinstance(keras_model.optimizer,
(tf_optimizer_module.Optimizer, optimizers.TFOptimizer)):
raise ValueError('Only TensorFlow native optimizers are supported with '
@@ -373,7 +215,7 @@ def _create_keras_model_fn(keras_model, custom_objects=None):
# We need to make sure that the output names of the last layer in the model
# is the same for each of the cloned models. This is required for mirrored
# strategy when we call regroup.
- if distribute_lib.has_distribution_strategy():
+ if distribution_strategy_context.has_distribution_strategy():
for name in model.output_names:
name = re.compile(r'_\d$').sub('', name)
model_output_names.append(name)
@@ -396,7 +238,7 @@ def _create_keras_model_fn(keras_model, custom_objects=None):
loss = model.total_loss
if model.metrics:
- # TODO(fchollet): support stateful metrics
+ # TODO(psv/fchollet): support stateful metrics
eval_metric_ops = {}
# When each metric maps to an output
if isinstance(model.metrics, dict):
@@ -423,7 +265,7 @@ def _create_keras_model_fn(keras_model, custom_objects=None):
if not model._is_graph_network:
# Reset model state to original state,
# to avoid `model_fn` being destructive for the initial model argument.
- _in_place_subclassed_model_state_restoration(keras_model)
+ models.in_place_subclassed_model_state_restoration(keras_model)
return model_fn_lib.EstimatorSpec(
mode=mode,
predictions=predictions,
@@ -487,8 +329,9 @@ def model_to_estimator(keras_model=None,
config=None):
"""Constructs an `Estimator` instance from given keras model.
- For usage example, please see
- @{$guide/estimators$creating_estimators_from_keras_models}.
+ For usage example, please see:
+ [Creating estimators from Keras
+ Models](https://tensorflow.org/guide/estimators#model_to_estimator).
Args:
keras_model: A compiled Keras model object. This argument is mutually
diff --git a/tensorflow/python/estimator/keras_test.py b/tensorflow/python/estimator/keras_test.py
index 332e385726..290c4604ce 100644
--- a/tensorflow/python/estimator/keras_test.py
+++ b/tensorflow/python/estimator/keras_test.py
@@ -184,12 +184,14 @@ class TestKerasEstimator(test_util.TensorFlowTestCase):
gfile.MakeDirs(self._base_dir)
self._config = run_config_lib.RunConfig(
tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir)
+ super(TestKerasEstimator, self).setUp()
def tearDown(self):
# Make sure nothing is stuck in limbo.
writer_cache.FileWriterCache.clear()
if os.path.isdir(self._base_dir):
gfile.DeleteRecursively(self._base_dir)
+ super(TestKerasEstimator, self).tearDown()
def test_train(self):
for model_type in ['sequential', 'functional']:
@@ -511,19 +513,19 @@ class TestKerasEstimator(test_util.TensorFlowTestCase):
input_dict = {'input_1': x_train}
output_dict = {'invalid_output_name': y_train}
return input_dict, output_dict
-
model = simple_functional_model()
model.compile(
loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
with self.test_session():
est_keras = keras_lib.model_to_estimator(
keras_model=model, config=self._config)
-
with self.test_session():
- with self.assertRaises(ValueError):
+ with self.assertRaisesRegexp(KeyError,
+ 'Difference: .*invalid_input_name'):
est_keras.train(input_fn=invald_input_name_input_fn, steps=100)
- with self.assertRaises(ValueError):
+ with self.assertRaisesRegexp(KeyError,
+ 'Difference: .*invalid_output_name'):
est_keras.train(input_fn=invald_output_name_input_fn, steps=100)
def test_custom_objects(self):
diff --git a/tensorflow/python/estimator/model_fn.py b/tensorflow/python/estimator/model_fn.py
index 9db9ccd01d..007970bef7 100644
--- a/tensorflow/python/estimator/model_fn.py
+++ b/tensorflow/python/estimator/model_fn.py
@@ -141,7 +141,7 @@ class EstimatorSpec(
prediction.
predictions: Predictions `Tensor` or dict of `Tensor`.
loss: Training loss `Tensor`. Must be either scalar, or with shape `[1]`.
- train_op: Op for the training step.
+ train_op: Op to run one training step.
eval_metric_ops: Dict of metric results keyed by name. The values of the
dict are the results of calling a metric function, namely a
`(metric_tensor, update_op)` tuple. `metric_tensor` should be evaluated
diff --git a/tensorflow/python/estimator/training.py b/tensorflow/python/estimator/training.py
index a01b2300dd..e6bd263c80 100644
--- a/tensorflow/python/estimator/training.py
+++ b/tensorflow/python/estimator/training.py
@@ -129,8 +129,8 @@ class TrainSpec(
Args:
input_fn: A function that provides input data for training as minibatches.
- See @{$premade_estimators#create_input_functions} for more
- information. The function should construct and return one of
+ See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions)
+ for more information. The function should construct and return one of
the following:
* A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
tuple (features, labels) with same constraints as below.
@@ -193,8 +193,8 @@ class EvalSpec(
Args:
input_fn: A function that constructs the input data for evaluation.
- See @{$premade_estimators#create_input_functions} for more
- information. The function should construct and return one of
+ See [Premade Estimators](https://tensorflow.org/api_guides/premade_estimators#create_input_functions)
+ for more information. The function should construct and return one of
the following:
* A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
tuple (features, labels) with same constraints as below.
@@ -323,6 +323,10 @@ def train_and_evaluate(estimator, train_spec, eval_spec):
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
```
+ Note that in current implementation `estimator.evaluate` will be called
+ multiple times. This means that evaluation graph (including eval_input_fn)
+ will be re-created for each `evaluate` call. `estimator.train` will be called
+ only once.
Example of distributed training:
@@ -833,6 +837,13 @@ class _TrainingExecutor(object):
if difference > 0:
logging.info('Waiting %f secs before starting next eval run.', difference)
time.sleep(difference)
+ elif (throttle_secs == 0 and
+ eval_result.status != _EvalStatus.EVALUATED):
+ # Prints a user-actionable warning to avoid unnecessary load on evaluator.
+ logging.warning(
+ 'EvalSpec.throttle_secs is set as 0. This might overload the job '
+ 'before finding (next) new checkpoint. Please consider to increase '
+ 'it.')
return (eval_result, should_early_stop)
diff --git a/tensorflow/python/estimator/training_test.py b/tensorflow/python/estimator/training_test.py
index dc106c7d3b..7d46917a6f 100644
--- a/tensorflow/python/estimator/training_test.py
+++ b/tensorflow/python/estimator/training_test.py
@@ -83,6 +83,9 @@ _INVALID_EVAL_LISTENER_MSG = 'must have type `_ContinuousEvalListener`'
_INVALID_CONFIG_FOR_STD_SERVER_MSG = 'Could not start server; .*TF_CONFIG'
_INVALID_LOCAL_TASK_WITH_CLUSTER = '`task.type` in TF_CONFIG cannot be `local`'
_INVALID_TASK_TYPE = '`estimator.config` must have task_type set.'
+_INPROPER_THROTTL_SECS = (
+ 'EvalSpec.throttle_secs is set as 0.*Please consider to increase')
+
# The message should NOT have 'local' word as part of it. As (?!word) is looking
# ahead, so, the $ (ending) check is required; otherwise, it will match
# partially and return successuful.
@@ -1281,7 +1284,7 @@ class TrainingExecutorRunEvaluatorTest(test.TestCase):
]
eval_spec = training.EvalSpec(
- input_fn=lambda: 1, start_delay_secs=0, throttle_secs=0)
+ input_fn=lambda: 1, start_delay_secs=0, throttle_secs=2)
executor = training._TrainingExecutor(mock_est, mock_train_spec, eval_spec)
with test.mock.patch.object(logging, 'warning') as mock_log:
@@ -1295,6 +1298,34 @@ class TrainingExecutorRunEvaluatorTest(test.TestCase):
# successuful evaluation)
self.assertEqual(2, mock_log.call_count)
+ def test_warning_if_throttle_secs_is_zero(self):
+ training_max_step = 200
+ mock_est = test.mock.Mock(spec=estimator_lib.Estimator)
+ mock_est.evaluate.side_effect = [
+ {_GLOBAL_STEP_KEY: training_max_step}
+ ]
+ mock_train_spec = test.mock.Mock(spec=training.TrainSpec)
+ mock_train_spec.max_steps = training_max_step
+
+ self._set_up_mock_est_to_train_and_evaluate_once(mock_est, mock_train_spec)
+
+ # We need to make the first one invalid, so it will check the
+ # throttle_secs=0.
+ mock_est.latest_checkpoint.side_effect = [None, 'path']
+
+ eval_spec = training.EvalSpec(
+ input_fn=lambda: 1, start_delay_secs=0, throttle_secs=0)
+
+ executor = training._TrainingExecutor(mock_est, mock_train_spec, eval_spec)
+ with test.mock.patch.object(logging, 'warning') as mock_log:
+ executor.run_evaluator()
+
+ # First ckpt is invalid.
+ self.assertEqual(2, mock_est.latest_checkpoint.call_count)
+ self.assertEqual(1, mock_est.evaluate.call_count)
+
+ self.assertRegexpMatches(str(mock_log.call_args), _INPROPER_THROTTL_SECS)
+
def test_continuous_eval_listener_eval_result(self):
training_max_step = 200
mock_est = test.mock.Mock(spec=estimator_lib.Estimator)
diff --git a/tensorflow/python/feature_column/BUILD b/tensorflow/python/feature_column/BUILD
index 80707030e6..1017d4ba47 100644
--- a/tensorflow/python/feature_column/BUILD
+++ b/tensorflow/python/feature_column/BUILD
@@ -122,7 +122,6 @@ py_test(
"//tensorflow/python:variables",
"//tensorflow/python/eager:backprop",
"//tensorflow/python/eager:context",
- "//tensorflow/python/estimator:numpy_io",
],
)
diff --git a/tensorflow/python/feature_column/feature_column.py b/tensorflow/python/feature_column/feature_column.py
index d091d2fe0a..2246d2f3e9 100644
--- a/tensorflow/python/feature_column/feature_column.py
+++ b/tensorflow/python/feature_column/feature_column.py
@@ -16,7 +16,7 @@
FeatureColumns provide a high level abstraction for ingesting and representing
features. FeatureColumns are also the primary way of encoding features for
-canned @{tf.estimator.Estimator}s.
+canned `tf.estimator.Estimator`s.
When using FeatureColumns with `Estimators`, the type of feature column you
should choose depends on (1) the feature type and (2) the model type.
@@ -1936,7 +1936,7 @@ class _FeatureColumn(object):
It is used for get_parsing_spec for `tf.parse_example`. Returned spec is a
dict from keys ('string') to `VarLenFeature`, `FixedLenFeature`, and other
- supported objects. Please check documentation of @{tf.parse_example} for all
+ supported objects. Please check documentation of `tf.parse_example` for all
supported spec objects.
Let's say a Feature column depends on raw feature ('raw') and another
@@ -1995,7 +1995,7 @@ class _DenseColumn(_FeatureColumn):
weight_collections: List of graph collections to which Variables (if any
will be created) are added.
trainable: If `True` also add variables to the graph collection
- `GraphKeys.TRAINABLE_VARIABLES` (see @{tf.Variable}).
+ `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
Returns:
`Tensor` of shape [batch_size] + `_variable_shape`.
@@ -2062,7 +2062,7 @@ class _CategoricalColumn(_FeatureColumn):
WARNING: Do not subclass this layer unless you know what you are doing:
the API is subject to future changes.
- A categorical feature typically handled with a @{tf.SparseTensor} of IDs.
+ A categorical feature typically handled with a `tf.SparseTensor` of IDs.
"""
__metaclass__ = abc.ABCMeta
@@ -2097,7 +2097,7 @@ class _CategoricalColumn(_FeatureColumn):
weight_collections: List of graph collections to which variables (if any
will be created) are added.
trainable: If `True` also add variables to the graph collection
- `GraphKeys.TRAINABLE_VARIABLES` (see @{tf.get_variable}).
+ `GraphKeys.TRAINABLE_VARIABLES` (see `tf.get_variable`).
"""
pass
diff --git a/tensorflow/python/feature_column/feature_column_test.py b/tensorflow/python/feature_column/feature_column_test.py
index 5bb47bfa47..6be930be87 100644
--- a/tensorflow/python/feature_column/feature_column_test.py
+++ b/tensorflow/python/feature_column/feature_column_test.py
@@ -30,7 +30,6 @@ from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.client import session
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
-from tensorflow.python.estimator.inputs import numpy_io
from tensorflow.python.feature_column import feature_column_lib as fc
from tensorflow.python.feature_column.feature_column import _CategoricalColumn
from tensorflow.python.feature_column.feature_column import _DenseColumn
@@ -52,8 +51,6 @@ from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables as variables_lib
from tensorflow.python.platform import test
-from tensorflow.python.training import coordinator
-from tensorflow.python.training import queue_runner_impl
def _initialized_session(config=None):
@@ -1803,39 +1800,6 @@ class LinearModelTest(test.TestCase):
features['price2']: [[1.], [5.]],
})
- def test_with_numpy_input_fn(self):
- price = fc.numeric_column('price')
- price_buckets = fc.bucketized_column(price, boundaries=[0., 10., 100.,])
- body_style = fc.categorical_column_with_vocabulary_list(
- 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
-
- input_fn = numpy_io.numpy_input_fn(
- x={
- 'price': np.array([-1., 2., 13., 104.]),
- 'body-style': np.array(['sedan', 'hardtop', 'wagon', 'sedan']),
- },
- batch_size=2,
- shuffle=False)
- features = input_fn()
- net = fc.linear_model(features, [price_buckets, body_style])
- # self.assertEqual(1 + 3 + 5, net.shape[1])
- with _initialized_session() as sess:
- coord = coordinator.Coordinator()
- threads = queue_runner_impl.start_queue_runners(sess, coord=coord)
-
- bias = get_linear_model_bias()
- price_buckets_var = get_linear_model_column_var(price_buckets)
- body_style_var = get_linear_model_column_var(body_style)
-
- sess.run(price_buckets_var.assign([[10.], [100.], [1000.], [10000.]]))
- sess.run(body_style_var.assign([[-10.], [-100.], [-1000.]]))
- sess.run(bias.assign([5.]))
-
- self.assertAllClose([[10 - 1000 + 5.], [100 - 10 + 5.]], sess.run(net))
-
- coord.request_stop()
- coord.join(threads)
-
def test_with_1d_sparse_tensor(self):
price = fc.numeric_column('price')
price_buckets = fc.bucketized_column(price, boundaries=[0., 10., 100.,])
@@ -2458,45 +2422,6 @@ class _LinearModelTest(test.TestCase):
features['price2']: [[1.], [5.]],
})
- def test_with_numpy_input_fn(self):
- price = fc.numeric_column('price')
- price_buckets = fc.bucketized_column(
- price, boundaries=[
- 0.,
- 10.,
- 100.,
- ])
- body_style = fc.categorical_column_with_vocabulary_list(
- 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
-
- input_fn = numpy_io.numpy_input_fn(
- x={
- 'price': np.array([-1., 2., 13., 104.]),
- 'body-style': np.array(['sedan', 'hardtop', 'wagon', 'sedan']),
- },
- batch_size=2,
- shuffle=False)
- features = input_fn()
- net = get_keras_linear_model_predictions(features,
- [price_buckets, body_style])
- # self.assertEqual(1 + 3 + 5, net.shape[1])
- with _initialized_session() as sess:
- coord = coordinator.Coordinator()
- threads = queue_runner_impl.start_queue_runners(sess, coord=coord)
-
- bias = get_linear_model_bias()
- price_buckets_var = get_linear_model_column_var(price_buckets)
- body_style_var = get_linear_model_column_var(body_style)
-
- sess.run(price_buckets_var.assign([[10.], [100.], [1000.], [10000.]]))
- sess.run(body_style_var.assign([[-10.], [-100.], [-1000.]]))
- sess.run(bias.assign([5.]))
-
- self.assertAllClose([[10 - 1000 + 5.], [100 - 10 + 5.]], sess.run(net))
-
- coord.request_stop()
- coord.join(threads)
-
def test_with_1d_sparse_tensor(self):
price = fc.numeric_column('price')
price_buckets = fc.bucketized_column(
@@ -3043,51 +2968,6 @@ class FunctionalInputLayerTest(test.TestCase):
['input_layer/aaa_bbb_shared_embedding/embedding_weights:0'],
[v.name for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)])
- def test_with_numpy_input_fn(self):
- embedding_values = (
- (1., 2., 3., 4., 5.), # id 0
- (6., 7., 8., 9., 10.), # id 1
- (11., 12., 13., 14., 15.) # id 2
- )
- def _initializer(shape, dtype, partition_info):
- del shape, dtype, partition_info
- return embedding_values
-
- # price has 1 dimension in input_layer
- price = fc.numeric_column('price')
- body_style = fc.categorical_column_with_vocabulary_list(
- 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan'])
- # one_hot_body_style has 3 dims in input_layer.
- one_hot_body_style = fc.indicator_column(body_style)
- # embedded_body_style has 5 dims in input_layer.
- embedded_body_style = fc.embedding_column(body_style, dimension=5,
- initializer=_initializer)
-
- input_fn = numpy_io.numpy_input_fn(
- x={
- 'price': np.array([11., 12., 13., 14.]),
- 'body-style': np.array(['sedan', 'hardtop', 'wagon', 'sedan']),
- },
- batch_size=2,
- shuffle=False)
- features = input_fn()
- net = fc.input_layer(features,
- [price, one_hot_body_style, embedded_body_style])
- self.assertEqual(1 + 3 + 5, net.shape[1])
- with _initialized_session() as sess:
- coord = coordinator.Coordinator()
- threads = queue_runner_impl.start_queue_runners(sess, coord=coord)
-
- # Each row is formed by concatenating `embedded_body_style`,
- # `one_hot_body_style`, and `price` in order.
- self.assertAllEqual(
- [[11., 12., 13., 14., 15., 0., 0., 1., 11.],
- [1., 2., 3., 4., 5., 1., 0., 0., 12]],
- sess.run(net))
-
- coord.request_stop()
- coord.join(threads)
-
def test_with_1d_sparse_tensor(self):
embedding_values = (
(1., 2., 3., 4., 5.), # id 0
diff --git a/tensorflow/python/feature_column/feature_column_v2.py b/tensorflow/python/feature_column/feature_column_v2.py
index b4dd23f58d..b6bf516286 100644
--- a/tensorflow/python/feature_column/feature_column_v2.py
+++ b/tensorflow/python/feature_column/feature_column_v2.py
@@ -16,7 +16,7 @@
FeatureColumns provide a high level abstraction for ingesting and representing
features. FeatureColumns are also the primary way of encoding features for
-canned @{tf.estimator.Estimator}s.
+canned `tf.estimator.Estimator`s.
When using FeatureColumns with `Estimators`, the type of feature column you
should choose depends on (1) the feature type and (2) the model type.
@@ -1904,7 +1904,7 @@ class FeatureColumn(object):
It is used for get_parsing_spec for `tf.parse_example`. Returned spec is a
dict from keys ('string') to `VarLenFeature`, `FixedLenFeature`, and other
- supported objects. Please check documentation of @{tf.parse_example} for all
+ supported objects. Please check documentation of `tf.parse_example` for all
supported spec objects.
Let's say a Feature column depends on raw feature ('raw') and another
@@ -2025,7 +2025,7 @@ def _create_dense_column_weighted_sum(column,
class CategoricalColumn(FeatureColumn):
"""Represents a categorical feature.
- A categorical feature typically handled with a @{tf.SparseTensor} of IDs.
+ A categorical feature typically handled with a `tf.SparseTensor` of IDs.
"""
__metaclass__ = abc.ABCMeta
diff --git a/tensorflow/python/framework/constant_op.py b/tensorflow/python/framework/constant_op.py
index b3eb57d067..eca34ac26e 100644
--- a/tensorflow/python/framework/constant_op.py
+++ b/tensorflow/python/framework/constant_op.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""Operations that generate constants.
-See the @{$python/constant_op$constants guide}.
+See the [constants guide](https://tensorflow.org/api_guides/python/constant_op).
"""
# Must be separate from array_ops to avoid a cyclic dependency.
@@ -145,6 +145,17 @@ def constant(value, dtype=None, shape=None, name="Const", verify_shape=False):
[-1. -1. -1.]]
```
+ `tf.constant` differs from `tf.fill` in a few ways:
+
+ * `tf.constant` supports arbitrary constants, not just uniform scalar
+ Tensors like `tf.fill`.
+ * `tf.constant` creates a `Const` node in the computation graph with the
+ exact value at graph construction time. On the other hand, `tf.fill`
+ creates an Op in the graph that is expanded at runtime.
+ * Because `tf.constant` only embeds constant values in the graph, it does
+ not support dynamic shapes based on other runtime Tensors, whereas
+ `tf.fill` does.
+
Args:
value: A constant value (or list) of output type `dtype`.
diff --git a/tensorflow/python/framework/errors_impl.py b/tensorflow/python/framework/errors_impl.py
index 84106c32c6..9f973de400 100644
--- a/tensorflow/python/framework/errors_impl.py
+++ b/tensorflow/python/framework/errors_impl.py
@@ -63,9 +63,9 @@ class OpError(Exception):
*N.B.* If the failed op was synthesized at runtime, e.g. a `Send`
or `Recv` op, there will be no corresponding
- @{tf.Operation}
+ `tf.Operation`
object. In that case, this will return `None`, and you should
- instead use the @{tf.OpError.node_def} to
+ instead use the `tf.OpError.node_def` to
discover information about the op.
Returns:
@@ -181,10 +181,10 @@ class CancelledError(OpError):
"""Raised when an operation or step is cancelled.
For example, a long-running operation (e.g.
- @{tf.QueueBase.enqueue} may be
+ `tf.QueueBase.enqueue` may be
cancelled by running another operation (e.g.
- @{tf.QueueBase.close},
- or by @{tf.Session.close}.
+ `tf.QueueBase.close`,
+ or by `tf.Session.close`.
A step that is running such a long-running operation will fail by raising
`CancelledError`.
@@ -221,9 +221,9 @@ class InvalidArgumentError(OpError):
This may occur, for example, if an operation is receives an input
tensor that has an invalid value or shape. For example, the
- @{tf.matmul} op will raise this
+ `tf.matmul` op will raise this
error if it receives an input that is not a matrix, and the
- @{tf.reshape} op will raise
+ `tf.reshape` op will raise
this error if the new shape does not match the number of elements in the input
tensor.
@@ -256,7 +256,7 @@ class NotFoundError(OpError):
"""Raised when a requested entity (e.g., a file or directory) was not found.
For example, running the
- @{tf.WholeFileReader.read}
+ `tf.WholeFileReader.read`
operation could raise `NotFoundError` if it receives the name of a file that
does not exist.
@@ -273,7 +273,7 @@ class AlreadyExistsError(OpError):
"""Raised when an entity that we attempted to create already exists.
For example, running an operation that saves a file
- (e.g. @{tf.train.Saver.save})
+ (e.g. `tf.train.Saver.save`)
could potentially raise this exception if an explicit filename for an
existing file was passed.
@@ -291,7 +291,7 @@ class PermissionDeniedError(OpError):
"""Raised when the caller does not have permission to run an operation.
For example, running the
- @{tf.WholeFileReader.read}
+ `tf.WholeFileReader.read`
operation could raise `PermissionDeniedError` if it receives the name of a
file for which the user does not have the read file permission.
@@ -340,7 +340,7 @@ class FailedPreconditionError(OpError):
"""Operation was rejected because the system is not in a state to execute it.
This exception is most commonly raised when running an operation
- that reads a @{tf.Variable}
+ that reads a `tf.Variable`
before it has been initialized.
@@__init__
@@ -357,9 +357,9 @@ class AbortedError(OpError):
"""The operation was aborted, typically due to a concurrent action.
For example, running a
- @{tf.QueueBase.enqueue}
+ `tf.QueueBase.enqueue`
operation may raise `AbortedError` if a
- @{tf.QueueBase.close} operation
+ `tf.QueueBase.close` operation
previously ran.
@@__init__
@@ -375,9 +375,9 @@ class OutOfRangeError(OpError):
"""Raised when an operation iterates past the valid input range.
This exception is raised in "end-of-file" conditions, such as when a
- @{tf.QueueBase.dequeue}
+ `tf.QueueBase.dequeue`
operation is blocked on an empty queue, and a
- @{tf.QueueBase.close}
+ `tf.QueueBase.close`
operation executes.
@@__init__
@@ -395,7 +395,7 @@ class UnimplementedError(OpError):
Some operations may raise this error when passed otherwise-valid
arguments that it does not currently support. For example, running
- the @{tf.nn.max_pool} operation
+ the `tf.nn.max_pool` operation
would raise this error if pooling was requested on the batch dimension,
because this is not yet supported.
@@ -443,7 +443,7 @@ class DataLossError(OpError):
"""Raised when unrecoverable data loss or corruption is encountered.
For example, this may be raised by running a
- @{tf.WholeFileReader.read}
+ `tf.WholeFileReader.read`
operation, if the file is truncated while it is being read.
@@__init__
@@ -475,8 +475,8 @@ _CODE_TO_EXCEPTION_CLASS = {
c_api.PyExceptionRegistry_Init(_CODE_TO_EXCEPTION_CLASS)
-_EXCEPTION_CLASS_TO_CODE = dict((
- (class_, code) for (code, class_) in _CODE_TO_EXCEPTION_CLASS.items()))
+_EXCEPTION_CLASS_TO_CODE = {
+ class_: code for code, class_ in _CODE_TO_EXCEPTION_CLASS.items()}
@tf_export("errors.exception_type_from_error_code")
diff --git a/tensorflow/python/framework/function.py b/tensorflow/python/framework/function.py
index 12bf03c5fa..f47c0d8a5e 100644
--- a/tensorflow/python/framework/function.py
+++ b/tensorflow/python/framework/function.py
@@ -665,7 +665,7 @@ class _FuncGraph(ops.Graph):
def container(self, container_name):
"""Returns a context manager that specifies the resource container to use.
- Overridden from @{tf.Graph} to update both the init_scope container
+ Overridden from `tf.Graph` to update both the init_scope container
and the present inner container. This is necessary to make sure setting
containers applies correctly both to created variables and to stateful
ops.
diff --git a/tensorflow/python/framework/importer.py b/tensorflow/python/framework/importer.py
index 687bfebd43..e48e67c8a1 100644
--- a/tensorflow/python/framework/importer.py
+++ b/tensorflow/python/framework/importer.py
@@ -344,9 +344,9 @@ def import_graph_def(graph_def,
This function provides a way to import a serialized TensorFlow
[`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
protocol buffer, and extract individual objects in the `GraphDef` as
- @{tf.Tensor} and @{tf.Operation} objects. Once extracted,
+ `tf.Tensor` and `tf.Operation` objects. Once extracted,
these objects are placed into the current default `Graph`. See
- @{tf.Graph.as_graph_def} for a way to create a `GraphDef`
+ `tf.Graph.as_graph_def` for a way to create a `GraphDef`
proto.
Args:
diff --git a/tensorflow/python/framework/ops.py b/tensorflow/python/framework/ops.py
index ed0bf1afe0..21eb306865 100644
--- a/tensorflow/python/framework/ops.py
+++ b/tensorflow/python/framework/ops.py
@@ -229,7 +229,7 @@ class Tensor(_TensorLike):
A `Tensor` is a symbolic handle to one of the outputs of an
`Operation`. It does not hold the values of that operation's output,
but instead provides a means of computing those values in a
- TensorFlow @{tf.Session}.
+ TensorFlow `tf.Session`.
This class has two primary purposes:
@@ -240,7 +240,7 @@ class Tensor(_TensorLike):
2. After the graph has been launched in a session, the value of the
`Tensor` can be computed by passing it to
- @{tf.Session.run}.
+ `tf.Session.run`.
`t.eval()` is a shortcut for calling
`tf.get_default_session().run(t)`.
@@ -365,7 +365,7 @@ class Tensor(_TensorLike):
The shape is computed using shape inference functions that are
registered in the Op for each `Operation`. See
- @{tf.TensorShape}
+ `tf.TensorShape`
for more details of what a shape represents.
The inferred shape of a tensor is used to provide shape
@@ -695,7 +695,7 @@ class Tensor(_TensorLike):
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
- See @{tf.Session.run} for a
+ See `tf.Session.run` for a
description of the valid feed values.
session: (Optional.) The `Session` to be used to evaluate this tensor. If
none, the default session will be used.
@@ -1455,10 +1455,10 @@ class IndexedSlices(_TensorLike):
The `IndexedSlices` class is used principally in the definition of
gradients for operations that have sparse gradients
- (e.g. @{tf.gather}).
+ (e.g. `tf.gather`).
Contrast this representation with
- @{tf.SparseTensor},
+ `tf.SparseTensor`,
which uses multi-dimensional indices and scalar values.
"""
@@ -1619,8 +1619,8 @@ class Operation(object):
more `Tensor` objects as input, and produces zero or more `Tensor`
objects as output. Objects of type `Operation` are created by
calling a Python op constructor (such as
- @{tf.matmul})
- or @{tf.Graph.create_op}.
+ `tf.matmul`)
+ or `tf.Graph.create_op`.
For example `c = tf.matmul(a, b)` creates an `Operation` of type
"MatMul" that takes tensors `a` and `b` as input, and produces `c`
@@ -1628,7 +1628,7 @@ class Operation(object):
After the graph has been launched in a session, an `Operation` can
be executed by passing it to
- @{tf.Session.run}.
+ `tf.Session.run`.
`op.run()` is a shortcut for calling `tf.get_default_session().run(op)`.
"""
@@ -2338,7 +2338,7 @@ class Operation(object):
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
- See @{tf.Session.run}
+ See `tf.Session.run`
for a description of the valid feed values.
session: (Optional.) The `Session` to be used to run to this operation. If
none, the default session will be used.
@@ -2727,13 +2727,13 @@ class Graph(object):
"""A TensorFlow computation, represented as a dataflow graph.
A `Graph` contains a set of
- @{tf.Operation} objects,
+ `tf.Operation` objects,
which represent units of computation; and
- @{tf.Tensor} objects, which represent
+ `tf.Tensor` objects, which represent
the units of data that flow between operations.
A default `Graph` is always registered, and accessible by calling
- @{tf.get_default_graph}.
+ `tf.get_default_graph`.
To add an operation to the default graph, simply call one of the functions
that defines a new `Operation`:
@@ -2743,7 +2743,7 @@ class Graph(object):
```
Another typical usage involves the
- @{tf.Graph.as_default}
+ `tf.Graph.as_default`
context manager, which overrides the current default graph for the
lifetime of the context:
@@ -2764,7 +2764,7 @@ class Graph(object):
that are identified by name. For convenience when building a large
graph, collections can store groups of related objects: for
example, the `tf.Variable` uses a collection (named
- @{tf.GraphKeys.GLOBAL_VARIABLES}) for
+ `tf.GraphKeys.GLOBAL_VARIABLES`) for
all variables that are created during the construction of a graph. The caller
may define additional collections by specifying a new name.
"""
@@ -2941,7 +2941,7 @@ class Graph(object):
"""Returns a version number that increases as ops are added to the graph.
Note that this is unrelated to the
- @{tf.Graph.graph_def_versions}.
+ `tf.Graph.graph_def_versions`.
Returns:
An integer version that increases as ops are added to the graph.
@@ -2991,7 +2991,7 @@ class Graph(object):
After calling `g.finalize()`, no new operations can be added to
`g`. This method is used to ensure that no operations are added
to a graph when it is shared between multiple threads, for example
- when using a @{tf.train.QueueRunner}.
+ when using a `tf.train.QueueRunner`.
"""
self._finalized = True
@@ -3040,7 +3040,7 @@ class Graph(object):
"""Returns a serialized `GraphDef` representation of this graph.
The serialized `GraphDef` can be imported into another `Graph`
- (using @{tf.import_graph_def}) or used with the
+ (using `tf.import_graph_def`) or used with the
[C++ Session API](../../../../api_docs/cc/index.md).
This method is thread-safe.
@@ -3086,7 +3086,7 @@ class Graph(object):
"""Returns a serialized `GraphDef` representation of this graph.
The serialized `GraphDef` can be imported into another `Graph`
- (using @{tf.import_graph_def}) or used with the
+ (using `tf.import_graph_def`) or used with the
[C++ Session API](../../api_docs/cc/index.md).
This method is thread-safe.
@@ -4860,6 +4860,18 @@ class Graph(object):
else:
self._graph_control_dependencies_stack = control_dependencies
+ @property
+ def _distribution_strategy_stack(self):
+ """A stack to maintain distribution strategy context for each thread."""
+ if not hasattr(self._thread_local, "_distribution_strategy_stack"):
+ self._thread_local._distribution_strategy_stack = [] # pylint: disable=protected-access
+ return self._thread_local._distribution_strategy_stack # pylint: disable=protected-access
+
+ @_distribution_strategy_stack.setter
+ def _distribution_strategy_stack(self, _distribution_strategy_stack):
+ self._thread_local._distribution_strategy_stack = ( # pylint: disable=protected-access
+ _distribution_strategy_stack)
+
def _mutation_lock(self):
"""Returns a lock to guard code that creates & mutates ops.
@@ -4884,7 +4896,7 @@ def device(device_name_or_function):
"""Wrapper for `Graph.device()` using the default graph.
See
- @{tf.Graph.device}
+ `tf.Graph.device`
for more details.
Args:
@@ -4950,7 +4962,7 @@ def colocate_with(op, ignore_existing=False):
def control_dependencies(control_inputs):
"""Wrapper for `Graph.control_dependencies()` using the default graph.
- See @{tf.Graph.control_dependencies}
+ See `tf.Graph.control_dependencies`
for more details.
When eager execution is enabled, any callable object in the `control_inputs`
@@ -5316,7 +5328,7 @@ def enable_eager_execution(config=None,
Eager execution provides an imperative interface to TensorFlow. With eager
execution enabled, TensorFlow functions execute operations immediately (as
- opposed to adding to a graph to be executed later in a @{tf.Session}) and
+ opposed to adding to a graph to be executed later in a `tf.Session`) and
return concrete values (as opposed to symbolic references to a node in a
computational graph).
@@ -5336,9 +5348,9 @@ def enable_eager_execution(config=None,
both with and without eager execution).
Args:
- config: (Optional.) A @{tf.ConfigProto} to use to configure the environment
- in which operations are executed. Note that @{tf.ConfigProto} is also
- used to configure graph execution (via @{tf.Session}) and many options
+ config: (Optional.) A `tf.ConfigProto` to use to configure the environment
+ in which operations are executed. Note that `tf.ConfigProto` is also
+ used to configure graph execution (via `tf.Session`) and many options
within `tf.ConfigProto` are not implemented (or are irrelevant) when
eager execution is enabled.
device_policy: (Optional.) Policy controlling how operations requiring
@@ -5638,7 +5650,7 @@ class GraphKeys(object):
* `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared
across distributed environment (model variables are subset of these). See
- @{tf.global_variables}
+ `tf.global_variables`
for more details.
Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`,
and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.
@@ -5650,19 +5662,19 @@ class GraphKeys(object):
`tf.contrib.framework.model_variable` to add to this collection.
* `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will
be trained by an optimizer. See
- @{tf.trainable_variables}
+ `tf.trainable_variables`
for more details.
* `SUMMARIES`: the summary `Tensor` objects that have been created in the
graph. See
- @{tf.summary.merge_all}
+ `tf.summary.merge_all`
for more details.
* `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to
produce input for a computation. See
- @{tf.train.start_queue_runners}
+ `tf.train.start_queue_runners`
for more details.
* `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also
keep moving averages. See
- @{tf.moving_average_variables}
+ `tf.moving_average_variables`
for more details.
* `REGULARIZATION_LOSSES`: regularization losses collected during graph
construction.
@@ -5772,11 +5784,43 @@ class GraphKeys(object):
return cls.GLOBAL_VARIABLES
+def dismantle_graph(graph):
+ """Cleans up reference cycles from a `Graph`.
+
+ Helpful for making sure the garbage collector doesn't need to run after a
+ temporary `Graph` is no longer needed.
+
+ Args:
+ graph: A `Graph` object to destroy. Neither it nor any of its ops are usable
+ after this function runs.
+ """
+ # pylint: disable=protected-access
+ # OrderedDict, constructed on Graph creation, makes a simple reference loop
+ # and hides it in an __attribute in some Python versions. We don't need to
+ # throw an error if we can't find it, but if we do find it we can break the
+ # loop to avoid creating work for the garbage collector.
+ graph_operations = graph.get_operations()
+ problematic_cycle = graph._functions.__dict__.get("_OrderedDict__root", None)
+ # pylint: enable=protected-access
+ if problematic_cycle:
+ try:
+ del problematic_cycle[0][:]
+ except TypeError:
+ # This is probably not one of the problematic Python versions. Continue
+ # with the rest of our cleanup.
+ pass
+ # Now clean up Operation<->Graph reference cycles by clearing all of the
+ # attributes for the Graph and its ops.
+ for op in graph_operations:
+ op.__dict__ = {}
+ graph.__dict__ = {}
+
+
@tf_export("add_to_collection")
def add_to_collection(name, value):
"""Wrapper for `Graph.add_to_collection()` using the default graph.
- See @{tf.Graph.add_to_collection}
+ See `tf.Graph.add_to_collection`
for more details.
Args:
@@ -5795,7 +5839,7 @@ def add_to_collection(name, value):
def add_to_collections(names, value):
"""Wrapper for `Graph.add_to_collections()` using the default graph.
- See @{tf.Graph.add_to_collections}
+ See `tf.Graph.add_to_collections`
for more details.
Args:
@@ -5815,7 +5859,7 @@ def add_to_collections(names, value):
def get_collection_ref(key):
"""Wrapper for `Graph.get_collection_ref()` using the default graph.
- See @{tf.Graph.get_collection_ref}
+ See `tf.Graph.get_collection_ref`
for more details.
Args:
@@ -5839,7 +5883,7 @@ def get_collection_ref(key):
def get_collection(key, scope=None):
"""Wrapper for `Graph.get_collection()` using the default graph.
- See @{tf.Graph.get_collection}
+ See `tf.Graph.get_collection`
for more details.
Args:
@@ -5882,7 +5926,7 @@ class name_scope(object): # pylint: disable=invalid-name
This context manager validates that the given `values` are from the
same graph, makes that graph the default graph, and pushes a
name scope in that graph (see
- @{tf.Graph.name_scope}
+ `tf.Graph.name_scope`
for more details on that).
For example, to define a new Python op called `my_op`:
diff --git a/tensorflow/python/framework/python_op_gen.cc b/tensorflow/python/framework/python_op_gen.cc
index 76d4c2017c..2022fbcbaa 100644
--- a/tensorflow/python/framework/python_op_gen.cc
+++ b/tensorflow/python/framework/python_op_gen.cc
@@ -102,15 +102,6 @@ string TensorPBString(const TensorProto& pb) {
return strings::StrCat("\"\"\"", ProtoShortDebugString(pb), "\"\"\"");
}
-const ApiDef::Arg* FindInputArg(StringPiece name, const ApiDef& api_def) {
- for (int i = 0; i < api_def.in_arg_size(); ++i) {
- if (api_def.in_arg(i).name() == name) {
- return &api_def.in_arg(i);
- }
- }
- return nullptr;
-}
-
class GenEagerPythonOp : public python_op_gen_internal::GenPythonOp {
public:
GenEagerPythonOp(const OpDef& op_def, const ApiDef& api_def,
diff --git a/tensorflow/python/framework/python_op_gen_internal.cc b/tensorflow/python/framework/python_op_gen_internal.cc
index 031b4a384e..f2270342b0 100644
--- a/tensorflow/python/framework/python_op_gen_internal.cc
+++ b/tensorflow/python/framework/python_op_gen_internal.cc
@@ -483,15 +483,6 @@ const ApiDef::Attr* FindAttr(StringPiece name, const ApiDef& api_def) {
return nullptr;
}
-const ApiDef::Arg* FindInputArg(StringPiece name, const ApiDef& api_def) {
- for (int i = 0; i < api_def.in_arg_size(); ++i) {
- if (api_def.in_arg(i).name() == name) {
- return &api_def.in_arg(i);
- }
- }
- return nullptr;
-}
-
GenPythonOp::GenPythonOp(const OpDef& op_def, const ApiDef& api_def,
const string& function_name)
: op_def_(op_def),
diff --git a/tensorflow/python/framework/random_seed.py b/tensorflow/python/framework/random_seed.py
index b724432e00..2f9504889a 100644
--- a/tensorflow/python/framework/random_seed.py
+++ b/tensorflow/python/framework/random_seed.py
@@ -43,7 +43,7 @@ def get_seed(op_seed):
graph, or for only specific operations.
For details on how the graph-level seed interacts with op seeds, see
- @{tf.set_random_seed}.
+ `tf.set_random_seed`.
Args:
op_seed: integer.
diff --git a/tensorflow/python/framework/sparse_tensor.py b/tensorflow/python/framework/sparse_tensor.py
index 6a5c6468f7..a45581190f 100644
--- a/tensorflow/python/framework/sparse_tensor.py
+++ b/tensorflow/python/framework/sparse_tensor.py
@@ -205,7 +205,7 @@ class SparseTensor(_TensorLike):
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
- See @{tf.Session.run} for a
+ See `tf.Session.run` for a
description of the valid feed values.
session: (Optional.) The `Session` to be used to evaluate this sparse
tensor. If none, the default session will be used.
diff --git a/tensorflow/python/framework/tensor_shape.py b/tensorflow/python/framework/tensor_shape.py
index c9be3d5005..11b681d544 100644
--- a/tensorflow/python/framework/tensor_shape.py
+++ b/tensorflow/python/framework/tensor_shape.py
@@ -498,9 +498,10 @@ class TensorShape(object):
If a tensor is produced by an operation of type `"Foo"`, its shape
may be inferred if there is a registered shape function for
- `"Foo"`. See @{$adding_an_op#shape-functions-in-c$`Shape functions in C++`}
+ `"Foo"`. See [Shape
+ functions](https://tensorflow.org/extend/adding_an_op#shape_functions_in_c)
for details of shape functions and how to register them. Alternatively,
- the shape may be set explicitly using @{tf.Tensor.set_shape}.
+ the shape may be set explicitly using `tf.Tensor.set_shape`.
"""
def __init__(self, dims):
diff --git a/tensorflow/python/framework/test_util.py b/tensorflow/python/framework/test_util.py
index 764e8bfacb..d690f08d88 100644
--- a/tensorflow/python/framework/test_util.py
+++ b/tensorflow/python/framework/test_util.py
@@ -369,6 +369,7 @@ def enable_c_shapes(fn):
fn(*args, **kwargs)
finally:
ops._USE_C_SHAPES = prev_value
+
# pylint: enable=protected-access
return wrapper
@@ -418,7 +419,8 @@ def assert_no_new_pyobjects_executing_eagerly(f):
previous_count = len(gc.get_objects())
collection_sizes_before = {
collection: len(ops.get_collection(collection))
- for collection in ops.get_default_graph().collections}
+ for collection in ops.get_default_graph().collections
+ }
for _ in range(3):
f(self, **kwargs)
# Note that gc.get_objects misses anything that isn't subject to garbage
@@ -430,8 +432,8 @@ def assert_no_new_pyobjects_executing_eagerly(f):
if len(collection) > size_before:
raise AssertionError(
("Collection %s increased in size from "
- "%d to %d (current items %s).")
- % (collection_key, size_before, len(collection), collection))
+ "%d to %d (current items %s).") % (collection_key, size_before,
+ len(collection), collection))
# Make sure our collection checks don't show up as leaked memory by
# removing references to temporary variables.
del collection
@@ -446,8 +448,8 @@ def assert_no_new_pyobjects_executing_eagerly(f):
# Using plain assert because not all classes using this decorator
# have assertLessEqual
assert new_count <= previous_count, (
- "new_count(%d) is not less than or equal to previous_count(%d)" % (
- new_count, previous_count))
+ "new_count(%d) is not less than or equal to previous_count(%d)" %
+ (new_count, previous_count))
gc.enable()
return decorator
@@ -547,10 +549,12 @@ def assert_no_garbage_created(f):
return "<%s %d>" % (obj.__class__.__name__, id(obj))
logging.error(" Object type: %s", _safe_object_str(obj))
- logging.error(" Referrer types: %s", ", ".join(
- [_safe_object_str(ref) for ref in gc.get_referrers(obj)]))
- logging.error(" Referent types: %s", ", ".join(
- [_safe_object_str(ref) for ref in gc.get_referents(obj)]))
+ logging.error(
+ " Referrer types: %s", ", ".join(
+ [_safe_object_str(ref) for ref in gc.get_referrers(obj)]))
+ logging.error(
+ " Referent types: %s", ", ".join(
+ [_safe_object_str(ref) for ref in gc.get_referents(obj)]))
logging.error(" Object attribute names: %s", dir(obj))
logging.error(" Object __str__:")
logging.error(obj)
@@ -629,9 +633,8 @@ def generate_combinations_with_testcase_name(**kwargs):
for combination in combinations:
assert isinstance(combination, OrderedDict)
name = "".join([
- "_{}_{}".format(
- "".join(filter(str.isalnum, key)),
- "".join(filter(str.isalnum, str(value))))
+ "_{}_{}".format("".join(filter(str.isalnum, key)), "".join(
+ filter(str.isalnum, str(value))))
for key, value in combination.items()
])
named_combinations.append(
@@ -659,10 +662,10 @@ def run_in_graph_and_eager_modes(func=None,
"""Execute the decorated test with and without enabling eager execution.
This function returns a decorator intended to be applied to test methods in
- a @{tf.test.TestCase} class. Doing so will cause the contents of the test
+ a `tf.test.TestCase` class. Doing so will cause the contents of the test
method to be executed twice - once normally, and once with eager execution
enabled. This allows unittests to confirm the equivalence between eager
- and graph execution (see @{tf.enable_eager_execution}).
+ and graph execution (see `tf.enable_eager_execution`).
For example, consider the following unittest:
@@ -736,15 +739,19 @@ def run_in_graph_and_eager_modes(func=None,
run_eagerly = assert_no_new_tensors(
assert_no_garbage_created(run_eagerly))
- with context.eager_mode():
+ if reset_test:
+ # This decorator runs the wrapped test twice.
+ # Reset the test environment between runs.
+ self.tearDown()
+ self._tempdir = None
+ # Create a new graph for the eagerly executed version of this test for
+ # better isolation.
+ graph_for_eager_test = ops.Graph()
+ with graph_for_eager_test.as_default(), context.eager_mode():
if reset_test:
- # This decorator runs the wrapped test twice.
- # Reset the test environment between runs.
- self.tearDown()
- self._tempdir = None
self.setUp()
-
run_eagerly(self, **kwargs)
+ ops.dismantle_graph(graph_for_eager_test)
return decorated
@@ -967,21 +974,64 @@ class TensorFlowTestCase(googletest.TestCase):
# pylint: disable=g-doc-return-or-yield
@contextlib.contextmanager
- def test_session(self,
- graph=None,
- config=None,
- use_gpu=False,
- force_gpu=False):
+ def session(self, graph=None, config=None, use_gpu=False, force_gpu=False):
"""Returns a TensorFlow Session for use in executing tests.
- This method should be used for all functional tests.
+ Note that this will set this session and the graph as global defaults.
- This method behaves different than session.Session: for performance reasons
- `test_session` will by default (if `graph` is None) reuse the same session
- across tests. This means you may want to either call the function
- `reset_default_graph()` before tests, or if creating an explicit new graph,
- pass it here (simply setting it with `as_default()` won't do it), which will
- trigger the creation of a new session.
+ Use the `use_gpu` and `force_gpu` options to control where ops are run. If
+ `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
+ `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
+ possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to
+ the CPU.
+
+ Example:
+ ```python
+ class MyOperatorTest(test_util.TensorFlowTestCase):
+ def testMyOperator(self):
+ with self.session(use_gpu=True):
+ valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
+ result = MyOperator(valid_input).eval()
+ self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
+ invalid_input = [-1.0, 2.0, 7.0]
+ with self.assertRaisesOpError("negative input not supported"):
+ MyOperator(invalid_input).eval()
+ ```
+
+ Args:
+ graph: Optional graph to use during the returned session.
+ config: An optional config_pb2.ConfigProto to use to configure the
+ session.
+ use_gpu: If True, attempt to run as many ops as possible on GPU.
+ force_gpu: If True, pin all ops to `/device:GPU:0`.
+
+ Yields:
+ A Session object that should be used as a context manager to surround
+ the graph building and execution code in a test case.
+ """
+ if context.executing_eagerly():
+ yield None
+ else:
+ sess = self._create_session(graph, config, use_gpu, force_gpu)
+ with self._constrain_devices_and_set_default(
+ sess, use_gpu, force_gpu) as constrained_sess:
+ # We need to do this to make sure the session closes, otherwise, even
+ # if the user does with self.session():, it will not close the session.
+ with constrained_sess:
+ yield constrained_sess
+
+ @contextlib.contextmanager
+ def cached_session(self,
+ graph=None,
+ config=None,
+ use_gpu=False,
+ force_gpu=False):
+ """Returns a TensorFlow Session for use in executing tests.
+
+ This method behaves differently than self.session(): for performance reasons
+ `cached_session` will by default reuse the same session within the same
+ test. The session returned by this function will only be closed at the end
+ of the test (in the TearDown function).
Use the `use_gpu` and `force_gpu` options to control where ops are run. If
`force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
@@ -993,7 +1043,7 @@ class TensorFlowTestCase(googletest.TestCase):
```python
class MyOperatorTest(test_util.TensorFlowTestCase):
def testMyOperator(self):
- with self.test_session(use_gpu=True):
+ with self.cached_session(use_gpu=True) as sess:
valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
result = MyOperator(valid_input).eval()
self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
@@ -1009,74 +1059,39 @@ class TensorFlowTestCase(googletest.TestCase):
use_gpu: If True, attempt to run as many ops as possible on GPU.
force_gpu: If True, pin all ops to `/device:GPU:0`.
- Returns:
+ Yields:
A Session object that should be used as a context manager to surround
the graph building and execution code in a test case.
"""
+ if context.executing_eagerly():
+ yield None
+ else:
+ with self._get_cached_session(
+ graph, config, use_gpu, force_gpu,
+ crash_if_inconsistent_args=True) as sess:
+ yield sess
+
+ @contextlib.contextmanager
+ def test_session(self,
+ graph=None,
+ config=None,
+ use_gpu=False,
+ force_gpu=False):
+ """Use cached_session instead."""
if self.id().endswith(".test_session"):
self.skipTest("Not a test.")
- def prepare_config(config):
- """Returns a config for sessions.
-
- Args:
- config: An optional config_pb2.ConfigProto to use to configure the
- session.
- Returns:
- A config_pb2.ConfigProto object.
- """
- if config is None:
- config = config_pb2.ConfigProto()
- config.allow_soft_placement = not force_gpu
- config.gpu_options.per_process_gpu_memory_fraction = 0.3
- elif force_gpu and config.allow_soft_placement:
- config = config_pb2.ConfigProto().CopyFrom(config)
- config.allow_soft_placement = False
- # Don't perform optimizations for tests so we don't inadvertently run
- # gpu ops on cpu
- config.graph_options.optimizer_options.opt_level = -1
- config.graph_options.rewrite_options.constant_folding = (
- rewriter_config_pb2.RewriterConfig.OFF)
- config.graph_options.rewrite_options.arithmetic_optimization = (
- rewriter_config_pb2.RewriterConfig.OFF)
- return config
-
if context.executing_eagerly():
yield None
- elif graph is None:
- if self._cached_session is None:
- self._cached_session = session.Session(
- graph=None, config=prepare_config(config))
- sess = self._cached_session
- with sess.graph.as_default(), sess.as_default():
- if force_gpu:
- # Use the name of an actual device if one is detected, or '/device:GPU:0'
- # otherwise
- gpu_name = gpu_device_name()
- if not gpu_name:
- gpu_name = "/device:GPU:0"
- with sess.graph.device(gpu_name):
- yield sess
- elif use_gpu:
- yield sess
- else:
- with sess.graph.device("/cpu:0"):
- yield sess
else:
- with session.Session(graph=graph, config=prepare_config(config)) as sess:
- if force_gpu:
- # Use the name of an actual device if one is detected, or '/device:GPU:0'
- # otherwise
- gpu_name = gpu_device_name()
- if not gpu_name:
- gpu_name = "/device:GPU:0"
- with sess.graph.device(gpu_name):
- yield sess
- elif use_gpu:
+ if graph is None:
+ with self._get_cached_session(
+ graph, config, use_gpu, force_gpu,
+ crash_if_inconsistent_args=False) as sess:
+ yield sess
+ else:
+ with self.session(graph, config, use_gpu, force_gpu) as sess:
yield sess
- else:
- with sess.graph.device("/cpu:0"):
- yield sess
# pylint: enable=g-doc-return-or-yield
@@ -1202,9 +1217,10 @@ class TensorFlowTestCase(googletest.TestCase):
msg: An optional string message to append to the failure message.
"""
# f1 == f2 is needed here as we might have: f1, f2 = inf, inf
- self.assertTrue(f1 == f2 or math.fabs(f1 - f2) <= err,
- "%f != %f +/- %f%s" % (f1, f2, err, " (%s)" % msg
- if msg is not None else ""))
+ self.assertTrue(
+ f1 == f2 or math.fabs(f1 - f2) <= err,
+ "%f != %f +/- %f%s" % (f1, f2, err, " (%s)" % msg
+ if msg is not None else ""))
def assertArrayNear(self, farray1, farray2, err, msg=None):
"""Asserts that two float arrays are near each other.
@@ -1250,8 +1266,9 @@ class TensorFlowTestCase(googletest.TestCase):
def _assertArrayLikeAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):
a = self._GetNdArray(a)
b = self._GetNdArray(b)
- self.assertEqual(a.shape, b.shape, "Shape mismatch: expected %s, got %s." %
- (a.shape, b.shape))
+ self.assertEqual(
+ a.shape, b.shape,
+ "Shape mismatch: expected %s, got %s." % (a.shape, b.shape))
if not np.allclose(a, b, rtol=rtol, atol=atol):
# Prints more details than np.testing.assert_allclose.
#
@@ -1453,8 +1470,9 @@ class TensorFlowTestCase(googletest.TestCase):
msg = msg if msg else ""
a = self._GetNdArray(a)
b = self._GetNdArray(b)
- self.assertEqual(a.shape, b.shape, "Shape mismatch: expected %s, got %s."
- " %s" % (a.shape, b.shape, msg))
+ self.assertEqual(
+ a.shape, b.shape, "Shape mismatch: expected %s, got %s."
+ " %s" % (a.shape, b.shape, msg))
same = (a == b)
if (a.dtype in [
@@ -1682,8 +1700,8 @@ class TensorFlowTestCase(googletest.TestCase):
self.fail(exception_type.__name__ + " not raised")
except Exception as e: # pylint: disable=broad-except
if not isinstance(e, exception_type) or not predicate(e):
- raise AssertionError("Exception of type %s: %s" % (str(type(e)),
- str(e)))
+ raise AssertionError(
+ "Exception of type %s: %s" % (str(type(e)), str(e)))
# pylint: enable=g-doc-return-or-yield
@@ -1719,8 +1737,9 @@ class TensorFlowTestCase(googletest.TestCase):
"""
device1 = pydev.canonical_name(device1)
device2 = pydev.canonical_name(device2)
- self.assertEqual(device1, device2, "Devices %s and %s are not equal. %s" %
- (device1, device2, msg))
+ self.assertEqual(
+ device1, device2,
+ "Devices %s and %s are not equal. %s" % (device1, device2, msg))
# Fix Python 3 compatibility issues
if six.PY3:
@@ -1734,6 +1753,113 @@ class TensorFlowTestCase(googletest.TestCase):
# pylint: enable=invalid-name
+ @contextlib.contextmanager
+ def _constrain_devices_and_set_default(self, sess, use_gpu, force_gpu):
+ """Set the session and its graph to global default and constrain devices."""
+ if context.executing_eagerly():
+ yield None
+ else:
+ with sess.graph.as_default(), sess.as_default():
+ if force_gpu:
+ # Use the name of an actual device if one is detected, or
+ # '/device:GPU:0' otherwise
+ gpu_name = gpu_device_name()
+ if not gpu_name:
+ gpu_name = "/device:GPU:0"
+ with sess.graph.device(gpu_name):
+ yield sess
+ elif use_gpu:
+ yield sess
+ else:
+ with sess.graph.device("/cpu:0"):
+ yield sess
+
+ def _create_session(self, graph, config, use_gpu, force_gpu):
+ """See session() for details."""
+ if context.executing_eagerly():
+ return None
+ else:
+
+ def prepare_config(config):
+ """Returns a config for sessions.
+
+ Args:
+ config: An optional config_pb2.ConfigProto to use to configure the
+ session.
+ Returns:
+ A config_pb2.ConfigProto object.
+ """
+ if config is None:
+ config = config_pb2.ConfigProto()
+ config.allow_soft_placement = not force_gpu
+ config.gpu_options.per_process_gpu_memory_fraction = 0.3
+ elif force_gpu and config.allow_soft_placement:
+ config = config_pb2.ConfigProto().CopyFrom(config)
+ config.allow_soft_placement = False
+ # Don't perform optimizations for tests so we don't inadvertently run
+ # gpu ops on cpu
+ config.graph_options.optimizer_options.opt_level = -1
+ config.graph_options.rewrite_options.constant_folding = (
+ rewriter_config_pb2.RewriterConfig.OFF)
+ config.graph_options.rewrite_options.arithmetic_optimization = (
+ rewriter_config_pb2.RewriterConfig.OFF)
+ return config
+
+ return session.Session(graph=graph, config=prepare_config(config))
+
+ @contextlib.contextmanager
+ def _get_cached_session(self,
+ graph=None,
+ config=None,
+ use_gpu=False,
+ force_gpu=False,
+ crash_if_inconsistent_args=True):
+ """See cached_session() for documentation."""
+ if context.executing_eagerly():
+ yield None
+ else:
+ if self._cached_session is None:
+ sess = self._create_session(
+ graph=graph, config=config, use_gpu=use_gpu, force_gpu=force_gpu)
+ self._cached_session = sess
+ self._cached_graph = graph
+ self._cached_config = config
+ self._cached_use_gpu = use_gpu
+ self._cached_force_gpu = force_gpu
+ with self._constrain_devices_and_set_default(
+ sess, use_gpu, force_gpu) as constrained_sess:
+ yield constrained_sess
+ else:
+ if crash_if_inconsistent_args and self._cached_graph is not graph:
+ raise ValueError("The graph used to get the cached session is "
+ "different than the one that was used to create the "
+ "session. Maybe create a new session with "
+ "self.session()")
+ if crash_if_inconsistent_args and self._cached_config is not config:
+ raise ValueError("The config used to get the cached session is "
+ "different than the one that was used to create the "
+ "session. Maybe create a new session with "
+ "self.session()")
+ if crash_if_inconsistent_args and self._cached_use_gpu is not use_gpu:
+ raise ValueError(
+ "The use_gpu value used to get the cached session is "
+ "different than the one that was used to create the "
+ "session. Maybe create a new session with "
+ "self.session()")
+ if crash_if_inconsistent_args and (self._cached_force_gpu is
+ not force_gpu):
+ raise ValueError(
+ "The force_gpu value used to get the cached session is "
+ "different than the one that was used to create the "
+ "session. Maybe create a new session with "
+ "self.session()")
+ # If you modify this logic, make sure to modify it in _create_session
+ # as well.
+ sess = self._cached_session
+ with self._constrain_devices_and_set_default(
+ sess, use_gpu, force_gpu) as constrained_sess:
+ yield constrained_sess
+
@tf_export("test.create_local_cluster")
def create_local_cluster(num_workers,
diff --git a/tensorflow/python/framework/test_util_test.py b/tensorflow/python/framework/test_util_test.py
index f983cbef04..f68c0ddecb 100644
--- a/tensorflow/python/framework/test_util_test.py
+++ b/tensorflow/python/framework/test_util_test.py
@@ -22,6 +22,7 @@ import collections
import copy
import random
import threading
+import weakref
import numpy as np
@@ -40,6 +41,7 @@ from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import resource_variable_ops
+from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
@@ -57,6 +59,33 @@ class TestUtilTest(test_util.TensorFlowTestCase):
self.assertRaises(ValueError, test_util.assert_ops_in_graph,
{"hello": "Variable"}, ops.get_default_graph())
+ def test_session_functions(self):
+ with self.test_session() as sess:
+ sess_ref = weakref.ref(sess)
+ with self.cached_session(graph=None, config=None) as sess2:
+ # We make sure that sess2 is sess.
+ assert sess2 is sess
+ # We make sure we raise an exception if we use cached_session with
+ # different values.
+ with self.assertRaises(ValueError):
+ with self.cached_session(graph=ops.Graph()) as sess2:
+ pass
+ with self.assertRaises(ValueError):
+ with self.cached_session(use_gpu=True) as sess2:
+ pass
+ with self.assertRaises(ValueError):
+ with self.cached_session(force_gpu=True) as sess2:
+ pass
+ # We make sure that test_session will cache the session even after the
+ # with scope.
+ assert not sess_ref()._closed
+ with self.session() as unique_sess:
+ unique_sess_ref = weakref.ref(unique_sess)
+ with self.session() as sess2:
+ assert sess2 is not unique_sess
+ # We make sure the session is closed when we leave the with statement.
+ assert unique_sess_ref()._closed
+
def test_assert_equal_graph_def(self):
with ops.Graph().as_default() as g:
def_empty = g.as_graph_def()
@@ -666,6 +695,22 @@ class TestUtilTest(test_util.TensorFlowTestCase):
self.assertEqual(modes[2:], ["setup_eager", "run_eager"])
+# Its own test case to reproduce variable sharing issues which only pop up when
+# setUp() is overridden and super() is not called.
+class GraphAndEagerNoVariableSharing(test_util.TensorFlowTestCase):
+
+ def setUp(self):
+ pass # Intentionally does not call TensorFlowTestCase's super()
+
+ @test_util.run_in_graph_and_eager_modes
+ def test_no_variable_sharing(self):
+ variable_scope.get_variable(
+ name="step_size",
+ initializer=np.array(1e-5, np.float32),
+ use_resource=True,
+ trainable=False)
+
+
class GarbageCollectionTest(test_util.TensorFlowTestCase):
def test_no_reference_cycle_decorator(self):
diff --git a/tensorflow/python/keras/BUILD b/tensorflow/python/keras/BUILD
index e04d0e93e2..e145b894f5 100755
--- a/tensorflow/python/keras/BUILD
+++ b/tensorflow/python/keras/BUILD
@@ -296,109 +296,15 @@ py_test(
)
py_test(
- name = "densenet_test",
- size = "large",
- srcs = ["applications/densenet_test.py"],
- srcs_version = "PY2AND3",
- tags = ["nomsan"], # times out, http://b/78650237
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- "//third_party/py/numpy",
- ],
-)
-
-py_test(
- name = "inception_resnet_v2_test",
- size = "medium",
- srcs = ["applications/inception_resnet_v2_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- "//third_party/py/numpy",
- ],
-)
-
-py_test(
- name = "inception_v3_test",
- size = "medium",
- srcs = ["applications/inception_v3_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- "//third_party/py/numpy",
- ],
-)
-
-py_test(
- name = "mobilenet_test",
- size = "medium",
- srcs = ["applications/mobilenet_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- "//third_party/py/numpy",
- ],
-)
-
-py_test(
- name = "nasnet_test",
- size = "large",
- srcs = ["applications/nasnet_test.py"],
- srcs_version = "PY2AND3",
- tags = ["nomsan"], # times out, http://b/78573625
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- "//third_party/py/numpy",
- ],
-)
-
-py_test(
- name = "resnet50_test",
- size = "medium",
- srcs = ["applications/resnet50_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- ],
-)
-
-py_test(
- name = "vgg16_test",
- size = "small",
- srcs = ["applications/vgg16_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- ],
-)
-
-py_test(
- name = "vgg19_test",
- size = "small",
- srcs = ["applications/vgg19_test.py"],
- srcs_version = "PY2AND3",
- deps = [
- ":keras",
- "//tensorflow/python:client_testlib",
- ],
-)
-
-py_test(
- name = "xception_test",
- size = "medium",
- srcs = ["applications/xception_test.py"],
+ name = "applications_test",
+ size = "enormous",
+ srcs = ["applications/applications_test.py"],
+ shard_count = 2,
srcs_version = "PY2AND3",
deps = [
":keras",
"//tensorflow/python:client_testlib",
- "//third_party/py/numpy",
+ "@absl_py//absl/testing:parameterized",
],
)
@@ -493,7 +399,7 @@ py_test(
py_test(
name = "local_test",
- size = "medium",
+ size = "large",
srcs = ["layers/local_test.py"],
srcs_version = "PY2AND3",
deps = [
@@ -719,14 +625,15 @@ cuda_py_test(
)
py_test(
- name = "imagenet_utils_test",
+ name = "conv_utils_test",
size = "small",
- srcs = ["applications/imagenet_utils_test.py"],
+ srcs = ["utils/conv_utils_test.py"],
srcs_version = "PY2AND3",
deps = [
":keras",
"//tensorflow/python:client_testlib",
"//third_party/py/numpy",
+ "@absl_py//absl/testing:parameterized",
],
)
@@ -781,7 +688,7 @@ py_test(
py_test(
name = "training_test",
- size = "large",
+ size = "enormous",
srcs = ["engine/training_test.py"],
srcs_version = "PY2AND3",
tags = ["notsan"],
diff --git a/tensorflow/python/keras/applications/__init__.py b/tensorflow/python/keras/applications/__init__.py
index 51cc51998c..cd9462d6b5 100644
--- a/tensorflow/python/keras/applications/__init__.py
+++ b/tensorflow/python/keras/applications/__init__.py
@@ -39,7 +39,7 @@ from tensorflow.python.keras.applications.densenet import DenseNet201
from tensorflow.python.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.python.keras.applications.inception_v3 import InceptionV3
from tensorflow.python.keras.applications.mobilenet import MobileNet
-from tensorflow.python.keras.applications.mobilenet_v2 import MobileNetV2
+# TODO(fchollet): enable MobileNetV2 in next version.
from tensorflow.python.keras.applications.nasnet import NASNetLarge
from tensorflow.python.keras.applications.nasnet import NASNetMobile
from tensorflow.python.keras.applications.resnet50 import ResNet50
diff --git a/tensorflow/python/keras/applications/applications_test.py b/tensorflow/python/keras/applications/applications_test.py
new file mode 100644
index 0000000000..ef3198a937
--- /dev/null
+++ b/tensorflow/python/keras/applications/applications_test.py
@@ -0,0 +1,58 @@
+# 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.
+# ==============================================================================
+"""Integration tests for Keras applications."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from absl.testing import parameterized
+
+from tensorflow.python.keras import applications
+from tensorflow.python.platform import test
+
+
+MODEL_LIST = [
+ (applications.ResNet50, 2048),
+ (applications.VGG16, 512),
+ (applications.VGG19, 512),
+ (applications.Xception, 2048),
+ (applications.InceptionV3, 2048),
+ (applications.InceptionResNetV2, 1536),
+ (applications.MobileNet, 1024),
+ # TODO(fchollet): enable MobileNetV2 in next version.
+ (applications.DenseNet121, 1024),
+ (applications.DenseNet169, 1664),
+ (applications.DenseNet201, 1920),
+ (applications.NASNetMobile, 1056),
+ (applications.NASNetLarge, 4032),
+]
+
+
+class ApplicationsTest(test.TestCase, parameterized.TestCase):
+
+ @parameterized.parameters(*MODEL_LIST)
+ def test_classification_model(self, model_fn, _):
+ model = model_fn(classes=1000, weights=None)
+ self.assertEqual(model.output_shape[-1], 1000)
+
+ @parameterized.parameters(*MODEL_LIST)
+ def test_feature_extration_model(self, model_fn, output_dim):
+ model = model_fn(include_top=False, weights=None)
+ self.assertEqual(model.output_shape, (None, None, None, output_dim))
+
+
+if __name__ == '__main__':
+ test.main()
diff --git a/tensorflow/python/keras/applications/densenet_test.py b/tensorflow/python/keras/applications/densenet_test.py
deleted file mode 100644
index 8b6aa281ad..0000000000
--- a/tensorflow/python/keras/applications/densenet_test.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# 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 DenseNet application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class DenseNet121Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.DenseNet121(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.DenseNet121(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 1024))
-
- def test_with_pooling(self):
- model = keras.applications.DenseNet121(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 1024))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.DenseNet121(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.DenseNet121(weights='imagenet',
- classes=2000)
-
-
-class DenseNet169Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.DenseNet169(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.DenseNet169(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 1664))
-
- def test_with_pooling(self):
- model = keras.applications.DenseNet169(weights=None,
- include_top=False,
- pooling='max')
- self.assertEqual(model.output_shape, (None, 1664))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.DenseNet169(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.DenseNet169(weights='imagenet',
- classes=2000)
-
-
-class DenseNet201(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.DenseNet201(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.DenseNet201(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 1920))
-
- def test_with_pooling(self):
- model = keras.applications.DenseNet201(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 1920))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.DenseNet201(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.DenseNet201(weights='imagenet',
- classes=2000)
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/imagenet_utils_test.py b/tensorflow/python/keras/applications/imagenet_utils_test.py
deleted file mode 100644
index 037e939ac5..0000000000
--- a/tensorflow/python/keras/applications/imagenet_utils_test.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright 2016 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 Inception V3 application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-
-from tensorflow.python import keras
-from tensorflow.python.keras.applications.imagenet_utils import preprocess_input
-from tensorflow.python.platform import test
-
-
-class ImageNetUtilsTest(test.TestCase):
-
- def test_preprocess_input(self):
- # Test batch of images
- x = np.random.uniform(0, 255, (2, 10, 10, 3))
- self.assertEqual(preprocess_input(x).shape, x.shape)
- out1 = preprocess_input(x, 'channels_last')
- out2 = preprocess_input(np.transpose(x, (0, 3, 1, 2)), 'channels_first')
- self.assertAllClose(out1, out2.transpose(0, 2, 3, 1))
-
- # Test single image
- x = np.random.uniform(0, 255, (10, 10, 3))
- self.assertEqual(preprocess_input(x).shape, x.shape)
- out1 = preprocess_input(x, 'channels_last')
- out2 = preprocess_input(np.transpose(x, (2, 0, 1)), 'channels_first')
- self.assertAllClose(out1, out2.transpose(1, 2, 0))
-
- def test_preprocess_input_symbolic(self):
- # Test image batch
- x = np.random.uniform(0, 255, (2, 10, 10, 3))
- inputs = keras.layers.Input(shape=x.shape[1:])
- outputs = keras.layers.Lambda(
- preprocess_input, output_shape=x.shape[1:])(inputs)
- model = keras.models.Model(inputs, outputs)
- assert model.predict(x).shape == x.shape
- # pylint: disable=g-long-lambda
- outputs1 = keras.layers.Lambda(lambda x:
- preprocess_input(x, 'channels_last'),
- output_shape=x.shape[1:])(inputs)
- model1 = keras.models.Model(inputs, outputs1)
- out1 = model1.predict(x)
- x2 = np.transpose(x, (0, 3, 1, 2))
- inputs2 = keras.layers.Input(shape=x2.shape[1:])
- # pylint: disable=g-long-lambda
- outputs2 = keras.layers.Lambda(lambda x:
- preprocess_input(x, 'channels_first'),
- output_shape=x2.shape[1:])(inputs2)
- model2 = keras.models.Model(inputs2, outputs2)
- out2 = model2.predict(x2)
- self.assertAllClose(out1, out2.transpose(0, 2, 3, 1))
-
- # Test single image
- x = np.random.uniform(0, 255, (10, 10, 3))
- inputs = keras.layers.Input(shape=x.shape)
- outputs = keras.layers.Lambda(preprocess_input,
- output_shape=x.shape)(inputs)
- model = keras.models.Model(inputs, outputs)
- assert model.predict(x[np.newaxis])[0].shape == x.shape
- # pylint: disable=g-long-lambda
- outputs1 = keras.layers.Lambda(lambda x:
- preprocess_input(x, 'channels_last'),
- output_shape=x.shape)(inputs)
- model1 = keras.models.Model(inputs, outputs1)
- out1 = model1.predict(x[np.newaxis])[0]
- x2 = np.transpose(x, (2, 0, 1))
- inputs2 = keras.layers.Input(shape=x2.shape)
- outputs2 = keras.layers.Lambda(lambda x:
- preprocess_input(x, 'channels_first'),
- output_shape=x2.shape)(inputs2) # pylint: disable=g-long-lambda
- model2 = keras.models.Model(inputs2, outputs2)
- out2 = model2.predict(x2[np.newaxis])[0]
- self.assertAllClose(out1, out2.transpose(1, 2, 0))
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/inception_resnet_v2_test.py b/tensorflow/python/keras/applications/inception_resnet_v2_test.py
deleted file mode 100644
index 0a12f88505..0000000000
--- a/tensorflow/python/keras/applications/inception_resnet_v2_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# Copyright 2016 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 Inception V3 application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class InceptionResNetV2Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.InceptionResNetV2(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.InceptionResNetV2(weights=None,
- include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 1536))
-
- def test_with_pooling(self):
- model = keras.applications.InceptionResNetV2(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 1536))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.InceptionResNetV2(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.InceptionResNetV2(weights='imagenet',
- classes=2000)
-
- def test_preprocess_input(self):
- x = np.random.uniform(0, 255, (2, 300, 200, 3))
- out1 = keras.applications.inception_resnet_v2.preprocess_input(x)
- self.assertAllClose(np.mean(out1), 0., atol=0.1)
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/inception_v3_test.py b/tensorflow/python/keras/applications/inception_v3_test.py
deleted file mode 100644
index a3fcdd5564..0000000000
--- a/tensorflow/python/keras/applications/inception_v3_test.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright 2016 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 Inception V3 application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class InceptionV3Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.InceptionV3(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.InceptionV3(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 2048))
-
- def test_with_pooling(self):
- model = keras.applications.InceptionV3(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 2048))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.InceptionV3(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.InceptionV3(weights='imagenet',
- classes=2000)
-
- def test_preprocess_input(self):
- x = np.random.uniform(0, 255, (2, 300, 200, 3))
- out1 = keras.applications.inception_v3.preprocess_input(x)
- self.assertAllClose(np.mean(out1), 0., atol=0.1)
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/mobilenet_test.py b/tensorflow/python/keras/applications/mobilenet_test.py
deleted file mode 100644
index 65e4991ded..0000000000
--- a/tensorflow/python/keras/applications/mobilenet_test.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# Copyright 2016 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 MobileNet application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class MobileNetTest(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.MobileNet(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.MobileNet(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 1024))
-
- def test_with_pooling(self):
- model = keras.applications.MobileNet(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 1024))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.MobileNet(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.MobileNet(weights='imagenet',
- classes=2000)
-
- def test_preprocess_input(self):
- x = np.random.uniform(0, 255, (2, 300, 200, 3))
- out1 = keras.applications.mobilenet.preprocess_input(x)
- self.assertAllClose(np.mean(out1), 0., atol=0.1)
-
- def test_mobilenet_variable_input_channels(self):
- input_shape = (None, None, 1)
- model = keras.applications.MobileNet(weights=None,
- include_top=False,
- input_shape=input_shape)
- self.assertEqual(model.output_shape, (None, None, None, 1024))
-
- input_shape = (None, None, 4)
- model = keras.applications.MobileNet(weights=None,
- include_top=False,
- input_shape=input_shape)
- self.assertEqual(model.output_shape, (None, None, None, 1024))
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/mobilenet_v2.py b/tensorflow/python/keras/applications/mobilenet_v2.py
index 74b8b029f8..9194c3ee14 100644
--- a/tensorflow/python/keras/applications/mobilenet_v2.py
+++ b/tensorflow/python/keras/applications/mobilenet_v2.py
@@ -19,14 +19,4 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-from keras_applications import mobilenet_v2
-
-from tensorflow.python.util.tf_export import tf_export
-
-MobileNetV2 = mobilenet_v2.MobileNetV2
-decode_predictions = mobilenet_v2.decode_predictions
-preprocess_input = mobilenet_v2.preprocess_input
-
-tf_export('keras.applications.mobilenet_v2.MobileNetV2',
- 'keras.applications.MobileNetV2')(MobileNetV2)
-tf_export('keras.applications.mobilenet_v2.preprocess_input')(preprocess_input)
+# TODO(fchollet): export MobileNetV2 as part of the public API in next version.
diff --git a/tensorflow/python/keras/applications/nasnet_test.py b/tensorflow/python/keras/applications/nasnet_test.py
deleted file mode 100644
index f96c3aa51c..0000000000
--- a/tensorflow/python/keras/applications/nasnet_test.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# 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 Nasnet application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class NASNetMobileTest(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.NASNetMobile(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.NASNetMobile(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 1056))
-
- def test_with_pooling(self):
- model = keras.applications.NASNetMobile(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 1056))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.NASNetMobile(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.NASNetMobile(weights='imagenet',
- classes=2000)
-
-
-class NASNetLargeTest(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.NASNetLarge(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.NASNetLarge(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 4032))
-
- def test_with_pooling(self):
- model = keras.applications.NASNetLarge(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 4032))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.NASNetLarge(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.NASNetLarge(weights='imagenet',
- classes=2000)
-
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/resnet50_test.py b/tensorflow/python/keras/applications/resnet50_test.py
deleted file mode 100644
index 22a3f05580..0000000000
--- a/tensorflow/python/keras/applications/resnet50_test.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright 2016 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 ResNet50 application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class ResNet50Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.ResNet50(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.ResNet50(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 2048))
-
- def test_with_pooling(self):
- model = keras.applications.ResNet50(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 2048))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.ResNet50(weights='unknown',
- include_top=False)
-
- with self.assertRaises(ValueError):
- keras.applications.ResNet50(weights='imagenet',
- classes=2000)
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/vgg16_test.py b/tensorflow/python/keras/applications/vgg16_test.py
deleted file mode 100644
index cad65765f3..0000000000
--- a/tensorflow/python/keras/applications/vgg16_test.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Copyright 2016 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 VGG16 application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class VGG16Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.VGG16(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.VGG16(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 512))
-
- def test_with_pooling(self):
- model = keras.applications.VGG16(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 512))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.VGG16(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.VGG16(weights='imagenet',
- classes=2000)
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/vgg19_test.py b/tensorflow/python/keras/applications/vgg19_test.py
deleted file mode 100644
index 61dccc0c5c..0000000000
--- a/tensorflow/python/keras/applications/vgg19_test.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Copyright 2016 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 VGG19 application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class VGG19Test(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.VGG19(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.VGG19(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 512))
-
- def test_with_pooling(self):
- model = keras.applications.VGG19(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 512))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.VGG19(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.VGG19(weights='imagenet',
- classes=2000)
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/applications/xception_test.py b/tensorflow/python/keras/applications/xception_test.py
deleted file mode 100644
index 7e2efd0017..0000000000
--- a/tensorflow/python/keras/applications/xception_test.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright 2016 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 Xception application."""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-
-from tensorflow.python import keras
-from tensorflow.python.platform import test
-
-
-class XceptionTest(test.TestCase):
-
- def test_with_top(self):
- model = keras.applications.Xception(weights=None)
- self.assertEqual(model.output_shape, (None, 1000))
-
- def test_no_top(self):
- model = keras.applications.Xception(weights=None, include_top=False)
- self.assertEqual(model.output_shape, (None, None, None, 2048))
-
- def test_with_pooling(self):
- model = keras.applications.Xception(weights=None,
- include_top=False,
- pooling='avg')
- self.assertEqual(model.output_shape, (None, 2048))
-
- def test_weight_loading(self):
- with self.assertRaises(ValueError):
- keras.applications.Xception(weights='unknown',
- include_top=False)
- with self.assertRaises(ValueError):
- keras.applications.Xception(weights='imagenet',
- classes=2000)
-
- def test_preprocess_input(self):
- x = np.random.uniform(0, 255, (2, 300, 200, 3))
- out1 = keras.applications.xception.preprocess_input(x)
- self.assertAllClose(np.mean(out1), 0., atol=0.1)
-
-if __name__ == '__main__':
- test.main()
diff --git a/tensorflow/python/keras/callbacks.py b/tensorflow/python/keras/callbacks.py
index 070d41147d..befe82f4ec 100644
--- a/tensorflow/python/keras/callbacks.py
+++ b/tensorflow/python/keras/callbacks.py
@@ -22,6 +22,7 @@ from __future__ import print_function
from collections import deque
from collections import Iterable
from collections import OrderedDict
+import copy
import csv
import json
import math
@@ -31,10 +32,12 @@ import time
import numpy as np
import six
+from tensorflow.python.data.ops import iterator_ops
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.engine.training_utils import standardize_input_data
+from tensorflow.python.keras.utils.data_utils import Sequence
from tensorflow.python.keras.utils.generic_utils import Progbar
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import state_ops
@@ -52,6 +55,110 @@ except ImportError:
requests = None
+def configure_callbacks(callbacks,
+ model,
+ do_validation=False,
+ val_inputs=None,
+ val_targets=None,
+ val_sample_weights=None,
+ batch_size=None,
+ epochs=None,
+ steps_per_epoch=None,
+ samples=None,
+ validation_steps=None,
+ verbose=1,
+ count_mode='steps'):
+ """Configures callbacks for use in various training loops.
+
+ Arguments:
+ callbacks: List of Callbacks.
+ model: Model being trained.
+ do_validation: Whether or not validation loop will be run.
+ val_inputs: Inputs to Model for validation loop. Can be any
+ data format Keras accepts.
+ val_targets: Targets for Model for validation loop. Can be any
+ data format Keras accepts.
+ val_sample_weights: Sample weights for Model for validation loop.
+ Can be any data format Keras accepts.
+ batch_size: Number of samples per batch.
+ epochs: Number of epoch to train.
+ steps_per_epoch: Number of batches to run per training epoch.
+ samples: Number of training samples.
+ validation_steps: Number of batches to run per validation epoch.
+ verbose: int, 0 or 1. Keras logging verbosity to pass to ProgbarLogger.
+ count_mode: One of 'steps' or 'samples'. Per-batch or per-sample count.
+
+ Returns:
+ Instance of CallbackList used to control all Callbacks.
+ """
+
+ # Add additional callbacks
+ model.history = History()
+ stateful_metric_names = None
+ if hasattr(model, 'stateful_metric_names'):
+ stateful_metric_names = model.stateful_metric_names
+ callbacks = [BaseLogger(stateful_metrics=stateful_metric_names)
+ ] + (callbacks or []) + [model.history]
+ if verbose:
+ callbacks.append(
+ ProgbarLogger(count_mode, stateful_metrics=stateful_metric_names))
+ callback_list = CallbackList(callbacks)
+
+ # Set callback model
+ callback_model = model._get_callback_model() # pylint: disable=protected-access
+ if do_validation and val_inputs and not context.executing_eagerly():
+ # Need to create the test_function before start of the first epoch
+ # because TensorBoard callback on_epoch_begin adds summary to the
+ # list of fetches of the test_function
+ callback_model._make_test_function() # pylint: disable=protected-access
+ callback_list.set_model(callback_model)
+
+ # Set callback parameters
+ callback_metrics = []
+ # When we have deferred build scenario with iterator input, we will compile
+ # when we standardize first batch of data.
+ if model._is_compiled: # pylint: disable=protected-access
+ callback_metrics = copy.copy(model.metrics_names)
+ if do_validation:
+ callback_metrics += ['val_' + n for n in model.metrics_names]
+ if validation_steps is None and isinstance(val_inputs, Sequence):
+ validation_steps = len(val_inputs)
+ callback_params = {
+ 'batch_size': batch_size,
+ 'epochs': epochs,
+ 'steps': steps_per_epoch,
+ 'samples': samples,
+ 'verbose': verbose,
+ 'do_validation': do_validation,
+ 'metrics': callback_metrics,
+ 'validation_steps': validation_steps
+ }
+ callback_list.set_params(callback_params)
+
+ # Pass validation data to callbacks
+ if not val_inputs:
+ val_data = []
+ elif _is_generator_like(val_inputs):
+ val_data = val_inputs
+ else:
+ val_data = val_inputs + val_targets
+ if val_sample_weights:
+ val_data += val_sample_weights
+ if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
+ val_data += [0.]
+ for cbk in callbacks:
+ cbk.validation_data = val_data
+
+ callback_list.model.stop_training = False
+ return callback_list
+
+
+def _is_generator_like(data):
+ """Checks if data is a generator, Sequence, or Iterator."""
+ return (hasattr(data, 'next') or hasattr(data, '__next__') or isinstance(
+ data, (Sequence, iterator_ops.Iterator, iterator_ops.EagerIterator)))
+
+
class CallbackList(object):
"""Container abstracting a list of callbacks.
@@ -65,15 +172,19 @@ class CallbackList(object):
callbacks = callbacks or []
self.callbacks = [c for c in callbacks]
self.queue_length = queue_length
+ self.params = {}
+ self.model = None
def append(self, callback):
self.callbacks.append(callback)
def set_params(self, params):
+ self.params = params
for callback in self.callbacks:
callback.set_params(params)
def set_model(self, model):
+ self.model = model
for callback in self.callbacks:
callback.set_model(model)
@@ -722,7 +833,7 @@ class TensorBoard(Callback):
Raises:
ValueError: If histogram_freq is set and no validation data is provided.
- @compatbility(eager)
+ @compatibility(eager)
Using `Tensorboard` callback will work while eager execution is enabled,
however outputting histogram summaries of weights and gradients is not
supported, and thus `histogram_freq` will be ignored.
@@ -939,7 +1050,7 @@ class TensorBoard(Callback):
"""Checks if histogram summaries can be run."""
# will never be set when in eager
if self.histogram_freq:
- if 'validation_steps' in self.params:
+ if self.params.get('validation_steps', None) is not None:
self._validation_batches = self.params['validation_steps']
elif self.validation_data:
self._validation_batches = math.ceil(
diff --git a/tensorflow/python/keras/callbacks_test.py b/tensorflow/python/keras/callbacks_test.py
index bd088a559c..e84e023384 100644
--- a/tensorflow/python/keras/callbacks_test.py
+++ b/tensorflow/python/keras/callbacks_test.py
@@ -728,6 +728,8 @@ class KerasCallbacksTest(test.TestCase):
verbose=0)
# fit generator without validation data
+ # histogram_freq must be zero
+ tsb.histogram_freq = 0
model.fit_generator(
data_generator(True),
len(x_train),
@@ -736,6 +738,7 @@ class KerasCallbacksTest(test.TestCase):
verbose=0)
# fit generator with validation data and accuracy
+ tsb.histogram_freq = 1
model.fit_generator(
data_generator(True),
len(x_train),
@@ -745,6 +748,7 @@ class KerasCallbacksTest(test.TestCase):
verbose=0)
# fit generator without validation data and accuracy
+ tsb.histogram_freq = 0
model.fit_generator(
data_generator(True), len(x_train), epochs=2, callbacks=cbks)
assert os.path.exists(temp_dir)
diff --git a/tensorflow/python/keras/engine/base_layer.py b/tensorflow/python/keras/engine/base_layer.py
index 33ad155072..d6d3db21fb 100644
--- a/tensorflow/python/keras/engine/base_layer.py
+++ b/tensorflow/python/keras/engine/base_layer.py
@@ -500,13 +500,13 @@ class Layer(checkpointable.CheckpointableBase):
use_resource: Whether to use `ResourceVariable`.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
getter: Variable getter argument to be passed to the `Checkpointable` API.
Returns:
@@ -1921,13 +1921,13 @@ def make_variable(name,
use_resource: Whether to use a `ResourceVariable`.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
partitioner: Not handled at this time.
Returns:
diff --git a/tensorflow/python/keras/engine/distributed_training_utils.py b/tensorflow/python/keras/engine/distributed_training_utils.py
index c78e6fe9ec..fcb073322c 100644
--- a/tensorflow/python/keras/engine/distributed_training_utils.py
+++ b/tensorflow/python/keras/engine/distributed_training_utils.py
@@ -184,14 +184,16 @@ def validate_distributed_dataset_inputs(distribution_strategy, x, y):
"""Validate all the components of a DistributedValue Dataset input.
Args:
- distribution_strategy: The current DistributionStrategy using to call
+ distribution_strategy: The current DistributionStrategy used to call
`fit`/`evaluate`.
x: Input Dataset DistributedValue object. For example, when we use
`MirroredStrategy` this is a PerDevice object with a tensor for each
- device set in the dict.
+ device set in the dict. x can also be a tuple or dict. The keys of the
+ dict should match the names of the input layers of the model.
y: Target Dataset DistributedValue object. For example, when we use
`MirroredStrategy` this is a PerDevice object with a tensor for each
- device set in the dict.
+ device set in the dict. y can also be a tuple or dict. The keys of the
+ dict should match the names of the output layers of the model.
Returns:
The unwrapped values list of the x and y DistributedValues inputs.
@@ -206,30 +208,50 @@ def validate_distributed_dataset_inputs(distribution_strategy, x, y):
# and targets to a model should be from a `tf.data.Dataset`.
# If each element of x and y are not tensors, we cannot standardize and
- # validate the input and targets.`
- if not tensor_util.is_tensor(x):
- raise ValueError('Dataset input to the model should be tensors instead they'
- ' are of type {}'.format(type(x)))
+ # validate the input and targets.
+ x_values_list = validate_per_device_inputs(distribution_strategy, x)
- if not tensor_util.is_tensor(y):
- raise ValueError('Dataset input to the model should be tensors instead they'
- ' are of type {}'.format(type(y)))
+ y_values_list = validate_per_device_inputs(distribution_strategy, y)
- # At this point both x and y contain tensors in the `DistributedValues`
- # structure.
- x_values = distribution_strategy.unwrap(x)
- y_values = distribution_strategy.unwrap(y)
+ # Return the unwrapped values to avoid calling `unwrap` a second time.
+ return x_values_list, y_values_list
- # Validate that the shape and dtype of all the elements in x are the same.
- validate_all_tensor_shapes(x, x_values)
- validate_all_tensor_types(x, x_values)
- # Similarly for y, we perform the same validation
- validate_all_tensor_shapes(y, y_values)
- validate_all_tensor_types(y, y_values)
+def validate_per_device_inputs(distribution_strategy, x):
+ """Validates PerDevice dataset input list.
- # Return the unwrapped values to avoid calling `unwrap` a second time.
- return x_values, y_values
+ Args:
+ distribution_strategy: The current DistributionStrategy used to call
+ `fit`, `evaluate` and `predict`.
+ x: A list of PerDevice objects that represent the input or
+ target values.
+
+ Returns:
+ List containing the first element of each of the PerDevice objects in
+ the input list.
+
+ Raises:
+ ValueError: If any of the objects in the `per_device_list` is not a tensor.
+
+ """
+ # Convert the inputs and targets into a list of PerDevice objects.
+ per_device_list = nest.flatten(x)
+ x_values_list = []
+ for x in per_device_list:
+ if not tensor_util.is_tensor(x):
+ raise ValueError('Dataset input to the model should be tensors instead '
+ 'they are of type {}'.format(type(x)))
+
+ # At this point both x and y contain tensors in the `DistributedValues`
+ # structure.
+ x_values = distribution_strategy.unwrap(x)
+
+ # Validate that the shape and dtype of all the elements in x are the same.
+ validate_all_tensor_shapes(x, x_values)
+ validate_all_tensor_types(x, x_values)
+
+ x_values_list.append(x_values[0])
+ return x_values_list
def validate_all_tensor_types(x, x_values):
diff --git a/tensorflow/python/keras/engine/network.py b/tensorflow/python/keras/engine/network.py
index bdff4497e2..cd74e36e68 100644
--- a/tensorflow/python/keras/engine/network.py
+++ b/tensorflow/python/keras/engine/network.py
@@ -43,6 +43,7 @@ from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.keras.utils.io_utils import ask_to_proceed_with_overwrite
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
+from tensorflow.python.training import checkpoint_management
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.training.checkpointable import data_structures
from tensorflow.python.training.checkpointable import layer_utils as checkpointable_layer_utils
@@ -393,10 +394,10 @@ class Network(base_layer.Layer):
no_dependency = isinstance(value, data_structures.NoDependency)
value = data_structures.sticky_attribute_assignment(
checkpointable=self, value=value, name=name)
- if isinstance(value, (
- base_layer.Layer,
- Network,
- data_structures.CheckpointableDataStructure)):
+ if (isinstance(value, (base_layer.Layer,
+ Network,
+ data_structures.CheckpointableDataStructure))
+ or checkpointable_layer_utils.has_weights(value)):
try:
is_graph_network = self._is_graph_network
except AttributeError:
@@ -688,14 +689,14 @@ class Network(base_layer.Layer):
def trainable_weights(self):
return checkpointable_layer_utils.gather_trainable_weights(
trainable=self.trainable,
- sub_layers=self.layers,
+ sub_layers=self._layers,
extra_variables=self._extra_variables)
@property
def non_trainable_weights(self):
return checkpointable_layer_utils.gather_non_trainable_weights(
trainable=self.trainable,
- sub_layers=self.layers,
+ sub_layers=self._layers,
extra_variables=self._extra_variables)
@property
@@ -1455,6 +1456,11 @@ class Network(base_layer.Layer):
'saved.\n\nConsider using a TensorFlow optimizer from `tf.train`.')
% (optimizer,))
self._checkpointable_saver.save(filepath, session=session)
+ # Record this checkpoint so it's visible from tf.train.latest_checkpoint.
+ checkpoint_management.update_checkpoint_state(
+ save_dir=os.path.dirname(filepath),
+ model_checkpoint_path=filepath,
+ all_model_checkpoint_paths=[filepath])
def load_weights(self, filepath, by_name=False):
"""Loads all layer weights, either from a TensorFlow or an HDF5 weight file.
diff --git a/tensorflow/python/keras/engine/saving.py b/tensorflow/python/keras/engine/saving.py
index d5ccd44604..a2eed7cb46 100644
--- a/tensorflow/python/keras/engine/saving.py
+++ b/tensorflow/python/keras/engine/saving.py
@@ -127,6 +127,7 @@ def save_model(model, filepath, overwrite=True, include_optimizer=True):
},
'loss': model.loss,
'metrics': model.metrics,
+ 'weighted_metrics': model.weighted_metrics,
'sample_weight_mode': model.sample_weight_mode,
'loss_weights': model.loss_weights,
},
@@ -246,6 +247,8 @@ def load_model(filepath, custom_objects=None, compile=True): # pylint: disable=
# Recover loss functions and metrics.
loss = convert_custom_objects(training_config['loss'])
metrics = convert_custom_objects(training_config['metrics'])
+ weighted_metrics = convert_custom_objects(
+ training_config['weighted_metrics'])
sample_weight_mode = training_config['sample_weight_mode']
loss_weights = training_config['loss_weights']
@@ -254,6 +257,7 @@ def load_model(filepath, custom_objects=None, compile=True): # pylint: disable=
optimizer=optimizer,
loss=loss,
metrics=metrics,
+ weighted_metrics=weighted_metrics,
loss_weights=loss_weights,
sample_weight_mode=sample_weight_mode)
diff --git a/tensorflow/python/keras/engine/saving_test.py b/tensorflow/python/keras/engine/saving_test.py
index f2f8a27b76..b7c2e9cb53 100644
--- a/tensorflow/python/keras/engine/saving_test.py
+++ b/tensorflow/python/keras/engine/saving_test.py
@@ -36,6 +36,7 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
+from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import training as training_module
try:
@@ -337,10 +338,18 @@ class TestWholeModelSaving(test.TestCase):
model.add(keras.layers.Dense(2, input_shape=(3,)))
model.add(keras.layers.RepeatVector(3))
model.add(keras.layers.TimeDistributed(keras.layers.Dense(3)))
- model.compile(loss=keras.losses.MSE,
- optimizer=keras.optimizers.RMSprop(lr=0.0001),
- metrics=[keras.metrics.categorical_accuracy],
- sample_weight_mode='temporal')
+ model.compile(
+ loss=keras.losses.MSE,
+ optimizer=keras.optimizers.RMSprop(lr=0.0001),
+ metrics=[
+ keras.metrics.categorical_accuracy,
+ keras.metrics.CategoricalAccuracy()
+ ],
+ weighted_metrics=[
+ keras.metrics.categorical_accuracy,
+ keras.metrics.CategoricalAccuracy()
+ ],
+ sample_weight_mode='temporal')
x = np.random.random((1, 3))
y = np.random.random((1, 3, 3))
model.train_on_batch(x, y)
@@ -435,9 +444,17 @@ class TestWholeModelSaving(test.TestCase):
output = keras.layers.Dense(3)(x)
model = keras.models.Model(inputs, output)
- model.compile(loss=keras.losses.MSE,
- optimizer=keras.optimizers.RMSprop(lr=0.0001),
- metrics=[keras.metrics.categorical_accuracy])
+ model.compile(
+ loss=keras.losses.MSE,
+ optimizer=keras.optimizers.RMSprop(lr=0.0001),
+ metrics=[
+ keras.metrics.categorical_accuracy,
+ keras.metrics.CategoricalAccuracy()
+ ],
+ weighted_metrics=[
+ keras.metrics.categorical_accuracy,
+ keras.metrics.CategoricalAccuracy()
+ ])
x = np.random.random((1, 3))
y = np.random.random((1, 3))
model.train_on_batch(x, y)
@@ -623,9 +640,13 @@ class TestWholeModelSaving(test.TestCase):
outputs = keras.layers.Dense(3)(x)
model = keras.Model(inputs, outputs)
- model.compile(loss=keras.losses.MSE,
- optimizer=keras.optimizers.Adam(),
- metrics=[keras.metrics.categorical_accuracy])
+ model.compile(
+ loss=keras.losses.MSE,
+ optimizer=keras.optimizers.Adam(),
+ metrics=[
+ keras.metrics.categorical_accuracy,
+ keras.metrics.CategoricalAccuracy()
+ ])
x = np.random.random((1, 3))
y = np.random.random((1, 3))
model.train_on_batch(x, y)
@@ -744,7 +765,7 @@ class TestWeightSavingAndLoadingTFFormat(test.TestCase):
model.compile(
loss='mse',
optimizer=training_module.RMSPropOptimizer(0.1),
- metrics=['acc'])
+ metrics=['acc', keras.metrics.CategoricalAccuracy()])
temp_dir = self.get_temp_dir()
prefix = os.path.join(temp_dir, 'ckpt')
train_x = np.random.random((3, 2))
@@ -781,7 +802,7 @@ class TestWeightSavingAndLoadingTFFormat(test.TestCase):
load_model.compile(
loss='mse',
optimizer=training_module.RMSPropOptimizer(0.1),
- metrics=['acc'])
+ metrics=['acc', keras.metrics.CategoricalAccuracy()])
load_model.train_on_batch(train_x, train_y)
self.assertAllClose(ref_y_after_train, self.evaluate(load_model(x)))
@@ -813,6 +834,9 @@ class TestWeightSavingAndLoadingTFFormat(test.TestCase):
session.run([v.initializer for v in model.variables])
ref_y = self.evaluate(ref_y_tensor)
model.save_weights(prefix)
+ self.assertEqual(
+ prefix,
+ checkpoint_management.latest_checkpoint(temp_dir))
for v in model.variables:
self.evaluate(
v.assign(random_ops.random_normal(shape=array_ops.shape(v))))
diff --git a/tensorflow/python/keras/engine/sequential.py b/tensorflow/python/keras/engine/sequential.py
index 415b15fde1..cf6fb44275 100644
--- a/tensorflow/python/keras/engine/sequential.py
+++ b/tensorflow/python/keras/engine/sequential.py
@@ -239,9 +239,9 @@ class Sequential(Model):
x = inputs
for layer in self.layers:
kwargs = {}
- if 'mask' in tf_inspect.getargspec(layer.call).args:
+ if 'mask' in tf_inspect.getfullargspec(layer.call).args:
kwargs['mask'] = mask
- if 'training' in tf_inspect.getargspec(layer.call).args:
+ if 'training' in tf_inspect.getfullargspec(layer.call).args:
kwargs['training'] = training
if isinstance(layer, Network) and layer._compute_output_and_mask_jointly:
diff --git a/tensorflow/python/keras/engine/sequential_test.py b/tensorflow/python/keras/engine/sequential_test.py
index 8744503632..3f8e120df0 100644
--- a/tensorflow/python/keras/engine/sequential_test.py
+++ b/tensorflow/python/keras/engine/sequential_test.py
@@ -95,7 +95,10 @@ class TestSequential(test.TestCase, parameterized.TestCase):
num_classes = 2
model = _get_small_mlp(num_hidden, num_classes)
- model.compile(loss='mse', optimizer=rmsprop.RMSPropOptimizer(1e-3))
+ model.compile(
+ loss='mse',
+ optimizer=rmsprop.RMSPropOptimizer(1e-3),
+ metrics=[keras.metrics.CategoricalAccuracy()])
self.assertEqual(len(model.layers), 2)
self.assertEqual(len(model.weights), 0)
self.assertFalse(model.built)
@@ -116,7 +119,10 @@ class TestSequential(test.TestCase, parameterized.TestCase):
steps_per_epoch = 10
model = _get_small_mlp(num_hidden, num_classes)
- model.compile(loss='mse', optimizer=rmsprop.RMSPropOptimizer(1e-3))
+ model.compile(
+ loss='mse',
+ optimizer=rmsprop.RMSPropOptimizer(1e-3),
+ metrics=[keras.metrics.CategoricalAccuracy()])
self.assertEqual(len(model.layers), 2)
self.assertEqual(len(model.weights), 0)
self.assertFalse(model.built)
@@ -257,7 +263,10 @@ class TestSequential(test.TestCase, parameterized.TestCase):
num_classes = 2
model = _get_small_mlp(num_hidden, num_classes)
- model.compile(loss='mse', optimizer=rmsprop.RMSPropOptimizer(1e-3))
+ model.compile(
+ loss='mse',
+ optimizer=rmsprop.RMSPropOptimizer(1e-3),
+ metrics=[keras.metrics.CategoricalAccuracy()])
self.assertFalse(model.built)
x = np.random.random((batch_size, input_dim))
@@ -341,6 +350,18 @@ class TestSequentialEagerIntegration(test.TestCase):
y = np.random.random((2, 5))
model.fit(x, y, epochs=1)
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_build_before_fit(self):
+ # Fix for b/112433577
+ model = _get_small_mlp(4, 5)
+ model.compile(loss='mse', optimizer=rmsprop.RMSPropOptimizer(1e-3))
+
+ model.build((None, 6))
+
+ x = np.random.random((2, 6))
+ y = np.random.random((2, 5))
+ model.fit(x, y, epochs=1)
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/python/keras/engine/training.py b/tensorflow/python/keras/engine/training.py
index 254de27ceb..502635c408 100644
--- a/tensorflow/python/keras/engine/training.py
+++ b/tensorflow/python/keras/engine/training.py
@@ -29,6 +29,7 @@ from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
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 distributed_training_utils
@@ -39,6 +40,8 @@ from tensorflow.python.keras.engine import training_generator
from tensorflow.python.keras.engine import training_utils
from tensorflow.python.keras.engine.network import Network
from tensorflow.python.keras.utils.generic_utils import slice_arrays
+from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import weights_broadcast_ops
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import optimizer as tf_optimizer_module
from tensorflow.python.training.checkpointable import base as checkpointable
@@ -138,6 +141,167 @@ class Model(Network):
if i not in skip_target_weighing_indices
]
+ def _get_metric_name(self, metric, output_index, weighted=False):
+ """Returns the metric name corresponding to the given metric input.
+
+ Arguments:
+ metric: Metric function name or reference.
+ output_index: Index of the current output.
+ weighted: Boolean indicating if the given metric is weighted.
+
+ Returns:
+ A metric name.
+ """
+ metric_name_prefix = 'weighted_' if weighted else ''
+ if metric in ('accuracy', 'acc', 'crossentropy', 'ce'):
+ if metric in ('accuracy', 'acc'):
+ suffix = 'acc'
+ elif metric in ('crossentropy', 'ce'):
+ suffix = 'ce'
+ else:
+ metric_fn = metrics_module.get(metric)
+ # Get metric name as string
+ if hasattr(metric_fn, 'name'):
+ suffix = metric_fn.name
+ else:
+ suffix = metric_fn.__name__
+ metric_name = metric_name_prefix + suffix
+
+ if len(self.output_names) > 1:
+ metric_name = '%s_%s' % (self.output_names[output_index], metric_name)
+ j = 1
+ base_metric_name = metric_name
+ while metric_name in self.metrics_names:
+ metric_name = '%s_%d' % (base_metric_name, j)
+ j += 1
+
+ return metric_name
+
+ def _handle_per_output_metrics(self,
+ metrics,
+ y_true,
+ y_pred,
+ output_index,
+ output_shape,
+ loss_fn,
+ mask,
+ weights=None):
+ """Calls metric functions and sets metric attributes for a single output.
+
+ Arguments:
+ metrics: List of metrics.
+ y_true: Target output.
+ y_pred: Predicted output.
+ output_index: Index of the current output.
+ output_shape: Shape of the current output.
+ loss_fn: Loss function corresponding to the current output.
+ mask: Computed mask value for the current output.
+ weights: Weights to be applied on the current output.
+
+ Returns:
+ A list of metric result tensors.
+ """
+ metric_results = []
+ for metric in metrics:
+ metric_fn = training_utils.get_metric_function(
+ metric, output_shape=output_shape, loss_fn=loss_fn)
+ metric_name = self._get_metric_name(
+ metric, output_index, weighted=weights is not None)
+
+ with K.name_scope(metric_name):
+ # If both outputs and targets are available, call the metric function.
+ if y_true is not None and y_pred is not None:
+ if isinstance(metric_fn, metrics_module.Metric):
+ # Call the stateful metric function.
+ if mask is not None:
+ mask = math_ops.cast(mask, y_pred.dtype)
+ # Update weights with mask.
+ if weights is None:
+ weights = mask
+ else:
+ # Update shape of weights if possible before adding mask.
+ # Update dimensions of weights to match with mask if possible.
+ mask, _, weights = metrics_module.squeeze_or_expand_dimensions(
+ mask, None, weights)
+ try:
+ # Broadcast weights if possible.
+ weights = weights_broadcast_ops.broadcast_weights(
+ weights, mask)
+ except ValueError:
+ pass
+ # TODO(psv): Handle case when mask and weight shapes are not
+ # compatible.
+ weights *= mask
+
+ metric_result = metric_fn(y_true, y_pred, weights)
+ else:
+ # Call the stateless metric function.
+ weighted_metric_fn = training_utils.weighted_masked_objective(
+ metric_fn)
+ metric_result = weighted_metric_fn(
+ y_true, y_pred, weights=weights, mask=mask)
+
+ if not context.executing_eagerly():
+ # Keep track of metric result tensor.
+ self.metrics_tensors.append(metric_result)
+ metric_results.append(metric_result)
+
+ # Keep track of metric name.
+ self.metrics_names.append(metric_name)
+
+ # Keep track of stateful metric attributes (name and metric function).
+ 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)
+ if not context.executing_eagerly():
+ # Keep track of updates created by stateful metrics.
+ self.metrics_updates += metric_fn.updates
+ return metric_results
+
+ def _handle_metrics(self,
+ outputs,
+ skip_target_indices=None,
+ targets=None,
+ sample_weights=None,
+ masks=None):
+ """Handles calling metric functions and setting model metric attributes.
+
+ Arguments:
+ outputs: List of outputs (predictions).
+ skip_target_indices: Optional. List of target ids to skip.
+ targets: List of targets.
+ sample_weights: Optional list of sample weight arrays.
+ masks: List of computed output mask values.
+
+ Returns:
+ A list of metric result tensors.
+ """
+ skip_target_indices = skip_target_indices or []
+ metric_results = []
+ with K.name_scope('metrics'):
+ for i in range(len(outputs)):
+ if i in skip_target_indices:
+ continue
+ output = outputs[i] if outputs else None
+ target = targets[i] if targets else None
+ output_shape = None if output is None else output.get_shape().as_list()
+ output_mask = masks[i] if masks else None
+ metric_results.extend(
+ self._handle_per_output_metrics(
+ self.nested_metrics[i], target, output, i, output_shape,
+ self.loss_functions[i], output_mask))
+ metric_results.extend(
+ self._handle_per_output_metrics(
+ self.nested_weighted_metrics[i],
+ target,
+ output,
+ i,
+ output_shape,
+ self.loss_functions[i],
+ output_mask,
+ weights=sample_weights[i]))
+ return metric_results
+
@checkpointable.no_automatic_dependency_tracking
def compile(self,
optimizer,
@@ -153,9 +317,9 @@ class Model(Network):
Arguments:
optimizer: String (name of optimizer) or optimizer instance.
- See [optimizers](/optimizers).
+ See [optimizers](/api_docs/python/tf/keras/optimizers).
loss: String (name of objective function) or objective function.
- See [losses](/losses).
+ See [losses](/api_docs/python/tf/losses).
If the model has multiple outputs, you can use a different loss
on each output by passing a dictionary or a list of losses.
The loss value that will be minimized by the model
@@ -233,8 +397,6 @@ class Model(Network):
self.metrics = metrics or []
self.loss_weights = loss_weights
self.sample_weight_mode = sample_weight_mode
- if context.executing_eagerly() and weighted_metrics is not None:
- raise ValueError('weighted_metrics is not supported in Eager mode.')
self.weighted_metrics = weighted_metrics
if context.executing_eagerly() and target_tensors is not None:
raise ValueError('target_tensors is not supported in Eager mode.')
@@ -337,6 +499,20 @@ class Model(Network):
str(loss_weights) + ' - expected a list of dicts.')
self.loss_weights_list = loss_weights_list
+ # Initialize model metric attributes.
+ self.metrics_names = ['loss']
+ self.metrics_tensors = []
+ self.metrics_updates = []
+ self.stateful_metric_names = []
+ self.stateful_metric_functions = []
+
+ # Nested metrics is a list of list of metrics.
+ # One list per output of the model.
+ self.nested_metrics = training_utils.collect_metrics(
+ metrics, self.output_names)
+ self.nested_weighted_metrics = training_utils.collect_metrics(
+ weighted_metrics, self.output_names)
+
# Initialization for Eager mode execution.
if context.executing_eagerly():
# Prepare sample weights.
@@ -347,19 +523,16 @@ class Model(Network):
raise ValueError('target_tensors are not currently supported in Eager '
'mode.')
self.total_loss = None
- self.metrics_tensors = []
- self.metrics_names = ['loss']
for i in range(len(self.outputs)):
if len(self.outputs) > 1:
self.metrics_names.append(self.output_names[i] + '_loss')
- self.nested_metrics = training_utils.collect_metrics(metrics,
- self.output_names)
- # TODO(fchollet): support stateful metrics in eager execution.
- self.stateful_metric_functions = []
- self.stateful_metric_names = []
-
- with K.name_scope('metrics'):
- training_utils.populate_metric_names(self)
+
+ # Set metric attributes on model.
+ self._handle_metrics(
+ self.outputs,
+ skip_target_indices=skip_target_indices,
+ sample_weights=self.sample_weights)
+
self.targets = []
for i in range(len(self.outputs)):
self._feed_output_names.append(self.output_names[i])
@@ -422,11 +595,6 @@ class Model(Network):
self._set_sample_weight_attributes(sample_weight_mode,
skip_target_weighing_indices)
- # Prepare metrics.
- self.weighted_metrics = weighted_metrics
- self.metrics_names = ['loss']
- self.metrics_tensors = []
-
# Compute total loss.
total_loss = None
with K.name_scope('loss'):
@@ -460,55 +628,13 @@ class Model(Network):
for loss_tensor in self.losses:
total_loss += loss_tensor
- # List of same size as output_names.
- # contains tuples (metrics for output, names of metrics).
- nested_metrics = training_utils.collect_metrics(metrics, self.output_names)
- nested_weighted_metrics = training_utils.collect_metrics(weighted_metrics,
- self.output_names)
- self.metrics_updates = []
- self.stateful_metric_names = []
- self.stateful_metric_functions = []
- with K.name_scope('metrics'):
- for i in range(len(self.outputs)):
- if i in skip_target_indices:
- continue
-
- y_true = self.targets[i]
- y_pred = self.outputs[i]
- weights = self.sample_weights[i]
- output_metrics = nested_metrics[i]
- output_weighted_metrics = nested_weighted_metrics[i]
- output_shape = self.outputs[i].get_shape().as_list()
- loss_fn = self.loss_functions[i]
-
- def handle_metrics(metrics, output_shape, loss_fn, weights=None):
- """Invokes metric functions for the output."""
-
- for metric in metrics:
- metric_fn = training_utils.get_metric_function(
- metric, output_shape=output_shape, loss_fn=loss_fn)
- metric_name = training_utils.get_metric_name(
- metric, weighted=weights is not None)
-
- with K.name_scope(metric_name):
- weighted_metric_fn = training_utils.weighted_masked_objective(
- metric_fn)
- metric_result = weighted_metric_fn(
- y_true, y_pred, weights=weights, mask=masks[i]) # pylint: disable=undefined-loop-variable
-
- metric_name = training_utils.add_metric_name(self, metric_name, i) # pylint: disable=undefined-loop-variable
- self.metrics_tensors.append(metric_result)
-
- # Keep track of state updates created by
- # stateful metrics (i.e. metrics layers).
- 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
-
- handle_metrics(output_metrics, output_shape, loss_fn)
- handle_metrics(
- output_weighted_metrics, output_shape, loss_fn, weights=weights)
+ # Invoke metric functions for all the outputs.
+ self._handle_metrics(
+ self.outputs,
+ masks=masks,
+ targets=self.targets,
+ skip_target_indices=skip_target_indices,
+ sample_weights=self.sample_weights)
# Prepare gradient updates and state updates.
self.total_loss = total_loss
@@ -674,18 +800,18 @@ class Model(Network):
RuntimeError: If the model was never compiled.
"""
if sample_weight is not None and sample_weight.all():
- raise NotImplementedError('sample_weight is currently not supported when '
- 'using DistributionStrategy.')
+ raise NotImplementedError('`sample_weight` is currently not supported '
+ 'when using DistributionStrategy.')
if class_weight:
- raise NotImplementedError('class_weight is currently not supported when '
- 'using DistributionStrategy.')
+ raise NotImplementedError('`class_weight` is currently not supported '
+ 'when using DistributionStrategy.')
# TODO(anjalisridhar): Can we use the iterator and getnext op cache?
# We require users to pass Datasets since we distribute the dataset across
# multiple devices.
if not isinstance(x, dataset_ops.Dataset):
- raise ValueError('When using DistributionStrategy you must specify a '
- 'Dataset object instead of a %s.' % type(x))
+ raise ValueError('When using DistributionStrategy, model inputs should be'
+ ' Dataset instances; found instead %s.' % type(x))
# TODO(anjalisridhar): We want distribute_dataset() to accept a Dataset or a
# function which returns a Dataset. Currently distribute_dataset() only
# accepts a function that returns a Dataset. Once we add support for being
@@ -708,8 +834,9 @@ class Model(Network):
next_element = iterator.get_next()
if not isinstance(next_element, (list, tuple)) or len(next_element) != 2:
- raise ValueError('Please provide data as a list or tuple of 2 elements '
- ' - input and target pair. Received %s' % next_element)
+ raise ValueError('Please provide model inputs as a list or tuple of 2 '
+ 'elements: input and target pair. '
+ 'Received %s' % next_element)
x, y = next_element
# Validate that all the elements in x and y are of the same type and shape.
# We can then pass the first element of x and y to `_standardize_weights`
@@ -719,8 +846,8 @@ class Model(Network):
x_values, y_values = distributed_training_utils.\
validate_distributed_dataset_inputs(self._distribution_strategy, x, y)
- _, _, sample_weights = self._standardize_weights(x_values[0],
- y_values[0],
+ _, _, sample_weights = self._standardize_weights(x_values,
+ y_values,
sample_weight,
class_weight,
batch_size)
@@ -845,8 +972,9 @@ class Model(Network):
'required number of samples.')
if not isinstance(next_element, (list, tuple)) or len(next_element) != 2:
- raise ValueError('Please provide data as a list or tuple of 2 elements '
- ' - input and target pair. Received %s' % next_element)
+ raise ValueError('Please provide model inputs as a list or tuple of 2 '
+ 'elements: input and target pair. '
+ 'Received %s' % next_element)
x, y = next_element
x, y, sample_weights = self._standardize_weights(x, y, sample_weight,
class_weight, batch_size)
@@ -854,11 +982,15 @@ class Model(Network):
def _standardize_weights(self, x, y, sample_weight=None, class_weight=None,
batch_size=None,):
+ if sample_weight is not None and class_weight is not None:
+ logging.warning(
+ 'Received both a `sample_weight` and `class_weight` argument. '
+ 'The `class_weight` argument will be ignored.')
# First, we build/compile the model on the fly if necessary.
all_inputs = []
is_build_called = False
is_compile_called = False
- if not self.built:
+ if not self.inputs:
# We need to use `x` to set the model inputs.
# We type-check that `x` and `y` are either single arrays
# or lists of arrays.
@@ -1266,7 +1398,7 @@ class Model(Network):
0 = silent, 1 = progress bar, 2 = one line per epoch.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
- See [callbacks](/callbacks).
+ See [callbacks](/api_docs/python/tf/keras/callbacks).
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
@@ -1884,6 +2016,10 @@ class Model(Network):
Raises:
ValueError: In case the generator yields data in an invalid format.
"""
+ if self._distribution_strategy:
+ raise NotImplementedError('`fit_generator` is not supported for '
+ 'models compiled with DistributionStrategy.')
+
if not self.built and not self._is_graph_network:
raise NotImplementedError(
'`fit_generator` is not yet enabled for unbuilt Model subclasses')
@@ -1951,6 +2087,10 @@ class Model(Network):
Raises:
ValueError: In case the generator yields data in an invalid format.
"""
+ if self._distribution_strategy:
+ raise NotImplementedError('`evaluate_generator` is not supported for '
+ 'models compiled with DistributionStrategy.')
+
if not self.built and not self._is_graph_network:
raise NotImplementedError(
'`evaluate_generator` is not yet enabled for '
@@ -2005,6 +2145,10 @@ class Model(Network):
Raises:
ValueError: In case the generator yields data in an invalid format.
"""
+ if self._distribution_strategy:
+ raise NotImplementedError('`predict_generator` is not supported for '
+ 'models compiled with DistributionStrategy.')
+
if not self.built and not self._is_graph_network:
raise NotImplementedError(
'`predict_generator` is not yet enabled for unbuilt Model subclasses')
@@ -2018,6 +2162,21 @@ class Model(Network):
use_multiprocessing=use_multiprocessing,
verbose=verbose)
+ def _get_callback_model(self):
+ """Returns the Callback Model for this Model."""
+
+ if hasattr(self, '_replicated_model') and self._replicated_model:
+ # When using training_distributed, we set the callback model
+ # to an instance of the `DistributedModel` that we create in
+ # the `compile` call. The `DistributedModel` is initialized
+ # with the first replicated model. We need to set the callback
+ # model to a DistributedModel to allow us to override saving
+ # and loading weights when we checkpoint the model during training.
+ return self._replicated_model
+ if hasattr(self, 'callback_model') and self.callback_model:
+ return self.callback_model
+ return self
+
class DistributedCallbackModel(Model):
"""Model that is used for callbacks with DistributionStrategy."""
@@ -2058,4 +2217,3 @@ class DistributedCallbackModel(Model):
logging.warning('You are accessing attribute ' + item + 'of the'
'DistributedCallbackModel that may not have been set'
'correctly.')
-
diff --git a/tensorflow/python/keras/engine/training_arrays.py b/tensorflow/python/keras/engine/training_arrays.py
index d24f4b64b9..e2c458c65f 100644
--- a/tensorflow/python/keras/engine/training_arrays.py
+++ b/tensorflow/python/keras/engine/training_arrays.py
@@ -19,8 +19,6 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import copy
-
import numpy as np
from tensorflow.python.framework import errors
@@ -92,14 +90,8 @@ def fit_loop(model,
val_sample_weights = val_sample_weights or []
if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
ins = inputs + targets + sample_weights + [1]
- if val_inputs:
- val_ins = val_inputs + val_targets + val_sample_weights + [1]
else:
ins = inputs + targets + sample_weights
- if val_inputs:
- val_ins = val_inputs + val_targets + val_sample_weights
- if not val_inputs:
- val_ins = []
do_validation = False
if val_inputs:
@@ -116,65 +108,27 @@ def fit_loop(model,
'training, i.e. `steps_per_epoch` '
'must be set.')
- out_labels = model.metrics_names
- if do_validation:
- callback_metrics = copy.copy(out_labels) + ['val_' + n for n in out_labels]
- # need to create the test_function before start of the first epoch
- # because TensorBoard callback on_epoch_begin adds summary to the
- # list of fetches of the test_function
- model._make_test_function()
- else:
- callback_metrics = copy.copy(out_labels)
-
num_train_samples = training_utils.check_num_samples(
ins, batch_size, steps_per_epoch, 'steps_per_epoch')
+ count_mode = 'steps' if steps_per_epoch else 'samples'
+ callbacks = cbks.configure_callbacks(
+ callbacks,
+ model,
+ do_validation=do_validation,
+ val_inputs=val_inputs,
+ val_targets=val_targets,
+ val_sample_weights=val_sample_weights,
+ batch_size=batch_size,
+ epochs=epochs,
+ steps_per_epoch=steps_per_epoch,
+ samples=num_train_samples,
+ validation_steps=validation_steps,
+ verbose=verbose,
+ count_mode=count_mode)
+
if num_train_samples is not None:
index_array = np.arange(num_train_samples)
- model.history = cbks.History()
- all_callbacks = [cbks.BaseLogger(
- stateful_metrics=model.stateful_metric_names)]
- if verbose:
- if steps_per_epoch is not None:
- count_mode = 'steps'
- else:
- count_mode = 'samples'
- all_callbacks.append(
- cbks.ProgbarLogger(
- count_mode, stateful_metrics=model.stateful_metric_names))
- all_callbacks += (callbacks or []) + [model.history]
- callbacks = cbks.CallbackList(all_callbacks)
- out_labels = out_labels or []
-
- # it's possible to callback a different model than self
- # (used by Sequential models)
- if hasattr(model, 'callback_model') and model.callback_model:
- callback_model = model.callback_model
- else:
- callback_model = model
-
- callbacks.set_model(callback_model)
-
- callback_params = {
- 'batch_size': batch_size,
- 'epochs': epochs,
- 'steps': steps_per_epoch,
- 'samples': num_train_samples,
- 'verbose': verbose,
- 'do_validation': do_validation,
- 'metrics': callback_metrics or [],
- }
- if validation_steps:
- callback_params.update({'validation_steps': validation_steps})
- callbacks.set_params(callback_params)
-
- for cbk in callbacks:
- cbk.validation_data = val_ins
- # validation_data must be set before on_train_begin() is called
- # so that TensorboardCallback can validate its input
- callbacks.on_train_begin()
- callback_model.stop_training = False
-
# To prevent a slowdown, we find beforehand the arrays that need conversion.
feed = model._feed_inputs + model._feed_targets + model._feed_sample_weights
indices_for_conversion_to_dense = []
@@ -182,6 +136,7 @@ def fit_loop(model,
if issparse is not None and issparse(ins[i]) and not K.is_sparse(feed[i]):
indices_for_conversion_to_dense.append(i)
+ callbacks.on_train_begin()
for epoch in range(initial_epoch, epochs):
# Reset stateful metrics
for m in model.stateful_metric_functions:
@@ -208,11 +163,11 @@ def fit_loop(model,
if not isinstance(outs, list):
outs = [outs]
- for l, o in zip(out_labels, outs):
+ for l, o in zip(model.metrics_names, outs):
batch_logs[l] = o
callbacks.on_batch_end(step_index, batch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
if do_validation:
@@ -226,7 +181,7 @@ def fit_loop(model,
if not isinstance(val_outs, list):
val_outs = [val_outs]
# Same labels assumed.
- for l, o in zip(out_labels, val_outs):
+ for l, o in zip(model.metrics_names, val_outs):
epoch_logs['val_' + l] = o
else:
# Sample-wise fit loop.
@@ -259,11 +214,11 @@ def fit_loop(model,
outs = f(ins_batch)
if not isinstance(outs, list):
outs = [outs]
- for l, o in zip(out_labels, outs):
+ for l, o in zip(model.metrics_names, outs):
batch_logs[l] = o
callbacks.on_batch_end(batch_index, batch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
if batch_index == len(batches) - 1: # Last batch.
@@ -278,10 +233,10 @@ def fit_loop(model,
if not isinstance(val_outs, list):
val_outs = [val_outs]
# Same labels assumed.
- for l, o in zip(out_labels, val_outs):
+ for l, o in zip(model.metrics_names, val_outs):
epoch_logs['val_' + l] = o
callbacks.on_epoch_end(epoch, epoch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
callbacks.on_train_end()
return model.history
diff --git a/tensorflow/python/keras/engine/training_distributed.py b/tensorflow/python/keras/engine/training_distributed.py
index 5fa6c3c47d..5feedc43a5 100644
--- a/tensorflow/python/keras/engine/training_distributed.py
+++ b/tensorflow/python/keras/engine/training_distributed.py
@@ -18,7 +18,6 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import copy
import numpy as np
from tensorflow.python.framework import errors
from tensorflow.python.keras import backend as K
@@ -38,7 +37,6 @@ def fit_loop(
callbacks=None,
val_inputs=None,
val_targets=None,
- callback_metrics=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None):
@@ -53,10 +51,6 @@ def fit_loop(
callbacks: List of callbacks to be called during training
val_inputs: List of input arrays.
val_targets: List of target arrays.
- callback_metrics: List of strings, the display names of the metrics
- passed to the callbacks. They should be the
- concatenation of list the display names of the outputs of
- `f` and the list of display names of the outputs of `f_val`.
initial_epoch: Epoch at which to start training
(useful for resuming a previous training run)
steps_per_epoch: Total number of steps (batches of samples)
@@ -126,50 +120,6 @@ def fit_loop(
'when doing step-wise '
'training, i.e. `steps_per_epoch` '
'must be set.')
- out_labels = model.metrics_names
- if do_validation:
- callback_metrics = copy.copy(out_labels) + [
- 'val_' + n for n in out_labels
- ]
- else:
- callback_metrics = copy.copy(out_labels)
-
- model.history = cbks.History()
- all_callbacks = [cbks.BaseLogger(
- stateful_metrics=model.stateful_metric_names)]
- if verbose:
- # We assume that `steps_per_epoch` is always set since we have to use
- # Datasets.
- count_mode = 'steps'
-
- all_callbacks.append(
- cbks.ProgbarLogger(
- count_mode, stateful_metrics=model.stateful_metric_names))
- all_callbacks += (callbacks or []) + [model.history]
- callbacks = cbks.CallbackList(all_callbacks)
- out_labels = out_labels or []
-
- # We set the callback model to an instance of the `DistributedModel` that we
- # create in the `compile` call. The `DistributedModel` is initialized with
- # the first replicated model. We need to set the callback model to a
- # DistributedModel to allow us to override saving and loading weights when
- # we checkpoint the model during training.
- callback_model = model._replicated_model
-
- callbacks.set_model(callback_model)
-
- callbacks.set_params({
- 'epochs': epochs,
- 'steps': steps_per_epoch,
- 'samples': None,
- 'verbose': verbose,
- 'do_validation': do_validation,
- 'metrics': callback_metrics or [],
- })
- callbacks.on_train_begin()
- callback_model.stop_training = False
-
- out_labels = out_labels or []
# Copy the weights from the original model to each of the replicated models.
orig_model_weights = model.get_weights()
@@ -178,6 +128,17 @@ def fit_loop(
distributed_training_utils.set_weights(
current_strategy, distributed_model, orig_model_weights)
+ callbacks = cbks.configure_callbacks(
+ callbacks,
+ model,
+ do_validation=do_validation,
+ val_inputs=None,
+ val_targets=None,
+ epochs=epochs,
+ steps_per_epoch=steps_per_epoch,
+ verbose=verbose)
+ out_labels = model.metrics_names or []
+ callbacks.on_train_begin()
for epoch in range(initial_epoch, epochs):
callbacks.on_epoch_begin(epoch)
if steps_per_epoch is not None:
@@ -203,7 +164,7 @@ def fit_loop(
for l, o in zip(out_labels, outs):
batch_logs[l] = o
callbacks.on_batch_end(step_index, batch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
if do_validation:
val_outs = test_loop(
@@ -219,7 +180,7 @@ def fit_loop(
epoch_logs['val_' + l] = o
callbacks.on_epoch_end(epoch, epoch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
callbacks.on_train_end()
diff --git a/tensorflow/python/keras/engine/training_eager.py b/tensorflow/python/keras/engine/training_eager.py
index d5a47efb98..1e377149b6 100644
--- a/tensorflow/python/keras/engine/training_eager.py
+++ b/tensorflow/python/keras/engine/training_eager.py
@@ -41,39 +41,25 @@ def _eager_loss_fn(outputs, targets, loss_fn, output_name):
return loss
-def _eager_metrics_fn(model, outputs, targets):
+def _eager_metrics_fn(model, outputs, targets, sample_weights=None, masks=None):
"""Calculates the metrics for each output of the given model.
Arguments:
model: The model on which metrics are being calculated.
outputs: The outputs of the given model.
targets: The predictions or targets of the given model.
+ sample_weights: Optional list of sample weights for each output.
+ masks: Optional list of masks for each output.
Returns:
Returns the metric results for each output of the model.
"""
- metric_results = []
- if not isinstance(outputs, list):
- outputs = [outputs]
-
- if not isinstance(targets, list):
- targets = [targets]
-
- for i in range(len(model.outputs)):
- output_metrics = model.nested_metrics[i]
- for nested_output_metric in output_metrics:
- metric_fn = training_utils.get_metric_function(
- nested_output_metric, backend.int_shape(model.outputs[i]),
- model.loss_functions[i])
- # weighted metrics are not supported in eager mode
- metric_name = training_utils.get_metric_name(
- nested_output_metric, weighted=False)
-
- with backend.name_scope(metric_name):
- metric_result = metric_fn(targets[i], outputs[i])
- metric_results.append(backend.mean(metric_result))
-
- return metric_results
+ outputs = generic_utils.to_list(outputs)
+ targets = generic_utils.to_list(targets)
+ # TODO(psv): Consider supporting skip target indices in eager mode?
+ metric_results = model._handle_metrics(
+ outputs, targets=targets, sample_weights=sample_weights, masks=masks)
+ return [backend.mean(t) for t in metric_results]
def _model_loss(model, inputs, targets, sample_weights=None, training=False):
@@ -87,9 +73,10 @@ def _model_loss(model, inputs, targets, sample_weights=None, training=False):
training: Whether the model should be run in inference or training mode.
Returns:
- Returns the model output, total loss and loss value calculated using the
- specified loss function. The total loss includes regularization losses and
- applies masking and sample weighting to the loss value.
+ Returns the model output, total loss, loss value calculated using the
+ specified loss function and masks for each output. The total loss includes
+ regularization losses and applies masking and sample weighting
+ to the loss value.
"""
total_loss = 0
kwargs = {}
@@ -146,15 +133,13 @@ def _model_loss(model, inputs, targets, sample_weights=None, training=False):
if custom_losses:
total_loss += sum(custom_losses)
- return outs, total_loss, loss_metrics
+ return outs, total_loss, loss_metrics, masks
def iterator_fit_loop(model,
inputs,
class_weight,
steps_per_epoch,
- callback_model,
- out_labels,
epoch_logs,
val_inputs=None,
val_targets=None,
@@ -162,7 +147,6 @@ def iterator_fit_loop(model,
epochs=1,
verbose=1,
callbacks=None,
- callback_metrics=None,
validation_steps=None,
do_validation=False,
batch_size=None):
@@ -179,19 +163,13 @@ def iterator_fit_loop(model,
steps_per_epoch: Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch.
- callback_model: Instance of `Model` to callback.
- out_labels: Output labels generated from model metric names.
epoch_logs: Dictionary of logs from every epoch.
val_inputs: Input data for validation.
val_targets: Target data for validation.
val_sample_weights: Sample weight data for validation.
epochs: Number of times to iterate over the data
verbose: Verbosity mode, 0, 1 or 2
- callbacks: List of callbacks to be called during training
- callback_metrics: List of strings, the display names of the metrics
- passed to the callbacks. They should be the
- concatenation of list the display names of the outputs of
- `f` and the list of display names of the outputs of `f_val`.
+ callbacks: CallbackList instance. Controls callbacks during training.
validation_steps: Number of steps to run validation for (only if doing
validation from data tensors). Ignored with default value of `None`.
do_validation: Boolean value indicating whether we should do validation.
@@ -244,40 +222,47 @@ def iterator_fit_loop(model,
if val is not None else None for val in sample_weights
]
- if step_index == 0 and not callback_metrics:
- out_labels = model.metrics_names
+ # Set stateful_metrics in callbacks. We do not do this before the
+ # `steps_per_epoch` loop because model will be compiled only in the first
+ # iteration of this loop in the deferred build scenario.
+ if step_index == 0:
+ for cbk in callbacks:
+ if (isinstance(cbk, cbks.BaseLogger) or
+ isinstance(cbk, cbks.ProgbarLogger)):
+ cbk.stateful_metrics = model.stateful_metric_names
+
+ if step_index == 0 and not callbacks.params['metrics']:
+ callback_metrics = copy.copy(model.metrics_names)
if do_validation:
- callback_metrics = copy.copy(out_labels) + [
- 'val_' + n for n in out_labels
- ]
- else:
- callback_metrics = copy.copy(out_labels)
+ callback_metrics += ['val_' + n for n in model.metrics_names]
callbacks.set_params({
+ 'batch_size': batch_size,
'epochs': epochs,
'steps': steps_per_epoch,
'verbose': verbose,
'do_validation': do_validation,
'metrics': callback_metrics or [],
+ 'validation_steps': validation_steps
})
# Train model.
- outs, loss, loss_metrics = _process_single_batch(
+ outs, loss, loss_metrics, masks = _process_single_batch(
model, x, y, sample_weights=sample_weights, training=True)
- if not isinstance(outs, list):
- outs = [outs]
+ outs = generic_utils.to_list(outs)
# Calculate metrics.
- for l, o in zip(out_labels, outs):
+ for l, o in zip(model.metrics_names, outs):
batch_logs[l] = o
# Required for eager execution
- metrics_results = _eager_metrics_fn(model, outs, y)
+ metrics_results = _eager_metrics_fn(
+ model, outs, y, sample_weights=sample_weights, masks=masks)
batch_logs['loss'] = tensor_util.constant_value(backend.mean(loss))
for k, v in zip(model.metrics_names,
[backend.mean(loss)] + loss_metrics + metrics_results):
batch_logs[k] = tensor_util.constant_value(v)
callbacks.on_batch_end(step_index, batch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
if step_index == steps_per_epoch - 1:
@@ -293,7 +278,7 @@ def iterator_fit_loop(model,
if not isinstance(val_outs, list):
val_outs = [val_outs]
# Same labels assumed.
- for l, o in zip(out_labels, val_outs):
+ for l, o in zip(model.metrics_names, val_outs):
epoch_logs['val_' + l] = o
@@ -357,10 +342,25 @@ def iterator_test_loop(model, inputs, steps, verbose=0):
if val is not None else None for val in sample_weights
]
+ if step_index == 0:
+ # Get stateful metrics indices. We do not do this before the `steps` loop
+ # because model will be compiled only in the first iteration of this loop
+ # in the deferred build scenario.
+ if hasattr(model, 'metrics'):
+ for m in model.stateful_metric_functions:
+ m.reset_states()
+ stateful_metric_indices = [
+ i for i, name in enumerate(model.metrics_names)
+ if str(name) in model.stateful_metric_names
+ ]
+ else:
+ stateful_metric_indices = []
+
# Calculate model output, loss values.
- loss_outs, loss, loss_metrics = _model_loss(
+ loss_outs, loss, loss_metrics, masks = _model_loss(
model, x, y, sample_weights=sample_weights, training=False)
- metrics_results = _eager_metrics_fn(model, loss_outs, y)
+ metrics_results = _eager_metrics_fn(
+ model, loss_outs, y, sample_weights=sample_weights, masks=masks)
batch_outs = []
for _, v in zip(model.metrics_names,
[backend.mean(loss)] + loss_metrics + metrics_results):
@@ -379,7 +379,10 @@ def iterator_test_loop(model, inputs, steps, verbose=0):
for _ in enumerate(batch_outs):
outs.append(0.)
for i, batch_out in enumerate(batch_outs):
- outs[i] += batch_out * step_size
+ if i in stateful_metric_indices:
+ outs[i] = batch_out
+ else:
+ outs[i] += batch_out * step_size
# Calculate sample size.
num_samples += step_size
@@ -387,7 +390,8 @@ def iterator_test_loop(model, inputs, steps, verbose=0):
progbar.update(step_index + 1)
for i in range(len(outs)):
- outs[i] /= num_samples
+ if i not in stateful_metric_indices:
+ outs[i] /= num_samples
if len(outs) == 1:
return outs[0]
return outs
@@ -484,16 +488,20 @@ def _process_single_batch(model,
set this to False.
Returns:
- output of the model, total loss and the loss associated with each output.
+ output of the model, total loss, the loss and the mask
+ associated with each output.
Raises:
ValueError: If the model has no loss to optimize.
"""
with backend.learning_phase_scope(1 if training else 0):
with GradientTape() as tape:
- outs, loss, loss_metrics = _model_loss(model, inputs, targets,
- sample_weights=sample_weights,
- training=training)
+ outs, loss, loss_metrics, masks = _model_loss(
+ model,
+ inputs,
+ targets,
+ sample_weights=sample_weights,
+ training=training)
if loss is None:
raise ValueError('The model cannot be run '
'because it has no loss to optimize.')
@@ -506,7 +514,7 @@ def _process_single_batch(model,
grads = tape.gradient(loss, model._collected_trainable_weights)
model.optimizer.apply_gradients(zip(grads,
model._collected_trainable_weights))
- return outs, loss, loss_metrics
+ return outs, loss, loss_metrics, masks
def train_on_batch(model, inputs, targets, sample_weights=None):
@@ -537,14 +545,18 @@ def train_on_batch(model, inputs, targets, sample_weights=None):
if val is not None else None for val in sample_weights
]
- outs, loss, _ = _process_single_batch(
+ outs, loss, loss_metrics, masks = _process_single_batch(
model, inputs, targets, sample_weights=sample_weights, training=True)
if not isinstance(outs, list):
outs = [outs]
- metrics_results = _eager_metrics_fn(model, outs, targets)
- if not isinstance(loss, list):
- loss = [loss]
- return loss + metrics_results
+ metrics_results = _eager_metrics_fn(
+ model, outs, targets, sample_weights=sample_weights, masks=masks)
+ loss = generic_utils.to_list(loss)
+
+ return [
+ tensor_util.constant_value(v)
+ for v in loss + loss_metrics + metrics_results
+ ]
def test_on_batch(model, inputs, targets, sample_weights=None):
@@ -574,14 +586,18 @@ def test_on_batch(model, inputs, targets, sample_weights=None):
ops.convert_to_tensor(val, dtype=backend.floatx())
if val is not None else None for val in sample_weights
]
- outs, loss, loss_metrics = _model_loss(
+ outs, loss, loss_metrics, masks = _model_loss(
model, inputs, targets, sample_weights=sample_weights, training=False)
if not isinstance(outs, list):
outs = [outs]
- metrics_results = _eager_metrics_fn(model, outs, targets)
- if not isinstance(loss, list):
- loss = [loss]
- return loss + loss_metrics + metrics_results
+ metrics_results = _eager_metrics_fn(
+ model, outs, targets, sample_weights=sample_weights, masks=masks)
+ loss = generic_utils.to_list(loss)
+
+ return [
+ tensor_util.constant_value(v)
+ for v in loss + loss_metrics + metrics_results
+ ]
def fit_loop(model,
@@ -643,65 +659,26 @@ def fit_loop(model,
shuffle=shuffle)
# Required for eager execution
with backend.learning_phase_scope(1):
- do_validation = False
- if val_inputs:
- do_validation = True
-
- num_train_samples = None
- out_labels = None
- callback_metrics = None
- if model._is_compiled:
- out_labels = model.metrics_names
- if do_validation:
- callback_metrics = copy.copy(out_labels) + [
- 'val_' + n for n in out_labels
- ]
- else:
- callback_metrics = copy.copy(out_labels)
-
- model.history = cbks.History()
- callbacks = [cbks.BaseLogger()] + (callbacks or []) + [model.history]
- if verbose:
- callbacks += [cbks.ProgbarLogger('steps')]
- callbacks = cbks.CallbackList(callbacks)
-
- # it's possible to callback a different model than self
- # (used by Sequential models)
- if hasattr(model, 'callback_model') and model.callback_model:
- callback_model = model.callback_model
- else:
- callback_model = model
-
- callbacks.set_model(callback_model)
-
- callback_params = {
- 'batch_size': batch_size,
- 'epochs': epochs,
- 'steps': steps_per_epoch,
- 'samples': num_train_samples,
- 'verbose': verbose,
- 'do_validation': do_validation,
- 'metrics': callback_metrics or [],
- }
- if validation_steps:
- callback_params.update({'validation_steps': validation_steps})
- callbacks.set_params(callback_params)
-
- for cbk in callbacks:
- if not val_inputs:
- cbk.validation_data = []
- elif isinstance(val_inputs, iterator_ops.EagerIterator):
- cbk.validation_data = val_inputs
- elif val_sample_weights:
- cbk.validation_data = val_inputs + val_targets + val_sample_weights
- else:
- cbk.validation_data = val_inputs + val_targets
- # validation_data must be set before on_train_begin() is called
- # so that TensorboardCallback can validate its input
- callbacks.on_train_begin()
- callback_model.stop_training = False
+ do_validation = val_inputs is not None
+ callbacks = cbks.configure_callbacks(
+ callbacks,
+ model,
+ do_validation=do_validation,
+ batch_size=batch_size,
+ epochs=epochs,
+ steps_per_epoch=steps_per_epoch,
+ val_inputs=val_inputs,
+ val_targets=val_targets,
+ val_sample_weights=val_sample_weights,
+ validation_steps=validation_steps,
+ verbose=verbose)
+ callbacks.on_train_begin()
for epoch in range(initial_epoch, epochs):
+ if model._is_compiled: # Model may not be compiled the first time.
+ # Reset stateful metrics
+ for m in model.stateful_metric_functions:
+ m.reset_states()
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
iterator_fit_loop(
@@ -709,8 +686,6 @@ def fit_loop(model,
inputs,
class_weight,
steps_per_epoch=steps_per_epoch,
- callback_model=callback_model,
- out_labels=out_labels,
epoch_logs=epoch_logs,
val_inputs=val_inputs,
val_targets=val_targets,
@@ -718,12 +693,11 @@ def fit_loop(model,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
- callback_metrics=callback_metrics,
validation_steps=validation_steps,
do_validation=do_validation,
batch_size=batch_size)
callbacks.on_epoch_end(epoch, epoch_logs)
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
callbacks.on_train_end()
return model.history
@@ -763,10 +737,7 @@ def test_loop(model, inputs, targets,
return iterator_test_loop(model, inputs, steps, verbose=verbose)
-def predict_loop(model, inputs,
- batch_size=32,
- verbose=0,
- steps=None):
+def predict_loop(model, inputs, batch_size=32, verbose=0, steps=None):
"""Predict function for eager execution.
Arguments:
diff --git a/tensorflow/python/keras/engine/training_eager_test.py b/tensorflow/python/keras/engine/training_eager_test.py
index 56f321732f..db7ccb181f 100644
--- a/tensorflow/python/keras/engine/training_eager_test.py
+++ b/tensorflow/python/keras/engine/training_eager_test.py
@@ -24,6 +24,7 @@ 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
+from tensorflow.python.keras import metrics as metrics_module
from tensorflow.python.platform import test
from tensorflow.python.training.rmsprop import RMSPropOptimizer
@@ -44,7 +45,7 @@ class TrainingTest(test.TestCase):
optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
loss_weights = [1., 0.5]
- metrics = ['mae']
+ metrics = ['mae', metrics_module.CategoricalAccuracy()]
model.compile(
optimizer,
loss,
@@ -109,7 +110,7 @@ class TrainingTest(test.TestCase):
optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
- metrics = ['mae']
+ metrics = ['mae', metrics_module.CategoricalAccuracy()]
model.compile(optimizer, loss, metrics=metrics)
inputs = keras.backend.zeros(shape=(10, 3))
@@ -128,7 +129,9 @@ class TrainingTest(test.TestCase):
model = keras.Sequential()
model.add(keras.layers.Dense(4, input_shape=(3,)))
optimizer = RMSPropOptimizer(learning_rate=0.001)
- model.compile(optimizer, 'mse', metrics=['mae'])
+ model.compile(
+ optimizer, 'mse', metrics=['mae',
+ metrics_module.CategoricalAccuracy()])
x = np.random.random((10, 3))
y = np.random.random((10, 4))
diff --git a/tensorflow/python/keras/engine/training_generator.py b/tensorflow/python/keras/engine/training_generator.py
index 432cf2bddd..413c1f4fba 100644
--- a/tensorflow/python/keras/engine/training_generator.py
+++ b/tensorflow/python/keras/engine/training_generator.py
@@ -21,7 +21,6 @@ from __future__ import print_function
import numpy as np
-from tensorflow.python.keras import backend as K
from tensorflow.python.keras import callbacks as cbks
from tensorflow.python.keras.utils.data_utils import GeneratorEnqueuer
from tensorflow.python.keras.utils.data_utils import OrderedEnqueuer
@@ -79,66 +78,37 @@ def fit_generator(model,
' class. Please specify `validation_steps` or use'
' the `keras.utils.Sequence` class.')
- # Prepare display labels.
- out_labels = model.metrics_names
- callback_metrics = out_labels + ['val_%s' % n for n in out_labels]
-
- # prepare callbacks
- model.history = cbks.History()
- callbacks = [cbks.BaseLogger()] + (callbacks or []) + [model.history]
- if verbose:
- callbacks += [cbks.ProgbarLogger(count_mode='steps')]
- callbacks = cbks.CallbackList(callbacks)
-
- # it's possible to callback a different model than self:
- if hasattr(model, 'callback_model') and model.callback_model:
- callback_model = model.callback_model
- else:
- callback_model = model
- callbacks.set_model(callback_model)
-
- callback_params = {
- 'epochs': epochs,
- 'steps': steps_per_epoch,
- 'verbose': verbose,
- 'do_validation': do_validation,
- 'metrics': callback_metrics,
- }
- if do_validation:
- # need to create the test_function before start of the first epoch
- # because TensorBoard callback on_epoch_begin adds summary to the
- # list of fetches of the test_function
- model._make_test_function()
- # determine the number of validation batches given a generator
- if validation_steps:
- callback_params.update({'validation_steps': validation_steps})
- elif isinstance(validation_data, Sequence):
- callback_params.update({'validation_steps': len(validation_data)})
- callbacks.set_params(callback_params)
-
enqueuer = None
val_enqueuer = None
try:
+ val_x, val_y, val_sample_weights = validation_data, None, None
if do_validation and not val_gen:
# Prepare data for validation
if len(validation_data) == 2:
val_x, val_y = validation_data # pylint: disable=unpacking-non-sequence
- val_sample_weight = None
+ val_sample_weights = None
elif len(validation_data) == 3:
- val_x, val_y, val_sample_weight = validation_data # pylint: disable=unpacking-non-sequence
+ val_x, val_y, val_sample_weights = validation_data # pylint: disable=unpacking-non-sequence
else:
raise ValueError(
'`validation_data` should be a tuple '
'`(val_x, val_y, val_sample_weight)` '
'or `(val_x, val_y)`. Found: ' + str(validation_data))
val_x, val_y, val_sample_weights = model._standardize_user_data(
- val_x, val_y, val_sample_weight)
- val_data = val_x + val_y + val_sample_weights
- if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
- val_data += [0.]
- for cbk in callbacks:
- cbk.validation_data = val_data
+ val_x, val_y, val_sample_weights)
+
+ callbacks = cbks.configure_callbacks(
+ callbacks,
+ model,
+ do_validation=do_validation,
+ val_inputs=val_x,
+ val_targets=val_y,
+ val_sample_weights=val_sample_weights,
+ epochs=epochs,
+ validation_steps=validation_steps,
+ steps_per_epoch=steps_per_epoch,
+ verbose=verbose)
if workers > 0:
if is_sequence:
@@ -159,9 +129,6 @@ def fit_generator(model,
else:
output_generator = generator
- callback_model.stop_training = False
- # validation_data must be set before on_train_begin() is called
- # so that TensorboardCallback can validate its input
callbacks.on_train_begin()
# Construct epoch logs.
epoch_logs = {}
@@ -205,7 +172,7 @@ def fit_generator(model,
if not isinstance(outs, list):
outs = [outs]
- for l, o in zip(out_labels, outs):
+ for l, o in zip(model.metrics_names, outs):
batch_logs[l] = o
callbacks.on_batch_end(batch_index, batch_logs)
@@ -235,15 +202,15 @@ def fit_generator(model,
if not isinstance(val_outs, list):
val_outs = [val_outs]
# Same labels assumed.
- for l, o in zip(out_labels, val_outs):
+ for l, o in zip(model.metrics_names, val_outs):
epoch_logs['val_' + l] = o
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
callbacks.on_epoch_end(epoch, epoch_logs)
epoch += 1
- if callback_model.stop_training:
+ if callbacks.model.stop_training:
break
finally:
@@ -266,7 +233,6 @@ def evaluate_generator(model,
use_multiprocessing=False,
verbose=0):
"""See docstring for `Model.evaluate_generator`."""
- stateful_metric_indices = []
if hasattr(model, 'metrics'):
for m in model.stateful_metric_functions:
m.reset_states()
@@ -364,7 +330,7 @@ def evaluate_generator(model,
averages.append(
np.average([out[i] for out in all_outs], weights=batch_sizes))
else:
- averages.append(float(all_outs[-1][i]))
+ averages.append(np.float64(all_outs[-1][i]))
return averages
diff --git a/tensorflow/python/keras/engine/training_test.py b/tensorflow/python/keras/engine/training_test.py
index 0e10eba4c6..5e5135b179 100644
--- a/tensorflow/python/keras/engine/training_test.py
+++ b/tensorflow/python/keras/engine/training_test.py
@@ -30,6 +30,7 @@ from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util as tf_test_util
+from tensorflow.python.keras import metrics as metrics_module
from tensorflow.python.keras import testing_utils
from tensorflow.python.keras.engine.training_utils import weighted_masked_objective
from tensorflow.python.keras.utils.generic_utils import slice_arrays
@@ -62,8 +63,11 @@ class TrainingTest(test.TestCase):
optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
loss_weights = [1., 0.5]
- metrics = ['mae']
- model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights)
+ model.compile(
+ optimizer,
+ loss,
+ metrics=[metrics_module.CategoricalAccuracy(), 'mae'],
+ loss_weights=loss_weights)
input_a_np = np.random.random((10, 3))
input_b_np = np.random.random((10, 3))
@@ -178,8 +182,10 @@ class TrainingTest(test.TestCase):
# Test with lists for loss, metrics
loss = ['mae', 'mse']
- metrics = ['acc', 'mae']
- model.compile(optimizer, loss, metrics=metrics)
+ model.compile(
+ optimizer,
+ loss,
+ metrics=[metrics_module.CategoricalAccuracy(), 'mae'])
model.fit(
[input_a_np, input_b_np], [output_d_np, output_e_np],
epochs=1,
@@ -189,7 +195,10 @@ class TrainingTest(test.TestCase):
# Test with dictionaries for loss, metrics, loss weights
loss = {'dense': 'mse', 'dropout': 'mae'}
loss_weights = {'dense': 1., 'dropout': 0.5}
- metrics = {'dense': 'mse', 'dropout': 'mae'}
+ metrics = {
+ 'dense': 'mse',
+ 'dropout': metrics_module.CategoricalAccuracy()
+ }
model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights)
model.fit(
[input_a_np, input_b_np], [output_d_np, output_e_np],
@@ -258,11 +267,10 @@ class TrainingTest(test.TestCase):
optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
loss_weights = [1., 0.5]
- metrics = ['mae']
model.compile(
optimizer,
loss,
- metrics=metrics,
+ metrics=['mae', metrics_module.CategoricalAccuracy()],
loss_weights=loss_weights,
sample_weight_mode=None)
@@ -277,20 +285,20 @@ class TrainingTest(test.TestCase):
[input_a_np, input_b_np], [output_d_np, output_e_np],
batch_size=5,
verbose=0)
- self.assertEqual(len(out), 5)
+ self.assertEqual(len(out), 7)
out = model.evaluate(
[input_a_np, input_b_np], [output_d_np, output_e_np],
batch_size=5,
verbose=1)
- self.assertEqual(len(out), 5)
+ self.assertEqual(len(out), 7)
out = model.evaluate(
[input_a_np, input_b_np], [output_d_np, output_e_np],
batch_size=5,
verbose=2)
- self.assertEqual(len(out), 5)
+ self.assertEqual(len(out), 7)
out = model.test_on_batch([input_a_np, input_b_np],
[output_d_np, output_e_np])
- self.assertEqual(len(out), 5)
+ self.assertEqual(len(out), 7)
# Test evaluate with dictionary inputs
model.evaluate(
@@ -326,7 +334,7 @@ class TrainingTest(test.TestCase):
self.assertEqual(len(out), 2)
@tf_test_util.run_in_graph_and_eager_modes
- def test_invalid_loss_or_metrics(self):
+ def test_invalid_loss(self):
num_classes = 5
train_samples = 1000
test_samples = 1000
@@ -350,10 +358,6 @@ class TrainingTest(test.TestCase):
with self.assertRaises(ValueError):
model.fit(x_train, np.concatenate([y_train, y_train], axis=-1))
- with self.assertRaises(TypeError):
- model.compile(
- optimizer, loss='categorical_crossentropy', metrics=set(0))
-
if not context.executing_eagerly():
# TODO(psv): Investigate these use cases in eager mode.
with self.assertRaises(ValueError):
@@ -379,7 +383,11 @@ class TrainingTest(test.TestCase):
out2 = keras.layers.Dense(4, name='dense_1')(in2)
model = keras.Model([in1, in2], [out1, out2])
model.predict(test_inputs, batch_size=2)
- model.compile('rmsprop', 'mse')
+ optimizer = RMSPropOptimizer(learning_rate=0.001)
+ model.compile(
+ optimizer,
+ 'mse',
+ metrics=['mae', metrics_module.CategoricalAccuracy()])
model.fit(test_inputs, test_outputs,
epochs=1, batch_size=2, validation_split=0.5)
model.evaluate(test_inputs, test_outputs, batch_size=2)
@@ -422,22 +430,24 @@ class TrainingTest(test.TestCase):
x2 = model.predict(val_a)
self.assertAllClose(x1, x2, atol=1e-7)
+ @tf_test_util.run_in_graph_and_eager_modes
def test_compile_warning_for_loss_missing_output(self):
with self.test_session():
inp = keras.layers.Input(shape=(16,), name='input_a')
out_1 = keras.layers.Dense(8, name='dense_1')(inp)
out_2 = keras.layers.Dense(3, activation='softmax', name='dense_2')(out_1)
model = keras.models.Model(inputs=[inp], outputs=[out_1, out_2])
+ optimizer = RMSPropOptimizer(learning_rate=0.001)
with test.mock.patch.object(logging, 'warning') as mock_log:
model.compile(
+ optimizer,
loss={
'dense_2': 'categorical_crossentropy',
},
- optimizer='rmsprop',
metrics={
'dense_2': 'categorical_accuracy',
- 'dense_1': 'categorical_accuracy',
+ 'dense_1': metrics_module.CategoricalAccuracy(),
})
msg = ('Output "dense_1" missing from loss dictionary. We assume this '
'was done on purpose. The fit and evaluate APIs will not be '
@@ -466,6 +476,8 @@ class LossWeightingTest(test.TestCase):
model.add(keras.layers.Activation('softmax'))
model.compile(
loss='categorical_crossentropy',
+ metrics=['acc'],
+ weighted_metrics=['mae'],
optimizer=RMSPropOptimizer(learning_rate=learning_rate))
np.random.seed(1337)
@@ -516,7 +528,7 @@ class LossWeightingTest(test.TestCase):
ref_score = model.evaluate(x_test, y_test, verbose=0)
score = model.evaluate(
x_test[test_ids, :], y_test[test_ids, :], verbose=0)
- self.assertLess(score, ref_score)
+ self.assertLess(score[0], ref_score[0])
@tf_test_util.run_in_graph_and_eager_modes
def test_sample_weights(self):
@@ -537,6 +549,8 @@ class LossWeightingTest(test.TestCase):
model.add(keras.layers.Activation('softmax'))
model.compile(
RMSPropOptimizer(learning_rate=learning_rate),
+ metrics=['acc'],
+ weighted_metrics=['mae'],
loss='categorical_crossentropy')
np.random.seed(43)
@@ -583,7 +597,30 @@ class LossWeightingTest(test.TestCase):
if not context.executing_eagerly():
score = model.evaluate(
x_test[test_ids, :], y_test[test_ids, :], verbose=0)
- self.assertLess(score, ref_score)
+ self.assertLess(score[0], ref_score[0])
+
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_warning_for_concurrent_sample_and_class_weights(self):
+ model = keras.models.Sequential()
+ model.add(keras.layers.Dense(10, input_shape=(3,)))
+ model.compile(
+ loss='mse',
+ optimizer=RMSPropOptimizer(learning_rate=0.01))
+ x_train = np.random.random((10, 3))
+ y_train = np.random.random((10, 10))
+ sample_weight = np.ones((y_train.shape[0]))
+ class_weight = {0: 1., 1: 1.}
+
+ with test.mock.patch.object(logging, 'warning') as mock_log:
+ model.fit(
+ x_train,
+ y_train,
+ epochs=1,
+ verbose=0,
+ sample_weight=sample_weight,
+ class_weight=class_weight)
+ msg = ('The `class_weight` argument will be ignored.')
+ self.assertRegexpMatches(str(mock_log.call_args), msg)
@tf_test_util.run_in_graph_and_eager_modes
def test_temporal_sample_weights(self):
@@ -641,6 +678,8 @@ class LossWeightingTest(test.TestCase):
model.compile(
RMSPropOptimizer(learning_rate=learning_rate),
loss='binary_crossentropy',
+ metrics=['acc'],
+ weighted_metrics=['mae'],
sample_weight_mode='temporal')
model.fit(
@@ -671,7 +710,7 @@ class LossWeightingTest(test.TestCase):
if not context.executing_eagerly():
score = model.evaluate(
temporal_x_test[test_ids], temporal_y_test[test_ids], verbose=0)
- self.assertLess(score, ref_score)
+ self.assertLess(score[0], ref_score[0])
@tf_test_util.run_in_graph_and_eager_modes
def test_class_weight_invalid_use_case(self):
@@ -1066,7 +1105,10 @@ class TestGeneratorMethods(test.TestCase):
x = keras.Input((2,))
y = keras.layers.Dense(1)(x)
fn_model = keras.models.Model(x, y)
- fn_model.compile(loss='mse', optimizer='sgd')
+ fn_model.compile(
+ loss='mse',
+ optimizer='sgd',
+ metrics=['mae', metrics_module.CategoricalAccuracy()])
seq_model = keras.models.Sequential()
seq_model.add(keras.layers.Dense(1, input_shape=(2,)))
@@ -1148,7 +1190,10 @@ class TestGeneratorMethods(test.TestCase):
with self.test_session():
model = keras.models.Sequential()
model.add(keras.layers.Dense(1, input_shape=(2,)))
- model.compile(loss='mse', optimizer='sgd')
+ model.compile(
+ loss='mse',
+ optimizer='sgd',
+ metrics=['mae', metrics_module.CategoricalAccuracy()])
model.fit_generator(custom_generator(),
steps_per_epoch=5,
@@ -1300,10 +1345,12 @@ class TestTrainingWithDataTensors(test.TestCase):
y = keras.layers.Dense(4, name='dense')(x)
model = keras.Model(x, y)
- optimizer = 'rmsprop'
+ optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
- metrics = ['mae']
- model.compile(optimizer, loss, metrics=metrics)
+ model.compile(
+ optimizer,
+ loss,
+ metrics=['mae', metrics_module.CategoricalAccuracy()])
inputs = keras.backend.zeros(shape=(10, 3))
targets = keras.backend.zeros(shape=(10, 4))
@@ -1347,8 +1394,11 @@ class TestTrainingWithDataTensors(test.TestCase):
optimizer = 'rmsprop'
loss = 'mse'
loss_weights = [1., 0.5]
- metrics = ['mae']
- model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights)
+ model.compile(
+ optimizer,
+ loss,
+ metrics=['mae', metrics_module.CategoricalAccuracy()],
+ loss_weights=loss_weights)
input_a_tf = keras.backend.zeros(shape=(10, 3))
input_b_tf = keras.backend.zeros(shape=(10, 3))
@@ -1786,8 +1836,11 @@ class TestTrainingWithDataTensors(test.TestCase):
model.train_on_batch(input_val, None)
# test with sample weights
- model.compile(optimizer='rmsprop', loss='mse',
- target_tensors=[target_a, target_b])
+ model.compile(
+ optimizer='rmsprop',
+ loss='mse',
+ metrics=['mae', metrics_module.CategoricalAccuracy()],
+ target_tensors=[target_a, target_b])
model.train_on_batch(input_val, None,
sample_weight={'dense_a': np.random.random((10,))})
@@ -1851,30 +1904,6 @@ class TestTrainingWithDataTensors(test.TestCase):
model.train_on_batch([input_a_np, input_b_np],
[output_a_np, output_b_np])
- @tf_test_util.run_in_graph_and_eager_modes
- def test_metric_names_are_identical_in_graph_and_eager(self):
- a = keras.layers.Input(shape=(3,), name='input_a')
- b = keras.layers.Input(shape=(3,), name='input_b')
-
- dense = keras.layers.Dense(4, name='dense')
- c = dense(a)
- d = dense(b)
- e = keras.layers.Dropout(0.5, name='dropout')(c)
-
- model = keras.models.Model([a, b], [d, e])
-
- optimizer = RMSPropOptimizer(learning_rate=0.001)
- loss = 'mse'
- loss_weights = [1., 0.5]
- metrics = ['mae', 'acc']
- model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights)
- reference_metric_names = ['loss', 'dense_loss', 'dropout_loss',
- 'dense_mean_absolute_error',
- 'dense_acc',
- 'dropout_mean_absolute_error',
- 'dropout_acc']
- self.assertEqual(reference_metric_names, model.metrics_names)
-
class TestTrainingWithDatasetIterators(test.TestCase):
@@ -1887,7 +1916,7 @@ class TestTrainingWithDatasetIterators(test.TestCase):
optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
- metrics = ['mae']
+ metrics = ['mae', metrics_module.CategoricalAccuracy()]
model.compile(optimizer, loss, metrics=metrics)
inputs = np.zeros((10, 3))
@@ -1944,6 +1973,7 @@ class TestTrainingWithDatasetIterators(test.TestCase):
'you should specify the `steps` argument'):
model.predict(iterator, verbose=0)
+ @tf_test_util.run_in_graph_and_eager_modes
def test_get_next_op_created_once(self):
with self.test_session():
x = keras.layers.Input(shape=(3,), name='input')
@@ -1996,6 +2026,7 @@ class TestTrainingWithDatasetIterators(test.TestCase):
class TestTrainingWithDataset(test.TestCase):
+ @tf_test_util.run_in_graph_and_eager_modes
def test_calling_model_on_same_dataset(self):
with self.test_session():
x = keras.layers.Input(shape=(3,), name='input')
@@ -2031,7 +2062,7 @@ class TestTrainingWithDataset(test.TestCase):
optimizer = RMSPropOptimizer(learning_rate=0.001)
loss = 'mse'
- metrics = ['mae']
+ metrics = ['mae', metrics_module.CategoricalAccuracy()]
model.compile(optimizer, loss, metrics=metrics)
inputs = np.zeros((10, 3))
@@ -2122,6 +2153,28 @@ class TestTrainingWithMetrics(test.TestCase):
"""Training tests related to metrics."""
@tf_test_util.run_in_graph_and_eager_modes
+ def test_metrics_names(self):
+ a = keras.layers.Input(shape=(3,), name='input_a')
+ b = keras.layers.Input(shape=(3,), name='input_b')
+
+ dense = keras.layers.Dense(4, name='dense')
+ c = dense(a)
+ d = dense(b)
+ e = keras.layers.Dropout(0.5, name='dropout')(c)
+
+ model = keras.models.Model([a, b], [d, e])
+
+ optimizer = RMSPropOptimizer(learning_rate=0.001)
+ metrics = ['mse', metrics_module.BinaryAccuracy()]
+ model.compile(optimizer, loss='mae', metrics=metrics)
+ reference_metric_names = [
+ 'loss', 'dense_loss', 'dropout_loss', 'dense_mean_squared_error',
+ 'dense_binary_accuracy', 'dropout_mean_squared_error',
+ 'dropout_binary_accuracy'
+ ]
+ self.assertEqual(reference_metric_names, model.metrics_names)
+
+ @tf_test_util.run_in_graph_and_eager_modes
def test_metrics_correctness(self):
with self.test_session():
model = keras.Sequential()
@@ -2133,7 +2186,7 @@ class TestTrainingWithMetrics(test.TestCase):
1, activation='sigmoid', kernel_initializer='ones'))
model.compile(
loss='mae',
- metrics=['accuracy'],
+ metrics=['accuracy', metrics_module.BinaryAccuracy()],
optimizer=RMSPropOptimizer(learning_rate=0.001))
# verify correctness of stateful and stateless metrics.
@@ -2141,41 +2194,48 @@ class TestTrainingWithMetrics(test.TestCase):
y = np.ones((100, 1))
outs = model.evaluate(x, y)
self.assertEqual(outs[1], 1.)
+ self.assertEqual(outs[2], 1.)
y = np.zeros((100, 1))
outs = model.evaluate(x, y)
self.assertEqual(outs[1], 0.)
+ self.assertEqual(outs[2], 0.)
@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.)
+ with self.test_session():
+ 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', metrics_module.BinaryAccuracy()],
+ 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)
+ self.assertEqual(np.around(outs[2], 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.)
+ self.assertEqual(outs[2], 0.)
+ @tf_test_util.run_in_graph_and_eager_modes
def test_metrics_correctness_with_weighted_metrics(self):
with self.test_session():
np.random.seed(1337)
@@ -2189,19 +2249,87 @@ class TestTrainingWithMetrics(test.TestCase):
RMSPropOptimizer(learning_rate=0.001),
loss='mse',
sample_weight_mode='temporal',
- weighted_metrics=['accuracy'])
+ weighted_metrics=['accuracy',
+ metrics_module.BinaryAccuracy()])
y = np.array([[[1.], [1.]], [[1.], [1.]]])
outs = model.evaluate(x, y)
- self.assertEqual(outs, [0.5, 0.5])
+ self.assertEqual(outs, [0.5, 0.5, 0.5])
w = np.array([[0., 0.], [0., 0.]])
outs = model.evaluate(x, y, sample_weight=w)
- self.assertEqual(outs, [0., 0.])
+ self.assertEqual(outs, [0., 0., 0.])
w = np.array([[3., 4.], [1., 2.]])
outs = model.evaluate(x, y, sample_weight=w)
- self.assertArrayNear(outs, [0.3, 0.7], .001)
+ self.assertArrayNear(outs, [0.3, 0.7, 0.7], .001)
+
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_metric_state_reset_between_fit_and_evaluate(self):
+ with self.test_session():
+ model = keras.Sequential()
+ model.add(keras.layers.Dense(3, activation='relu', input_dim=4))
+ model.add(keras.layers.Dense(1, activation='sigmoid'))
+ acc_obj = metrics_module.BinaryAccuracy()
+ model.compile(
+ loss='mae',
+ metrics=[acc_obj],
+ optimizer=RMSPropOptimizer(learning_rate=0.001))
+
+ x_train = np.random.random((100, 4))
+ y_train = np.random.random((100, 1))
+ model.fit(x_train, y_train, batch_size=5, epochs=2)
+ self.assertEqual(self.evaluate(acc_obj.count), 100)
+
+ x_test = np.random.random((10, 4))
+ y_test = np.random.random((10, 1))
+ model.evaluate(x_test, y_test, batch_size=5)
+ self.assertEqual(self.evaluate(acc_obj.count), 10)
+
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_invalid_metrics(self):
+ num_classes = 5
+ input_dim = 5
+
+ with self.test_session():
+ model = keras.models.Sequential()
+ model.add(
+ keras.layers.Dense(10, activation='relu', input_shape=(input_dim,)))
+ model.add(keras.layers.Dense(num_classes, activation='softmax'))
+
+ with self.assertRaisesRegexp(
+ TypeError, 'Type of `metrics` argument not understood. '
+ 'Expected a list or dictionary, found: '):
+ model.compile(
+ RMSPropOptimizer(learning_rate=0.001),
+ loss='categorical_crossentropy',
+ metrics=metrics_module.CategoricalAccuracy())
+
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_metrics_masking(self):
+ with self.test_session():
+ np.random.seed(1337)
+ model = keras.models.Sequential()
+ model.add(keras.layers.Masking(mask_value=0, input_shape=(2, 1)))
+ model.add(
+ keras.layers.TimeDistributed(
+ keras.layers.Dense(1, kernel_initializer='ones')))
+ model.compile(
+ RMSPropOptimizer(learning_rate=0.001),
+ loss='mse',
+ weighted_metrics=['accuracy',
+ metrics_module.BinaryAccuracy()])
+
+ # verify that masking is applied for stateless and stateful metrics.
+ x = np.array([[[1], [1]], [[1], [1]], [[0], [0]]])
+ y = np.array([[[1], [1]], [[0], [1]], [[1], [1]]])
+ scores = model.train_on_batch(x, y)
+ self.assertArrayNear(scores, [0.25, 0.75, 0.75], 0.1)
+
+ # verify that masking is combined with sample weights.
+ w = np.array([3, 2, 4])
+ scores = model.train_on_batch(x, y, sample_weight=w)
+ self.assertArrayNear(scores, [0.2, 0.8, 0.8], 0.1)
if __name__ == '__main__':
diff --git a/tensorflow/python/keras/engine/training_utils.py b/tensorflow/python/keras/engine/training_utils.py
index 38b64e69ec..f94697c913 100644
--- a/tensorflow/python/keras/engine/training_utils.py
+++ b/tensorflow/python/keras/engine/training_utils.py
@@ -570,13 +570,24 @@ def weighted_masked_objective(fn):
# score_array has ndim >= 2
score_array = fn(y_true, y_pred)
if mask is not None:
- # Cast the mask to floatX to avoid float64 upcasting in theano
- mask = math_ops.cast(mask, K.floatx())
- # mask should have the same shape as score_array
- score_array *= mask
- # the loss per batch should be proportional
- # to the number of unmasked samples.
- score_array /= K.mean(mask)
+ mask = math_ops.cast(mask, y_pred.dtype)
+ # Update weights with mask.
+ if weights is None:
+ weights = mask
+ else:
+ # Update shape of weights if possible before adding mask.
+ # Update dimensions of weights to match with mask if possible.
+ mask, _, weights = metrics_module.squeeze_or_expand_dimensions(
+ mask, None, weights)
+ try:
+ # Broadcast weights if possible.
+ weights = weights_broadcast_ops.broadcast_weights(weights, mask)
+ weights *= mask
+ except ValueError:
+ score_array *= mask
+ score_array /= K.mean(mask)
+ # TODO(psv): Handle case when mask and weight shapes are not
+ # compatible.
# Apply sample weighting.
if weights is not None:
@@ -709,43 +720,6 @@ def has_tensors(ls):
return tensor_util.is_tensor(ls)
-def populate_metric_names(model):
- for i in range(len(model.outputs)):
- metrics = model.nested_metrics[i]
- for metric in metrics:
- base_metric_name = get_metric_name(metric)
- add_metric_name(model, base_metric_name, i)
-
-
-def get_metric_name(metric, weighted=False):
- """Returns the metric name corresponding to the given metric input.
-
- Arguments:
- metric: Metric function name or reference.
- weighted: Boolean indicating if the given metric is weighted.
-
- Returns:
- a metric name.
- """
- metric_name_prefix = 'weighted_' if weighted else ''
- if metric in ('accuracy', 'acc', 'crossentropy', 'ce'):
- if metric in ('accuracy', 'acc'):
- suffix = 'acc'
- elif metric in ('crossentropy', 'ce'):
- suffix = 'ce'
- metric_name = metric_name_prefix + suffix
- else:
- metric_fn = metrics_module.get(metric)
- # Get metric name as string
- if hasattr(metric_fn, 'name'):
- metric_name = metric_fn.name
- else:
- metric_name = metric_fn.__name__
- metric_name = metric_name_prefix + metric_name
-
- return metric_name
-
-
def get_metric_function(metric, output_shape=None, loss_fn=None):
"""Returns the metric function corresponding to the given metric input.
@@ -776,33 +750,6 @@ def get_metric_function(metric, output_shape=None, loss_fn=None):
return metrics_module.get(metric)
-def add_metric_name(model, metric_name, index):
- """Makes the metric name unique and adds it to the model's metric name list.
-
- If there are multiple outputs for which the metrics are calculated, the
- metric names have to be made unique by appending an integer.
-
- Arguments:
- model: Model to which we are adding metric names.
- metric_name: Metric name that corresponds to the metric specified by the
- user. For example: 'acc'
- index: The index of the model output for which the metric name is being
- added.
-
- Returns:
- string, name of the model's unique metric name
- """
- if len(model.output_names) > 1:
- metric_name = '%s_%s' % (model.output_names[index], metric_name)
- j = 1
- base_metric_name = metric_name
- while metric_name in model.metrics_names:
- metric_name = '%s_%d' % (base_metric_name, j)
- j += 1
- model.metrics_names.append(metric_name)
- return metric_name
-
-
def validate_iterator_input(x, y, sample_weight, validation_split=None):
"""Validates user input arguments when a dataset iterator is passed.
diff --git a/tensorflow/python/keras/integration_test.py b/tensorflow/python/keras/integration_test.py
index 2a05699407..a103b9fbf2 100644
--- a/tensorflow/python/keras/integration_test.py
+++ b/tensorflow/python/keras/integration_test.py
@@ -21,9 +21,11 @@ from __future__ import print_function
import numpy as np
from tensorflow.python import keras
+from tensorflow.python.framework import dtypes
from tensorflow.python.keras import testing_utils
from tensorflow.python.layers import core as tf_core_layers
from tensorflow.python.ops import nn
+from tensorflow.python.ops import rnn_cell
from tensorflow.python.platform import test
@@ -103,6 +105,30 @@ class KerasIntegrationTest(test.TestCase):
verbose=2)
self.assertGreater(history.history['val_acc'][-1], 0.7)
+ def test_temporal_classification_sequential_tf_rnn(self):
+ with self.test_session():
+ np.random.seed(1337)
+ (x_train, y_train), _ = testing_utils.get_test_data(
+ train_samples=100,
+ test_samples=0,
+ input_shape=(4, 10),
+ num_classes=2)
+ y_train = keras.utils.to_categorical(y_train)
+
+ model = keras.models.Sequential()
+ model.add(keras.layers.RNN(rnn_cell.LSTMCell(5), return_sequences=True,
+ input_shape=x_train.shape[1:]))
+ model.add(keras.layers.RNN(rnn_cell.GRUCell(y_train.shape[-1],
+ activation='softmax',
+ dtype=dtypes.float32)))
+ model.compile(loss='categorical_crossentropy',
+ optimizer=keras.optimizers.Adam(lr=0.1),
+ metrics=['accuracy'])
+ history = model.fit(x_train, y_train, epochs=15, batch_size=16,
+ validation_data=(x_train, y_train),
+ verbose=2)
+ self.assertGreater(history.history['val_acc'][-1], 0.7)
+
def test_image_classification_sequential(self):
with self.test_session():
np.random.seed(1337)
diff --git a/tensorflow/python/keras/layers/local.py b/tensorflow/python/keras/layers/local.py
index 0ebafe07cc..33d09a1660 100644
--- a/tensorflow/python/keras/layers/local.py
+++ b/tensorflow/python/keras/layers/local.py
@@ -85,6 +85,28 @@ class LocallyConnected1D(Layer):
the output of the layer (its "activation")..
kernel_constraint: Constraint function applied to the kernel matrix.
bias_constraint: Constraint function applied to the bias vector.
+ implementation: implementation mode, either `1` or `2`.
+ `1` loops over input spatial locations to perform the forward pass.
+ It is memory-efficient but performs a lot of (small) ops.
+
+ `2` stores layer weights in a dense but sparsely-populated 2D matrix
+ and implements the forward pass as a single matrix-multiply. It uses
+ a lot of RAM but performs few (large) ops.
+
+ Depending on the inputs, layer parameters, hardware, and
+ `tf.executing_eagerly()` one implementation can be dramatically faster
+ (e.g. 50X) than another.
+
+ It is recommended to benchmark both in the setting of interest to pick
+ the most efficient one (in terms of speed and memory usage).
+
+ Following scenarios could benefit from setting `implementation=2`:
+ - eager execution;
+ - inference;
+ - running on CPU;
+ - large amount of RAM available;
+ - small models (few filters, small kernel);
+ - using `padding=same` (only possible with `implementation=2`).
Input shape:
3D tensor with shape: `(batch_size, steps, input_dim)`
@@ -109,15 +131,17 @@ class LocallyConnected1D(Layer):
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
+ implementation=1,
**kwargs):
super(LocallyConnected1D, self).__init__(**kwargs)
self.filters = filters
self.kernel_size = conv_utils.normalize_tuple(kernel_size, 1, 'kernel_size')
self.strides = conv_utils.normalize_tuple(strides, 1, 'strides')
self.padding = conv_utils.normalize_padding(padding)
- if self.padding != 'valid':
+ if self.padding != 'valid' and implementation == 1:
raise ValueError('Invalid border mode for LocallyConnected1D '
- '(only "valid" is supported): ' + padding)
+ '(only "valid" is supported if implementation is 1): '
+ + padding)
self.data_format = conv_utils.normalize_data_format(data_format)
self.activation = activations.get(activation)
self.use_bias = use_bias
@@ -128,6 +152,7 @@ class LocallyConnected1D(Layer):
self.activity_regularizer = regularizers.get(activity_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
+ self.implementation = implementation
self.input_spec = InputSpec(ndim=3)
@tf_utils.shape_type_conversion
@@ -142,14 +167,45 @@ class LocallyConnected1D(Layer):
'Found shape:', input_shape)
self.output_length = conv_utils.conv_output_length(
input_length, self.kernel_size[0], self.padding, self.strides[0])
- self.kernel_shape = (self.output_length, self.kernel_size[0] * input_dim,
- self.filters)
- self.kernel = self.add_weight(
- shape=self.kernel_shape,
- initializer=self.kernel_initializer,
- name='kernel',
- regularizer=self.kernel_regularizer,
- constraint=self.kernel_constraint)
+
+ if self.implementation == 1:
+ self.kernel_shape = (self.output_length, self.kernel_size[0] * input_dim,
+ self.filters)
+
+ self.kernel = self.add_weight(
+ shape=self.kernel_shape,
+ initializer=self.kernel_initializer,
+ name='kernel',
+ regularizer=self.kernel_regularizer,
+ constraint=self.kernel_constraint)
+
+ elif self.implementation == 2:
+ if self.data_format == 'channels_first':
+ self.kernel_shape = (input_dim, input_length,
+ self.filters, self.output_length)
+ else:
+ self.kernel_shape = (input_length, input_dim,
+ self.output_length, self.filters)
+
+ self.kernel = self.add_weight(shape=self.kernel_shape,
+ initializer=self.kernel_initializer,
+ name='kernel',
+ regularizer=self.kernel_regularizer,
+ constraint=self.kernel_constraint)
+
+ self.kernel_mask = get_locallyconnected_mask(
+ input_shape=(input_length,),
+ kernel_shape=self.kernel_size,
+ strides=self.strides,
+ padding=self.padding,
+ data_format=self.data_format,
+ dtype=self.kernel.dtype
+ )
+
+ else:
+ raise ValueError('Unrecognized implementation mode: %d.'
+ % self.implementation)
+
if self.use_bias:
self.bias = self.add_weight(
shape=(self.output_length, self.filters),
@@ -182,8 +238,17 @@ class LocallyConnected1D(Layer):
return (input_shape[0], length, self.filters)
def call(self, inputs):
- output = K.local_conv(inputs, self.kernel, self.kernel_size, self.strides,
- (self.output_length,), self.data_format)
+ if self.implementation == 1:
+ output = K.local_conv(inputs, self.kernel, self.kernel_size, self.strides,
+ (self.output_length,), self.data_format)
+
+ elif self.implementation == 2:
+ output = local_conv_matmul(inputs, self.kernel, self.kernel_mask,
+ self.compute_output_shape(inputs.shape))
+
+ else:
+ raise ValueError('Unrecognized implementation mode: %d.'
+ % self.implementation)
if self.use_bias:
output = K.bias_add(output, self.bias, data_format=self.data_format)
@@ -220,7 +285,9 @@ class LocallyConnected1D(Layer):
'kernel_constraint':
constraints.serialize(self.kernel_constraint),
'bias_constraint':
- constraints.serialize(self.bias_constraint)
+ constraints.serialize(self.bias_constraint),
+ 'implementation':
+ self.implementation
}
base_config = super(LocallyConnected1D, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@@ -284,9 +351,31 @@ class LocallyConnected2D(Layer):
the `kernel` weights matrix.
bias_regularizer: Regularizer function applied to the bias vector.
activity_regularizer: Regularizer function applied to
- the output of the layer (its "activation")..
+ the output of the layer (its "activation").
kernel_constraint: Constraint function applied to the kernel matrix.
bias_constraint: Constraint function applied to the bias vector.
+ implementation: implementation mode, either `1` or `2`.
+ `1` loops over input spatial locations to perform the forward pass.
+ It is memory-efficient but performs a lot of (small) ops.
+
+ `2` stores layer weights in a dense but sparsely-populated 2D matrix
+ and implements the forward pass as a single matrix-multiply. It uses
+ a lot of RAM but performs few (large) ops.
+
+ Depending on the inputs, layer parameters, hardware, and
+ `tf.executing_eagerly()` one implementation can be dramatically faster
+ (e.g. 50X) than another.
+
+ It is recommended to benchmark both in the setting of interest to pick
+ the most efficient one (in terms of speed and memory usage).
+
+ Following scenarios could benefit from setting `implementation=2`:
+ - eager execution;
+ - inference;
+ - running on CPU;
+ - large amount of RAM available;
+ - small models (few filters, small kernel);
+ - using `padding=same` (only possible with `implementation=2`).
Input shape:
4D tensor with shape:
@@ -317,15 +406,17 @@ class LocallyConnected2D(Layer):
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
+ implementation=1,
**kwargs):
super(LocallyConnected2D, self).__init__(**kwargs)
self.filters = filters
self.kernel_size = conv_utils.normalize_tuple(kernel_size, 2, 'kernel_size')
self.strides = conv_utils.normalize_tuple(strides, 2, 'strides')
self.padding = conv_utils.normalize_padding(padding)
- if self.padding != 'valid':
+ if self.padding != 'valid' and implementation == 1:
raise ValueError('Invalid border mode for LocallyConnected2D '
- '(only "valid" is supported): ' + padding)
+ '(only "valid" is supported if implementation is 1): '
+ + padding)
self.data_format = conv_utils.normalize_data_format(data_format)
self.activation = activations.get(activation)
self.use_bias = use_bias
@@ -336,6 +427,7 @@ class LocallyConnected2D(Layer):
self.activity_regularizer = regularizers.get(activity_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
+ self.implementation = implementation
self.input_spec = InputSpec(ndim=4)
@tf_utils.shape_type_conversion
@@ -357,15 +449,47 @@ class LocallyConnected2D(Layer):
self.padding, self.strides[1])
self.output_row = output_row
self.output_col = output_col
- self.kernel_shape = (
- output_row * output_col,
- self.kernel_size[0] * self.kernel_size[1] * input_filter, self.filters)
- self.kernel = self.add_weight(
- shape=self.kernel_shape,
- initializer=self.kernel_initializer,
- name='kernel',
- regularizer=self.kernel_regularizer,
- constraint=self.kernel_constraint)
+
+ if self.implementation == 1:
+ self.kernel_shape = (
+ output_row * output_col,
+ self.kernel_size[0] * self.kernel_size[1] * input_filter,
+ self.filters)
+
+ self.kernel = self.add_weight(
+ shape=self.kernel_shape,
+ initializer=self.kernel_initializer,
+ name='kernel',
+ regularizer=self.kernel_regularizer,
+ constraint=self.kernel_constraint)
+
+ elif self.implementation == 2:
+ if self.data_format == 'channels_first':
+ self.kernel_shape = (input_filter, input_row, input_col,
+ self.filters, self.output_row, self.output_col)
+ else:
+ self.kernel_shape = (input_row, input_col, input_filter,
+ self.output_row, self.output_col, self.filters)
+
+ self.kernel = self.add_weight(shape=self.kernel_shape,
+ initializer=self.kernel_initializer,
+ name='kernel',
+ regularizer=self.kernel_regularizer,
+ constraint=self.kernel_constraint)
+
+ self.kernel_mask = get_locallyconnected_mask(
+ input_shape=(input_row, input_col),
+ kernel_shape=self.kernel_size,
+ strides=self.strides,
+ padding=self.padding,
+ data_format=self.data_format,
+ dtype=self.kernel.dtype
+ )
+
+ else:
+ raise ValueError('Unrecognized implementation mode: %d.'
+ % self.implementation)
+
if self.use_bias:
self.bias = self.add_weight(
shape=(output_row, output_col, self.filters),
@@ -401,8 +525,18 @@ class LocallyConnected2D(Layer):
return (input_shape[0], rows, cols, self.filters)
def call(self, inputs):
- output = K.local_conv(inputs, self.kernel, self.kernel_size, self.strides,
- (self.output_row, self.output_col), self.data_format)
+ if self.implementation == 1:
+ output = K.local_conv(inputs, self.kernel, self.kernel_size, self.strides,
+ (self.output_row, self.output_col),
+ self.data_format)
+
+ elif self.implementation == 2:
+ output = local_conv_matmul(inputs, self.kernel, self.kernel_mask,
+ self.compute_output_shape(inputs.shape))
+
+ else:
+ raise ValueError('Unrecognized implementation mode: %d.'
+ % self.implementation)
if self.use_bias:
output = K.bias_add(output, self.bias, data_format=self.data_format)
@@ -439,7 +573,157 @@ class LocallyConnected2D(Layer):
'kernel_constraint':
constraints.serialize(self.kernel_constraint),
'bias_constraint':
- constraints.serialize(self.bias_constraint)
+ constraints.serialize(self.bias_constraint),
+ 'implementation':
+ self.implementation
}
base_config = super(LocallyConnected2D, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
+
+
+def get_locallyconnected_mask(input_shape,
+ kernel_shape,
+ strides,
+ padding,
+ data_format,
+ dtype):
+ """Return a mask representing connectivity of a locally-connected operation.
+
+ This method returns a masking tensor of 0s and 1s (of type `dtype`) that,
+ when element-wise multiplied with a fully-connected weight tensor, masks out
+ the weights between disconnected input-output pairs and thus implements local
+ connectivity through a sparse fully-connected weight tensor.
+
+ Assume an unshared convolution with given parameters is applied to an input
+ having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)`
+ to produce an output with spatial shape `(d_out1, ..., d_outN)` (determined
+ by layer parameters such as `strides`).
+
+ This method returns a mask which can be broadcast-multiplied (element-wise)
+ with a 2*(N+1)-D weight matrix (equivalent to a fully-connected layer between
+ (N+1)-D activations (N spatial + 1 channel dimensions for input and output)
+ to make it perform an unshared convolution with given `kernel_shape`,
+ `strides`, `padding` and `data_format`.
+
+ Arguments:
+ input_shape: tuple of size N: `(d_in1, ..., d_inN)`
+ spatial shape of the input.
+ kernel_shape: tuple of size N, spatial shape of the convolutional kernel
+ / receptive field.
+ strides: tuple of size N, strides along each spatial dimension.
+ padding: type of padding, string `"same"` or `"valid"`.
+ data_format: a string, `"channels_first"` or `"channels_last"`.
+ dtype: type of the layer operation, e.g. `tf.float64`.
+
+ Returns:
+ a `dtype`-tensor of shape
+ `(1, d_in1, ..., d_inN, 1, d_out1, ..., d_outN)`
+ if `data_format == `"channels_first"`, or
+ `(d_in1, ..., d_inN, 1, d_out1, ..., d_outN, 1)`
+ if `data_format == "channels_last"`.
+
+ Raises:
+ ValueError: if `data_format` is neither `"channels_first"` nor
+ `"channels_last"`.
+ """
+ mask = conv_utils.conv_kernel_mask(
+ input_shape=input_shape,
+ kernel_shape=kernel_shape,
+ strides=strides,
+ padding=padding
+ )
+
+ ndims = int(mask.ndim / 2)
+ mask = K.variable(mask, dtype)
+
+ if data_format == 'channels_first':
+ mask = K.expand_dims(mask, 0)
+ mask = K.expand_dims(mask, - ndims - 1)
+
+ elif data_format == 'channels_last':
+ mask = K.expand_dims(mask, ndims)
+ mask = K.expand_dims(mask, -1)
+
+ else:
+ raise ValueError('Unrecognized data_format: ' + str(data_format))
+
+ return mask
+
+
+def local_conv_matmul(inputs, kernel, kernel_mask, output_shape):
+ """Apply N-D convolution with un-shared weights using a single matmul call.
+
+ This method outputs `inputs . (kernel * kernel_mask)`
+ (with `.` standing for matrix-multiply and `*` for element-wise multiply)
+ and requires a precomputed `kernel_mask` to zero-out weights in `kernel` and
+ hence perform the same operation as a convolution with un-shared
+ (the remaining entries in `kernel`) weights. It also does the necessary
+ reshapes to make `inputs` and `kernel` 2-D and `output` (N+2)-D.
+
+ Arguments:
+ inputs: (N+2)-D tensor with shape
+ `(batch_size, channels_in, d_in1, ..., d_inN)`
+ or
+ `(batch_size, d_in1, ..., d_inN, channels_in)`.
+ kernel: the unshared weights for N-D convolution,
+ an (N+2)-D tensor of shape:
+ `(d_in1, ..., d_inN, channels_in, d_out2, ..., d_outN, channels_out)`
+ or
+ `(channels_in, d_in1, ..., d_inN, channels_out, d_out2, ..., d_outN)`,
+ with the ordering of channels and spatial dimensions matching
+ that of the input.
+ Each entry is the weight between a particular input and
+ output location, similarly to a fully-connected weight matrix.
+ kernel_mask: a float 0/1 mask tensor of shape:
+ `(d_in1, ..., d_inN, 1, d_out2, ..., d_outN, 1)`
+ or
+ `(1, d_in1, ..., d_inN, 1, d_out2, ..., d_outN)`,
+ with the ordering of singleton and spatial dimensions
+ matching that of the input.
+ Mask represents the connectivity pattern of the layer and is
+ precomputed elsewhere based on layer parameters: stride,
+ padding, and the receptive field shape.
+ output_shape: a tuple of (N+2) elements representing the output shape:
+ `(batch_size, channels_out, d_out1, ..., d_outN)`
+ or
+ `(batch_size, d_out1, ..., d_outN, channels_out)`,
+ with the ordering of channels and spatial dimensions matching that of
+ the input.
+
+ Returns:
+ Output (N+2)-D tensor with shape `output_shape`.
+ """
+ inputs_flat = K.reshape(inputs, (K.shape(inputs)[0], -1))
+
+ kernel = kernel_mask * kernel
+ kernel = make_2d(kernel, split_dim=K.ndim(kernel) // 2)
+
+ output_flat = K.math_ops.sparse_matmul(inputs_flat, kernel, b_is_sparse=True)
+ output = K.reshape(output_flat,
+ [K.shape(output_flat)[0],] + output_shape.as_list()[1:])
+ return output
+
+
+def make_2d(tensor, split_dim):
+ """Reshapes an N-dimensional tensor into a 2D tensor.
+
+ Dimensions before (excluding) and after (including) `split_dim` are grouped
+ together.
+
+ Arguments:
+ tensor: a tensor of shape `(d0, ..., d(N-1))`.
+ split_dim: an integer from 1 to N-1, index of the dimension to group
+ dimensions before (excluding) and after (including).
+
+ Returns:
+ Tensor of shape
+ `(d0 * ... * d(split_dim-1), d(split_dim) * ... * d(N-1))`.
+ """
+ shape = K.array_ops.shape(tensor)
+ in_dims = shape[:split_dim]
+ out_dims = shape[split_dim:]
+
+ in_size = K.math_ops.reduce_prod(in_dims)
+ out_size = K.math_ops.reduce_prod(out_dims)
+
+ return K.array_ops.reshape(tensor, (in_size, out_size))
diff --git a/tensorflow/python/keras/layers/local_test.py b/tensorflow/python/keras/layers/local_test.py
index 9639e0251f..4781bcae07 100644
--- a/tensorflow/python/keras/layers/local_test.py
+++ b/tensorflow/python/keras/layers/local_test.py
@@ -24,6 +24,7 @@ from tensorflow.python import keras
from tensorflow.python.framework import test_util as tf_test_util
from tensorflow.python.keras import testing_utils
from tensorflow.python.platform import test
+from tensorflow.python.training.rmsprop import RMSPropOptimizer
class LocallyConnectedLayersTest(test.TestCase):
@@ -36,21 +37,30 @@ class LocallyConnectedLayersTest(test.TestCase):
filter_length = 3
filters = 4
- for padding in ['valid']:
+ for padding in ['valid', 'same']:
for strides in [1]:
if padding == 'same' and strides != 1:
continue
for data_format in ['channels_first', 'channels_last']:
- testing_utils.layer_test(
- keras.layers.LocallyConnected1D,
- kwargs={
- 'filters': filters,
- 'kernel_size': filter_length,
- 'padding': padding,
- 'strides': strides,
- 'data_format': data_format
- },
- input_shape=(num_samples, num_steps, input_dim))
+ for implementation in [1, 2]:
+ kwargs = {
+ 'filters': filters,
+ 'kernel_size': filter_length,
+ 'padding': padding,
+ 'strides': strides,
+ 'data_format': data_format,
+ 'implementation': implementation
+ }
+
+ if padding == 'same' and implementation == 1:
+ self.assertRaises(ValueError,
+ keras.layers.LocallyConnected1D,
+ **kwargs)
+ else:
+ testing_utils.layer_test(
+ keras.layers.LocallyConnected1D,
+ kwargs=kwargs,
+ input_shape=(num_samples, num_steps, input_dim))
def test_locallyconnected_1d_regularization(self):
num_samples = 2
@@ -59,38 +69,47 @@ class LocallyConnectedLayersTest(test.TestCase):
filter_length = 3
filters = 4
for data_format in ['channels_first', 'channels_last']:
- kwargs = {
- 'filters': filters,
- 'kernel_size': filter_length,
- 'kernel_regularizer': 'l2',
- 'bias_regularizer': 'l2',
- 'activity_regularizer': 'l2',
- 'data_format': data_format
- }
-
- with self.test_session():
- layer = keras.layers.LocallyConnected1D(**kwargs)
- layer.build((num_samples, num_steps, input_dim))
- self.assertEqual(len(layer.losses), 2)
- layer(
- keras.backend.variable(np.ones((num_samples,
- num_steps,
- input_dim))))
- self.assertEqual(len(layer.losses), 3)
-
- k_constraint = keras.constraints.max_norm(0.01)
- b_constraint = keras.constraints.max_norm(0.01)
- kwargs = {
- 'filters': filters,
- 'kernel_size': filter_length,
- 'kernel_constraint': k_constraint,
- 'bias_constraint': b_constraint,
- }
- with self.test_session():
- layer = keras.layers.LocallyConnected1D(**kwargs)
- layer.build((num_samples, num_steps, input_dim))
- self.assertEqual(layer.kernel.constraint, k_constraint)
- self.assertEqual(layer.bias.constraint, b_constraint)
+ for padding in ['valid', 'same']:
+ for implementation in [1, 2]:
+ kwargs = {
+ 'filters': filters,
+ 'kernel_size': filter_length,
+ 'kernel_regularizer': 'l2',
+ 'bias_regularizer': 'l2',
+ 'activity_regularizer': 'l2',
+ 'data_format': data_format,
+ 'implementation': implementation,
+ 'padding': padding
+ }
+
+ if padding == 'same' and implementation == 1:
+ self.assertRaises(ValueError,
+ keras.layers.LocallyConnected1D,
+ **kwargs)
+ else:
+ with self.test_session():
+ layer = keras.layers.LocallyConnected1D(**kwargs)
+ layer.build((num_samples, num_steps, input_dim))
+ self.assertEqual(len(layer.losses), 2)
+ layer(
+ keras.backend.variable(np.ones((num_samples,
+ num_steps,
+ input_dim))))
+ self.assertEqual(len(layer.losses), 3)
+
+ k_constraint = keras.constraints.max_norm(0.01)
+ b_constraint = keras.constraints.max_norm(0.01)
+ kwargs = {
+ 'filters': filters,
+ 'kernel_size': filter_length,
+ 'kernel_constraint': k_constraint,
+ 'bias_constraint': b_constraint,
+ }
+ with self.test_session():
+ layer = keras.layers.LocallyConnected1D(**kwargs)
+ layer.build((num_samples, num_steps, input_dim))
+ self.assertEqual(layer.kernel.constraint, k_constraint)
+ self.assertEqual(layer.bias.constraint, b_constraint)
@tf_test_util.run_in_graph_and_eager_modes
def test_locallyconnected_2d(self):
@@ -100,23 +119,32 @@ class LocallyConnectedLayersTest(test.TestCase):
num_row = 6
num_col = 10
- for padding in ['valid']:
+ for padding in ['valid', 'same']:
for strides in [(1, 1), (2, 2)]:
- if padding == 'same' and strides != (1, 1):
- continue
+ for implementation in [1, 2]:
+ if padding == 'same' and strides != (1, 1):
+ continue
- testing_utils.layer_test(
- keras.layers.LocallyConnected2D,
- kwargs={
- 'filters': filters,
- 'kernel_size': 3,
- 'padding': padding,
- 'kernel_regularizer': 'l2',
- 'bias_regularizer': 'l2',
- 'strides': strides,
- 'data_format': 'channels_last'
- },
- input_shape=(num_samples, num_row, num_col, stack_size))
+ kwargs = {
+ 'filters': filters,
+ 'kernel_size': 3,
+ 'padding': padding,
+ 'kernel_regularizer': 'l2',
+ 'bias_regularizer': 'l2',
+ 'strides': strides,
+ 'data_format': 'channels_last',
+ 'implementation': implementation
+ }
+
+ if padding == 'same' and implementation == 1:
+ self.assertRaises(ValueError,
+ keras.layers.LocallyConnected2D,
+ **kwargs)
+ else:
+ testing_utils.layer_test(
+ keras.layers.LocallyConnected2D,
+ kwargs=kwargs,
+ input_shape=(num_samples, num_row, num_col, stack_size))
@tf_test_util.run_in_graph_and_eager_modes
def test_locallyconnected_2d_channels_first(self):
@@ -126,14 +154,25 @@ class LocallyConnectedLayersTest(test.TestCase):
num_row = 6
num_col = 10
- testing_utils.layer_test(
- keras.layers.LocallyConnected2D,
- kwargs={
+ for implementation in [1, 2]:
+ for padding in ['valid', 'same']:
+ kwargs = {
'filters': filters,
'kernel_size': 3,
- 'data_format': 'channels_first'
- },
- input_shape=(num_samples, num_row, num_col, stack_size))
+ 'data_format': 'channels_first',
+ 'implementation': implementation,
+ 'padding': padding
+ }
+
+ if padding == 'same' and implementation == 1:
+ self.assertRaises(ValueError,
+ keras.layers.LocallyConnected2D,
+ **kwargs)
+ else:
+ testing_utils.layer_test(
+ keras.layers.LocallyConnected2D,
+ kwargs=kwargs,
+ input_shape=(num_samples, num_row, num_col, stack_size))
def test_locallyconnected_2d_regularization(self):
num_samples = 8
@@ -141,35 +180,271 @@ class LocallyConnectedLayersTest(test.TestCase):
stack_size = 4
num_row = 6
num_col = 10
- kwargs = {
- 'filters': filters,
- 'kernel_size': 3,
- 'kernel_regularizer': 'l2',
- 'bias_regularizer': 'l2',
- 'activity_regularizer': 'l2',
- }
- with self.test_session():
- layer = keras.layers.LocallyConnected2D(**kwargs)
- layer.build((num_samples, num_row, num_col, stack_size))
- self.assertEqual(len(layer.losses), 2)
- layer(
- keras.backend.variable(
- np.ones((num_samples, num_row, num_col, stack_size))))
- self.assertEqual(len(layer.losses), 3)
-
- k_constraint = keras.constraints.max_norm(0.01)
- b_constraint = keras.constraints.max_norm(0.01)
- kwargs = {
- 'filters': filters,
- 'kernel_size': 3,
- 'kernel_constraint': k_constraint,
- 'bias_constraint': b_constraint,
- }
- with self.test_session():
- layer = keras.layers.LocallyConnected2D(**kwargs)
- layer.build((num_samples, num_row, num_col, stack_size))
- self.assertEqual(layer.kernel.constraint, k_constraint)
- self.assertEqual(layer.bias.constraint, b_constraint)
+ for implementation in [1, 2]:
+ for padding in ['valid', 'same']:
+ kwargs = {
+ 'filters': filters,
+ 'kernel_size': 3,
+ 'kernel_regularizer': 'l2',
+ 'bias_regularizer': 'l2',
+ 'activity_regularizer': 'l2',
+ 'implementation': implementation,
+ 'padding': padding
+ }
+
+ if padding == 'same' and implementation == 1:
+ self.assertRaises(ValueError,
+ keras.layers.LocallyConnected2D,
+ **kwargs)
+ else:
+ with self.test_session():
+ layer = keras.layers.LocallyConnected2D(**kwargs)
+ layer.build((num_samples, num_row, num_col, stack_size))
+ self.assertEqual(len(layer.losses), 2)
+ layer(
+ keras.backend.variable(
+ np.ones((num_samples, num_row, num_col, stack_size))))
+ self.assertEqual(len(layer.losses), 3)
+
+ k_constraint = keras.constraints.max_norm(0.01)
+ b_constraint = keras.constraints.max_norm(0.01)
+ kwargs = {
+ 'filters': filters,
+ 'kernel_size': 3,
+ 'kernel_constraint': k_constraint,
+ 'bias_constraint': b_constraint,
+ }
+ with self.test_session():
+ layer = keras.layers.LocallyConnected2D(**kwargs)
+ layer.build((num_samples, num_row, num_col, stack_size))
+ self.assertEqual(layer.kernel.constraint, k_constraint)
+ self.assertEqual(layer.bias.constraint, b_constraint)
+
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_locallyconnected_implementation(self):
+ n_train = 4
+ n_classes = 3
+ n_epochs = 2
+
+ np.random.seed(1)
+ targets = np.random.randint(0, n_classes, (n_train,))
+
+ for width in [1, 17]:
+ for height in [16]:
+ for filters in [2]:
+ for data_format in ['channels_first', 'channels_last']:
+ inputs = get_inputs(data_format, filters, height, n_train, width)
+
+ for kernel_x in [(3,)]:
+ for kernel_y in [()] if width == 1 else [(2,)]:
+ for stride_x in [(1,)]:
+ for stride_y in [()] if width == 1 else [(3,)]:
+ for layers in [2]:
+ kwargs = {
+ 'layers': layers,
+ 'filters': filters,
+ 'kernel_size': kernel_x + kernel_y,
+ 'strides': stride_x + stride_y,
+ 'data_format': data_format,
+ 'n_classes': n_classes,
+ 'input_shape': inputs.shape
+ }
+
+ model_1 = get_model(implementation=1, **kwargs)
+ model_2 = get_model(implementation=2, **kwargs)
+
+ copy_model_weights(model_2, model_1)
+
+ # Compare outputs at initialization.
+ out_1 = model_1.call(inputs)
+ out_2 = model_2.call(inputs)
+ self.assertAllCloseAccordingToType(out_1, out_2,
+ rtol=1e-5, atol=1e-5)
+
+ # Train.
+ model_1.fit(x=inputs,
+ y=targets,
+ epochs=n_epochs,
+ batch_size=n_train)
+
+ model_2.fit(x=inputs,
+ y=targets,
+ epochs=n_epochs,
+ batch_size=n_train)
+
+ # Compare outputs after a few training steps.
+ out_1 = model_1.call(inputs)
+ out_2 = model_2.call(inputs)
+ self.assertAllCloseAccordingToType(out_1, out_2,
+ rtol=1e-5, atol=1e-5)
+
+ @tf_test_util.run_in_graph_and_eager_modes
+ def test_make_2d(self):
+ input_shapes = [
+ (0,),
+ (0, 0),
+ (1,),
+ (2,),
+ (3,),
+ (1, 0),
+ (0, 3),
+ (1, 1),
+ (1, 2),
+ (3, 1),
+ (2, 2),
+ (3, 3),
+ (1, 0, 1),
+ (5, 2, 3),
+ (3, 5, 6, 7, 0),
+ (3, 2, 2, 4, 4),
+ (1, 2, 3, 4, 7, 2),
+ ]
+ np.random.seed(1)
+
+ for input_shape in input_shapes:
+ inputs = np.random.normal(0, 1, input_shape)
+ inputs_tf = keras.backend.variable(inputs)
+
+ split_dim = np.random.randint(0, inputs.ndim + 1)
+ shape_2d = (int(np.prod(inputs.shape[:split_dim])),
+ int(np.prod(inputs.shape[split_dim:])))
+ inputs_2d = np.reshape(inputs, shape_2d)
+
+ inputs_2d_tf = keras.layers.local.make_2d(inputs_tf, split_dim)
+ inputs_2d_tf = keras.backend.get_value(inputs_2d_tf)
+
+ self.assertAllCloseAccordingToType(inputs_2d, inputs_2d_tf)
+
+
+def get_inputs(data_format, filters, height, n_train, width):
+ if data_format == 'channels_first':
+ if width == 1:
+ input_shape = (filters, height)
+ else:
+ input_shape = (filters, height, width)
+
+ elif data_format == 'channels_last':
+ if width == 1:
+ input_shape = (height, filters)
+ else:
+ input_shape = (height, width, filters)
+
+ else:
+ raise NotImplementedError(data_format)
+
+ inputs = np.random.normal(0, 1,
+ (n_train,) + input_shape).astype(np.float32)
+ return inputs
+
+
+def xent(y_true, y_pred):
+ y_true = keras.backend.cast(
+ keras.backend.reshape(y_true, (-1,)),
+ keras.backend.dtypes_module.int32)
+
+ return keras.backend.nn.sparse_softmax_cross_entropy_with_logits(
+ labels=y_true,
+ logits=y_pred)
+
+
+def get_model(implementation,
+ filters,
+ kernel_size,
+ strides,
+ layers,
+ n_classes,
+ data_format,
+ input_shape):
+ model = keras.Sequential()
+
+ if len(kernel_size) == 1:
+ lc_layer = keras.layers.LocallyConnected1D
+ elif len(kernel_size) == 2:
+ lc_layer = keras.layers.LocallyConnected2D
+ else:
+ raise NotImplementedError(kernel_size)
+
+ for _ in range(layers):
+ model.add(lc_layer(
+ padding='valid',
+ kernel_initializer=keras.initializers.random_normal(),
+ bias_initializer=keras.initializers.random_normal(),
+ filters=filters,
+ strides=strides,
+ kernel_size=kernel_size,
+ activation=keras.activations.relu,
+ data_format=data_format,
+ implementation=implementation))
+
+ model.add(keras.layers.Flatten())
+ model.add(keras.layers.Dense(n_classes))
+ model.compile(
+ optimizer=RMSPropOptimizer(0.01),
+ metrics=[keras.metrics.categorical_accuracy],
+ loss=xent
+ )
+ model.build(input_shape)
+ return model
+
+
+def copy_lc_weights(lc_layer_2_from, lc_layer_1_to):
+ lc_2_kernel, lc_2_bias = lc_layer_2_from.weights
+ lc_2_kernel_masked = lc_2_kernel * lc_layer_2_from.kernel_mask
+
+ data_format = lc_layer_2_from.data_format
+
+ if data_format == 'channels_first':
+ if isinstance(lc_layer_2_from, keras.layers.LocallyConnected1D):
+ permutation = (3, 0, 1, 2)
+ elif isinstance(lc_layer_2_from, keras.layers.LocallyConnected2D):
+ permutation = (4, 5, 0, 1, 2, 3)
+ else:
+ raise NotImplementedError(lc_layer_2_from)
+
+ elif data_format == 'channels_last':
+ if isinstance(lc_layer_2_from, keras.layers.LocallyConnected1D):
+ permutation = (2, 0, 1, 3)
+ elif isinstance(lc_layer_2_from, keras.layers.LocallyConnected2D):
+ permutation = (3, 4, 0, 1, 2, 5)
+ else:
+ raise NotImplementedError(lc_layer_2_from)
+
+ else:
+ raise NotImplementedError(data_format)
+
+ lc_2_kernel_masked = keras.backend.permute_dimensions(
+ lc_2_kernel_masked, permutation)
+
+ lc_2_kernel_mask = keras.backend.math_ops.not_equal(
+ lc_2_kernel_masked, 0)
+ lc_2_kernel_flat = keras.backend.array_ops.boolean_mask(
+ lc_2_kernel_masked, lc_2_kernel_mask)
+ lc_2_kernel_reshaped = keras.backend.reshape(lc_2_kernel_flat,
+ lc_layer_1_to.kernel.shape)
+
+ lc_2_kernel_reshaped = keras.backend.get_value(lc_2_kernel_reshaped)
+ lc_2_bias = keras.backend.get_value(lc_2_bias)
+
+ lc_layer_1_to.set_weights([lc_2_kernel_reshaped, lc_2_bias])
+
+
+def copy_model_weights(model_2_from, model_1_to):
+ for l in range(len(model_2_from.layers)):
+ layer_2_from = model_2_from.layers[l]
+ layer_1_to = model_1_to.layers[l]
+
+ if isinstance(layer_2_from, (keras.layers.LocallyConnected2D,
+ keras.layers.LocallyConnected1D)):
+ copy_lc_weights(layer_2_from, layer_1_to)
+
+ elif isinstance(layer_2_from, keras.layers.Dense):
+ weights_2, bias_2 = layer_2_from.weights
+ weights_2 = keras.backend.get_value(weights_2)
+ bias_2 = keras.backend.get_value(bias_2)
+ layer_1_to.set_weights([weights_2, bias_2])
+
+ else:
+ continue
if __name__ == '__main__':
diff --git a/tensorflow/python/keras/layers/normalization.py b/tensorflow/python/keras/layers/normalization.py
index a7835bc0a2..cd26e04c39 100644
--- a/tensorflow/python/keras/layers/normalization.py
+++ b/tensorflow/python/keras/layers/normalization.py
@@ -36,7 +36,7 @@ from tensorflow.python.ops import nn
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.util.tf_export import tf_export
@@ -345,16 +345,16 @@ class BatchNormalization(Layer):
aggregation=variable_scope.VariableAggregation.MEAN)
return var
- with distribute_lib.get_distribution_strategy().colocate_vars_with(
- self.moving_mean):
+ with distribution_strategy_context.get_distribution_strategy(
+ ).colocate_vars_with(self.moving_mean):
self.renorm_mean = _renorm_variable('renorm_mean', param_shape)
self.renorm_mean_weight = _renorm_variable('renorm_mean_weight', ())
# We initialize renorm_stddev to 0, and maintain the (0-initialized)
# renorm_stddev_weight. This allows us to (1) mix the average
# stddev with the minibatch stddev early in training, and (2) compute
# the unbiased average stddev by dividing renorm_stddev by the weight.
- with distribute_lib.get_distribution_strategy().colocate_vars_with(
- self.moving_variance):
+ with distribution_strategy_context.get_distribution_strategy(
+ ).colocate_vars_with(self.moving_variance):
self.renorm_stddev = _renorm_variable('renorm_stddev', param_shape)
self.renorm_stddev_weight = _renorm_variable('renorm_stddev_weight',
())
diff --git a/tensorflow/python/keras/layers/recurrent.py b/tensorflow/python/keras/layers/recurrent.py
index acc4ba37c0..12c82a53f6 100644
--- a/tensorflow/python/keras/layers/recurrent.py
+++ b/tensorflow/python/keras/layers/recurrent.py
@@ -93,6 +93,13 @@ class StackedRNNCells(Layer):
state_size.append(cell.state_size)
return tuple(state_size)
+ @property
+ def output_size(self):
+ if hasattr(self.cells[-1], 'output_size'):
+ return self.cells[-1].output_size
+ else:
+ return self.state_size[0]
+
def call(self, inputs, states, constants=None, **kwargs):
# Recover per-cell states.
nested_states = []
@@ -244,13 +251,16 @@ class RNN(Layer):
cell can also take the optional argument `constants`, see
section "Note on passing external constants" below.
- a `state_size` attribute. This can be a single integer
- (single state) in which case it is the size of the recurrent state
- (which should be the same as the size of the cell output).
- This can also be a list/tuple of integers (one size per state).
- In this case, the first entry (`state_size[0]`) should be the same
- as the size of the cell output.
+ (single state) in which case it is the size of the recurrent
+ state. This can also be a list/tuple of integers (one size per
+ state).
The `state_size` can also be TensorShape or tuple/list of
TensorShape, to represent high dimension state.
+ - a `output_size` attribute. This can be a single integer or a
+ TensorShape, which represent the shape of the output. For backward
+ compatible reason, if this attribute is not available for the
+ cell, the value will be inferred by the first element of the
+ `state_size`.
In the case that `cell` is a list of RNN cell instances, the cells
will be stacked on after the other in the RNN, implementing an
efficient stacked RNN.
@@ -289,13 +299,13 @@ class RNN(Layer):
Output shape:
- if `return_state`: a list of tensors. The first tensor is
the output. The remaining tensors are the last states,
- each with shape `(batch_size, ...)`, where `...` is in the shape of
- `state_size`.
+ each with shape `(batch_size, state_size)`, where `state_size` could
+ be a high dimension tensor shape.
- if `return_sequences`: N-D tensor with shape
- `(batch_size, timesteps, ...)`, where `...` is in the shape of output
- size.
- - else, N-D tensor with shape `(batch_size, ...)`, where `...` is in the
- shape of output size.
+ `(batch_size, timesteps, output_size)`, where `output_size` could
+ be a high dimension tensor shape.
+ - else, N-D tensor with shape `(batch_size, output_size)`, where
+ `output_size` could be a high dimension tensor shape.
# Masking
This layer supports masking for input data with a variable number
@@ -442,8 +452,12 @@ class RNN(Layer):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
- # Note that state_size[0] could be a tensor_shape or int.
- output_dim = tensor_shape.as_shape(state_size[0]).as_list()
+
+ if hasattr(self.cell, 'output_size'):
+ output_dim = tensor_shape.as_shape(self.cell.output_size).as_list()
+ else:
+ # Note that state_size[0] could be a tensor_shape or int.
+ output_dim = tensor_shape.as_shape(state_size[0]).as_list()
if self.return_sequences:
output_shape = tuple([input_shape[0], input_shape[1]] + output_dim)
@@ -656,6 +670,8 @@ class RNN(Layer):
if generic_utils.has_arg(self.cell.call, 'training'):
kwargs['training'] = training
+ # TF RNN cells expect single tensor as state instead of list wrapped tensor.
+ is_tf_rnn_cell = getattr(self.cell, '_is_tf_rnn_cell', None) is not None
if constants:
if not generic_utils.has_arg(self.cell.call, 'constants'):
raise ValueError('RNN cell does not support constants')
@@ -663,11 +679,21 @@ class RNN(Layer):
def step(inputs, states):
constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type
states = states[:-self._num_constants] # pylint: disable=invalid-unary-operand-type
- return self.cell.call(inputs, states, constants=constants, **kwargs)
+
+ states = states[0] if len(states) == 1 and is_tf_rnn_cell else states
+ output, new_states = self.cell.call(
+ inputs, states, constants=constants, **kwargs)
+ if not nest.is_sequence(new_states):
+ new_states = [new_states]
+ return output, new_states
else:
def step(inputs, states):
- return self.cell.call(inputs, states, **kwargs)
+ states = states[0] if len(states) == 1 and is_tf_rnn_cell else states
+ output, new_states = self.cell.call(inputs, states, **kwargs)
+ if not nest.is_sequence(new_states):
+ new_states = [new_states]
+ return output, new_states
last_output, outputs, states = K.rnn(
step,
@@ -893,6 +919,7 @@ class SimpleRNNCell(Layer):
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.state_size = self.units
+ self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
@@ -1296,6 +1323,7 @@ class GRUCell(Layer):
self.implementation = implementation
self.reset_after = reset_after
self.state_size = self.units
+ self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
@@ -1841,6 +1869,7 @@ class LSTMCell(Layer):
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
self.implementation = implementation
self.state_size = (self.units, self.units)
+ self.output_size = self.units
self._dropout_mask = None
self._recurrent_dropout_mask = None
diff --git a/tensorflow/python/keras/layers/recurrent_test.py b/tensorflow/python/keras/layers/recurrent_test.py
index 9be439ea14..13bd070528 100644
--- a/tensorflow/python/keras/layers/recurrent_test.py
+++ b/tensorflow/python/keras/layers/recurrent_test.py
@@ -654,6 +654,30 @@ class RNNTest(test.TestCase):
'however `cell.state_size` is'):
layer(x, initial_state=s)
+ def test_inconsistent_output_state_size(self):
+ with self.test_session():
+ batch = 32
+ time_step = 4
+ state_size = 5
+ input_size = 6
+ cell = PlusOneRNNCell(state_size)
+ x = keras.Input((None, input_size))
+ layer = keras.layers.RNN(cell)
+ y = layer(x)
+
+ self.assertEqual(cell.state_size, state_size)
+ init_state = layer.get_initial_state(x)
+ self.assertEqual(len(init_state), 1)
+ self.assertEqual(init_state[0].get_shape().as_list(),
+ [None, state_size])
+
+ model = keras.models.Model(x, y)
+ model.compile(optimizer='rmsprop', loss='mse')
+ model.train_on_batch(
+ np.zeros((batch, time_step, input_size)),
+ np.zeros((batch, input_size)))
+ self.assertEqual(model.output_shape, (None, input_size))
+
class Minimal2DRNNCell(keras.layers.Layer):
"""The minimal 2D RNN cell is a simple combination of 2 1-D RNN cell.
@@ -666,6 +690,7 @@ class Minimal2DRNNCell(keras.layers.Layer):
self.unit_a = unit_a
self.unit_b = unit_b
self.state_size = tensor_shape.as_shape([unit_a, unit_b])
+ self.output_size = tensor_shape.as_shape([unit_a, unit_b])
super(Minimal2DRNNCell, self).__init__(**kwargs)
def build(self, input_shape):
@@ -692,5 +717,21 @@ class Minimal2DRNNCell(keras.layers.Layer):
return output, [output]
+class PlusOneRNNCell(keras.layers.Layer):
+ """Add one to the input and state.
+
+ This cell is used for testing state_size and output_size."""
+
+ def __init__(self, num_unit, **kwargs):
+ self.state_size = num_unit
+ super(PlusOneRNNCell, self).__init__(**kwargs)
+
+ def build(self, input_shape):
+ self.output_size = input_shape[-1]
+
+ def call(self, inputs, states):
+ return inputs + 1, [states[0] + 1]
+
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/python/keras/metrics.py b/tensorflow/python/keras/metrics.py
index b18f12612a..9b87170ebe 100644
--- a/tensorflow/python/keras/metrics.py
+++ b/tensorflow/python/keras/metrics.py
@@ -55,7 +55,7 @@ from tensorflow.python.ops import nn
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.ops import weights_broadcast_ops
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.util import tf_decorator
from tensorflow.python.util.tf_export import tf_export
@@ -68,25 +68,19 @@ def check_is_tensor_or_operation(x, name):
def update_state_wrapper(update_state_fn):
- """Decorator to wrap metric `update_state()` with `defun()`, `add_update()`.
+ """Decorator to wrap metric `update_state()` with `add_update()`.
Args:
update_state_fn: function that accumulates metric statistics.
Returns:
- If eager execution is enabled, returns None.
- If graph execution is enabled, returns an update op. This op should be
- executed to update the metric state with the given inputs.
+ Decorated function that wraps `update_state_fn()` with `add_update()`.
"""
def decorated(metric_obj, *args, **kwargs):
- """Decorated function with `defun()` and `add_update()`."""
+ """Decorated function with `add_update()`."""
- # Converting update_state_fn() into a graph function, so that
- # we can return a single op that performs all of the variable updates.
- # Assigning to a different method name to avoid reference cycle.
- defuned_update_state_fn = function.defun(update_state_fn)
- update_op = defuned_update_state_fn(*args, **kwargs)
+ update_op = update_state_fn(*args, **kwargs)
if update_op is not None: # update_op will be None in eager execution.
metric_obj.add_update(update_op, inputs=True)
check_is_tensor_or_operation(
@@ -111,12 +105,13 @@ def result_wrapper(result_fn):
result_fn: function that computes the metric result.
Returns:
- The metric result tensor.
+ Decorated function that wraps `result_fn()` in distribution strategy
+ `merge_call()`.
"""
def decorated(metric_obj, *args):
"""Decorated function with merge_call."""
- tower_context = distribute_lib.get_tower_context()
+ tower_context = distribution_strategy_context.get_tower_context()
if tower_context is None: # if in cross tower context already
result_t = result_fn(*args)
else:
@@ -255,6 +250,28 @@ class Metric(Layer):
print('Final result: ', sess.run(m.result()))
```
+ Usage with tf.keras API:
+
+ ```python
+ model = tf.keras.Sequential()
+ model.add(tf.keras.layers.Dense(64, activation='relu'))
+ model.add(tf.keras.layers.Dense(64, activation='relu'))
+ model.add(tf.keras.layers.Dense(10, activation='softmax'))
+
+ model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),
+ loss=tf.keras.losses.categorical_crossentropy,
+ metrics=[tf.keras.metrics.CategoricalAccuracy()])
+
+ data = np.random.random((1000, 32))
+ labels = np.random.random((1000, 10))
+
+ dataset = tf.data.Dataset.from_tensor_slices((data, labels))
+ dataset = dataset.batch(32)
+ dataset = dataset.repeat()
+
+ model.fit(dataset, epochs=10, steps_per_epoch=30)
+ ```
+
To be implemented by subclasses:
* `__init__()`: All state variables should be created in this method by
calling `self.add_weight()` like: `self.var = self.add_weight(...)`
@@ -267,7 +284,7 @@ class Metric(Layer):
```
class BinaryTruePositives(Metric):
- def __init__(self, name='binary-true-positives', dtype=None):
+ def __init__(self, name='binary_true_positives', dtype=None):
super(BinaryTruePositives, self).__init__(name=name, dtype=dtype)
self.true_positives = self.add_weight(
'true_positives', initializer=init_ops.zeros_initializer)
@@ -299,9 +316,14 @@ class Metric(Layer):
self._dtype = K.floatx() if dtype is None else dtypes.as_dtype(dtype).name
def __new__(cls, *args, **kwargs):
- obj = super(Metric, cls).__new__(cls, *args, **kwargs)
+ obj = super(Metric, cls).__new__(cls)
+ # TODO(psv): Fix reference cycle issue here.
+
+ # Converting update_state_fn() into a graph function, so that
+ # we can return a single op that performs all of the variable updates.
+ defuned_update_state_fn = function.defun(obj.update_state)
obj.update_state = types.MethodType(
- update_state_wrapper(obj.update_state), obj)
+ update_state_wrapper(defuned_update_state_fn), obj)
obj.result = types.MethodType(result_wrapper(obj.result), obj)
return obj
@@ -359,6 +381,12 @@ class Metric(Layer):
"""
NotImplementedError('Must be implemented in subclasses.')
+ @classmethod
+ def from_config(cls, config):
+ if 'trainable' in config:
+ config.pop('trainable')
+ return cls(**config)
+
### For use by subclasses ###
def add_weight(self,
name,
@@ -502,7 +530,7 @@ class BinaryAccuracy(MeanMetricWrapper):
Use `sample_weight` of 0 to mask values.
"""
- def __init__(self, name='binary-accuracy', dtype=None, threshold=0.5):
+ def __init__(self, name='binary_accuracy', dtype=None, threshold=0.5):
"""Creates a `BinaryAccuracy` instance.
Args:
@@ -515,6 +543,29 @@ class BinaryAccuracy(MeanMetricWrapper):
binary_accuracy, name, dtype=dtype, threshold=threshold)
+class CategoricalAccuracy(MeanMetricWrapper):
+ """Calculates how often predictions matches labels.
+
+ This metric creates two local variables, `total` and `count` that are used to
+ compute the frequency with which `y_pred` matches `y_true`. This frequency is
+ ultimately returned as `categorical accuracy`: an idempotent operation that
+ simply divides `total` by `count`.
+
+ If `sample_weight` is `None`, weights default to 1.
+ Use `sample_weight` of 0 to mask values.
+ """
+
+ def __init__(self, name='categorical_accuracy', dtype=None):
+ """Creates a `CategoricalAccuracy` instance.
+
+ Args:
+ name: (Optional) string name of the metric instance.
+ dtype: (Optional) data type of the metric result.
+ """
+ super(CategoricalAccuracy, self).__init__(
+ categorical_accuracy, name, dtype=dtype)
+
+
@tf_export('keras.metrics.binary_accuracy')
def binary_accuracy(y_true, y_pred, threshold=0.5):
threshold = math_ops.cast(threshold, y_pred.dtype)
@@ -578,8 +629,7 @@ def deserialize(config, custom_objects=None):
@tf_export('keras.metrics.get')
def get(identifier):
if isinstance(identifier, dict):
- config = {'class_name': str(identifier), 'config': {}}
- return deserialize(config)
+ return deserialize(identifier)
elif isinstance(identifier, six.string_types):
return deserialize(str(identifier))
elif callable(identifier):
diff --git a/tensorflow/python/keras/metrics_test.py b/tensorflow/python/keras/metrics_test.py
index 49f3ae40d9..2ac74219d4 100644
--- a/tensorflow/python/keras/metrics_test.py
+++ b/tensorflow/python/keras/metrics_test.py
@@ -363,6 +363,30 @@ class KerasMetricsTest(test.TestCase):
self.assertAlmostEqual(result, 0.5, 2)
@test_util.run_in_graph_and_eager_modes
+ def test_categorical_accuracy(self):
+ acc_obj = metrics.CategoricalAccuracy(name='my acc')
+
+ # check config
+ self.assertEqual(acc_obj.name, 'my acc')
+ self.assertTrue(acc_obj.stateful)
+ self.assertEqual(len(acc_obj.variables), 2)
+ self.assertEqual(acc_obj.dtype, dtypes.float32)
+ self.evaluate(variables.global_variables_initializer())
+
+ # verify that correct value is returned
+ update_op = acc_obj.update_state([[0, 0, 1], [0, 1, 0]],
+ [[0.1, 0.1, 0.8], [0.05, 0.95, 0]])
+ self.evaluate(update_op)
+ result = self.evaluate(acc_obj.result())
+ self.assertEqual(result, 1) # 2/2
+
+ # check with sample_weight
+ result_t = acc_obj([[0, 0, 1], [0, 1, 0]],
+ [[0.1, 0.1, 0.8], [0.05, 0, 0.95]], [[0.5], [0.2]])
+ result = self.evaluate(result_t)
+ self.assertAlmostEqual(result, 0.93, 2) # 2.5/2.7
+
+ @test_util.run_in_graph_and_eager_modes
def test_invalid_result(self):
class InvalidResult(metrics.Metric):
diff --git a/tensorflow/python/keras/model_subclassing_test.py b/tensorflow/python/keras/model_subclassing_test.py
index 6cbea45bd5..71c1987cee 100644
--- a/tensorflow/python/keras/model_subclassing_test.py
+++ b/tensorflow/python/keras/model_subclassing_test.py
@@ -425,9 +425,10 @@ class ModelSubclassingTest(test.TestCase):
model = SimpleTestModel(num_classes=num_classes,
use_dp=True,
use_bn=True)
- model.compile(loss='mse',
- optimizer=RMSPropOptimizer(learning_rate=0.001),
- metrics=['acc'])
+ model.compile(
+ loss='mse',
+ optimizer=RMSPropOptimizer(learning_rate=0.001),
+ metrics=['acc', keras.metrics.CategoricalAccuracy()])
x = np.ones((num_samples, input_dim))
y = np.zeros((num_samples, num_classes))
diff --git a/tensorflow/python/keras/models.py b/tensorflow/python/keras/models.py
index 0bd6620220..b6aa9adb47 100644
--- a/tensorflow/python/keras/models.py
+++ b/tensorflow/python/keras/models.py
@@ -20,13 +20,19 @@ from __future__ import division
from __future__ import print_function
from tensorflow.python.keras import backend as K
+from tensorflow.python.keras import optimizers
from tensorflow.python.keras.engine import saving
from tensorflow.python.keras.engine import sequential
from tensorflow.python.keras.engine import training
+from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.keras.engine.input_layer import Input
from tensorflow.python.keras.engine.input_layer import InputLayer
+from tensorflow.python.keras.engine.network import Network
from tensorflow.python.keras.utils import generic_utils
-
+from tensorflow.python.keras.utils.generic_utils import CustomObjectScope
+from tensorflow.python.training import training_util
+from tensorflow.python.training.checkpointable import base as checkpointable
+from tensorflow.python.training.checkpointable import data_structures
# API entries importable from `keras.models`:
Model = training.Model # pylint: disable=invalid-name
@@ -246,3 +252,213 @@ def clone_model(model, input_tensors=None):
return _clone_sequential_model(model, input_tensors=input_tensors)
else:
return _clone_functional_model(model, input_tensors=input_tensors)
+
+
+# "Clone" a subclassed model by reseting all of the attributes.
+
+
+def _in_place_subclassed_model_reset(model):
+ """Substitute for model cloning that works for subclassed models.
+
+ Subclassed models cannot be cloned because their topology is not serializable.
+ To "instantiate" an identical model in a new TF graph, we reuse the original
+ model object, but we clear its state.
+
+ After calling this function on a model instance, you can use the model
+ instance as if it were a model clone (in particular you can use it in a new
+ graph).
+
+ This method clears the state of the input model. It is thus destructive.
+ However the original state can be restored fully by calling
+ `_in_place_subclassed_model_state_restoration`.
+
+ Args:
+ model: Instance of a Keras model created via subclassing.
+
+ Raises:
+ ValueError: In case the model uses a subclassed model as inner layer.
+ """
+ assert not model._is_graph_network # Only makes sense for subclassed networks
+ # Retrieve all layers tracked by the model as well as their attribute names
+ attributes_cache = {}
+ for name in dir(model):
+ try:
+ value = getattr(model, name)
+ except (AttributeError, ValueError, TypeError):
+ continue
+ if isinstance(value, Layer):
+ attributes_cache[name] = value
+ assert value in model._layers
+ elif isinstance(value, (list, tuple)) and name not in ('layers', '_layers'):
+ # Handle case: list/tuple of layers (also tracked by the Network API).
+ if value and all(isinstance(val, Layer) for val in value):
+ raise ValueError('We do not support the use of list-of-layers '
+ 'attributes in subclassed models used with '
+ '`model_to_estimator` at this time. Found list '
+ 'model: %s' % name)
+
+ # Replace layers on the model with fresh layers
+ layers_to_names = {value: key for key, value in attributes_cache.items()}
+ original_layers = model._layers[:]
+ model._layers = data_structures.NoDependency([])
+ for layer in original_layers: # We preserve layer order.
+ config = layer.get_config()
+ # This will not work for nested subclassed models used as layers.
+ # This would be theoretically possible to support, but would add complexity.
+ # Only do it if users complain.
+ if isinstance(layer, Network) and not layer._is_graph_network:
+ raise ValueError('We do not support the use of nested subclassed models '
+ 'in `model_to_estimator` at this time. Found nested '
+ 'model: %s' % layer)
+ fresh_layer = layer.__class__.from_config(config)
+ name = layers_to_names[layer]
+ setattr(model, name, fresh_layer)
+
+ # Cache original model build attributes (in addition to layers)
+ if (not hasattr(model, '_original_attributes_cache') or
+ model._original_attributes_cache is None):
+ if model.built:
+ attributes_to_cache = [
+ 'inputs',
+ 'outputs',
+ '_feed_outputs',
+ '_feed_output_names',
+ '_feed_output_shapes',
+ '_feed_loss_fns',
+ 'loss_weights_list',
+ 'targets',
+ '_feed_targets',
+ 'sample_weight_modes',
+ 'weighted_metrics',
+ 'metrics_names',
+ 'metrics_tensors',
+ 'metrics_updates',
+ 'stateful_metric_names',
+ 'total_loss',
+ 'sample_weights',
+ '_feed_sample_weights',
+ 'train_function',
+ 'test_function',
+ 'predict_function',
+ '_collected_trainable_weights',
+ '_feed_inputs',
+ '_feed_input_names',
+ '_feed_input_shapes',
+ 'optimizer',
+ ]
+ for name in attributes_to_cache:
+ attributes_cache[name] = getattr(model, name)
+ model._original_attributes_cache = data_structures.NoDependency(
+ attributes_cache)
+ # Reset built state
+ model.built = False
+ model.inputs = None
+ model.outputs = None
+
+
+def in_place_subclassed_model_state_restoration(model):
+ """Restores the original state of a model after it was "reset".
+
+ This undoes this action of `_in_place_subclassed_model_reset`, which is called
+ in `clone_and_build_model` if `in_place_reset` is set to True.
+
+ Args:
+ model: Instance of a Keras model created via subclassing, on which
+ `_in_place_subclassed_model_reset` was previously called.
+ """
+ assert not model._is_graph_network
+ # Restore layers and build attributes
+ if (hasattr(model, '_original_attributes_cache') and
+ model._original_attributes_cache is not None):
+ # Models have sticky attribute assignment, so we want to be careful to add
+ # back the previous attributes and track Layers by their original names
+ # without adding dependencies on "utility" attributes which Models exempt
+ # when they're constructed.
+ model._layers = data_structures.NoDependency([])
+ for name, value in model._original_attributes_cache.items():
+ if not isinstance(value, checkpointable.CheckpointableBase):
+ # If this value is not already checkpointable, it's probably that way
+ # for a reason; we don't want to start tracking data structures that the
+ # original Model didn't.
+ value = data_structures.NoDependency(value)
+ setattr(model, name, value)
+ model._original_attributes_cache = None
+ else:
+ # Restore to the state of a never-called model.
+ model.built = False
+ model.inputs = None
+ model.outputs = None
+
+
+def clone_and_build_model(
+ model, input_tensors=None, target_tensors=None, custom_objects=None,
+ compile_clone=True, in_place_reset=False):
+ """Clone a `Model` and build/compile it with the same settings used before.
+
+ This function should be run in the same graph as the model.
+
+ Args:
+ model: `tf.keras.Model` object. Can be Functional, Sequential, or
+ sub-classed.
+ input_tensors: Optional list of input tensors to build the model upon. If
+ not provided, placeholders will be created.
+ target_tensors: Optional list of target tensors for compiling the model. If
+ not provided, placeholders will be created.
+ custom_objects: Optional dictionary mapping string names to custom classes
+ or functions.
+ compile_clone: Boolean, whether to compile model clone (default `True`).
+ in_place_reset: Boolean, whether to reset the model in place. Only used if
+ the model is not a graph network. If the model is a subclassed model, then
+ this argument must be set to `True` (default `False`). To restore the
+ original model, use the function
+ `in_place_subclassed_model_state_restoration(model)`.
+
+ Returns:
+ Clone of the model.
+
+ Raises:
+ ValueError: if trying to clone a subclassed model, and `in_place_reset` is
+ set to False.
+ """
+ if model._is_graph_network:
+ if custom_objects:
+ with CustomObjectScope(custom_objects):
+ clone = clone_model(model, input_tensors=input_tensors)
+ else:
+ clone = clone_model(model, input_tensors=input_tensors)
+ else:
+ if not in_place_reset:
+ raise ValueError(
+ 'Model is not a graph network (usually means that it is a subclassed '
+ 'model). The model cannot be cloned, but there is a workaround where '
+ 'the model is reset in-place. To use this, please set the argument '
+ '`in_place_reset` to `True`. This will reset the attributes in the '
+ 'original model. To restore the attributes, call '
+ '`in_place_subclassed_model_state_restoration(model)`.')
+ clone = model
+ _in_place_subclassed_model_reset(clone)
+ if input_tensors is not None:
+ clone._set_inputs(input_tensors)
+
+ # Compile/Build model
+ if not compile_clone:
+ if isinstance(clone, Sequential):
+ clone.build()
+ elif model.optimizer:
+ if isinstance(model.optimizer, optimizers.TFOptimizer):
+ optimizer = model.optimizer
+ else:
+ optimizer_config = model.optimizer.get_config()
+ optimizer = model.optimizer.__class__.from_config(optimizer_config)
+ optimizer.iterations = training_util.get_or_create_global_step()
+
+ clone.compile(
+ optimizer,
+ model.loss,
+ metrics=model.metrics,
+ loss_weights=model.loss_weights,
+ sample_weight_mode=model.sample_weight_mode,
+ weighted_metrics=model.weighted_metrics,
+ target_tensors=target_tensors)
+
+ return clone
diff --git a/tensorflow/python/keras/models_test.py b/tensorflow/python/keras/models_test.py
index 1385ad5390..5f755f7b5e 100644
--- a/tensorflow/python/keras/models_test.py
+++ b/tensorflow/python/keras/models_test.py
@@ -24,6 +24,8 @@ import numpy as np
from tensorflow.python import keras
from tensorflow.python.framework import test_util
+from tensorflow.python.keras import metrics
+from tensorflow.python.keras import models
from tensorflow.python.platform import test
from tensorflow.python.training import adam
@@ -169,6 +171,7 @@ class CheckpointingTests(test.TestCase):
model.load_weights(save_prefix)
self.assertEqual(12., self.evaluate(beta1_power))
+
class TestModelBackend(test.TestCase):
def test_model_backend_float64_use_cases(self):
@@ -183,5 +186,136 @@ class TestModelBackend(test.TestCase):
keras.backend.set_floatx(floatx)
+
+class TestCloneAndBuildModel(test.TestCase):
+
+ def test_clone_and_build_non_compiled_model(self):
+ with self.test_session():
+ inp = np.random.random((10, 4))
+ out = np.random.random((10, 4))
+
+ model = keras.models.Sequential()
+ model.add(keras.layers.Dense(4, input_shape=(4,)))
+ model.add(keras.layers.BatchNormalization())
+ model.add(keras.layers.Dropout(0.5))
+ model.add(keras.layers.Dense(4))
+
+ # Everything should work in a new session.
+ keras.backend.clear_session()
+
+ with self.test_session():
+ # With placeholder creation
+ new_model = models.clone_and_build_model(model, compile_clone=True)
+ with self.assertRaisesRegexp(RuntimeError, 'must compile'):
+ new_model.evaluate(inp, out)
+ with self.assertRaisesRegexp(RuntimeError, 'must compile'):
+ new_model.train_on_batch(inp, out)
+ new_model.compile('rmsprop', 'mse')
+ new_model.train_on_batch(inp, out)
+
+ # Create new tensors for inputs and targets
+ input_a = keras.Input(shape=(4,))
+ target_a = keras.Input(shape=(4,))
+ new_model = models.clone_and_build_model(model, input_tensors=input_a,
+ target_tensors=[target_a],
+ compile_clone=True)
+ with self.assertRaisesRegexp(RuntimeError, 'must compile'):
+ new_model.evaluate(inp, out)
+ with self.assertRaisesRegexp(RuntimeError, 'must compile'):
+ new_model.train_on_batch(inp, out)
+ new_model.compile('rmsprop', 'mse')
+ new_model.train_on_batch(inp, out)
+
+ def _assert_same_compile_params(self, model):
+ """Assert that two models have the same compile parameters."""
+
+ self.assertEqual('mse', model.loss)
+ self.assertTrue(
+ isinstance(model.optimizer, keras.optimizers.RMSprop))
+ self.assertEqual(['acc', metrics.categorical_accuracy], model.metrics)
+
+ def _clone_and_build_test_helper(self, model, is_subclassed=False):
+ inp = np.random.random((10, 4))
+ out = np.random.random((10, 4))
+
+ # Everything should work in a new session.
+ keras.backend.clear_session()
+
+ with self.test_session():
+ # With placeholder creation
+ new_model = models.clone_and_build_model(
+ model, compile_clone=True, in_place_reset=is_subclassed)
+
+ self._assert_same_compile_params(new_model)
+ new_model.train_on_batch(inp, out)
+ new_model.evaluate(inp, out)
+
+ # Create new tensors for inputs and targets
+ input_a = keras.Input(shape=(4,), name='a')
+ new_model = models.clone_and_build_model(
+ model, input_tensors=input_a, compile_clone=True,
+ in_place_reset=is_subclassed)
+ self._assert_same_compile_params(new_model)
+ new_model.train_on_batch(inp, out)
+ new_model.evaluate(inp, out)
+
+ target_a = keras.Input(shape=(4,), name='b')
+ new_model = models.clone_and_build_model(
+ model, input_tensors=input_a, target_tensors=[target_a],
+ compile_clone=True, in_place_reset=is_subclassed)
+ self._assert_same_compile_params(new_model)
+ new_model.train_on_batch(inp, out)
+ new_model.evaluate(inp, out)
+
+ def test_clone_and_build_compiled_sequential_model(self):
+ with self.test_session():
+ model = keras.models.Sequential()
+ model.add(keras.layers.Dense(4, input_shape=(4,)))
+ model.add(keras.layers.BatchNormalization())
+ model.add(keras.layers.Dropout(0.5))
+ model.add(keras.layers.Dense(4))
+ model.compile('rmsprop', 'mse',
+ metrics=['acc', metrics.categorical_accuracy])
+
+ self._clone_and_build_test_helper(model)
+
+ def test_clone_and_build_functional_model(self):
+ with self.test_session():
+ input_a = keras.Input(shape=(4,))
+ dense_1 = keras.layers.Dense(4,)
+ dense_2 = keras.layers.Dense(4,)
+
+ x_a = dense_1(input_a)
+ x_a = keras.layers.Dropout(0.5)(x_a)
+ x_a = keras.layers.BatchNormalization()(x_a)
+ x_a = dense_2(x_a)
+ model = keras.models.Model(input_a, x_a)
+ model.compile('rmsprop', 'mse',
+ metrics=['acc', metrics.categorical_accuracy])
+
+ self._clone_and_build_test_helper(model)
+
+ def test_clone_and_build_subclassed_model(self):
+ class SubclassedModel(keras.Model):
+
+ def __init__(self):
+ super(SubclassedModel, self).__init__()
+ self.layer1 = keras.layers.Dense(4)
+ self.layer2 = keras.layers.Dense(4)
+
+ def call(self, inp):
+ out = self.layer1(inp)
+ out = keras.layers.BatchNormalization()(out)
+ out = keras.layers.Dropout(0.5)(out)
+ out = self.layer2(out)
+ return out
+
+ with self.test_session():
+ model = SubclassedModel()
+ model.compile('rmsprop', 'mse',
+ metrics=['acc', metrics.categorical_accuracy])
+ self._clone_and_build_test_helper(model, True)
+
+
if __name__ == '__main__':
test.main()
diff --git a/tensorflow/python/keras/optimizers.py b/tensorflow/python/keras/optimizers.py
index 4f97442e82..f339a7e047 100644
--- a/tensorflow/python/keras/optimizers.py
+++ b/tensorflow/python/keras/optimizers.py
@@ -28,7 +28,7 @@ from tensorflow.python.keras.utils.generic_utils import serialize_keras_object
from tensorflow.python.ops import clip_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import optimizer as tf_optimizer_module
from tensorflow.python.training import training_util
from tensorflow.python.training.checkpointable import base as checkpointable
@@ -705,7 +705,7 @@ class TFOptimizer(Optimizer, checkpointable.CheckpointableBase):
return self.optimizer.compute_gradients(loss, params)
def get_updates(self, loss, params):
- if distribute_lib.has_distribution_strategy():
+ if distribution_strategy_context.has_distribution_strategy():
self.updates = []
if not params:
diff --git a/tensorflow/python/keras/utils/conv_utils.py b/tensorflow/python/keras/utils/conv_utils.py
index 5419e7ae05..3a176c3316 100644
--- a/tensorflow/python/keras/utils/conv_utils.py
+++ b/tensorflow/python/keras/utils/conv_utils.py
@@ -18,6 +18,7 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import itertools
import numpy as np
from six.moves import range # pylint: disable=redefined-builtin
@@ -199,3 +200,168 @@ def convert_kernel(kernel):
no_flip = (slice(None, None), slice(None, None))
slices[-2:] = no_flip
return np.copy(kernel[slices])
+
+
+def conv_kernel_mask(input_shape, kernel_shape, strides, padding):
+ """Compute a mask representing the connectivity of a convolution operation.
+
+ Assume a convolution with given parameters is applied to an input having N
+ spatial dimensions with `input_shape = (d_in1, ..., d_inN)` to produce an
+ output with shape `(d_out1, ..., d_outN)`. This method returns a boolean array
+ of shape `(d_in1, ..., d_inN, d_out1, ..., d_outN)` with `True` entries
+ indicating pairs of input and output locations that are connected by a weight.
+
+ Example:
+ ```python
+ >>> input_shape = (4,)
+ >>> kernel_shape = (2,)
+ >>> strides = (1,)
+ >>> padding = "valid"
+ >>> conv_kernel_mask(input_shape, kernel_shape, strides, padding)
+ array([[ True, False, False],
+ [ True, True, False],
+ [False, True, True],
+ [False, False, True]], dtype=bool)
+ ```
+ where rows and columns correspond to inputs and outputs respectively.
+
+
+ Args:
+ input_shape: tuple of size N: `(d_in1, ..., d_inN)`,
+ spatial shape of the input.
+ kernel_shape: tuple of size N, spatial shape of the convolutional kernel
+ / receptive field.
+ strides: tuple of size N, strides along each spatial dimension.
+ padding: type of padding, string `"same"` or `"valid"`.
+
+ Returns:
+ A boolean 2N-D `np.ndarray` of shape
+ `(d_in1, ..., d_inN, d_out1, ..., d_outN)`, where `(d_out1, ..., d_outN)`
+ is the spatial shape of the output. `True` entries in the mask represent
+ pairs of input-output locations that are connected by a weight.
+
+ Raises:
+ ValueError: if `input_shape`, `kernel_shape` and `strides` don't have the
+ same number of dimensions.
+ NotImplementedError: if `padding` is not in {`"same"`, `"valid"`}.
+ """
+ if padding not in {'same', 'valid'}:
+ raise NotImplementedError('Padding type %s not supported. '
+ 'Only "valid" and "same" '
+ 'are implemented.' % padding)
+
+ in_dims = len(input_shape)
+ if isinstance(kernel_shape, int):
+ kernel_shape = (kernel_shape,) * in_dims
+ if isinstance(strides, int):
+ strides = (strides,) * in_dims
+
+ kernel_dims = len(kernel_shape)
+ stride_dims = len(strides)
+ if kernel_dims != in_dims or stride_dims != in_dims:
+ raise ValueError('Number of strides, input and kernel dimensions must all '
+ 'match. Received: %d, %d, %d.' %
+ (stride_dims, in_dims, kernel_dims))
+
+ output_shape = conv_output_shape(input_shape, kernel_shape, strides, padding)
+
+ mask_shape = input_shape + output_shape
+ mask = np.zeros(mask_shape, np.bool)
+
+ output_axes_ticks = [range(dim) for dim in output_shape]
+ for output_position in itertools.product(*output_axes_ticks):
+ input_axes_ticks = conv_connected_inputs(input_shape,
+ kernel_shape,
+ output_position,
+ strides,
+ padding)
+ for input_position in itertools.product(*input_axes_ticks):
+ mask[input_position + output_position] = True
+
+ return mask
+
+
+def conv_connected_inputs(input_shape,
+ kernel_shape,
+ output_position,
+ strides,
+ padding):
+ """Return locations of the input connected to an output position.
+
+ Assume a convolution with given parameters is applied to an input having N
+ spatial dimensions with `input_shape = (d_in1, ..., d_inN)`. This method
+ returns N ranges specifying the input region that was convolved with the
+ kernel to produce the output at position
+ `output_position = (p_out1, ..., p_outN)`.
+
+ Example:
+ ```python
+ >>> input_shape = (4, 4)
+ >>> kernel_shape = (2, 1)
+ >>> output_position = (1, 1)
+ >>> strides = (1, 1)
+ >>> padding = "valid"
+ >>> conv_connected_inputs(input_shape, kernel_shape, output_position,
+ >>> strides, padding)
+ [xrange(1, 3), xrange(1, 2)]
+ ```
+ Args:
+ input_shape: tuple of size N: `(d_in1, ..., d_inN)`,
+ spatial shape of the input.
+ kernel_shape: tuple of size N, spatial shape of the convolutional kernel
+ / receptive field.
+ output_position: tuple of size N: `(p_out1, ..., p_outN)`,
+ a single position in the output of the convolution.
+ strides: tuple of size N, strides along each spatial dimension.
+ padding: type of padding, string `"same"` or `"valid"`.
+
+ Returns:
+ N ranges `[[p_in_left1, ..., p_in_right1], ...,
+ [p_in_leftN, ..., p_in_rightN]]` specifying the region in the
+ input connected to output_position.
+ """
+ ranges = []
+
+ ndims = len(input_shape)
+ for d in range(ndims):
+ left_shift = int(kernel_shape[d] / 2)
+ right_shift = kernel_shape[d] - left_shift
+
+ center = output_position[d] * strides[d]
+
+ if padding == 'valid':
+ center += left_shift
+
+ start = max(0, center - left_shift)
+ end = min(input_shape[d], center + right_shift)
+
+ ranges.append(range(start, end))
+
+ return ranges
+
+
+def conv_output_shape(input_shape, kernel_shape, strides, padding):
+ """Return the output shape of an N-D convolution.
+
+ Forces dimensions where input is empty (size 0) to remain empty.
+
+ Args:
+ input_shape: tuple of size N: `(d_in1, ..., d_inN)`,
+ spatial shape of the input.
+ kernel_shape: tuple of size N, spatial shape of the convolutional kernel
+ / receptive field.
+ strides: tuple of size N, strides along each spatial dimension.
+ padding: type of padding, string `"same"` or `"valid"`.
+
+ Returns:
+ tuple of size N: `(d_out1, ..., d_outN)`, spatial shape of the output.
+ """
+ dims = range(len(kernel_shape))
+ output_shape = [conv_output_length(input_shape[d],
+ kernel_shape[d],
+ padding,
+ strides[d])
+ for d in dims]
+ output_shape = tuple([0 if input_shape[d] == 0 else output_shape[d]
+ for d in dims])
+ return output_shape
diff --git a/tensorflow/python/keras/utils/conv_utils_test.py b/tensorflow/python/keras/utils/conv_utils_test.py
new file mode 100644
index 0000000000..eb2a360bfd
--- /dev/null
+++ b/tensorflow/python/keras/utils/conv_utils_test.py
@@ -0,0 +1,232 @@
+# 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.
+# 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 conv_utils."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import itertools
+
+from absl.testing import parameterized
+import numpy as np
+
+from tensorflow.python.keras.utils import conv_utils
+from tensorflow.python.platform import test
+
+
+def _get_const_output_shape(input_shape, dim):
+ return tuple([min(d, dim) for d in input_shape])
+
+
+input_shapes = [
+ (0,),
+ (0, 0),
+ (1,),
+ (2,),
+ (3,),
+ (1, 0),
+ (0, 3),
+ (1, 1),
+ (1, 2),
+ (3, 1),
+ (2, 2),
+ (3, 3),
+ (1, 0, 1),
+ (5, 2, 3),
+ (3, 5, 6, 7, 0),
+ (3, 2, 2, 4, 4),
+ (1, 2, 3, 4, 7, 2),
+]
+
+
+@parameterized.parameters(input_shapes)
+class TestConvUtils(test.TestCase, parameterized.TestCase):
+
+ def test_conv_kernel_mask_fc(self, *input_shape):
+ padding = 'valid'
+ kernel_shape = input_shape
+ ndims = len(input_shape)
+ strides = (1,) * ndims
+ output_shape = _get_const_output_shape(input_shape, dim=1)
+ mask = np.ones(input_shape + output_shape, np.bool)
+ self.assertAllEqual(
+ mask,
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ padding
+ )
+ )
+
+ def test_conv_kernel_mask_diag(self, *input_shape):
+ ndims = len(input_shape)
+ kernel_shape = (1,) * ndims
+ strides = (1,) * ndims
+
+ for padding in ['valid', 'same']:
+ mask = np.identity(int(np.prod(input_shape)), np.bool)
+ mask = np.reshape(mask, input_shape * 2)
+ self.assertAllEqual(
+ mask,
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ padding
+ )
+ )
+
+ def test_conv_kernel_mask_full_stride(self, *input_shape):
+ padding = 'valid'
+ ndims = len(input_shape)
+ kernel_shape = (1,) * ndims
+ strides = tuple([max(d, 1) for d in input_shape])
+ output_shape = _get_const_output_shape(input_shape, dim=1)
+
+ mask = np.zeros(input_shape + output_shape, np.bool)
+ if all(d > 0 for d in mask.shape):
+ mask[(0,) * len(output_shape)] = True
+
+ self.assertAllEqual(
+ mask,
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ padding
+ )
+ )
+
+ def test_conv_kernel_mask_almost_full_stride(self, *input_shape):
+ padding = 'valid'
+ ndims = len(input_shape)
+ kernel_shape = (1,) * ndims
+ strides = tuple([max(d - 1, 1) for d in input_shape])
+ output_shape = _get_const_output_shape(input_shape, dim=2)
+
+ mask = np.zeros(input_shape + output_shape, np.bool)
+ if all(d > 0 for d in mask.shape):
+ for in_position in itertools.product(*[[0, d - 1] for d in input_shape]):
+ out_position = tuple([min(p, 1) for p in in_position])
+ mask[in_position + out_position] = True
+
+ self.assertAllEqual(
+ mask,
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ padding
+ )
+ )
+
+ def test_conv_kernel_mask_rect_kernel(self, *input_shape):
+ padding = 'valid'
+ ndims = len(input_shape)
+ strides = (1,) * ndims
+
+ for d in range(ndims):
+ kernel_shape = [1] * ndims
+ kernel_shape[d] = input_shape[d]
+
+ output_shape = list(input_shape)
+ output_shape[d] = min(1, input_shape[d])
+
+ mask = np.identity(int(np.prod(input_shape)), np.bool)
+ mask = np.reshape(mask, input_shape * 2)
+
+ for p in itertools.product(*[range(input_shape[dim])
+ for dim in range(ndims)]):
+ p = list(p)
+ p[d] = slice(None)
+ mask[p * 2] = True
+
+ mask = np.take(mask, range(0, min(1, input_shape[d])), ndims + d)
+
+ self.assertAllEqual(
+ mask,
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ padding
+ )
+ )
+
+ def test_conv_kernel_mask_wrong_padding(self, *input_shape):
+ ndims = len(input_shape)
+ kernel_shape = (1,) * ndims
+ strides = (1,) * ndims
+
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ 'valid'
+ )
+
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ 'same'
+ )
+
+ self.assertRaises(NotImplementedError,
+ conv_utils.conv_kernel_mask,
+ input_shape, kernel_shape, strides, 'full')
+
+ def test_conv_kernel_mask_wrong_dims(self, *input_shape):
+ kernel_shape = 1
+ strides = 1
+
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ 'valid'
+ )
+
+ ndims = len(input_shape)
+
+ kernel_shape = (2,) * (ndims + 1)
+ self.assertRaises(ValueError,
+ conv_utils.conv_kernel_mask,
+ input_shape, kernel_shape, strides, 'same')
+
+ strides = (1,) * ndims
+ self.assertRaises(ValueError,
+ conv_utils.conv_kernel_mask,
+ input_shape, kernel_shape, strides, 'valid')
+
+ kernel_shape = (1,) * ndims
+ strides = (2,) * (ndims - 1)
+ self.assertRaises(ValueError,
+ conv_utils.conv_kernel_mask,
+ input_shape, kernel_shape, strides, 'valid')
+
+ strides = (2,) * ndims
+ conv_utils.conv_kernel_mask(
+ input_shape,
+ kernel_shape,
+ strides,
+ 'valid'
+ )
+
+
+if __name__ == '__main__':
+ test.main()
diff --git a/tensorflow/python/kernel_tests/BUILD b/tensorflow/python/kernel_tests/BUILD
index 2451dc7257..447e9b949b 100644
--- a/tensorflow/python/kernel_tests/BUILD
+++ b/tensorflow/python/kernel_tests/BUILD
@@ -73,6 +73,17 @@ tf_py_test(
)
tf_py_test(
+ name = "batch_gather_op_test",
+ srcs = ["batch_gather_op_test.py"],
+ additional_deps = [
+ "//tensorflow/python:array_ops",
+ "//tensorflow/python:client_testlib",
+ "//tensorflow/python:constant_op",
+ "//tensorflow/python:dtypes",
+ ],
+)
+
+tf_py_test(
name = "bcast_ops_test",
size = "small",
srcs = ["bcast_ops_test.py"],
@@ -736,6 +747,7 @@ tf_py_test(
size = "small",
srcs = ["regex_replace_op_test.py"],
additional_deps = [
+ "@absl_py//absl/testing:parameterized",
"//tensorflow/python:client_testlib",
"//tensorflow/python:constant_op",
"//tensorflow/python:dtypes",
@@ -949,6 +961,17 @@ tf_py_test(
)
tf_py_test(
+ name = "string_length_op_test",
+ size = "small",
+ srcs = ["string_length_op_test.py"],
+ additional_deps = [
+ "//tensorflow/python:client_testlib",
+ "//tensorflow/python:framework_for_generated_wrappers",
+ "//tensorflow/python:string_ops",
+ ],
+)
+
+tf_py_test(
name = "string_strip_op_test",
size = "small",
srcs = ["string_strip_op_test.py"],
@@ -2181,7 +2204,6 @@ cuda_py_test(
"//tensorflow/python:framework_for_generated_wrappers",
"//tensorflow/python:parsing_ops",
],
- tags = ["no_windows"],
)
cuda_py_test(
diff --git a/tensorflow/python/kernel_tests/array_ops_test.py b/tensorflow/python/kernel_tests/array_ops_test.py
index 40567571e6..81442d12e9 100644
--- a/tensorflow/python/kernel_tests/array_ops_test.py
+++ b/tensorflow/python/kernel_tests/array_ops_test.py
@@ -245,6 +245,7 @@ class BooleanMaskTest(test_util.TensorFlowTestCase):
array_ops.boolean_mask(tensor, mask).eval()
+@test_util.run_all_in_graph_and_eager_modes
class OperatorShapeTest(test_util.TensorFlowTestCase):
def testExpandScalar(self):
@@ -262,7 +263,8 @@ class OperatorShapeTest(test_util.TensorFlowTestCase):
matrix_squeezed = array_ops.squeeze(matrix, [0])
self.assertEqual(matrix_squeezed.get_shape(), (3))
- with self.assertRaises(ValueError):
+ with self.assertRaisesRegexp(
+ Exception, "Can not squeeze dim.1., expected a dimension of 1, got 3"):
matrix_squeezed = array_ops.squeeze(matrix, [1])
def testSqueezeScalarDim(self):
@@ -270,6 +272,11 @@ class OperatorShapeTest(test_util.TensorFlowTestCase):
matrix_squeezed = array_ops.squeeze(matrix, 0)
self.assertEqual(matrix_squeezed.get_shape(), (3))
+ def testExpandDimsWithNonScalarDim(self):
+ with self.assertRaisesRegexp(Exception,
+ "must be a tensor with a single value"):
+ array_ops.expand_dims(1, axis=[0, 1])
+
class ReverseV2Test(test_util.TensorFlowTestCase):
diff --git a/tensorflow/python/kernel_tests/as_string_op_test.py b/tensorflow/python/kernel_tests/as_string_op_test.py
index 94ed8ebd31..51aa17babe 100644
--- a/tensorflow/python/kernel_tests/as_string_op_test.py
+++ b/tensorflow/python/kernel_tests/as_string_op_test.py
@@ -160,7 +160,7 @@ class AsStringOpTest(test.TestCase):
complex_inputs_ = [(x + (x + 1) * 1j) for x in float_inputs_]
with self.test_session():
- for dtype in (dtypes.complex64,):
+ for dtype in (dtypes.complex64, dtypes.complex128):
input_ = array_ops.placeholder(dtype)
def clean_nans(s_l):
diff --git a/tensorflow/python/kernel_tests/batch_gather_op_test.py b/tensorflow/python/kernel_tests/batch_gather_op_test.py
new file mode 100644
index 0000000000..8e7ae89f9d
--- /dev/null
+++ b/tensorflow/python/kernel_tests/batch_gather_op_test.py
@@ -0,0 +1,116 @@
+# Copyright 2015 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.ops.tf.gather."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import numpy as np
+
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
+from tensorflow.python.ops import array_ops
+from tensorflow.python.platform import test
+
+_TEST_TYPES = (dtypes.int64, dtypes.float32,
+ dtypes.complex64, dtypes.complex128)
+
+
+class GatherTest(test.TestCase):
+
+ def _buildParams(self, data, dtype):
+ data = data.astype(dtype.as_numpy_dtype)
+ # For complex types, add an index-dependent imaginary component so we can
+ # tell we got the right value.
+ if dtype.is_complex:
+ return data + 10j * data
+ return data
+
+ def testSimpleGather(self):
+ data = np.array([0, 1, 2, 3, 7, 5, 8, 9, 10, 11, 15, 13])
+ indices = [3, 4]
+ with self.test_session(use_gpu=True):
+ for dtype in _TEST_TYPES:
+ params_np = self._buildParams(data, dtype)
+ params = constant_op.constant(params_np)
+ indices_tf = constant_op.constant(indices)
+ gather_t = array_ops.batch_gather(params, indices_tf)
+ expected_result = np.array([3, 7])
+ np_val = self._buildParams(expected_result, dtype)
+ gather_val = gather_t.eval()
+ self.assertAllEqual(np_val, gather_val)
+ self.assertEqual(np_val.shape, gather_t.get_shape())
+
+ def test2DArray(self):
+ data = np.array([[0, 1, 2, 3, 7, 5], [8, 9, 10, 11, 15, 13]])
+ indices = [[3], [4]]
+ with self.test_session(use_gpu=True):
+ for dtype in _TEST_TYPES:
+ params_np = self._buildParams(data, dtype)
+ params = constant_op.constant(params_np)
+ indices_tf = constant_op.constant(indices)
+ gather_t = array_ops.batch_gather(params, indices_tf)
+ expected_result = np.array([[3], [15]])
+ np_val = self._buildParams(expected_result, dtype)
+ gather_val = gather_t.eval()
+ self.assertAllEqual(np_val, gather_val)
+ self.assertEqual(np_val.shape, gather_t.get_shape())
+
+ def testHigherRank(self):
+ data = np.array([[[0, 1, 2], [3, 7, 5]], [[8, 9, 10], [11, 15, 13]]])
+ indices = [[[2, 0], [1, 2]], [[2, 0], [0, 1]]]
+ with self.test_session(use_gpu=True):
+ for dtype in _TEST_TYPES:
+ params_np = self._buildParams(data, dtype)
+ params = constant_op.constant(params_np)
+ indices_tf = constant_op.constant(indices)
+ gather_t = array_ops.batch_gather(params, indices_tf)
+ gather_val = gather_t.eval()
+ expected_result = np.array([[[2, 0], [7, 5]], [[10, 8], [11, 15]]])
+ np_val = self._buildParams(expected_result, dtype)
+ self.assertAllEqual(np_val, gather_val)
+ self.assertEqual(np_val.shape, gather_t.get_shape())
+
+ def testString(self):
+ params = np.array([[b"asdf", b"zxcv"], [b"qwer", b"uiop"]])
+ with self.test_session():
+ indices_tf = constant_op.constant([1])
+ self.assertAllEqual([[b"qwer", b"uiop"]],
+ array_ops.batch_gather(params, indices_tf).eval())
+
+ def testUnknownIndices(self):
+ params = constant_op.constant([[0, 1, 2]])
+ indices = array_ops.placeholder(dtypes.int32, shape=[None, None])
+ gather_t = array_ops.batch_gather(params, indices)
+ self.assertEqual([1, None], gather_t.get_shape().as_list())
+
+ def testBadIndicesCPU(self):
+ with self.test_session(use_gpu=False):
+ params = [[0, 1, 2], [3, 4, 5]]
+ with self.assertRaisesOpError(r"indices\[0\] = 7 is not in \[0, 2\)"):
+ array_ops.batch_gather(params, [7]).eval()
+
+ def testEmptySlices(self):
+ with self.test_session(use_gpu=True):
+ for dtype in _TEST_TYPES:
+ for itype in np.int32, np.int64:
+ params = np.zeros((7, 0, 0), dtype=dtype.as_numpy_dtype)
+ indices = np.array([3, 4], dtype=itype)
+ gather = array_ops.batch_gather(params, indices)
+ self.assertAllEqual(gather.eval(), np.zeros((2, 0, 0)))
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/python/kernel_tests/clip_ops_test.py b/tensorflow/python/kernel_tests/clip_ops_test.py
index fb52d10475..400d38b936 100644
--- a/tensorflow/python/kernel_tests/clip_ops_test.py
+++ b/tensorflow/python/kernel_tests/clip_ops_test.py
@@ -22,6 +22,7 @@ import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import clip_ops
@@ -369,6 +370,21 @@ class ClipTest(test.TestCase):
self.assertAllClose(np_ans_0, tf_ans_1)
self.assertAllClose(np_ans_1, tf_ans_2)
+ def testClipByGlobalNormInf(self):
+ with self.test_session(use_gpu=True):
+ x0 = constant_op.constant([-2.0, 0.0, np.inf, 4.0, 0.0, 0.0],
+ shape=[2, 3])
+ x1 = constant_op.constant([1.0, -2.0])
+ clip_norm = 6.0
+
+ ans, norm = clip_ops.clip_by_global_norm([x0, x1], clip_norm)
+ with self.assertRaisesRegexp(errors.InvalidArgumentError, "global norm"):
+ norm.eval()
+ with self.assertRaisesRegexp(errors.InvalidArgumentError, "global norm"):
+ ans[0].eval()
+ with self.assertRaisesRegexp(errors.InvalidArgumentError, "global norm"):
+ ans[1].eval()
+
def testClipByAverageNormClipped(self):
# Norm clipping when average clip_norm < 0.83333333
with self.test_session(use_gpu=True):
diff --git a/tensorflow/python/kernel_tests/cond_v2_test.py b/tensorflow/python/kernel_tests/cond_v2_test.py
index 4d074218d1..b9910133d8 100644
--- a/tensorflow/python/kernel_tests/cond_v2_test.py
+++ b/tensorflow/python/kernel_tests/cond_v2_test.py
@@ -257,6 +257,32 @@ class CondV2Test(test.TestCase):
run_test(True)
run_test(False)
+ def testNestedCondBothBranches(self):
+
+ def run_test(pred_value):
+
+ def build_graph():
+ pred = array_ops.placeholder(dtypes.bool, name="pred")
+ x = constant_op.constant(1.0, name="x")
+ y = constant_op.constant(2.0, name="y")
+
+ def true_fn():
+ return _cond(pred, lambda: x + y, lambda: x * x, name=None)
+
+ def false_fn():
+ return _cond(pred, lambda: x - y, lambda: y * y, name=None)
+
+ return x, y, pred, true_fn, false_fn
+
+ with ops.Graph().as_default():
+ x, y, pred, true_fn, false_fn = build_graph()
+ self._testCond(true_fn, false_fn, [x, y], {pred: pred_value})
+ self._testCond(true_fn, false_fn, [x], {pred: pred_value})
+ self._testCond(true_fn, false_fn, [y], {pred: pred_value})
+
+ run_test(True)
+ run_test(False)
+
def testDoubleNestedCond(self):
def run_test(pred1_value, pred2_value):
diff --git a/tensorflow/python/kernel_tests/confusion_matrix_test.py b/tensorflow/python/kernel_tests/confusion_matrix_test.py
index ae6875340e..93f5323c41 100644
--- a/tensorflow/python/kernel_tests/confusion_matrix_test.py
+++ b/tensorflow/python/kernel_tests/confusion_matrix_test.py
@@ -448,7 +448,7 @@ class RemoveSqueezableDimensionsTest(test.TestCase):
}
with self.assertRaisesRegexp(
errors_impl.InvalidArgumentError,
- "Tried to explicitly squeeze dimension 2"):
+ "Can not squeeze dim\[2\]"):
dynamic_labels.eval(feed_dict=feed_dict)
self.assertAllEqual(
prediction_values, dynamic_predictions.eval(feed_dict=feed_dict))
@@ -475,7 +475,7 @@ class RemoveSqueezableDimensionsTest(test.TestCase):
label_values, dynamic_labels.eval(feed_dict=feed_dict))
with self.assertRaisesRegexp(
errors_impl.InvalidArgumentError,
- "Tried to explicitly squeeze dimension 2"):
+ "Can not squeeze dim\[2\]"):
dynamic_predictions.eval(feed_dict=feed_dict)
diff --git a/tensorflow/python/kernel_tests/control_flow_ops_py_test.py b/tensorflow/python/kernel_tests/control_flow_ops_py_test.py
index b567b71424..1a29d0816d 100644
--- a/tensorflow/python/kernel_tests/control_flow_ops_py_test.py
+++ b/tensorflow/python/kernel_tests/control_flow_ops_py_test.py
@@ -647,7 +647,8 @@ class ControlFlowTest(test.TestCase):
# feeding into the fill is dominated by a Switch.
zero = graph.get_operation_by_name("gradients/zeros/Const")
self.assertEqual(len(zero.control_inputs), 1)
- self.assertEqual(zero.control_inputs[0].type, "Switch")
+ self.assertEqual(zero.control_inputs[0].type, "Identity")
+ self.assertEqual(zero.control_inputs[0].inputs[0].op.type, "Switch")
def testCondGrad_2(self):
with self.test_session():
diff --git a/tensorflow/python/kernel_tests/functional_ops_test.py b/tensorflow/python/kernel_tests/functional_ops_test.py
index 24800d2b7a..5db2e9821d 100644
--- a/tensorflow/python/kernel_tests/functional_ops_test.py
+++ b/tensorflow/python/kernel_tests/functional_ops_test.py
@@ -978,6 +978,8 @@ class FunctionalOpsTest(test.TestCase):
self.assertAllEqual(sess.run(bvals), [17., 16.])
+# TODO(akshayka): Replace `function.Defun` with tf.contrib.eager.defun` in the
+# below test cases.
class PartitionedCallTest(test.TestCase):
def testBasicSingleDevice(self):
@@ -1053,7 +1055,7 @@ class PartitionedCallTest(test.TestCase):
self.assertEqual(output, 6.)
def testShardsRunOnRequestedDevices(self):
- config = config_pb2.ConfigProto(device_count={"CPU": 3})
+ config = config_pb2.ConfigProto(device_count={"CPU": 4})
@function.Defun()
def Body():
@@ -1073,13 +1075,30 @@ class PartitionedCallTest(test.TestCase):
with ops.device("/cpu:2"):
s3 = iterator_ops.Iterator.from_structure(
(dtypes.float32,)).string_handle()
- return s1, s2, s3
+ with ops.device(""):
+ # TODO(akshayka): This is unfortunate and brittle. It prevents
+ # `Iterator.from_structure` from assigning the iterator op to 'cpu:0'.
+ # Remove this hack once we have a way of obtaining metadata about
+ # function execution.
+ s4 = iterator_ops.Iterator.from_structure(
+ (dtypes.float32,)).string_handle()
+ return s1, s2, s3, s4
- with self.test_session(config=config):
- outputs = functional_ops.partitioned_call(args=[], f=Body)
- self.assertTrue(compat.as_bytes("CPU:0") in outputs[0].eval())
- self.assertTrue(compat.as_bytes("CPU:1") in outputs[1].eval())
- self.assertTrue(compat.as_bytes("CPU:2") in outputs[2].eval())
+ with self.test_session(config=config, use_gpu=True) as sess:
+ with ops.device("/cpu:3"):
+ outputs = sess.run(functional_ops.partitioned_call(args=[], f=Body))
+ self.assertIn(compat.as_bytes("CPU:0"), outputs[0])
+ self.assertIn(compat.as_bytes("CPU:1"), outputs[1])
+ self.assertIn(compat.as_bytes("CPU:2"), outputs[2])
+ self.assertIn(compat.as_bytes("CPU:3"), outputs[3])
+
+ with self.test_session(config=config, use_gpu=True):
+ with ops.device("/cpu:0"):
+ outputs = sess.run(functional_ops.partitioned_call(args=[], f=Body))
+ self.assertIn(compat.as_bytes("CPU:0"), outputs[0])
+ self.assertIn(compat.as_bytes("CPU:1"), outputs[1])
+ self.assertIn(compat.as_bytes("CPU:2"), outputs[2])
+ self.assertIn(compat.as_bytes("CPU:0"), outputs[3])
def testAssignAddResourceVariable(self):
diff --git a/tensorflow/python/kernel_tests/list_ops_test.py b/tensorflow/python/kernel_tests/list_ops_test.py
index bf82e08551..3193222262 100644
--- a/tensorflow/python/kernel_tests/list_ops_test.py
+++ b/tensorflow/python/kernel_tests/list_ops_test.py
@@ -421,6 +421,31 @@ class ListOpsTest(test_util.TensorFlowTestCase):
"Invalid data type at index 0"):
self.evaluate(list_ops.tensor_list_push_back_batch(l_batch, [3, 4]))
+ @test_util.run_in_graph_and_eager_modes
+ def testZerosLike(self):
+ for dtype in (dtypes.uint8, dtypes.uint16, dtypes.int8, dtypes.int16,
+ dtypes.int32, dtypes.int64, dtypes.float16, dtypes.float32,
+ dtypes.float64, dtypes.complex64, dtypes.complex128,
+ dtypes.bool):
+ l_empty = list_ops.empty_tensor_list(
+ element_dtype=dtype, element_shape=scalar_shape())
+ l_empty_zeros = array_ops.zeros_like(l_empty)
+ t_empty_zeros = list_ops.tensor_list_stack(
+ l_empty_zeros, element_dtype=dtype)
+
+ l_full = list_ops.tensor_list_push_back(l_empty,
+ math_ops.cast(0, dtype=dtype))
+ l_full = list_ops.tensor_list_push_back(l_full,
+ math_ops.cast(1, dtype=dtype))
+ l_full_zeros = array_ops.zeros_like(l_full)
+ t_full_zeros = list_ops.tensor_list_stack(
+ l_full_zeros, element_dtype=dtype)
+
+ self.assertAllEqual(self.evaluate(t_empty_zeros), [])
+ self.assertAllEqual(
+ self.evaluate(t_full_zeros), np.zeros(
+ (2,), dtype=dtype.as_numpy_dtype))
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/kernel_tests/partitioned_variables_test.py b/tensorflow/python/kernel_tests/partitioned_variables_test.py
index f5c6255c34..1d0c2dceba 100644
--- a/tensorflow/python/kernel_tests/partitioned_variables_test.py
+++ b/tensorflow/python/kernel_tests/partitioned_variables_test.py
@@ -18,6 +18,8 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import os
+
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
@@ -25,12 +27,16 @@ from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import init_ops
+from tensorflow.python.ops import math_ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
+from tensorflow.python.training import gradient_descent
+from tensorflow.python.training import saver as saver_lib
class PartitionerCreatorsTest(test.TestCase):
@@ -543,32 +549,6 @@ class PartitionedVariablesTestCase(test.TestCase):
partitioned_variables.create_partitioned_variables(
[10, 43], [1, 50], rnd.initialized_value())
- def testControlDepsNone(self):
- with self.test_session() as session:
- c = constant_op.constant(1.0)
- with ops.control_dependencies([c]):
- # d get the control dependency.
- d = constant_op.constant(2.0)
- # Partitioned variables do not.
- var_x = variable_scope.get_variable(
- "x",
- shape=[2],
- initializer=init_ops.ones_initializer(),
- partitioner=partitioned_variables.variable_axis_size_partitioner(4))
-
- ops_before_read = session.graph.get_operations()
- var_x.as_tensor() # Caches the ops for subsequent reads.
- reading_ops = [
- op for op in session.graph.get_operations()
- if op not in ops_before_read
- ]
-
- self.assertEqual([c.op], d.op.control_inputs)
- # Tests that no control dependencies are added to reading a partitioned
- # variable which is similar to reading a variable.
- for op in reading_ops:
- self.assertEqual([], op.control_inputs)
-
def testConcat(self):
with self.test_session() as session:
var_x = variable_scope.get_variable(
@@ -594,6 +574,89 @@ class PartitionedVariablesTestCase(test.TestCase):
variables.global_variables_initializer().run()
self.assertAllClose(value.eval(), var_x.as_tensor().eval())
+ def testVariableCreationInALoop(self):
+ """Tests the variable created inside a loop can be used outside the loop."""
+ with self.test_session():
+ with variable_scope.variable_scope("ascope") as scope:
+ def Body(i, _):
+ var_x = variable_scope.get_variable(
+ "x",
+ shape=[2],
+ initializer=init_ops.ones_initializer(),
+ partitioner=partitioned_variables.variable_axis_size_partitioner(
+ 4))
+ return (i + 1, var_x.as_tensor())
+
+ cond = lambda i, _: i < 2
+ _, x = control_flow_ops.while_loop(
+ cond, Body, (0, constant_op.constant([7, 8], dtypes.float32)))
+ variables.global_variables_initializer().run()
+ self.assertAllClose([1.0, 1.0], x.eval())
+
+ scope.reuse_variables()
+ var_x = variable_scope.get_variable(
+ "x",
+ shape=[2],
+ initializer=init_ops.ones_initializer(),
+ partitioner=partitioned_variables.variable_axis_size_partitioner(4))
+
+ self.assertAllClose([1.0, 1.0], var_x.as_tensor().eval())
+
+ def testReadInWhileLoop(self):
+ """Tests the value is current (not cached) when read within a loop."""
+ with self.test_session():
+ var_x = variable_scope.get_variable(
+ "x",
+ shape=[2],
+ initializer=init_ops.ones_initializer(),
+ partitioner=partitioned_variables.variable_axis_size_partitioner(4))
+
+ def Body(i, _):
+ # Use a SGD step to update the variable's value.
+ loss = math_ops.reduce_sum(var_x)
+ optimizer = gradient_descent.GradientDescentOptimizer(1.0)
+ minimize = optimizer.minimize(loss * 0.7)
+ with ops.control_dependencies([minimize]):
+ return (i + 1, var_x.as_tensor())
+
+ cond = lambda i, _: i < 2
+ _, x = control_flow_ops.while_loop(
+ cond, Body, (0, constant_op.constant([7, 8], dtypes.float32)))
+ variables.global_variables_initializer().run()
+ self.assertAllClose([-0.4, -0.4], x.eval())
+
+ def testMetaGraphSaveLoad(self):
+ save_prefix = os.path.join(self.get_temp_dir(), "ckpt")
+ save_graph = ops.Graph()
+ with save_graph.as_default(), self.test_session(
+ graph=save_graph) as session:
+ partitioner = partitioned_variables.fixed_size_partitioner(5, axis=0)
+ with variable_scope.variable_scope("root", partitioner=partitioner):
+ v0 = variable_scope.get_variable(
+ "v0", dtype=dtypes.float32, shape=(10, 10))
+ v0_list = v0._get_variable_list()
+ v0_part = v0._get_partitions()
+ self.assertEqual(len(v0_list), 5)
+ self.assertAllEqual(v0_part, (5, 1))
+ variables.global_variables_initializer().run()
+
+ save_graph.get_collection_ref("partvar").append(v0)
+ saver = saver_lib.Saver()
+ save_graph.finalize()
+ save_path = saver.save(sess=session, save_path=save_prefix)
+ previous_value = session.run(
+ save_graph.get_tensor_by_name(v0.name + ":0"))
+
+ restore_graph = ops.Graph()
+ with restore_graph.as_default(), self.test_session(
+ graph=restore_graph) as session:
+ saver = saver_lib.import_meta_graph(save_path + ".meta")
+ saver.restore(sess=session, save_path=save_path)
+ v0, = save_graph.get_collection_ref("partvar")
+ self.assertIsInstance(v0, variables.PartitionedVariable)
+ self.assertAllEqual(
+ previous_value,
+ session.run(restore_graph.get_tensor_by_name(v0.name + ":0")))
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/kernel_tests/regex_replace_op_test.py b/tensorflow/python/kernel_tests/regex_replace_op_test.py
index 6739ac3224..f0e84b8fca 100644
--- a/tensorflow/python/kernel_tests/regex_replace_op_test.py
+++ b/tensorflow/python/kernel_tests/regex_replace_op_test.py
@@ -18,54 +18,104 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+from absl.testing import parameterized
+
+from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
+from tensorflow.python.ops import gen_string_ops
from tensorflow.python.ops import string_ops
from tensorflow.python.platform import test
-class RegexReplaceOpTest(test.TestCase):
+@parameterized.parameters(
+ (gen_string_ops.regex_replace),
+ (gen_string_ops.static_regex_replace))
+class RegexReplaceOpVariantsTest(test.TestCase, parameterized.TestCase):
+
+ def testForwarding(self, op):
+ with self.test_session():
+ # Generate an input that is uniquely consumed by the regex op.
+ # This exercises code paths which are optimized for this case
+ # (e.g., using forwarding).
+ inp = string_ops.substr(
+ constant_op.constant(["AbCdEfG",
+ "HiJkLmN"], dtypes.string),
+ pos=0,
+ len=5)
+ stripped = op(inp, "\\p{Ll}", ".").eval()
+ self.assertAllEqual([b"A.C.E", b"H.J.L"], stripped)
- def testRemovePrefix(self):
+ def testRemovePrefix(self, op):
values = ["a:foo", "a:bar", "a:foo", "b:baz", "b:qux", "ca:b"]
with self.test_session():
input_vector = constant_op.constant(values, dtypes.string)
- stripped = string_ops.regex_replace(
- input_vector, "^(a:|b:)", "", replace_global=False).eval()
+ stripped = op(input_vector, "^(a:|b:)", "", replace_global=False).eval()
self.assertAllEqual([b"foo", b"bar", b"foo", b"baz", b"qux", b"ca:b"],
stripped)
- def testRegexReplace(self):
+ def testRegexReplace(self, op):
values = ["aba\naba", "abcdabcde"]
with self.test_session():
input_vector = constant_op.constant(values, dtypes.string)
- stripped = string_ops.regex_replace(input_vector, "a.*a", "(\\0)").eval()
+ stripped = op(input_vector, "a.*a", "(\\0)").eval()
self.assertAllEqual([b"(aba)\n(aba)", b"(abcda)bcde"], stripped)
- def testEmptyMatch(self):
+ def testEmptyMatch(self, op):
values = ["abc", "1"]
with self.test_session():
input_vector = constant_op.constant(values, dtypes.string)
- stripped = string_ops.regex_replace(input_vector, "", "x").eval()
+ stripped = op(input_vector, "", "x").eval()
self.assertAllEqual([b"xaxbxcx", b"x1x"], stripped)
- def testInvalidPattern(self):
+ def testInvalidPattern(self, op):
values = ["abc", "1"]
with self.test_session():
input_vector = constant_op.constant(values, dtypes.string)
invalid_pattern = "A["
- replace = string_ops.regex_replace(input_vector, invalid_pattern, "x")
+ replace = op(input_vector, invalid_pattern, "x")
with self.assertRaisesOpError("Invalid pattern"):
replace.eval()
- def testGlobal(self):
+ def testGlobal(self, op):
values = ["ababababab", "abcabcabc", ""]
with self.test_session():
input_vector = constant_op.constant(values, dtypes.string)
- stripped = string_ops.regex_replace(input_vector, "ab", "abc",
- True).eval()
+ stripped = op(input_vector, "ab", "abc", True).eval()
self.assertAllEqual([b"abcabcabcabcabc", b"abccabccabcc", b""], stripped)
+def as_string(s):
+ return s
+
+
+def as_tensor(s):
+ return constant_op.constant(s, dtypes.string)
+
+
+class RegexReplaceTest(test.TestCase, parameterized.TestCase):
+
+ @parameterized.parameters(
+ (as_string, as_tensor),
+ (as_tensor, as_string),
+ (as_tensor, as_tensor))
+ def testRegexReplaceDelegation(self, pattern_fn, rewrite_fn):
+ with compat.forward_compatibility_horizon(2018, 10, 11):
+ with self.test_session():
+ input_vector = constant_op.constant("foo", dtypes.string)
+ pattern = pattern_fn("[a-z]")
+ replace = rewrite_fn(".")
+ op = string_ops.regex_replace(input_vector, pattern, replace)
+ self.assertTrue(op.name.startswith("RegexReplace"))
+
+ def testStaticRegexReplaceDelegation(self):
+ with compat.forward_compatibility_horizon(2018, 10, 11):
+ with self.test_session():
+ input_vector = constant_op.constant("foo", dtypes.string)
+ pattern = "[a-z]"
+ replace = "."
+ op = string_ops.regex_replace(input_vector, pattern, replace)
+ self.assertTrue(op.name.startswith("StaticRegexReplace"))
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/kernel_tests/resource_variable_ops_test.py b/tensorflow/python/kernel_tests/resource_variable_ops_test.py
index c739cd2c0d..f815348b2a 100644
--- a/tensorflow/python/kernel_tests/resource_variable_ops_test.py
+++ b/tensorflow/python/kernel_tests/resource_variable_ops_test.py
@@ -106,6 +106,13 @@ class ResourceVariableOpsTest(test_util.TensorFlowTestCase):
v = resource_variable_ops.ResourceVariable(False, name="bool_test")
self.assertAllEqual(bool(v), False)
+ @test_util.run_in_graph_and_eager_modes
+ def testStridedSliceAssign(self):
+ v = resource_variable_ops.ResourceVariable([1.0, 2.0])
+ self.evaluate(variables.global_variables_initializer())
+ self.evaluate(v[0].assign(2.0))
+ self.assertAllEqual(self.evaluate(v), [2.0, 2.0])
+
def testDifferentAssignGraph(self):
with ops.Graph().as_default():
v = resource_variable_ops.ResourceVariable(1.0)
@@ -835,6 +842,12 @@ class ResourceVariableOpsTest(test_util.TensorFlowTestCase):
state_ops.scatter_add(v, [1], [3])
self.assertAllEqual([1.0, 5.0], v.numpy())
+ def testScatterSubStateOps(self):
+ with context.eager_mode():
+ v = resource_variable_ops.ResourceVariable([1.0, 2.0], name="sub")
+ state_ops.scatter_sub(v, [1], [3])
+ self.assertAllEqual([1.0, -1.0], v.numpy())
+
def testScatterNdAddStateOps(self):
with context.eager_mode():
v = resource_variable_ops.ResourceVariable(
diff --git a/tensorflow/python/kernel_tests/rnn_test.py b/tensorflow/python/kernel_tests/rnn_test.py
index 2405f65270..c72ada11da 100644
--- a/tensorflow/python/kernel_tests/rnn_test.py
+++ b/tensorflow/python/kernel_tests/rnn_test.py
@@ -27,6 +27,7 @@ import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib import rnn as contrib_rnn
from tensorflow.core.protobuf import config_pb2
+from tensorflow.python import keras
from tensorflow.python.client import session
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
@@ -299,6 +300,43 @@ class RNNTest(test.TestCase):
save.restore(sess, save_path)
self.assertAllEqual([10.] * 4, self.evaluate(lstm_cell._bias))
+ def testRNNCellSerialization(self):
+ for cell in [
+ rnn_cell_impl.LSTMCell(32, use_peepholes=True, cell_clip=True),
+ rnn_cell_impl.BasicLSTMCell(32, dtype=dtypes.float32),
+ rnn_cell_impl.BasicRNNCell(32, activation="relu", dtype=dtypes.float32),
+ rnn_cell_impl.GRUCell(
+ 32, kernel_initializer="ones", dtype=dtypes.float32)
+ ]:
+ with self.test_session():
+ x = keras.Input((None, 5))
+ layer = keras.layers.RNN(cell)
+ y = layer(x)
+ model = keras.models.Model(x, y)
+ model.compile(optimizer="rmsprop", loss="mse")
+
+ # Test basic case serialization.
+ x_np = np.random.random((6, 5, 5))
+ y_np = model.predict(x_np)
+ weights = model.get_weights()
+ config = layer.get_config()
+ # The custom_objects is important here since rnn_cell_impl is
+ # not visible as a Keras layer, and also has a name conflict with
+ # keras.LSTMCell and GRUCell.
+ layer = keras.layers.RNN.from_config(
+ config,
+ custom_objects={
+ "BasicRNNCell": rnn_cell_impl.BasicRNNCell,
+ "GRUCell": rnn_cell_impl.GRUCell,
+ "LSTMCell": rnn_cell_impl.LSTMCell,
+ "BasicLSTMCell": rnn_cell_impl.BasicLSTMCell
+ })
+ y = layer(x)
+ model = keras.models.Model(x, y)
+ model.set_weights(weights)
+ y_np_2 = model.predict(x_np)
+ self.assertAllClose(y_np, y_np_2, atol=1e-4)
+
######### Benchmarking RNN code
diff --git a/tensorflow/python/kernel_tests/split_op_test.py b/tensorflow/python/kernel_tests/split_op_test.py
index 419cd5ecda..3f9b029a6a 100644
--- a/tensorflow/python/kernel_tests/split_op_test.py
+++ b/tensorflow/python/kernel_tests/split_op_test.py
@@ -174,6 +174,26 @@ class SplitOpTest(test.TestCase):
for dtype in _TEST_DTYPES:
self._testHugeNumberOfTensorsVariable(dtype)
+ @test_util.run_in_graph_and_eager_modes
+ def testDegenerateVariable(self):
+ inp = np.random.rand(4, 4).astype("f")
+ with test_util.device(use_gpu=True):
+ result = self.evaluate(array_ops.split(inp, [-1, 4], 0))
+ self.assertAllEqual(result[0], inp[0:0, :])
+ self.assertAllEqual(result[1], inp[0:4, :])
+
+ result = self.evaluate(array_ops.split(inp, [4, -1], 0))
+ self.assertAllEqual(result[0], inp[0:4, :])
+ self.assertAllEqual(result[1], inp[4:4, :])
+
+ result = self.evaluate(array_ops.split(inp, [-1, 4], 1))
+ self.assertAllEqual(result[0], inp[:, 0:0])
+ self.assertAllEqual(result[1], inp[:, 0:4])
+
+ result = self.evaluate(array_ops.split(inp, [4, -1], 1))
+ self.assertAllEqual(result[0], inp[:, 0:4])
+ self.assertAllEqual(result[1], inp[:, 4:4])
+
def _testGradientsSimpleVariable(self, dtype):
inp = self._makeData((4, 4), dtype)
with test_util.device(use_gpu=True):
@@ -336,6 +356,16 @@ class SplitOpTest(test.TestCase):
for s in splits:
self.assertEqual(None, s.get_shape().ndims)
+ def testVariableShapeFunction(self):
+ # size_splits too big
+ with self.assertRaises(ValueError):
+ array_ops.split([0, 1], [3, -1], axis=0)
+
+ # Correct inference of variable dimension
+ s0, s1 = array_ops.split([0, 1, 2], [2, -1], axis=0)
+ assert s0.shape.as_list() == [2]
+ assert s1.shape.as_list() == [1]
+
def testNonexistentDimTensor(self):
x = array_ops.placeholder(dtypes.int32)
values = np.zeros([5, 30])
diff --git a/tensorflow/python/kernel_tests/string_length_op_test.py b/tensorflow/python/kernel_tests/string_length_op_test.py
new file mode 100644
index 0000000000..075a3204ad
--- /dev/null
+++ b/tensorflow/python/kernel_tests/string_length_op_test.py
@@ -0,0 +1,37 @@
+# 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 string_length_op."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.python.ops import string_ops
+from tensorflow.python.platform import test
+
+
+class StringLengthOpTest(test.TestCase):
+
+ def testStringLength(self):
+ strings = [[["1", "12"], ["123", "1234"], ["12345", "123456"]]]
+
+ with self.test_session() as sess:
+ lengths = string_ops.string_length(strings)
+ values = sess.run(lengths)
+ self.assertAllEqual(values, [[[1, 2], [3, 4], [5, 6]]])
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/tensorflow/python/kernel_tests/string_split_op_test.py b/tensorflow/python/kernel_tests/string_split_op_test.py
index e20daccb28..b6a0f45adc 100644
--- a/tensorflow/python/kernel_tests/string_split_op_test.py
+++ b/tensorflow/python/kernel_tests/string_split_op_test.py
@@ -58,14 +58,28 @@ class StringSplitOpTest(test.TestCase):
self.assertAllEqual(shape, [3, 5])
def testStringSplitEmptyToken(self):
- strings = [" hello ", "", "world "]
+ strings = ["", " a", "b ", " c", " ", " d ", " e", "f ", " g ", " "]
with self.test_session() as sess:
tokens = string_ops.string_split(strings)
indices, values, shape = sess.run(tokens)
- self.assertAllEqual(indices, [[0, 0], [2, 0]])
- self.assertAllEqual(values, [b"hello", b"world"])
- self.assertAllEqual(shape, [3, 1])
+ self.assertAllEqual(
+ indices,
+ [[1, 0], [2, 0], [3, 0], [5, 0], [6, 0], [7, 0], [8, 0]])
+ self.assertAllEqual(values, [b"a", b"b", b"c", b"d", b"e", b"f", b"g"])
+ self.assertAllEqual(shape, [10, 1])
+
+ def testStringSplitOnSetEmptyToken(self):
+ strings = ["", " a", "b ", " c", " ", " d ", ". e", "f .", " .g. ", " ."]
+
+ with self.test_session() as sess:
+ tokens = string_ops.string_split(strings, delimiter=" .")
+ indices, values, shape = sess.run(tokens)
+ self.assertAllEqual(
+ indices,
+ [[1, 0], [2, 0], [3, 0], [5, 0], [6, 0], [7, 0], [8, 0]])
+ self.assertAllEqual(values, [b"a", b"b", b"c", b"d", b"e", b"f", b"g"])
+ self.assertAllEqual(shape, [10, 1])
def testStringSplitWithDelimiter(self):
strings = ["hello|world", "hello world"]
diff --git a/tensorflow/python/kernel_tests/template_test.py b/tensorflow/python/kernel_tests/template_test.py
index 0b3a396d6b..9dcdaa61ed 100644
--- a/tensorflow/python/kernel_tests/template_test.py
+++ b/tensorflow/python/kernel_tests/template_test.py
@@ -25,6 +25,7 @@ from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
+from tensorflow.python.keras.engine import training
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
@@ -359,6 +360,23 @@ class TemplateTest(test.TestCase):
self.assertEqual(2, len(tmpl1._checkpoint_dependencies))
self.assertEqual("nested", tmpl1._checkpoint_dependencies[0].name)
self.assertEqual("nested_1", tmpl1._checkpoint_dependencies[1].name)
+ model = training.Model()
+ model.template = tmpl1
+ self.assertEqual(model.variables, [v1, v2])
+ self.assertEqual(model.trainable_variables, [v1, v2])
+ self.assertEqual(len(model.non_trainable_variables), 0)
+ model.templates = [tmpl2]
+ self.assertEqual(model.variables, [v1, v2, v5, v6])
+ self.assertEqual(model.trainable_variables, [v1, v2, v5, v6])
+ self.assertEqual(len(model.non_trainable_variables), 0)
+ # Make sure losses, layers, and updates aren't broken by having a Template
+ # in the mix, which does not expose any updates or losses.
+ self.assertEqual([], model.layers)
+ self.assertEqual([], model.updates)
+ self.assertEqual([], model.losses)
+ self.assertEqual([], model.templates.layers)
+ self.assertEqual([], model.templates.updates)
+ self.assertEqual([], model.templates.losses)
@test_util.run_in_graph_and_eager_modes
def test_nested_templates_with_defun(self):
diff --git a/tensorflow/python/kernel_tests/where_op_test.py b/tensorflow/python/kernel_tests/where_op_test.py
index 17575da6f1..29fb002ef4 100644
--- a/tensorflow/python/kernel_tests/where_op_test.py
+++ b/tensorflow/python/kernel_tests/where_op_test.py
@@ -135,6 +135,15 @@ class WhereOpTest(test.TestCase):
tf_val = array_ops.where(constant_op.constant(x) > 0, x * x, -x).eval()
self.assertAllEqual(tf_val, np_val)
+ def testBatchSelect(self):
+ x = np.array([[-2, 3, -1] * 64, [1, -3, -3] * 64] * 8192) # [16384, 192]
+ c_mat = np.array([[False] * 192, [True] * 192] * 8192) # [16384, 192]
+ c_vec = np.array([False, True] * 8192) # [16384]
+ np_val = np.where(c_mat, x * x, -x)
+ with self.test_session(use_gpu=True):
+ tf_val = array_ops.where(c_vec, x * x, -x).eval()
+ self.assertAllEqual(tf_val, np_val)
+
class WhereBenchmark(test.Benchmark):
@@ -163,5 +172,32 @@ class WhereBenchmark(test.Benchmark):
"Throughput: %0.03g GB/s" % (name, r["wall_time"], throughput))
sys.stdout.flush()
+ def benchmarkBatchSelect(self):
+ for (m, n, use_gpu) in itertools.product([1000, 10000, 100000],
+ [10, 100, 1000], [False, True]):
+ name = "m_%d_n_%d_use_gpu_%s" % (m, n, use_gpu)
+ device = "/%s:0" % ("gpu" if use_gpu else "cpu")
+ with ops.Graph().as_default():
+ with ops.device(device):
+ x_gen = random_ops.random_uniform([m, n], dtype=dtypes.float32)
+ y_gen = random_ops.random_uniform([m, n], dtype=dtypes.float32)
+ c_gen = random_ops.random_uniform([m], dtype=dtypes.float32) <= 0.5
+ x = resource_variable_ops.ResourceVariable(x_gen)
+ y = resource_variable_ops.ResourceVariable(y_gen)
+ c = resource_variable_ops.ResourceVariable(c_gen)
+ op = array_ops.where(c, x, y)
+ with session.Session() as sess:
+ x.initializer.run()
+ y.initializer.run()
+ c.initializer.run()
+ r = self.run_op_benchmark(sess, op, min_iters=100, name=name)
+ # approximate size of output: m*n*2 floats for each axis.
+ gb_processed = m * n * 8 / 1.0e9
+ throughput = gb_processed / r["wall_time"]
+ print("Benchmark: %s \t wall_time: %0.03g s \t "
+ "Throughput: %0.03g GB/s" % (name, r["wall_time"], throughput))
+ sys.stdout.flush()
+
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/layers/base.py b/tensorflow/python/layers/base.py
index cf13b52617..3ba880d7a1 100644
--- a/tensorflow/python/layers/base.py
+++ b/tensorflow/python/layers/base.py
@@ -183,13 +183,13 @@ class Layer(base_layer.Layer):
use_resource: Whether to use `ResourceVariable`.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
partitioner: (optional) partitioner instance (callable). If
provided, when the requested variable is created it will be split
into multiple partitions according to `partitioner`. In this case,
@@ -262,11 +262,13 @@ class Layer(base_layer.Layer):
use_resource = (use_resource or
self._use_resource_variables or
scope.use_resource)
+ if initializer is None:
+ initializer = scope.initializer
variable = super(Layer, self).add_weight(
name,
shape,
dtype=dtypes.as_dtype(dtype),
- initializer=initializer or scope.initializer,
+ initializer=initializer,
trainable=trainable,
constraint=constraint,
partitioner=partitioner,
diff --git a/tensorflow/python/layers/core.py b/tensorflow/python/layers/core.py
index 261281ae7e..9879e5020f 100644
--- a/tensorflow/python/layers/core.py
+++ b/tensorflow/python/layers/core.py
@@ -127,8 +127,8 @@ def dense(
"""Functional interface for the densely-connected layer.
This layer implements the operation:
- `outputs = activation(inputs.kernel + bias)`
- Where `activation` is the activation function passed as the `activation`
+ `outputs = activation(inputs * kernel + bias)`
+ where `activation` is the activation function passed as the `activation`
argument (if not `None`), `kernel` is a weights matrix created by the layer,
and `bias` is a bias vector created by the layer
(only if `use_bias` is `True`).
@@ -203,7 +203,7 @@ class Dropout(keras_layers.Dropout, base.Layer):
to be the same for all timesteps, you can use
`noise_shape=[batch_size, 1, features]`.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}.
+ `tf.set_random_seed`.
for behavior.
name: The name of the layer (string).
"""
@@ -248,7 +248,7 @@ def dropout(inputs,
to be the same for all timesteps, you can use
`noise_shape=[batch_size, 1, features]`.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
training: Either a Python boolean, or a TensorFlow boolean scalar tensor
(e.g. a placeholder). Whether to return the output in training mode
diff --git a/tensorflow/python/lib/core/py_func.cc b/tensorflow/python/lib/core/py_func.cc
index 7c107138be..6189503d8f 100644
--- a/tensorflow/python/lib/core/py_func.cc
+++ b/tensorflow/python/lib/core/py_func.cc
@@ -398,7 +398,7 @@ Status ConvertNdarrayToTensor(PyObject* obj, Tensor* ret) {
TF_RETURN_IF_ERROR(NumericNpDTypeToTfDType(PyArray_TYPE(input), &dtype));
CHECK(DataTypeCanUseMemcpy(dtype));
if (reinterpret_cast<intptr_t>(PyArray_DATA(input)) %
- EIGEN_MAX_ALIGN_BYTES !=
+ std::max(1, EIGEN_MAX_ALIGN_BYTES) !=
0) {
Tensor t(dtype, shape);
StringPiece p = t.tensor_data();
@@ -507,6 +507,17 @@ class PyFuncOp : public OpKernel {
call.ins.push_back(ctx->input(i));
}
+ // NOTE(mrry): There is a potential time-of-check-to-time-of-use race here.
+ // because it is possible that `Py_Finalize()` could be called in another
+ // thread between this check and the call to `PyGILState_Ensure()`, which
+ // will abort the process if `Py_Finalize()` has been called. A more robust
+ // solution would be welcome, but it is not obvious how to make this work
+ // using the current Python C API.
+ OP_REQUIRES(ctx, Py_IsInitialized(),
+ errors::FailedPrecondition(
+ "Python interpreter state is not initialized. "
+ "The process may be terminated."));
+
PyGILState_STATE py_threadstate;
py_threadstate = PyGILState_Ensure();
bool log_on_error;
diff --git a/tensorflow/python/lib/core/py_util.cc b/tensorflow/python/lib/core/py_util.cc
index 2ee898ea1d..739cab46b1 100644
--- a/tensorflow/python/lib/core/py_util.cc
+++ b/tensorflow/python/lib/core/py_util.cc
@@ -18,6 +18,8 @@ limitations under the License.
// Place `<locale>` before <Python.h> to avoid build failure in macOS.
#include <locale>
+// The empty line above is on purpose as otherwise clang-format will
+// automatically move <Python.h> before <locale>.
#include <Python.h>
#include "tensorflow/core/lib/core/errors.h"
diff --git a/tensorflow/python/lib/io/py_record_writer.cc b/tensorflow/python/lib/io/py_record_writer.cc
index 3c64813735..e4e5268b0f 100644
--- a/tensorflow/python/lib/io/py_record_writer.cc
+++ b/tensorflow/python/lib/io/py_record_writer.cc
@@ -52,10 +52,17 @@ PyRecordWriter::~PyRecordWriter() {
file_.reset();
}
-bool PyRecordWriter::WriteRecord(tensorflow::StringPiece record) {
- if (writer_ == nullptr) return false;
+void PyRecordWriter::WriteRecord(tensorflow::StringPiece record,
+ TF_Status* out_status) {
+ if (writer_ == nullptr) {
+ TF_SetStatus(out_status, TF_FAILED_PRECONDITION,
+ "Writer not initialized or previously closed");
+ return;
+ }
Status s = writer_->WriteRecord(record);
- return s.ok();
+ if (!s.ok()) {
+ Set_TF_Status_from_Status(out_status, s);
+ }
}
void PyRecordWriter::Flush(TF_Status* out_status) {
diff --git a/tensorflow/python/lib/io/py_record_writer.h b/tensorflow/python/lib/io/py_record_writer.h
index 9d66c031d4..61a4960ee6 100644
--- a/tensorflow/python/lib/io/py_record_writer.h
+++ b/tensorflow/python/lib/io/py_record_writer.h
@@ -43,7 +43,7 @@ class PyRecordWriter {
TF_Status* out_status);
~PyRecordWriter();
- bool WriteRecord(tensorflow::StringPiece record);
+ void WriteRecord(tensorflow::StringPiece record, TF_Status* out_status);
void Flush(TF_Status* out_status);
void Close(TF_Status* out_status);
diff --git a/tensorflow/python/lib/io/python_io.py b/tensorflow/python/lib/io/python_io.py
index aec12ab3ea..404423ce07 100644
--- a/tensorflow/python/lib/io/python_io.py
+++ b/tensorflow/python/lib/io/python_io.py
@@ -15,7 +15,7 @@
"""Python functions for directly manipulating TFRecord-formatted files.
-See the @{$python/python_io} guide.
+See the [Python IO](https://tensorflow.org/api_guides/python/python_io) guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/lib/io/tf_record.py b/tensorflow/python/lib/io/tf_record.py
index 941d6cd67c..2b3e986f6b 100644
--- a/tensorflow/python/lib/io/tf_record.py
+++ b/tensorflow/python/lib/io/tf_record.py
@@ -125,8 +125,8 @@ class TFRecordWriter(object):
Args:
record: str
"""
- # TODO(sethtroisi): Failures are currently swallowed, change that.
- self._writer.WriteRecord(record)
+ with errors.raise_exception_on_not_ok_status() as status:
+ self._writer.WriteRecord(record, status)
def flush(self):
"""Flush the file."""
diff --git a/tensorflow/python/lib/io/tf_record_test.py b/tensorflow/python/lib/io/tf_record_test.py
index 4743c037ec..b853b64ae4 100644
--- a/tensorflow/python/lib/io/tf_record_test.py
+++ b/tensorflow/python/lib/io/tf_record_test.py
@@ -358,12 +358,12 @@ class TFRecordWriterCloseAndFlushTests(test.TestCase):
with self.assertRaises(errors_impl.FailedPreconditionError):
self._writer.flush()
- def testWriteAfterClose(self):
+ def testWriteAfterCloseIsError(self):
self._writer.write(self._Record(0))
self._writer.close()
- # TODO(sethtroisi): No way to know this failed, changed that.
- self._writer.write(self._Record(1))
+ with self.assertRaises(errors_impl.FailedPreconditionError):
+ self._writer.write(self._Record(1))
class TFRecordWriterCloseAndFlushGzipTests(TFRecordWriterCloseAndFlushTests):
diff --git a/tensorflow/python/ops/array_ops.py b/tensorflow/python/ops/array_ops.py
index ec6488ea63..66bc4df18c 100644
--- a/tensorflow/python/ops/array_ops.py
+++ b/tensorflow/python/ops/array_ops.py
@@ -15,7 +15,7 @@
# Tests for this file live in python/kernel_tests/array_ops_test.py
"""Support for manipulating tensors.
-See the @{$python/array_ops} guide.
+See the [Array Ops](https://tensorflow.org/api_guides/python/array_ops) guide.
"""
from __future__ import absolute_import
@@ -538,7 +538,7 @@ def slice(input_, begin, size, name=None):
words, `begin[i]` is the offset into the 'i'th dimension of `input` that you
want to slice from.
- Note that @{tf.Tensor.__getitem__} is typically a more pythonic way to
+ Note that `tf.Tensor.__getitem__` is typically a more pythonic way to
perform slices, as it allows you to write `foo[3:7, :-2]` instead of
`tf.slice(foo, [3, 0], [4, foo.get_shape()[1]-2])`.
@@ -594,7 +594,7 @@ def strided_slice(input_,
**Instead of calling this op directly most users will want to use the
NumPy-style slicing syntax (e.g. `tensor[..., 3:4:-1, tf.newaxis, 3]`), which
- is supported via @{tf.Tensor.__getitem__} and @{tf.Variable.__getitem__}.**
+ is supported via `tf.Tensor.__getitem__` and `tf.Variable.__getitem__`.**
The interface of this op is a low-level encoding of the slicing syntax.
Roughly speaking, this op extracts a slice of size `(end-begin)/stride`
@@ -712,10 +712,7 @@ def strided_slice(input_,
new_axis_mask=new_axis_mask,
shrink_axis_mask=shrink_axis_mask)
- if not context.executing_eagerly():
- # TODO(apassos) In eager mode assignment will be done by overriding
- # __setitem__ instead.
- op.assign = assign
+ op.assign = assign
return op
@@ -723,7 +720,7 @@ def _SliceHelperVar(var, slice_spec):
"""Creates a slice helper object given a variable.
This allows creating a sub-tensor from part of the current contents
- of a variable. See @{tf.Tensor.__getitem__} for detailed examples
+ of a variable. See `tf.Tensor.__getitem__` for detailed examples
of slicing.
This function in addition also allows assignment to a sliced range.
@@ -2662,6 +2659,76 @@ def gather(params, indices, validate_indices=None, name=None, axis=0):
gather.__doc__ = gen_array_ops.gather_v2.__doc__
+@tf_export("batch_gather")
+def batch_gather(params, indices, name=None):
+ """Gather slices from `params` according to `indices` with leading batch dims.
+
+ This operation assumes that the leading dimensions of `indices` are dense,
+ and the gathers on the axis corresponding to the last dimension of `indices`.
+ More concretely it computes:
+
+ result[i1, ..., in] = params[i1, ..., in-1, indices[i1, ..., in]]
+
+ Therefore `params` should be a Tensor of shape [A1, ..., AN, B1, ..., BM],
+ `indices` should be a Tensor of shape [A1, ..., AN-1, C] and `result` will be
+ a Tensor of size `[A1, ..., AN-1, C, B1, ..., BM]`.
+
+ In the case in which indices is a 1D tensor, this operation is equivalent to
+ `tf.gather`.
+
+ See also `tf.gather` and `tf.gather_nd`.
+
+ Args:
+ params: A Tensor. The tensor from which to gather values.
+ indices: A Tensor. Must be one of the following types: int32, int64. Index
+ tensor. Must be in range `[0, params.shape[axis]`, where `axis` is the
+ last dimension of `indices` itself.
+ name: A name for the operation (optional).
+
+ Returns:
+ A Tensor. Has the same type as `params`.
+
+ Raises:
+ ValueError: if `indices` has an unknown shape.
+ """
+
+ with ops.name_scope(name):
+ indices = ops.convert_to_tensor(indices, name="indices")
+ params = ops.convert_to_tensor(params, name="params")
+ indices_shape = shape(indices)
+ params_shape = shape(params)
+ ndims = indices.shape.ndims
+ if ndims is None:
+ raise ValueError("batch_gather does not allow indices with unknown "
+ "shape.")
+ batch_indices = indices
+ accum_dim_value = 1
+ for dim in range(ndims-1, 0, -1):
+ dim_value = params_shape[dim-1]
+ accum_dim_value *= params_shape[dim]
+ dim_indices = gen_math_ops._range(0, dim_value, 1)
+ dim_indices *= accum_dim_value
+ dim_shape = stack([1] * (dim - 1) + [dim_value] + [1] * (ndims - dim),
+ axis=0)
+ batch_indices += reshape(dim_indices, dim_shape)
+
+ flat_indices = reshape(batch_indices, [-1])
+ outer_shape = params_shape[ndims:]
+ flat_inner_shape = gen_math_ops.prod(
+ params_shape[:ndims], [0], False)
+
+ flat_params = reshape(
+ params, concat([[flat_inner_shape], outer_shape], axis=0))
+ flat_result = gather(flat_params, flat_indices)
+ result = reshape(flat_result, concat([indices_shape, outer_shape], axis=0))
+ final_shape = indices.get_shape()[:ndims-1].merge_with(
+ params.get_shape()[:ndims -1])
+ final_shape = final_shape.concatenate(indices.get_shape()[ndims-1])
+ final_shape = final_shape.concatenate(params.get_shape()[ndims:])
+ result.set_shape(final_shape)
+ return result
+
+
# Define quantize_v2 here in order to make name the second-to-last attribute,
# because round_mode was added later.
@tf_export("quantize_v2")
diff --git a/tensorflow/python/ops/check_ops.py b/tensorflow/python/ops/check_ops.py
index 375a5ec2c3..c5a0f2949e 100644
--- a/tensorflow/python/ops/check_ops.py
+++ b/tensorflow/python/ops/check_ops.py
@@ -15,7 +15,8 @@
# pylint: disable=g-short-docstring-punctuation
"""Asserts and Boolean Checks.
-See the @{$python/check_ops} guide.
+See the [Asserts and
+checks](https://tensorflow.org/api_guides/python/check_ops) guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/ops/clip_ops.py b/tensorflow/python/ops/clip_ops.py
index e2580e8a2e..78b395a6c1 100644
--- a/tensorflow/python/ops/clip_ops.py
+++ b/tensorflow/python/ops/clip_ops.py
@@ -29,6 +29,7 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import numerics
from tensorflow.python.util.tf_export import tf_export
@@ -57,7 +58,7 @@ def clip_by_value(t, clip_value_min, clip_value_max,
A clipped `Tensor`.
Raises:
- ValueError: if the clip tensors would trigger array broadcasting
+ ValueError: If the clip tensors would trigger array broadcasting
that would make the returned tensor larger than the input.
"""
with ops.name_scope(name, "clip_by_value",
@@ -246,6 +247,7 @@ def clip_by_global_norm(t_list, clip_norm, use_norm=None, name=None):
Raises:
TypeError: If `t_list` is not a sequence.
+ InvalidArgumentError: If global norm is not finite.
"""
if (not isinstance(t_list, collections.Sequence)
or isinstance(t_list, six.string_types)):
@@ -253,6 +255,8 @@ def clip_by_global_norm(t_list, clip_norm, use_norm=None, name=None):
t_list = list(t_list)
if use_norm is None:
use_norm = global_norm(t_list, name)
+ use_norm = numerics.verify_tensor_all_finite(use_norm,
+ "Found Inf or NaN global norm.")
with ops.name_scope(name, "clip_by_global_norm",
t_list + [clip_norm]) as name:
diff --git a/tensorflow/python/ops/cond_v2_impl.py b/tensorflow/python/ops/cond_v2_impl.py
index 680632d6f8..b3dacff6d6 100644
--- a/tensorflow/python/ops/cond_v2_impl.py
+++ b/tensorflow/python/ops/cond_v2_impl.py
@@ -65,20 +65,27 @@ def cond_v2(pred, true_fn, false_fn, name="cond"):
caller_colocation_stack = ops.get_default_graph()._colocation_stack
caller_container = ops.get_default_graph()._container
caller_collection_ref = ops.get_default_graph()._collections
- # pylint: enable=protected-access
- func_name_prefix = scope.replace("/", "_")
+ with ops.name_scope(None):
+ # Find the outer most graph for uniquing function names.
+ # TODO(jpienaar): Make this work in eager mode.
+ graph = ops.get_default_graph()
+ while isinstance(graph, _function._FuncGraph):
+ graph = graph._outer_graph
+ true_name = graph.unique_name(("%strue" % scope).replace("/", "_"))
+ false_name = graph.unique_name(("%sfalse" % scope).replace("/", "_"))
+ # pylint: enable=protected-access
true_graph = _function.func_graph_from_py_func(
true_fn, [], [],
- name="%strue" % func_name_prefix,
+ name=true_name,
device=caller_device,
colocation_stack=caller_colocation_stack,
collections_ref=caller_collection_ref,
container=caller_container)
false_graph = _function.func_graph_from_py_func(
false_fn, [], [],
- name="%sfalse" % func_name_prefix,
+ name=false_name,
device=caller_device,
colocation_stack=caller_colocation_stack,
collections_ref=caller_collection_ref,
diff --git a/tensorflow/python/ops/control_flow_ops.py b/tensorflow/python/ops/control_flow_ops.py
index c7061b36dd..d1095c8954 100644
--- a/tensorflow/python/ops/control_flow_ops.py
+++ b/tensorflow/python/ops/control_flow_ops.py
@@ -14,7 +14,8 @@
# ==============================================================================
"""Control Flow Operations.
-See the @{$python/control_flow_ops} guide.
+See the [Control
+Flow](https://tensorflow.org/api_guides/python/control_flow_ops) guide.
"""
# pylint: disable=g-bad-name
from __future__ import absolute_import
@@ -1449,14 +1450,17 @@ def ZerosLikeOutsideLoop(op, index):
pred = op_ctxt.pred
branch = op_ctxt.branch
switch_val = switch(op.inputs[0], pred)[1 - branch]
+ # A op is created along the branch taken as control dependencies are on
+ # the whole op and not on the tensor output.
+ pivot = array_ops.identity(switch_val)
if val.dtype == dtypes.resource:
- with ops.control_dependencies([switch_val]):
+ with ops.control_dependencies([pivot]):
return array_ops.zeros(
gen_resource_variable_ops.variable_shape(switch_val))
zeros_shape = array_ops.shape_internal(switch_val, optimize=False)
# Ensure ops created within array_ops.zeros are dominated by switch in
# cond context.
- with ops.control_dependencies([switch_val]):
+ with ops.control_dependencies([pivot]):
return array_ops.zeros(zeros_shape, dtype=val.dtype)
else:
return array_ops.zeros_like(val, optimize=False)
@@ -2065,21 +2069,25 @@ def cond(pred,
# Build the graph for the true branch in a new context.
context_t = CondContext(pred, pivot_1, branch=1)
- context_t.Enter()
- orig_res_t, res_t = context_t.BuildCondBranch(true_fn)
- if orig_res_t is None:
- raise ValueError("true_fn must have a return value.")
- context_t.ExitResult(res_t)
- context_t.Exit()
+ try:
+ context_t.Enter()
+ orig_res_t, res_t = context_t.BuildCondBranch(true_fn)
+ if orig_res_t is None:
+ raise ValueError("true_fn must have a return value.")
+ context_t.ExitResult(res_t)
+ finally:
+ context_t.Exit()
# Build the graph for the false branch in a new context.
context_f = CondContext(pred, pivot_2, branch=0)
- context_f.Enter()
- orig_res_f, res_f = context_f.BuildCondBranch(false_fn)
- if orig_res_f is None:
- raise ValueError("false_fn must have a return value.")
- context_f.ExitResult(res_f)
- context_f.Exit()
+ try:
+ context_f.Enter()
+ orig_res_f, res_f = context_f.BuildCondBranch(false_fn)
+ if orig_res_f is None:
+ raise ValueError("false_fn must have a return value.")
+ context_f.ExitResult(res_f)
+ finally:
+ context_f.Exit()
if not strict:
orig_res_t = _UnpackIfSingleton(orig_res_t)
@@ -3069,7 +3077,7 @@ def while_loop(cond,
`loop_vars` is the same in every iteration. The `shape_invariants` argument
allows the caller to specify a less specific shape invariant for each loop
variable, which is needed if the shape varies between iterations. The
- @{tf.Tensor.set_shape}
+ `tf.Tensor.set_shape`
function may also be used in the `body` function to indicate that
the output loop variable has a particular shape. The shape invariant for
SparseTensor and IndexedSlices are treated specially as follows:
@@ -3320,7 +3328,7 @@ def with_dependencies(dependencies, output_tensor, name=None):
no guarantee that `output_tensor` will be evaluated after any `dependencies`
have run.
- See also @{tf.tuple$tuple} and @{tf.group$group}.
+ See also `tf.tuple` and `tf.group`.
Args:
dependencies: Iterable of operations to run before this op finishes.
@@ -3365,8 +3373,8 @@ def group(*inputs, **kwargs):
When this op finishes, all ops in `inputs` have finished. This op has no
output.
- See also @{tf.tuple$tuple} and
- @{tf.control_dependencies$control_dependencies}.
+ See also `tf.tuple` and
+ `tf.control_dependencies`.
Args:
*inputs: Zero or more tensors to group.
@@ -3435,8 +3443,8 @@ def tuple(tensors, name=None, control_inputs=None): # pylint: disable=redefined
returned by `tuple` are only available after all the parallel computations
are done.
- See also @{tf.group$group} and
- @{tf.control_dependencies$control_dependencies}.
+ See also `tf.group` and
+ `tf.control_dependencies`.
Args:
tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`.
diff --git a/tensorflow/python/ops/custom_gradient.py b/tensorflow/python/ops/custom_gradient.py
index 9f77a6cca1..871f236f78 100644
--- a/tensorflow/python/ops/custom_gradient.py
+++ b/tensorflow/python/ops/custom_gradient.py
@@ -73,7 +73,7 @@ def custom_gradient(f):
With this definition, the gradient at x=100 will be correctly evaluated as
1.0.
- See also @{tf.RegisterGradient} which registers a gradient function for a
+ See also `tf.RegisterGradient` which registers a gradient function for a
primitive TensorFlow operation. `tf.custom_gradient` on the other hand allows
for fine grained control over the gradient computation of a sequence of
operations.
@@ -100,7 +100,7 @@ def custom_gradient(f):
Returns:
A function `h(x)` which returns the same value as `f(x)[0]` and whose
- gradient (as calculated by @{tf.gradients}) is determined by `f(x)[1]`.
+ gradient (as calculated by `tf.gradients`) is determined by `f(x)[1]`.
"""
def decorated(*args, **kwargs):
diff --git a/tensorflow/python/ops/data_flow_ops.py b/tensorflow/python/ops/data_flow_ops.py
index abf597ca55..7af2ca56be 100644
--- a/tensorflow/python/ops/data_flow_ops.py
+++ b/tensorflow/python/ops/data_flow_ops.py
@@ -126,8 +126,8 @@ class QueueBase(object):
handle single elements, versions that support enqueuing and
dequeuing a batch of elements at once.
- See @{tf.FIFOQueue} and
- @{tf.RandomShuffleQueue} for concrete
+ See `tf.FIFOQueue` and
+ `tf.RandomShuffleQueue` for concrete
implementations of this class, and instructions on how to create
them.
"""
@@ -309,12 +309,12 @@ class QueueBase(object):
until the element has been enqueued.
At runtime, this operation may raise an error if the queue is
- @{tf.QueueBase.close} before or during its execution. If the
+ `tf.QueueBase.close` before or during its execution. If the
queue is closed before this operation runs,
`tf.errors.CancelledError` will be raised. If this operation is
blocked, and either (i) the queue is closed by a close operation
with `cancel_pending_enqueues=True`, or (ii) the session is
- @{tf.Session.close},
+ `tf.Session.close`,
`tf.errors.CancelledError` will be raised.
Args:
@@ -352,12 +352,12 @@ class QueueBase(object):
until all of the elements have been enqueued.
At runtime, this operation may raise an error if the queue is
- @{tf.QueueBase.close} before or during its execution. If the
+ `tf.QueueBase.close` before or during its execution. If the
queue is closed before this operation runs,
`tf.errors.CancelledError` will be raised. If this operation is
blocked, and either (i) the queue is closed by a close operation
with `cancel_pending_enqueues=True`, or (ii) the session is
- @{tf.Session.close},
+ `tf.Session.close`,
`tf.errors.CancelledError` will be raised.
Args:
@@ -413,11 +413,11 @@ class QueueBase(object):
until there is an element to dequeue.
At runtime, this operation may raise an error if the queue is
- @{tf.QueueBase.close} before or during its execution. If the
+ `tf.QueueBase.close` before or during its execution. If the
queue is closed, the queue is empty, and there are no pending
enqueue operations that can fulfill this request,
`tf.errors.OutOfRangeError` will be raised. If the session is
- @{tf.Session.close},
+ `tf.Session.close`,
`tf.errors.CancelledError` will be raised.
Args:
@@ -455,11 +455,11 @@ class QueueBase(object):
`OutOfRange` exception is raised.
At runtime, this operation may raise an error if the queue is
- @{tf.QueueBase.close} before or during its execution. If the
+ `tf.QueueBase.close` before or during its execution. If the
queue is closed, the queue contains fewer than `n` elements, and
there are no pending enqueue operations that can fulfill this
request, `tf.errors.OutOfRangeError` will be raised. If the
- session is @{tf.Session.close},
+ session is `tf.Session.close`,
`tf.errors.CancelledError` will be raised.
Args:
@@ -500,7 +500,7 @@ class QueueBase(object):
If the queue is closed and there are more than `0` but fewer than
`n` elements remaining, then instead of raising a
- `tf.errors.OutOfRangeError` like @{tf.QueueBase.dequeue_many},
+ `tf.errors.OutOfRangeError` like `tf.QueueBase.dequeue_many`,
less than `n` elements are returned immediately. If the queue is
closed and there are `0` elements left in the queue, then a
`tf.errors.OutOfRangeError` is raised just like in `dequeue_many`.
@@ -608,7 +608,7 @@ def _shared_name(shared_name):
class RandomShuffleQueue(QueueBase):
"""A queue implementation that dequeues elements in a random order.
- See @{tf.QueueBase} for a description of the methods on
+ See `tf.QueueBase` for a description of the methods on
this class.
"""
@@ -657,7 +657,7 @@ class RandomShuffleQueue(QueueBase):
with the same length as `dtypes`, or `None`. If specified the dequeue
methods return a dictionary with the names as keys.
seed: A Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
shared_name: (Optional.) If non-empty, this queue will be shared under
the given name across multiple sessions.
@@ -693,7 +693,7 @@ class RandomShuffleQueue(QueueBase):
class FIFOQueue(QueueBase):
"""A queue implementation that dequeues elements in first-in first-out order.
- See @{tf.QueueBase} for a description of the methods on
+ See `tf.QueueBase` for a description of the methods on
this class.
"""
@@ -753,7 +753,7 @@ class PaddingFIFOQueue(QueueBase):
A `PaddingFIFOQueue` may contain components with dynamic shape, while also
supporting `dequeue_many`. See the constructor for more details.
- See @{tf.QueueBase} for a description of the methods on
+ See `tf.QueueBase` for a description of the methods on
this class.
"""
@@ -824,7 +824,7 @@ class PaddingFIFOQueue(QueueBase):
class PriorityQueue(QueueBase):
"""A queue implementation that dequeues elements in prioritized order.
- See @{tf.QueueBase} for a description of the methods on
+ See `tf.QueueBase` for a description of the methods on
this class.
"""
diff --git a/tensorflow/python/ops/distributions/distribution.py b/tensorflow/python/ops/distributions/distribution.py
index c03ef967e6..ddf9442cd2 100644
--- a/tensorflow/python/ops/distributions/distribution.py
+++ b/tensorflow/python/ops/distributions/distribution.py
@@ -526,8 +526,8 @@ class Distribution(_BaseDistribution):
# Remove "self", "__class__", or other special variables. These can appear
# if the subclass used:
# `parameters = dict(locals())`.
- return dict((k, v) for k, v in self._parameters.items()
- if not k.startswith("__") and k != "self")
+ return {k: v for k, v in self._parameters.items()
+ if not k.startswith("__") and k != "self"}
@property
def reparameterization_type(self):
diff --git a/tensorflow/python/ops/embedding_ops.py b/tensorflow/python/ops/embedding_ops.py
index 27c2fa7017..7b9e7de145 100644
--- a/tensorflow/python/ops/embedding_ops.py
+++ b/tensorflow/python/ops/embedding_ops.py
@@ -253,7 +253,7 @@ def embedding_lookup(
This function is used to perform parallel lookups on the list of
tensors in `params`. It is a generalization of
- @{tf.gather}, where `params` is
+ `tf.gather`, where `params` is
interpreted as a partitioning of a large embedding tensor. `params` may be
a `PartitionedVariable` as returned by using `tf.get_variable()` with a
partitioner.
diff --git a/tensorflow/python/ops/functional_ops.py b/tensorflow/python/ops/functional_ops.py
index 4ecc74675a..a6be82673f 100644
--- a/tensorflow/python/ops/functional_ops.py
+++ b/tensorflow/python/ops/functional_ops.py
@@ -15,7 +15,8 @@
"""Functional operations.
-See the @{$python/functional_ops} guide.
+See the [Higher Order
+Functions](https://tensorflow.org/api_guides/python/functional_ops) guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/ops/histogram_ops.py b/tensorflow/python/ops/histogram_ops.py
index e86a8e5a5b..7291e05685 100644
--- a/tensorflow/python/ops/histogram_ops.py
+++ b/tensorflow/python/ops/histogram_ops.py
@@ -14,8 +14,6 @@
# ==============================================================================
# pylint: disable=g-short-docstring-punctuation
"""Histograms.
-
-Please see @{$python/histogram_ops} guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/ops/image_ops.py b/tensorflow/python/ops/image_ops.py
index 343531ac55..3de46e7cf3 100644
--- a/tensorflow/python/ops/image_ops.py
+++ b/tensorflow/python/ops/image_ops.py
@@ -16,7 +16,7 @@
# pylint: disable=g-short-docstring-punctuation
"""Image processing and decoding ops.
-See the @{$python/image} guide.
+See the [Images](https://tensorflow.org/api_guides/python/image) guide.
"""
from __future__ import absolute_import
from __future__ import division
diff --git a/tensorflow/python/ops/image_ops_impl.py b/tensorflow/python/ops/image_ops_impl.py
index 855a4d0c33..12356944f8 100644
--- a/tensorflow/python/ops/image_ops_impl.py
+++ b/tensorflow/python/ops/image_ops_impl.py
@@ -265,7 +265,7 @@ def random_flip_up_down(image, seed=None):
image: 4-D Tensor of shape `[batch, height, width, channels]` or
3-D Tensor of shape `[height, width, channels]`.
seed: A Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
Returns:
@@ -287,7 +287,7 @@ def random_flip_left_right(image, seed=None):
image: 4-D Tensor of shape `[batch, height, width, channels]` or
3-D Tensor of shape `[height, width, channels]`.
seed: A Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
Returns:
@@ -307,7 +307,7 @@ def _random_flip(image, flip_index, seed, scope_name):
flip_index: The dimension along which to flip the image.
Vertical: 0, Horizontal: 1
seed: A Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
scope_name: Name of the scope in which the ops are added.
@@ -948,7 +948,7 @@ def resize_images(images,
Resized images will be distorted if their original aspect ratio is not
the same as `size`. To avoid distortions see
- @{tf.image.resize_image_with_pad}.
+ `tf.image.resize_image_with_pad`.
`method` can be one of:
@@ -1167,7 +1167,7 @@ def resize_image_with_pad(image,
_ImageDimensions(padded, rank=4)
if not is_batch:
- padded = array_ops.squeeze(padded, squeeze_dims=[0])
+ padded = array_ops.squeeze(padded, axis=[0])
return padded
@@ -1227,7 +1227,7 @@ def random_brightness(image, max_delta, seed=None):
image: An image.
max_delta: float, must be non-negative.
seed: A Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
Returns:
@@ -1255,7 +1255,7 @@ def random_contrast(image, lower, upper, seed=None):
lower: float. Lower bound for the random contrast factor.
upper: float. Upper bound for the random contrast factor.
seed: A Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
Returns:
diff --git a/tensorflow/python/ops/image_ops_test.py b/tensorflow/python/ops/image_ops_test.py
index cf9761803b..2c61bb232a 100644
--- a/tensorflow/python/ops/image_ops_test.py
+++ b/tensorflow/python/ops/image_ops_test.py
@@ -1410,6 +1410,14 @@ class AdjustContrastTest(test_util.TensorFlowTestCase):
y_tf = self._adjustContrastTf(x_np, contrast_factor)
self.assertAllClose(y_tf, y_np, rtol=1e-5, atol=1e-5)
+ def testContrastFactorShape(self):
+ x_shape = [1, 2, 2, 3]
+ x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1]
+ x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape)
+ with self.assertRaisesRegexp(
+ ValueError, 'Shape must be rank 0 but is rank 1'):
+ image_ops.adjust_contrast(x_np, [2.0])
+
class AdjustBrightnessTest(test_util.TensorFlowTestCase):
@@ -1956,7 +1964,7 @@ class PadToBoundingBoxTest(test_util.TensorFlowTestCase):
"all dims of 'image.shape' must be > 0",
use_tensor_inputs_options=[False])
- # The orignal error message does not contain back slashes. However, they
+ # The original error message does not contain back slashes. However, they
# are added by either the assert op or the runtime. If this behavior
# changes in the future, the match string will also needs to be changed.
self._assertRaises(
@@ -2985,7 +2993,7 @@ class ResizeImageWithCropOrPadTest(test_util.TensorFlowTestCase):
"all dims of 'image.shape' must be > 0",
use_tensor_inputs_options=[False])
- # The orignal error message does not contain back slashes. However, they
+ # The original error message does not contain back slashes. However, they
# are added by either the assert op or the runtime. If this behavior
# changes in the future, the match string will also needs to be changed.
self._assertRaises(
@@ -3201,7 +3209,8 @@ class PngTest(test_util.TensorFlowTestCase):
def testExisting(self):
# Read some real PNGs, converting to different channel numbers
prefix = "tensorflow/core/lib/png/testdata/"
- inputs = (1, "lena_gray.png"), (4, "lena_rgba.png")
+ inputs = ((1, "lena_gray.png"), (4, "lena_rgba.png"),
+ (3, "lena_palette.png"), (4, "lena_palette_trns.png"))
for channels_in, filename in inputs:
for channels in 0, 1, 3, 4:
with self.test_session(use_gpu=True) as sess:
@@ -3649,6 +3658,41 @@ class NonMaxSuppressionTest(test_util.TensorFlowTestCase):
image_ops.non_max_suppression(boxes, scores, 3, [[0.5]])
+class NonMaxSuppressionPaddedTest(test_util.TensorFlowTestCase):
+
+ def testSelectFromThreeClusters(self):
+ boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9],
+ [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]]
+ scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]
+ max_output_size_np = 5
+ iou_threshold_np = 0.5
+ boxes = constant_op.constant(boxes_np)
+ scores = constant_op.constant(scores_np)
+ max_output_size = constant_op.constant(max_output_size_np)
+ iou_threshold = constant_op.constant(iou_threshold_np)
+ selected_indices_padded, num_valid_padded = \
+ image_ops.non_max_suppression_padded(
+ boxes,
+ scores,
+ max_output_size,
+ iou_threshold,
+ pad_to_max_output_size=True)
+ selected_indices, num_valid = image_ops.non_max_suppression_padded(
+ boxes,
+ scores,
+ max_output_size,
+ iou_threshold,
+ pad_to_max_output_size=False)
+ # The output shape of the padded operation must be fully defined.
+ self.assertEqual(selected_indices_padded.shape.is_fully_defined(), True)
+ self.assertEqual(selected_indices.shape.is_fully_defined(), False)
+ with self.test_session():
+ self.assertAllClose(selected_indices_padded.eval(), [3, 0, 5, 0, 0])
+ self.assertEqual(num_valid_padded.eval(), 3)
+ self.assertAllClose(selected_indices.eval(), [3, 0, 5])
+ self.assertEqual(num_valid.eval(), 3)
+
+
class VerifyCompatibleImageShapesTest(test_util.TensorFlowTestCase):
"""Tests utility function used by ssim() and psnr()."""
diff --git a/tensorflow/python/ops/init_ops.py b/tensorflow/python/ops/init_ops.py
index c315722b6b..4d75ee3974 100644
--- a/tensorflow/python/ops/init_ops.py
+++ b/tensorflow/python/ops/init_ops.py
@@ -238,7 +238,7 @@ class RandomUniform(Initializer):
maxval: A python scalar or a scalar tensor. Upper bound of the range
of random values to generate. Defaults to 1 for float types.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type.
"""
@@ -276,7 +276,7 @@ class RandomNormal(Initializer):
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type. Only floating point types are supported.
"""
@@ -319,7 +319,7 @@ class TruncatedNormal(Initializer):
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type. Only floating point types are supported.
"""
@@ -369,7 +369,7 @@ class UniformUnitScaling(Initializer):
Args:
factor: Float. A multiplicative factor by which the values will be scaled.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type. Only floating point types are supported.
"""
@@ -427,7 +427,7 @@ class VarianceScaling(Initializer):
mode: One of "fan_in", "fan_out", "fan_avg".
distribution: Random distribution to use. One of "normal", "uniform".
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type. Only floating point types are supported.
@@ -517,7 +517,7 @@ class Orthogonal(Initializer):
Args:
gain: multiplicative factor to apply to the orthogonal matrix
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type.
"""
@@ -572,7 +572,7 @@ class ConvolutionDeltaOrthogonal(Initializer):
The 2-norm of an input is multiplied by a factor of 'sqrt(gain)' after
applying this convolution.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
dtype: The data type.
"""
@@ -628,7 +628,7 @@ class ConvolutionOrthogonal(Initializer):
The 2-norm of an input is multiplied by a factor of 'sqrt(gain)' after
applying this convolution.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
dtype: The data type.
"""
@@ -693,7 +693,7 @@ class ConvolutionOrthogonal2D(ConvolutionOrthogonal):
This has the effect of scaling the output 2-norm by a factor of
`sqrt(gain)`.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
dtype: The data type.
"""
@@ -829,7 +829,7 @@ class ConvolutionOrthogonal1D(ConvolutionOrthogonal):
The 2-norm of an input is multiplied by a factor of 'sqrt(gain)' after
applying this convolution.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type.
"""
@@ -946,7 +946,7 @@ class ConvolutionOrthogonal3D(ConvolutionOrthogonal):
The 2-norm of an input is multiplied by a factor of 'sqrt(gain)' after
applying this convolution.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed} for behavior.
+ `tf.set_random_seed` for behavior.
dtype: The data type.
"""
@@ -1150,7 +1150,7 @@ def glorot_uniform_initializer(seed=None, dtype=dtypes.float32):
Args:
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type. Only floating point types are supported.
@@ -1175,7 +1175,7 @@ def glorot_normal_initializer(seed=None, dtype=dtypes.float32):
Args:
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
dtype: The data type. Only floating point types are supported.
diff --git a/tensorflow/python/ops/io_ops.py b/tensorflow/python/ops/io_ops.py
index b5274ef2ed..fbc1350c61 100644
--- a/tensorflow/python/ops/io_ops.py
+++ b/tensorflow/python/ops/io_ops.py
@@ -16,7 +16,8 @@
# pylint: disable=line-too-long
"""Inputs and Readers.
-See the @{$python/io_ops} guide.
+See the [Inputs and
+Readers](https://tensorflow.org/api_guides/python/io_ops) guide.
"""
from __future__ import absolute_import
diff --git a/tensorflow/python/ops/losses/losses_impl.py b/tensorflow/python/ops/losses/losses_impl.py
index 66633c8b12..806539747e 100644
--- a/tensorflow/python/ops/losses/losses_impl.py
+++ b/tensorflow/python/ops/losses/losses_impl.py
@@ -190,10 +190,10 @@ def compute_weighted_loss(
When calculating the gradient of a weighted loss contributions from
both `losses` and `weights` are considered. If your `weights` depend
on some model parameters but you do not want this to affect the loss
- gradient, you need to apply @{tf.stop_gradient} to `weights` before
+ gradient, you need to apply `tf.stop_gradient` to `weights` before
passing them to `compute_weighted_loss`.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -266,7 +266,7 @@ def absolute_difference(
`labels` or if the shape of `weights` is invalid or if `labels`
or `predictions` is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -317,7 +317,7 @@ def cosine_distance(
ValueError: If `predictions` shape doesn't match `labels` shape, or
`axis`, `labels`, `predictions` or `weights` is `None`.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -369,7 +369,7 @@ def hinge_loss(labels, logits, weights=1.0, scope=None,
ValueError: If the shapes of `logits` and `labels` don't match or
if `labels` or `logits` is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -437,7 +437,7 @@ def huber_loss(labels, predictions, weights=1.0, delta=1.0, scope=None,
if the shape of `weights` is invalid. Also if `labels` or
`predictions` is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -503,7 +503,7 @@ def log_loss(labels, predictions, weights=1.0, epsilon=1e-7, scope=None,
if the shape of `weights` is invalid. Also if `labels` or `predictions`
is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -571,7 +571,7 @@ def mean_pairwise_squared_error(
if the shape of `weights` is invalid. Also if `labels` or `predictions`
is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -654,7 +654,7 @@ def mean_squared_error(
if the shape of `weights` is invalid. Also if `labels` or `predictions`
is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -711,7 +711,7 @@ def sigmoid_cross_entropy(
`multi_class_labels` or if the shape of `weights` is invalid, or if
`weights` is None. Also if `multi_class_labels` or `logits` is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -777,7 +777,7 @@ def softmax_cross_entropy(
or if the shape of `weights` is invalid or if `weights` is None. Also if
`onehot_labels` or `logits` is None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
@@ -894,7 +894,7 @@ def sparse_softmax_cross_entropy(
ValueError: If the shapes of `logits`, `labels`, and `weights` are
incompatible, or if any of them are None.
- @compatbility(eager)
+ @compatibility(eager)
The `loss_collection` argument is ignored when executing eagerly. Consider
holding on to the return value or collecting losses via a `tf.keras.Model`.
@end_compatibility
diff --git a/tensorflow/python/ops/math_grad.py b/tensorflow/python/ops/math_grad.py
index f0c6bd532f..8e11c4bce1 100644
--- a/tensorflow/python/ops/math_grad.py
+++ b/tensorflow/python/ops/math_grad.py
@@ -972,6 +972,24 @@ def _RealDivGrad(op, grad):
grad * math_ops.realdiv(math_ops.realdiv(-x, y), y), ry), sy))
+@ops.RegisterGradient("DivNoNan")
+def _DivNoNanGrad(op, grad):
+ """DivNoNan op gradient."""
+ x = op.inputs[0]
+ y = op.inputs[1]
+ sx = array_ops.shape(x)
+ sy = array_ops.shape(y)
+ rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy)
+ x = math_ops.conj(x)
+ y = math_ops.conj(y)
+ return (array_ops.reshape(
+ math_ops.reduce_sum(math_ops.div_no_nan(grad, y), rx), sx),
+ array_ops.reshape(
+ math_ops.reduce_sum(
+ grad * math_ops.div_no_nan(math_ops.div_no_nan(-x, y), y),
+ ry), sy))
+
+
@ops.RegisterGradient("Pow")
def _PowGrad(op, grad):
"""Returns grad * (y*x^(y-1), z*log(x))."""
diff --git a/tensorflow/python/ops/math_grad_test.py b/tensorflow/python/ops/math_grad_test.py
index fa47b8f9b8..059c8ebd7e 100644
--- a/tensorflow/python/ops/math_grad_test.py
+++ b/tensorflow/python/ops/math_grad_test.py
@@ -25,6 +25,7 @@ from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker
+from tensorflow.python.ops import gradients
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
@@ -230,5 +231,30 @@ class FloorModGradientTest(test.TestCase):
self.assertLess(error, 1e-4)
+class DivNoNanGradientTest(test.TestCase):
+
+ def testBasicGradient(self):
+ inputs = constant_op.constant(np.arange(-3, 3),
+ dtype=dtypes.float32)
+ outputs = math_ops.div_no_nan(inputs, 1 + math_ops.abs(inputs))
+ with self.test_session():
+ error = gradient_checker.compute_gradient_error(
+ inputs,
+ inputs.get_shape().as_list(), outputs,
+ outputs.get_shape().as_list())
+ self.assertLess(error, 1e-4)
+
+ def testGradientWithDenominatorIsZero(self):
+ x = constant_op.constant(np.arange(-3, 3),
+ dtype=dtypes.float32)
+ y = array_ops.zeros_like(x,
+ dtype=dtypes.float32)
+ outputs = math_ops.div_no_nan(x, y)
+ with self.test_session():
+ dx, dy = gradients.gradients(outputs, [x, y])
+ self.assertAllClose(dx.eval(), np.zeros(x.shape.as_list()))
+ self.assertAllClose(dy.eval(), np.zeros(y.shape.as_list()))
+
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/ops/math_ops.py b/tensorflow/python/ops/math_ops.py
index fbe6b62302..67ea534639 100644
--- a/tensorflow/python/ops/math_ops.py
+++ b/tensorflow/python/ops/math_ops.py
@@ -14,7 +14,7 @@
# ==============================================================================
"""Basic arithmetic operators.
-See the @{$python/math_ops} guide.
+See the [python/math_ops](python/math_ops) guide.
"""
from __future__ import absolute_import
from __future__ import division
@@ -1038,6 +1038,29 @@ def div(x, y, name=None):
return _div_python2(x, y, name)
+@tf_export("div_no_nan")
+def div_no_nan(x, y, name=None):
+ """Computes an unsafe divide which returns 0 if the y is zero.
+
+ Args:
+ x: A `Tensor`. Must be one of the following types: `float32`, `float64`.
+ y: A `Tensor` whose dtype is compatible with `x`.
+ name: A name for the operation (optional).
+ Returns:
+ The element-wise value of the x divided by y.
+ """
+
+ with ops.name_scope(name, "div_no_nan", [x, y]) as name:
+ x = ops.convert_to_tensor(x, name="x")
+ y = ops.convert_to_tensor(y, name="y", dtype=x.dtype.base_dtype)
+ x_dtype = x.dtype.base_dtype
+ y_dtype = y.dtype.base_dtype
+ if x_dtype != y_dtype:
+ raise TypeError("x and y must have the same dtype, got %r != %r" %
+ (x_dtype, y_dtype))
+ return gen_math_ops.div_no_nan(x, y, name=name)
+
+
# TODO(aselle): This should be removed
mod = gen_math_ops.floor_mod
@@ -2105,7 +2128,8 @@ def add_n(inputs, name=None):
"""Adds all input tensors element-wise.
Args:
- inputs: A list of `Tensor` objects, each with same shape and type.
+ inputs: A list of `Tensor` or `IndexedSlices` objects, each with same shape
+ and type.
name: A name for the operation (optional).
Returns:
@@ -2116,17 +2140,21 @@ def add_n(inputs, name=None):
cannot be inferred.
"""
if not inputs or not isinstance(inputs, (list, tuple)):
- raise ValueError("inputs must be a list of at least one Tensor with the "
- "same dtype and shape")
+ raise ValueError("inputs must be a list of at least one"
+ "Tensor/IndexedSlices with the same dtype and shape")
inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs)
- if not all(isinstance(x, ops.Tensor) for x in inputs):
- raise ValueError("inputs must be a list of at least one Tensor with the "
- "same dtype and shape")
+ if not all(isinstance(x, (ops.Tensor, ops.IndexedSlices)) for x in inputs):
+ raise ValueError("inputs must be a list of at least one"
+ "Tensor/IndexedSlices with the same dtype and shape")
if len(inputs) == 1:
+ if isinstance(inputs[0], ops.IndexedSlices):
+ values = inputs[0].values
+ else:
+ values = inputs[0]
if name:
- return array_ops.identity(inputs[0], name=name)
- return inputs[0]
+ return array_ops.identity(values, name=name)
+ return values
return gen_math_ops.add_n(inputs, name=name)
@@ -2534,8 +2562,9 @@ def _unsorted_segment_N(data, segment_ids, num_segments):
def unsorted_segment_mean(data, segment_ids, num_segments, name=None):
r""" Computes the mean along segments of a tensor.
- Read @{$math_ops#segmentation$the section on segmentation} for an explanation
- of segments.
+ Read [the section on
+ segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)
+ for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
@@ -2566,8 +2595,9 @@ def unsorted_segment_mean(data, segment_ids, num_segments, name=None):
def unsorted_segment_sqrt_n(data, segment_ids, num_segments, name=None):
r"""Computes the sum along segments of a tensor divided by the sqrt(N).
- Read @{$math_ops#segmentation$the section on segmentation} for an explanation
- of segments.
+ Read [the section on
+ segmentation](https://tensorflow.org/api_guides/python/math_ops#segmentation)
+ for an explanation of segments.
This operator is similar to the unsorted segment sum operator found
[here](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).
@@ -2602,8 +2632,9 @@ def sparse_segment_sum(data, indices, segment_ids, name=None,
num_segments=None):
r"""Computes the sum along sparse segments of a tensor.
- Read @{$math_ops#Segmentation$the section on segmentation} for an explanation
- of segments.
+ Read [the section on
+ segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+ for an explanation of segments.
Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
@@ -2677,8 +2708,9 @@ def sparse_segment_mean(data,
num_segments=None):
r"""Computes the mean along sparse segments of a tensor.
- Read @{$math_ops#Segmentation$the section on segmentation} for an explanation
- of segments.
+ Read [the section on
+ segmentation](https://tensorflow.org/api_guides/python/math_ops#Segmentation)
+ for an explanation of segments.
Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first
dimension, selecting a subset of dimension 0, specified by `indices`.
diff --git a/tensorflow/python/ops/math_ops_test.py b/tensorflow/python/ops/math_ops_test.py
index 6b709e5e7f..5ac7e133d9 100644
--- a/tensorflow/python/ops/math_ops_test.py
+++ b/tensorflow/python/ops/math_ops_test.py
@@ -473,5 +473,20 @@ class DivAndModTest(test_util.TensorFlowTestCase):
self.assertAllEqual(tf_result, expanded_nums)
+class DivNoNanTest(test_util.TensorFlowTestCase):
+
+ def testBasic(self):
+ for dtype in [np.float32, np.float64]:
+ nums = np.arange(-10, 10, .25, dtype=dtype).reshape(80, 1)
+ divs = np.arange(-3, 3, .25, dtype=dtype).reshape(1, 24)
+
+ np_result = np.true_divide(nums, divs)
+ np_result[:, divs[0] == 0] = 0
+
+ with self.test_session():
+ tf_result = math_ops.div_no_nan(nums, divs).eval()
+ self.assertAllEqual(tf_result, np_result)
+
+
if __name__ == "__main__":
googletest.main()
diff --git a/tensorflow/python/ops/metrics_impl.py b/tensorflow/python/ops/metrics_impl.py
index 3aedeb6acd..763877c2d2 100644
--- a/tensorflow/python/ops/metrics_impl.py
+++ b/tensorflow/python/ops/metrics_impl.py
@@ -34,7 +34,7 @@ from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import weights_broadcast_ops
from tensorflow.python.platform import tf_logging as logging
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.util.deprecation import deprecated
from tensorflow.python.util.tf_export import tf_export
@@ -57,7 +57,8 @@ def metric_variable(shape, dtype, validate_shape=True, name=None):
Furthermore, the final answer should be computed once instead of
in every replica/tower. Both of these are accomplished by
running the computation of the final result value inside
- `tf.contrib.distribute.get_tower_context().merge_call(fn)`.
+ `tf.contrib.distribution_strategy_context.get_tower_context(
+ ).merge_call(fn)`.
Inside the `merge_call()`, ops are only added to the graph once
and access to a tower-local variable in a computation returns
the sum across all replicas/towers.
@@ -300,6 +301,40 @@ def _streaming_confusion_matrix(labels, predictions, num_classes, weights=None):
return total_cm, update_op
+def _aggregate_across_towers(metrics_collections, metric_value_fn, *args):
+ """Aggregate metric value across towers."""
+ def fn(distribution, *a):
+ """Call `metric_value_fn` in the correct control flow context."""
+ if hasattr(distribution, '_outer_control_flow_context'):
+ # If there was an outer context captured before this method was called,
+ # then we enter that context to create the metric value op. If the
+ # caputred context is `None`, ops.control_dependencies(None) gives the
+ # desired behavior. Else we use `Enter` and `Exit` to enter and exit the
+ # captured context.
+ # This special handling is needed because sometimes the metric is created
+ # inside a while_loop (and perhaps a TPU rewrite context). But we don't
+ # want the value op to be evaluated every step or on the TPU. So we
+ # create it outside so that it can be evaluated at the end on the host,
+ # once the update ops have been evaluted.
+
+ # pylint: disable=protected-access
+ if distribution._outer_control_flow_context is None:
+ with ops.control_dependencies(None):
+ metric_value = metric_value_fn(distribution, *a)
+ else:
+ distribution._outer_control_flow_context.Enter()
+ metric_value = metric_value_fn(distribution, *a)
+ distribution._outer_control_flow_context.Exit()
+ # pylint: enable=protected-access
+ else:
+ metric_value = metric_value_fn(distribution, *a)
+ if metrics_collections:
+ ops.add_to_collections(metrics_collections, metric_value)
+ return metric_value
+
+ return distribution_strategy_context.get_tower_context().merge_call(fn, *args)
+
+
@tf_export('metrics.mean')
def mean(values,
weights=None,
@@ -367,14 +402,10 @@ def mean(values,
with ops.control_dependencies([values]):
update_count_op = state_ops.assign_add(count, num_values)
- def aggregate_across_towers(_, t, c):
- mean_t = _safe_div(t, c, 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, mean_t)
- return mean_t
+ compute_mean = lambda _, t, c: _safe_div(t, c, 'value')
- mean_t = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, total, count)
+ mean_t = _aggregate_across_towers(
+ metrics_collections, compute_mean, total, count)
update_op = _safe_div(update_total_op, update_count_op, 'update_op')
if updates_collections:
@@ -611,14 +642,8 @@ def _confusion_matrix_at_thresholds(labels,
def _aggregate_variable(v, collections):
-
- def f(distribution, value):
- value = distribution.read_var(value)
- if collections:
- ops.add_to_collections(collections, value)
- return value
-
- return distribute_lib.get_tower_context().merge_call(f, v)
+ f = lambda distribution, value: distribution.read_var(value)
+ return _aggregate_across_towers(collections, f, v)
@tf_export('metrics.auc')
@@ -806,15 +831,12 @@ def auc(labels,
raise ValueError('Invalid summation_method: %s' % summation_method)
# sum up the areas of all the trapeziums
- def aggregate_auc(_, values):
- auc_value = compute_auc(values['tp'], values['fn'], values['tn'],
- values['fp'], 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, auc_value)
- return auc_value
-
- auc_value = distribute_lib.get_tower_context().merge_call(
- aggregate_auc, values)
+ def compute_auc_value(_, values):
+ return compute_auc(values['tp'], values['fn'], values['tn'], values['fp'],
+ 'value')
+
+ auc_value = _aggregate_across_towers(
+ metrics_collections, compute_auc_value, values)
update_op = compute_auc(update_ops['tp'], update_ops['fn'],
update_ops['tn'], update_ops['fp'], 'update_op')
@@ -1045,16 +1067,14 @@ def mean_per_class_accuracy(labels,
update_total_op = state_ops.scatter_add(total, labels, ones)
update_count_op = state_ops.scatter_add(count, labels, is_correct)
- def aggregate_mean_accuracy(_, count, total):
+ def compute_mean_accuracy(_, count, total):
per_class_accuracy = _safe_div(count, total, None)
mean_accuracy_v = math_ops.reduce_mean(
per_class_accuracy, name='mean_accuracy')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, mean_accuracy_v)
return mean_accuracy_v
- mean_accuracy_v = distribute_lib.get_tower_context().merge_call(
- aggregate_mean_accuracy, count, total)
+ mean_accuracy_v = _aggregate_across_towers(
+ metrics_collections, compute_mean_accuracy, count, total)
update_op = _safe_div(update_count_op, update_total_op, name='update_op')
if updates_collections:
@@ -1127,7 +1147,7 @@ def mean_iou(labels,
total_cm, update_op = _streaming_confusion_matrix(labels, predictions,
num_classes, weights)
- def compute_mean_iou(total_cm, name):
+ def compute_mean_iou(_, total_cm):
"""Compute the mean intersection-over-union via the confusion matrix."""
sum_over_row = math_ops.to_float(math_ops.reduce_sum(total_cm, 0))
sum_over_col = math_ops.to_float(math_ops.reduce_sum(total_cm, 1))
@@ -1151,17 +1171,12 @@ def mean_iou(labels,
# If the number of valid entries is 0 (no classes) we return 0.
result = array_ops.where(
math_ops.greater(num_valid_entries, 0),
- math_ops.reduce_sum(iou, name=name) / num_valid_entries, 0)
+ math_ops.reduce_sum(iou, name='mean_iou') / num_valid_entries, 0)
return result
- def mean_iou_across_towers(_, v):
- mean_iou_v = compute_mean_iou(v, 'mean_iou')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, mean_iou_v)
- return mean_iou_v
-
- mean_iou_v = distribute_lib.get_tower_context().merge_call(
- mean_iou_across_towers, total_cm)
+ # TODO(priyag): Use outside_compilation if in TPU context.
+ mean_iou_v = _aggregate_across_towers(
+ metrics_collections, compute_mean_iou, total_cm)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
@@ -1370,14 +1385,10 @@ def mean_tensor(values,
with ops.control_dependencies([values]):
update_count_op = state_ops.assign_add(count, num_values)
- def aggregate_across_towers(_, t, c):
- mean_t = _safe_div(t, c, 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, mean_t)
- return mean_t
+ compute_mean = lambda _, t, c: _safe_div(t, c, 'value')
- mean_t = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, total, count)
+ mean_t = _aggregate_across_towers(
+ metrics_collections, compute_mean, total, count)
update_op = _safe_div(update_total_op, update_count_op, 'update_op')
if updates_collections:
@@ -2003,13 +2014,10 @@ def precision(labels,
math_ops.greater(tp + fp, 0), math_ops.div(tp, tp + fp), 0, name)
def once_across_towers(_, true_p, false_p):
- p = compute_precision(true_p, false_p, 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, p)
- return p
+ return compute_precision(true_p, false_p, 'value')
- p = distribute_lib.get_tower_context().merge_call(
- once_across_towers, true_p, false_p)
+ p = _aggregate_across_towers(metrics_collections, once_across_towers,
+ true_p, false_p)
update_op = compute_precision(true_positives_update_op,
false_positives_update_op, 'update_op')
@@ -2087,13 +2095,10 @@ def precision_at_thresholds(labels,
return math_ops.div(tp, epsilon + tp + fp, name='precision_' + name)
def precision_across_towers(_, values):
- prec = compute_precision(values['tp'], values['fp'], 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, prec)
- return prec
+ return compute_precision(values['tp'], values['fp'], 'value')
- prec = distribute_lib.get_tower_context().merge_call(
- precision_across_towers, values)
+ prec = _aggregate_across_towers(
+ metrics_collections, precision_across_towers, values)
update_op = compute_precision(update_ops['tp'], update_ops['fp'],
'update_op')
@@ -2183,13 +2188,10 @@ def recall(labels,
math_ops.div(true_p, true_p + false_n), 0, name)
def once_across_towers(_, true_p, false_n):
- rec = compute_recall(true_p, false_n, 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, rec)
- return rec
+ return compute_recall(true_p, false_n, 'value')
- rec = distribute_lib.get_tower_context().merge_call(
- once_across_towers, true_p, false_n)
+ rec = _aggregate_across_towers(
+ metrics_collections, once_across_towers, true_p, false_n)
update_op = compute_recall(true_positives_update_op,
false_negatives_update_op, 'update_op')
@@ -2621,14 +2623,11 @@ def recall_at_top_k(labels,
class_id=class_id,
weights=weights)
- def aggregate_across_towers(_, tp, fn):
- metric = math_ops.div(tp, math_ops.add(tp, fn), name=scope)
- if metrics_collections:
- ops.add_to_collections(metrics_collections, metric)
- return metric
+ def compute_recall(_, tp, fn):
+ return math_ops.div(tp, math_ops.add(tp, fn), name=scope)
- metric = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, tp, fn)
+ metric = _aggregate_across_towers(
+ metrics_collections, compute_recall, tp, fn)
update = math_ops.div(
tp_update, math_ops.add(tp_update, fn_update), name='update')
@@ -2703,13 +2702,10 @@ def recall_at_thresholds(labels,
return math_ops.div(tp, epsilon + tp + fn, name='recall_' + name)
def recall_across_towers(_, values):
- rec = compute_recall(values['tp'], values['fn'], 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, rec)
- return rec
+ return compute_recall(values['tp'], values['fn'], 'value')
- rec = distribute_lib.get_tower_context().merge_call(
- recall_across_towers, values)
+ rec = _aggregate_across_towers(
+ metrics_collections, recall_across_towers, values)
update_op = compute_recall(update_ops['tp'], update_ops['fn'], 'update_op')
if updates_collections:
@@ -2777,14 +2773,9 @@ def root_mean_squared_error(labels,
mse, update_mse_op = mean_squared_error(labels, predictions, weights, None,
None, name or
'root_mean_squared_error')
- def once_across_towers(_, mse):
- rmse = math_ops.sqrt(mse)
- if metrics_collections:
- ops.add_to_collections(metrics_collections, rmse)
- return rmse
- rmse = distribute_lib.get_tower_context().merge_call(
- once_across_towers, mse)
+ once_across_towers = lambda _, mse: math_ops.sqrt(mse)
+ rmse = _aggregate_across_towers(metrics_collections, once_across_towers, mse)
update_rmse_op = math_ops.sqrt(update_mse_op)
if updates_collections:
@@ -2879,15 +2870,12 @@ def sensitivity_at_specificity(labels,
return math_ops.div(tp[tf_index], tp[tf_index] + fn[tf_index] + kepsilon,
name)
- def aggregate_across_towers(_, values):
- sensitivity = compute_sensitivity_at_specificity(
+ def sensitivity_across_towers(_, values):
+ return compute_sensitivity_at_specificity(
values['tp'], values['tn'], values['fp'], values['fn'], 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, sensitivity)
- return sensitivity
- sensitivity = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, values)
+ sensitivity = _aggregate_across_towers(
+ metrics_collections, sensitivity_across_towers, values)
update_op = compute_sensitivity_at_specificity(
update_ops['tp'], update_ops['tn'], update_ops['fp'], update_ops['fn'],
@@ -3156,14 +3144,11 @@ def _streaming_sparse_average_precision_at_top_k(labels,
total_update = state_ops.assign_add(total_var, batch_total, name='update')
# Divide total by max to get mean, for both vars and the update ops.
- def aggregate_across_towers(_, total_var, max_var):
- mean_average_precision = _safe_scalar_div(total_var, max_var, name='mean')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, mean_average_precision)
- return mean_average_precision
+ def precision_across_towers(_, total_var, max_var):
+ return _safe_scalar_div(total_var, max_var, name='mean')
- mean_average_precision = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, total_var, max_var)
+ mean_average_precision = _aggregate_across_towers(
+ metrics_collections, precision_across_towers, total_var, max_var)
update = _safe_scalar_div(total_update, max_update, name=scope)
if updates_collections:
@@ -3442,14 +3427,11 @@ def precision_at_top_k(labels,
class_id=class_id,
weights=weights)
- def aggregate_across_towers(_, tp, fp):
- metric = math_ops.div(tp, math_ops.add(tp, fp), name=scope)
- if metrics_collections:
- ops.add_to_collections(metrics_collections, metric)
- return metric
+ def precision_across_towers(_, tp, fp):
+ return math_ops.div(tp, math_ops.add(tp, fp), name=scope)
- metric = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, tp, fp)
+ metric = _aggregate_across_towers(
+ metrics_collections, precision_across_towers, tp, fp)
update = math_ops.div(
tp_update, math_ops.add(tp_update, fp_update), name='update')
@@ -3680,15 +3662,12 @@ def specificity_at_sensitivity(labels,
return math_ops.div(tn[tf_index], tn[tf_index] + fp[tf_index] + kepsilon,
name)
- def aggregate_across_towers(_, values):
- specificity = compute_specificity_at_sensitivity(
+ def specificity_across_towers(_, values):
+ return compute_specificity_at_sensitivity(
values['tp'], values['tn'], values['fp'], values['fn'], 'value')
- if metrics_collections:
- ops.add_to_collections(metrics_collections, specificity)
- return specificity
- specificity = distribute_lib.get_tower_context().merge_call(
- aggregate_across_towers, values)
+ specificity = _aggregate_across_towers(
+ metrics_collections, specificity_across_towers, values)
update_op = compute_specificity_at_sensitivity(
update_ops['tp'], update_ops['tn'], update_ops['fp'], update_ops['fn'],
diff --git a/tensorflow/python/ops/nn.py b/tensorflow/python/ops/nn.py
index 339684122e..4b73fc830e 100644
--- a/tensorflow/python/ops/nn.py
+++ b/tensorflow/python/ops/nn.py
@@ -16,7 +16,7 @@
# pylint: disable=unused-import,g-bad-import-order
"""Neural network support.
-See the @{$python/nn} guide.
+See the [Neural network](https://tensorflow.org/api_guides/python/nn) guide.
"""
from __future__ import absolute_import
from __future__ import division
diff --git a/tensorflow/python/ops/nn_grad.py b/tensorflow/python/ops/nn_grad.py
index df23ac55ce..a648653909 100644
--- a/tensorflow/python/ops/nn_grad.py
+++ b/tensorflow/python/ops/nn_grad.py
@@ -471,7 +471,9 @@ def _SoftmaxCrossEntropyWithLogitsGrad(op, grad_loss, grad_grad):
softmax = nn_ops.softmax(logits)
grad += ((grad_grad - array_ops.squeeze(
- math_ops.matmul(grad_grad[:, None, :], softmax[:, :, None]), axis=1)) *
+ math_ops.matmul(array_ops.expand_dims(grad_grad, 1),
+ array_ops.expand_dims(softmax, 2)),
+ axis=1)) *
softmax)
return grad, _BroadcastMul(grad_loss, -nn_ops.log_softmax(logits))
diff --git a/tensorflow/python/ops/nn_impl.py b/tensorflow/python/ops/nn_impl.py
index f47f38e29e..2a1919e66f 100644
--- a/tensorflow/python/ops/nn_impl.py
+++ b/tensorflow/python/ops/nn_impl.py
@@ -425,7 +425,7 @@ def depthwise_conv2d(input,
strides: 1-D of size 4. The stride of the sliding window for each
dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
rate: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
@@ -507,7 +507,7 @@ def separable_conv2d(input,
strides: 1-D of size 4. The strides for the depthwise convolution for
each dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
rate: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
@@ -1189,7 +1189,7 @@ def nce_loss(weights,
Note: By default this uses a log-uniform (Zipfian) distribution for sampling,
so your labels must be sorted in order of decreasing frequency to achieve
good results. For more details, see
- @{tf.nn.log_uniform_candidate_sampler}.
+ `tf.nn.log_uniform_candidate_sampler`.
Note: In the case where `num_true` > 1, we assign to each target class
the target probability 1 / `num_true` so that the target probabilities
@@ -1210,7 +1210,9 @@ def nce_loss(weights,
num_true]`. The target classes.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
- num_sampled: An `int`. The number of classes to randomly sample per batch.
+ num_sampled: An `int`. The number of negative classes to randomly sample
+ per batch. This single sample of negative classes is evaluated for each
+ element in the batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
diff --git a/tensorflow/python/ops/nn_ops.py b/tensorflow/python/ops/nn_ops.py
index 5cdb7726a7..edc6e04b48 100644
--- a/tensorflow/python/ops/nn_ops.py
+++ b/tensorflow/python/ops/nn_ops.py
@@ -698,7 +698,7 @@ def convolution(
`padded_input` is obtained by zero padding the input using an effective
spatial filter shape of `(spatial_filter_shape-1) * dilation_rate + 1` and
output striding `strides` as described in the
- @{$python/nn#Convolution$comment here}.
+ [comment here](https://tensorflow.org/api_guides/python/nn#Convolution).
In the case that `data_format` does start with `"NC"`, the `input` and output
(but not the `filter`) are simply transposed as follows:
@@ -898,8 +898,8 @@ def pool(
```
where the reduction function REDUCE depends on the value of `pooling_type`,
- and pad_before is defined based on the value of `padding` as described in the
- @{tf.nn.convolution$comment here}.
+ and pad_before is defined based on the value of `padding` as described in
+ the "returns" section of `tf.nn.convolution` for details.
The reduction never includes out-of-bounds positions.
In the case that `data_format` starts with `"NC"`, the `input` and output are
@@ -921,7 +921,7 @@ def pool(
window_shape: Sequence of N ints >= 1.
pooling_type: Specifies pooling operation, must be "AVG" or "MAX".
padding: The padding algorithm, must be "SAME" or "VALID".
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
dilation_rate: Optional. Dilation rate. List of N ints >= 1.
Defaults to [1]*N. If any value of dilation_rate is > 1, then all values
of strides must be 1.
@@ -1045,8 +1045,8 @@ def atrous_conv2d(value, filters, rate, padding, name=None):
"""Atrous convolution (a.k.a. convolution with holes or dilated convolution).
This function is a simpler wrapper around the more general
- @{tf.nn.convolution}, and exists only for backwards compatibility. You can
- use @{tf.nn.convolution} to perform 1-D, 2-D, or 3-D atrous convolution.
+ `tf.nn.convolution`, and exists only for backwards compatibility. You can
+ use `tf.nn.convolution` to perform 1-D, 2-D, or 3-D atrous convolution.
Computes a 2-D atrous convolution, also known as convolution with holes or
@@ -1205,7 +1205,7 @@ def conv2d_transpose(
strides: A list of ints. The stride of the sliding window for each
dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: Optional name for the returned tensor.
@@ -1430,7 +1430,7 @@ def conv3d_transpose(
strides: A list of ints. The stride of the sliding window for each
dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
data_format: A string, either `'NDHWC'` or `'NCDHW`' specifying the layout
of the input and output tensors. Defaults to `'NDHWC'`.
name: Optional name for the returned tensor.
@@ -1819,7 +1819,7 @@ def softmax_cross_entropy_with_logits_v2(
or `float64`).
Backpropagation will happen into both `logits` and `labels`. To disallow
- backpropagation into `labels`, pass label tensors through @{tf.stop_gradient}
+ backpropagation into `labels`, pass label tensors through `tf.stop_gradient`
before feeding it to this function.
**Note that to avoid confusion, it is required to pass only named arguments to
@@ -1836,8 +1836,9 @@ def softmax_cross_entropy_with_logits_v2(
name: A name for the operation (optional).
Returns:
- A `Tensor` of the same shape as `labels` and of the same type as `logits`
- with the softmax cross entropy loss.
+ A `Tensor` that contains the softmax cross entropy loss. Its type is the
+ same as `logits` and its shape is the same as `labels` except that it does
+ not have the last dimension of `labels`.
"""
_ensure_xent_args("softmax_cross_entropy_with_logits", _sentinel, labels,
logits)
@@ -1909,7 +1910,7 @@ _XENT_DEPRECATION = """
Future major versions of TensorFlow will allow gradients to flow
into the labels input on backprop by default.
-See @{tf.nn.softmax_cross_entropy_with_logits_v2}.
+See `tf.nn.softmax_cross_entropy_with_logits_v2`.
"""
@@ -1946,7 +1947,7 @@ def softmax_cross_entropy_with_logits(
Backpropagation will happen only into `logits`. To calculate a cross entropy
loss that allows backpropagation into both `logits` and `labels`, see
- @{tf.nn.softmax_cross_entropy_with_logits_v2}.
+ `tf.nn.softmax_cross_entropy_with_logits_v2`.
**Note that to avoid confusion, it is required to pass only named arguments to
this function.**
@@ -1962,8 +1963,9 @@ def softmax_cross_entropy_with_logits(
name: A name for the operation (optional).
Returns:
- A `Tensor` of the same shape as `labels` and of the same type as `logits`
- with the softmax cross entropy loss.
+ A `Tensor` that contains the softmax cross entropy loss. Its type is the
+ same as `logits` and its shape is the same as `labels` except that it does
+ not have the last dimension of `labels`.
"""
_ensure_xent_args("softmax_cross_entropy_with_logits", _sentinel, labels,
logits)
@@ -2003,8 +2005,8 @@ def sparse_softmax_cross_entropy_with_logits(
A common use case is to have logits and labels of shape
`[batch_size, num_classes]`, but higher dimensions are supported, in which
case the `dim`-th dimension is assumed to be of size `num_classes`.
- `logits` and `labels` must have the same dtype (either `float16`, `float32`,
- or `float64`).
+ `logits` must have the dtype of `float16`, `float32`, or `float64`, and
+ `labels` must have the dtype of `int32` or `int64`.
**Note that to avoid confusion, it is required to pass only named arguments to
this function.**
@@ -2114,7 +2116,7 @@ def avg_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
strides: A list or tuple of 4 ints. The stride of the sliding window for
each dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: Optional name for the operation.
@@ -2143,7 +2145,7 @@ def max_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
strides: A list or tuple of 4 ints. The stride of the sliding window for
each dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported.
name: Optional name for the operation.
@@ -2301,7 +2303,7 @@ def dropout(x, keep_prob, noise_shape=None, seed=None, name=None): # pylint: di
noise_shape: A 1-D `Tensor` of type `int32`, representing the
shape for randomly generated keep/drop flags.
seed: A Python integer. Used to create random seeds. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: A name for this operation (optional).
@@ -2521,7 +2523,7 @@ def conv1d_transpose(
stride: An `integer`. The number of entries by which
the filter is moved right at each step.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
- See the @{tf.nn.convolution$comment here}
+ See the "returns" section of `tf.nn.convolution` for details.
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: Optional name for the returned tensor.
diff --git a/tensorflow/python/ops/nn_test.py b/tensorflow/python/ops/nn_test.py
index 4cd357d0c8..ce0db6b264 100644
--- a/tensorflow/python/ops/nn_test.py
+++ b/tensorflow/python/ops/nn_test.py
@@ -220,7 +220,7 @@ class L2LossTest(test_lib.TestCase):
output = nn_ops.l2_loss(x)
err = gradient_checker.compute_gradient_error(x, x_shape, output, [1])
print("L2Loss gradient err = %g " % err)
- err_tolerance = 1e-11
+ err_tolerance = 1e-10
self.assertLess(err, err_tolerance)
diff --git a/tensorflow/python/ops/numerics.py b/tensorflow/python/ops/numerics.py
index d348e47f57..8fcbd7d834 100644
--- a/tensorflow/python/ops/numerics.py
+++ b/tensorflow/python/ops/numerics.py
@@ -56,8 +56,8 @@ def add_check_numerics_ops():
`check_numerics` op for all of its (`half`, `float`, or `double`) inputs
is guaranteed to run before the `check_numerics` op on any of its outputs.
- Note: This API is not compatible with the use of @{tf.cond} or
- @{tf.while_loop}, and will raise a `ValueError` if you attempt to call it
+ Note: This API is not compatible with the use of `tf.cond` or
+ `tf.while_loop`, and will raise a `ValueError` if you attempt to call it
in such a graph.
Returns:
diff --git a/tensorflow/python/ops/parallel_for/BUILD b/tensorflow/python/ops/parallel_for/BUILD
index 6c804a50e7..015181af47 100644
--- a/tensorflow/python/ops/parallel_for/BUILD
+++ b/tensorflow/python/ops/parallel_for/BUILD
@@ -85,6 +85,7 @@ py_library(
cuda_py_test(
name = "control_flow_ops_test",
+ size = "large",
srcs = ["control_flow_ops_test.py"],
additional_deps = [
":control_flow_ops",
diff --git a/tensorflow/python/ops/parallel_for/pfor.py b/tensorflow/python/ops/parallel_for/pfor.py
index 77ec3bc0d4..2e4b2fd64e 100644
--- a/tensorflow/python/ops/parallel_for/pfor.py
+++ b/tensorflow/python/ops/parallel_for/pfor.py
@@ -2117,7 +2117,7 @@ def _convert_print(pfor_input):
# 2a Elements written to the array are "stacked"
# To simulate multiple TensorArrays, we may increase the dimension of each
# element of the array. i.e. the i_th row of the j_th entry of the converted
-# TensorArray corresponds to to the j_th entry of the TensorArray in the i_th
+# TensorArray corresponds to the j_th entry of the TensorArray in the i_th
# pfor iteration.
#
# 2b Elements written to the array are "unstacked"
diff --git a/tensorflow/python/ops/random_ops.py b/tensorflow/python/ops/random_ops.py
index b8738adf66..4baf506385 100644
--- a/tensorflow/python/ops/random_ops.py
+++ b/tensorflow/python/ops/random_ops.py
@@ -61,7 +61,7 @@ def random_normal(shape,
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: A name for the operation (optional).
@@ -110,7 +110,7 @@ def parameterized_truncated_normal(shape,
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: A name for the operation (optional).
@@ -158,7 +158,7 @@ def truncated_normal(shape,
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: A name for the operation (optional).
@@ -212,7 +212,7 @@ def random_uniform(shape,
dtype: The type of the output: `float16`, `float32`, `float64`, `int32`,
or `int64`.
seed: A Python integer. Used to create a random seed for the distribution.
- See @{tf.set_random_seed}
+ See `tf.set_random_seed`
for behavior.
name: A name for the operation (optional).
@@ -264,7 +264,7 @@ def random_shuffle(value, seed=None, name=None):
value: A Tensor to be shuffled.
seed: A Python integer. Used to create a random seed for the distribution.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: A name for the operation (optional).
@@ -292,7 +292,7 @@ def random_crop(value, size, seed=None, name=None):
value: Input tensor to crop.
size: 1-D tensor with size the rank of `value`.
seed: Python integer. Used to create a random seed. See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: A name for this operation (optional).
@@ -338,7 +338,7 @@ def multinomial(logits, num_samples, seed=None, name=None, output_dtype=None):
num_samples: 0-D. Number of independent samples to draw for each row slice.
seed: A Python integer. Used to create a random seed for the distribution.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: Optional name for the operation.
output_dtype: integer type to use for the output. Defaults to int64.
@@ -417,7 +417,7 @@ def random_gamma(shape,
`float64`.
seed: A Python integer. Used to create a random seed for the distributions.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: Optional name for the operation.
@@ -467,7 +467,7 @@ def random_poisson(lam, shape, dtype=dtypes.float32, seed=None, name=None):
`int64`.
seed: A Python integer. Used to create a random seed for the distributions.
See
- @{tf.set_random_seed}
+ `tf.set_random_seed`
for behavior.
name: Optional name for the operation.
diff --git a/tensorflow/python/ops/resource_variable_ops.py b/tensorflow/python/ops/resource_variable_ops.py
index d533731c07..3d0205f768 100644
--- a/tensorflow/python/ops/resource_variable_ops.py
+++ b/tensorflow/python/ops/resource_variable_ops.py
@@ -94,26 +94,8 @@ def _eager_safe_variable_handle(shape, dtype, shared_name, name, graph_mode):
ops.set_shape_and_handle_data_for_outputs(h.op)
handle._handle_data = h._handle_data
# pylint: enable=protected-access
-
- # Clean up our reference cycles to avoid making the garbage collector run.
- # pylint: disable=protected-access
- # OrderedDict, constructed on Graph creation, makes a simple reference loop
- # and hides it in an __attribute in some Python versions. We don't need to
- # throw an error if we can't find it, but if we do find it we can break the
- # loop to avoid creating work for the garbage collector.
- problematic_cycle = graph._functions.__dict__.get("_OrderedDict__root", None)
- # pylint: enable=protected-access
- if problematic_cycle:
- try:
- del problematic_cycle[0][:]
- except TypeError:
- # This is probably not one of the problematic Python versions. Continue
- # with the rest of our cleanup.
- pass
- # Now clean up our own reference cycles by clearing all of the attributes for
- # the Graph and op we created.
- h.__dict__ = {}
- graph.__dict__ = {}
+ # Clean up op->graph->op reference cycles.
+ ops.dismantle_graph(graph)
return handle
@@ -185,7 +167,8 @@ def shape_safe_assign_variable_handle(handle, shape, value, name=None):
class ResourceVariable(variables.RefVariable):
"""Variable based on resource handles.
- See the @{$variables$Variables How To} for a high level overview.
+ See the [Variables How To](https://tensorflow.org/guide/variables)
+ for a high level overview.
A `ResourceVariable` allows you to maintain state across subsequent calls to
session.run.
diff --git a/tensorflow/python/ops/rnn_cell_impl.py b/tensorflow/python/ops/rnn_cell_impl.py
index 8356fbbb9d..85a6a2233c 100644
--- a/tensorflow/python/ops/rnn_cell_impl.py
+++ b/tensorflow/python/ops/rnn_cell_impl.py
@@ -34,6 +34,9 @@ from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
+from tensorflow.python.keras import activations
+from tensorflow.python.keras import initializers
+from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.layers import base as base_layer
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import clip_ops
@@ -190,6 +193,13 @@ class RNNCell(base_layer.Layer):
for each `s` in `self.batch_size`.
"""
+ def __init__(self, trainable=True, name=None, dtype=None, **kwargs):
+ super(RNNCell, self).__init__(
+ trainable=trainable, name=name, dtype=dtype, **kwargs)
+ # Attribute that indicates whether the cell is a TF RNN cell, due the slight
+ # difference between TF and Keras RNN cell.
+ self._is_tf_rnn_cell = True
+
def __call__(self, inputs, state, scope=None):
"""Run this RNN cell on inputs, starting from the given state.
@@ -336,7 +346,8 @@ class BasicRNNCell(LayerRNNCell):
Args:
num_units: int, The number of units in the RNN cell.
- activation: Nonlinearity to use. Default: `tanh`.
+ activation: Nonlinearity to use. Default: `tanh`. It could also be string
+ that is within Keras activation function names.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
@@ -345,6 +356,8 @@ class BasicRNNCell(LayerRNNCell):
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
+ **kwargs: Dict, keyword named properties for common layer attributes, like
+ `trainable` etc when constructing the cell from configs of get_config().
"""
def __init__(self,
@@ -352,14 +365,19 @@ class BasicRNNCell(LayerRNNCell):
activation=None,
reuse=None,
name=None,
- dtype=None):
- super(BasicRNNCell, self).__init__(_reuse=reuse, name=name, dtype=dtype)
+ dtype=None,
+ **kwargs):
+ super(BasicRNNCell, self).__init__(
+ _reuse=reuse, name=name, dtype=dtype, **kwargs)
# Inputs must be 2-dimensional.
self.input_spec = base_layer.InputSpec(ndim=2)
self._num_units = num_units
- self._activation = activation or math_ops.tanh
+ if activation:
+ self._activation = activations.get(activation)
+ else:
+ self._activation = math_ops.tanh
@property
def state_size(self):
@@ -369,12 +387,13 @@ class BasicRNNCell(LayerRNNCell):
def output_size(self):
return self._num_units
+ @tf_utils.shape_type_conversion
def build(self, inputs_shape):
- if inputs_shape[1].value is None:
+ if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% inputs_shape)
- input_depth = inputs_shape[1].value
+ input_depth = inputs_shape[-1]
self._kernel = self.add_variable(
_WEIGHTS_VARIABLE_NAME,
shape=[input_depth + self._num_units, self._num_units])
@@ -394,6 +413,15 @@ class BasicRNNCell(LayerRNNCell):
output = self._activation(gate_inputs)
return output, output
+ def get_config(self):
+ config = {
+ "num_units": self._num_units,
+ "activation": activations.serialize(self._activation),
+ "reuse": self._reuse,
+ }
+ base_config = super(BasicRNNCell, self).get_config()
+ return dict(list(base_config.items()) + list(config.items()))
+
@tf_export("nn.rnn_cell.GRUCell")
class GRUCell(LayerRNNCell):
@@ -413,6 +441,8 @@ class GRUCell(LayerRNNCell):
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
+ **kwargs: Dict, keyword named properties for common layer attributes, like
+ `trainable` etc when constructing the cell from configs of get_config().
"""
def __init__(self,
@@ -422,16 +452,21 @@ class GRUCell(LayerRNNCell):
kernel_initializer=None,
bias_initializer=None,
name=None,
- dtype=None):
- super(GRUCell, self).__init__(_reuse=reuse, name=name, dtype=dtype)
+ dtype=None,
+ **kwargs):
+ super(GRUCell, self).__init__(
+ _reuse=reuse, name=name, dtype=dtype, **kwargs)
# Inputs must be 2-dimensional.
self.input_spec = base_layer.InputSpec(ndim=2)
self._num_units = num_units
- self._activation = activation or math_ops.tanh
- self._kernel_initializer = kernel_initializer
- self._bias_initializer = bias_initializer
+ if activation:
+ self._activation = activations.get(activation)
+ else:
+ self._activation = math_ops.tanh
+ self._kernel_initializer = initializers.get(kernel_initializer)
+ self._bias_initializer = initializers.get(bias_initializer)
@property
def state_size(self):
@@ -441,12 +476,13 @@ class GRUCell(LayerRNNCell):
def output_size(self):
return self._num_units
+ @tf_utils.shape_type_conversion
def build(self, inputs_shape):
- if inputs_shape[1].value is None:
+ if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% inputs_shape)
- input_depth = inputs_shape[1].value
+ input_depth = inputs_shape[-1]
self._gate_kernel = self.add_variable(
"gates/%s" % _WEIGHTS_VARIABLE_NAME,
shape=[input_depth + self._num_units, 2 * self._num_units],
@@ -492,6 +528,17 @@ class GRUCell(LayerRNNCell):
new_h = u * state + (1 - u) * c
return new_h, new_h
+ def get_config(self):
+ config = {
+ "num_units": self._num_units,
+ "kernel_initializer": initializers.serialize(self._kernel_initializer),
+ "bias_initializer": initializers.serialize(self._bias_initializer),
+ "activation": activations.serialize(self._activation),
+ "reuse": self._reuse,
+ }
+ base_config = super(GRUCell, self).get_config()
+ return dict(list(base_config.items()) + list(config.items()))
+
_LSTMStateTuple = collections.namedtuple("LSTMStateTuple", ("c", "h"))
@@ -531,7 +578,7 @@ class BasicLSTMCell(LayerRNNCell):
It does not allow cell clipping, a projection layer, and does not
use peep-hole connections: it is the basic baseline.
- For advanced models, please use the full @{tf.nn.rnn_cell.LSTMCell}
+ For advanced models, please use the full `tf.nn.rnn_cell.LSTMCell`
that follows.
"""
@@ -546,7 +593,8 @@ class BasicLSTMCell(LayerRNNCell):
activation=None,
reuse=None,
name=None,
- dtype=None):
+ dtype=None,
+ **kwargs):
"""Initialize the basic LSTM cell.
Args:
@@ -557,7 +605,8 @@ class BasicLSTMCell(LayerRNNCell):
state_is_tuple: If True, accepted and returned states are 2-tuples of
the `c_state` and `m_state`. If False, they are concatenated
along the column axis. The latter behavior will soon be deprecated.
- activation: Activation function of the inner states. Default: `tanh`.
+ activation: Activation function of the inner states. Default: `tanh`. It
+ could also be string that is within Keras activation function names.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
@@ -566,11 +615,14 @@ class BasicLSTMCell(LayerRNNCell):
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
+ **kwargs: Dict, keyword named properties for common layer attributes, like
+ `trainable` etc when constructing the cell from configs of get_config().
When restoring from CudnnLSTM-trained checkpoints, must use
`CudnnCompatibleLSTMCell` instead.
"""
- super(BasicLSTMCell, self).__init__(_reuse=reuse, name=name, dtype=dtype)
+ super(BasicLSTMCell, self).__init__(
+ _reuse=reuse, name=name, dtype=dtype, **kwargs)
if not state_is_tuple:
logging.warn("%s: Using a concatenated state is slower and will soon be "
"deprecated. Use state_is_tuple=True.", self)
@@ -581,7 +633,10 @@ class BasicLSTMCell(LayerRNNCell):
self._num_units = num_units
self._forget_bias = forget_bias
self._state_is_tuple = state_is_tuple
- self._activation = activation or math_ops.tanh
+ if activation:
+ self._activation = activations.get(activation)
+ else:
+ self._activation = math_ops.tanh
@property
def state_size(self):
@@ -592,12 +647,13 @@ class BasicLSTMCell(LayerRNNCell):
def output_size(self):
return self._num_units
+ @tf_utils.shape_type_conversion
def build(self, inputs_shape):
- if inputs_shape[1].value is None:
+ if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% inputs_shape)
- input_depth = inputs_shape[1].value
+ input_depth = inputs_shape[-1]
h_depth = self._num_units
self._kernel = self.add_variable(
_WEIGHTS_VARIABLE_NAME,
@@ -655,6 +711,17 @@ class BasicLSTMCell(LayerRNNCell):
new_state = array_ops.concat([new_c, new_h], 1)
return new_h, new_state
+ def get_config(self):
+ config = {
+ "num_units": self._num_units,
+ "forget_bias": self._forget_bias,
+ "state_is_tuple": self._state_is_tuple,
+ "activation": activations.serialize(self._activation),
+ "reuse": self._reuse,
+ }
+ base_config = super(BasicLSTMCell, self).get_config()
+ return dict(list(base_config.items()) + list(config.items()))
+
@tf_export("nn.rnn_cell.LSTMCell")
class LSTMCell(LayerRNNCell):
@@ -684,7 +751,7 @@ class LSTMCell(LayerRNNCell):
initializer=None, num_proj=None, proj_clip=None,
num_unit_shards=None, num_proj_shards=None,
forget_bias=1.0, state_is_tuple=True,
- activation=None, reuse=None, name=None, dtype=None):
+ activation=None, reuse=None, name=None, dtype=None, **kwargs):
"""Initialize the parameters for an LSTM cell.
Args:
@@ -710,7 +777,8 @@ class LSTMCell(LayerRNNCell):
state_is_tuple: If True, accepted and returned states are 2-tuples of
the `c_state` and `m_state`. If False, they are concatenated
along the column axis. This latter behavior will soon be deprecated.
- activation: Activation function of the inner states. Default: `tanh`.
+ activation: Activation function of the inner states. Default: `tanh`. It
+ could also be string that is within Keras activation function names.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
@@ -719,11 +787,14 @@ class LSTMCell(LayerRNNCell):
cases.
dtype: Default dtype of the layer (default of `None` means use the type
of the first input). Required when `build` is called before `call`.
+ **kwargs: Dict, keyword named properties for common layer attributes, like
+ `trainable` etc when constructing the cell from configs of get_config().
When restoring from CudnnLSTM-trained checkpoints, use
`CudnnCompatibleLSTMCell` instead.
"""
- super(LSTMCell, self).__init__(_reuse=reuse, name=name, dtype=dtype)
+ super(LSTMCell, self).__init__(
+ _reuse=reuse, name=name, dtype=dtype, **kwargs)
if not state_is_tuple:
logging.warn("%s: Using a concatenated state is slower and will soon be "
"deprecated. Use state_is_tuple=True.", self)
@@ -739,14 +810,17 @@ class LSTMCell(LayerRNNCell):
self._num_units = num_units
self._use_peepholes = use_peepholes
self._cell_clip = cell_clip
- self._initializer = initializer
+ self._initializer = initializers.get(initializer)
self._num_proj = num_proj
self._proj_clip = proj_clip
self._num_unit_shards = num_unit_shards
self._num_proj_shards = num_proj_shards
self._forget_bias = forget_bias
self._state_is_tuple = state_is_tuple
- self._activation = activation or math_ops.tanh
+ if activation:
+ self._activation = activations.get(activation)
+ else:
+ self._activation = math_ops.tanh
if num_proj:
self._state_size = (
@@ -767,12 +841,13 @@ class LSTMCell(LayerRNNCell):
def output_size(self):
return self._output_size
+ @tf_utils.shape_type_conversion
def build(self, inputs_shape):
- if inputs_shape[1].value is None:
+ if inputs_shape[-1] is None:
raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s"
% inputs_shape)
- input_depth = inputs_shape[1].value
+ input_depth = inputs_shape[-1]
h_depth = self._num_units if self._num_proj is None else self._num_proj
maybe_partitioner = (
partitioned_variables.fixed_size_partitioner(self._num_unit_shards)
@@ -886,6 +961,24 @@ class LSTMCell(LayerRNNCell):
array_ops.concat([c, m], 1))
return m, new_state
+ def get_config(self):
+ config = {
+ "num_units": self._num_units,
+ "use_peepholes": self._use_peepholes,
+ "cell_clip": self._cell_clip,
+ "initializer": initializers.serialize(self._initializer),
+ "num_proj": self._num_proj,
+ "proj_clip": self._proj_clip,
+ "num_unit_shards": self._num_unit_shards,
+ "num_proj_shards": self._num_proj_shards,
+ "forget_bias": self._forget_bias,
+ "state_is_tuple": self._state_is_tuple,
+ "activation": activations.serialize(self._activation),
+ "reuse": self._reuse,
+ }
+ base_config = super(LSTMCell, self).get_config()
+ return dict(list(base_config.items()) + list(config.items()))
+
def _enumerated_map_structure_up_to(shallow_structure, map_fn, *args, **kwargs):
ix = [0]
diff --git a/tensorflow/python/ops/script_ops.py b/tensorflow/python/ops/script_ops.py
index af103d3cc7..8d66de6b20 100644
--- a/tensorflow/python/ops/script_ops.py
+++ b/tensorflow/python/ops/script_ops.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
-"""Script Language Operators. See the @{$python/script_ops} guide."""
+"""Script Language Operators."""
# pylint: disable=g-bad-name
from __future__ import absolute_import
@@ -313,8 +313,8 @@ def eager_py_func(func, inp, Tout, name=None):
in a once-differentiable TensorFlow operation that executes it with eager
exeuction enabled. As a consequence, `tf.contrib.eager.py_func` makes it
possible to express control flow using Python constructs (`if`, `while`,
- `for`, etc.), instead of TensorFlow control flow constructs (@{tf.cond},
- @{tf.while_loop}). For example, you might use `tf.contrib.eager.py_func` to
+ `for`, etc.), instead of TensorFlow control flow constructs (`tf.cond`,
+ `tf.while_loop`). For example, you might use `tf.contrib.eager.py_func` to
implement the log huber function:
```python
@@ -343,17 +343,18 @@ 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 @{$guide/eager}.
+ For more information on eager execution, see the
+ [Eager guide](https://tensorflow.org/guide/eager).
- `tf.contrib.eager.py_func` is similar in spirit to @{tf.py_func}, but unlike
+ `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
- Python function. In particular, while @{tf.py_func} only runs on CPUs and
+ Python function. In particular, while `tf.py_func` only runs on CPUs and
wraps functions that take NumPy arrays as inputs and return NumPy arrays as
outputs, `tf.contrib.eager.py_func` can be placed on GPUs and wraps functions
that take Tensors as inputs, execute TensorFlow operations in their bodies,
and return Tensors as outputs.
- Like @{tf.py_func}, `tf.contrib.eager.py_func` has the following limitations
+ Like `tf.py_func`, `tf.contrib.eager.py_func` has the following limitations
with respect to serialization and distribution:
* The body of the function (i.e. `func`) will not be serialized in a
diff --git a/tensorflow/python/ops/session_ops.py b/tensorflow/python/ops/session_ops.py
index dee84bab0c..e229501c10 100644
--- a/tensorflow/python/ops/session_ops.py
+++ b/tensorflow/python/ops/session_ops.py
@@ -13,7 +13,11 @@
# limitations under the License.
# ==============================================================================
-"""Tensor Handle Operations. See the @{$python/session_ops} guide."""
+"""Tensor Handle Operations.
+
+See the [Session Ops](https://tensorflow.org/api_guides/python/session_ops)
+guide.
+"""
# pylint: disable=g-bad-name
from __future__ import absolute_import
diff --git a/tensorflow/python/ops/sparse_ops.py b/tensorflow/python/ops/sparse_ops.py
index c3b16a7bd5..e91813b4a8 100644
--- a/tensorflow/python/ops/sparse_ops.py
+++ b/tensorflow/python/ops/sparse_ops.py
@@ -14,7 +14,10 @@
# ==============================================================================
# pylint: disable=g-short-docstring-punctuation
-"""Sparse Tensor Representation. See the @{$python/sparse_ops} guide."""
+"""Sparse Tensor Representation.
+
+See the [Sparse Ops](https://tensorflow.org/api_guides/python/sparse_ops) guide.
+"""
from __future__ import absolute_import
from __future__ import division
@@ -777,8 +780,10 @@ def sparse_to_dense(sparse_indices,
@tf_export("sparse_reduce_max")
-def sparse_reduce_max(sp_input, axis=None, keep_dims=False,
- reduction_axes=None):
+@deprecation.deprecated_args(
+ None, "keep_dims is deprecated, use keepdims instead", "keep_dims")
+def sparse_reduce_max(sp_input, axis=None, keepdims=None,
+ reduction_axes=None, keep_dims=None):
"""Computes the max of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to
@@ -786,14 +791,19 @@ def sparse_reduce_max(sp_input, axis=None, keep_dims=False,
instead of a sparse one.
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless
- `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
- `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained
+ `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in
+ `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained
with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor
with a single element is returned. Additionally, the axes can be negative,
similar to the indexing rules in Python.
+ The values not defined in `sp_input` don't participate in the reduce max,
+ as opposed to be implicitly assumed 0 -- hence it can return negative values
+ for sparse `reduction_axes`. But, in case there are no values in
+ `reduction_axes`, it will reduce to 0. See second example below.
+
For example:
```python
@@ -803,30 +813,44 @@ def sparse_reduce_max(sp_input, axis=None, keep_dims=False,
tf.sparse_reduce_max(x) ==> 3
tf.sparse_reduce_max(x, 0) ==> [1, 3, 2]
tf.sparse_reduce_max(x, 1) ==> [2, 3] # Can also use -1 as the axis.
- tf.sparse_reduce_max(x, 1, keep_dims=True) ==> [[2], [3]]
+ tf.sparse_reduce_max(x, 1, keepdims=True) ==> [[2], [3]]
tf.sparse_reduce_max(x, [0, 1]) ==> 3
+
+ # 'y' represents [[-7, ?]
+ # [ 4, 3]
+ # [ ?, ?]
+ tf.sparse_reduce_max(x, 1) ==> [-7, 4, 0]
```
Args:
sp_input: The SparseTensor to reduce. Should have numeric type.
axis: The dimensions to reduce; list or scalar. If `None` (the
default), reduces all dimensions.
- keep_dims: If true, retain reduced dimensions with length 1.
+ keepdims: If true, retain reduced dimensions with length 1.
reduction_axes: Deprecated name of axis.
+ keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced Tensor.
"""
+ keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims,
+ "keep_dims", keep_dims)
+ if keepdims is None:
+ keepdims = False
+
return gen_sparse_ops.sparse_reduce_max(
sp_input.indices, sp_input.values, sp_input.dense_shape,
- math_ops._ReductionDims(sp_input, axis, reduction_axes), keep_dims)
+ math_ops._ReductionDims(sp_input, axis, reduction_axes), keepdims)
@tf_export("sparse_reduce_max_sparse")
+@deprecation.deprecated_args(
+ None, "keep_dims is deprecated, use keepdims instead", "keep_dims")
def sparse_reduce_max_sparse(sp_input,
axis=None,
- keep_dims=False,
- reduction_axes=None):
+ keepdims=None,
+ reduction_axes=None,
+ keep_dims=None):
"""Computes the max of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to
@@ -834,8 +858,8 @@ def sparse_reduce_max_sparse(sp_input,
SparseTensor.
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless
- `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
- `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained
+ `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in
+ `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained
with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor
@@ -846,23 +870,31 @@ def sparse_reduce_max_sparse(sp_input,
sp_input: The SparseTensor to reduce. Should have numeric type.
axis: The dimensions to reduce; list or scalar. If `None` (the
default), reduces all dimensions.
- keep_dims: If true, retain reduced dimensions with length 1.
- reduction_axes: Deprecated name of axis
+ keepdims: If true, retain reduced dimensions with length 1.
+ reduction_axes: Deprecated name of axis.
+ keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced SparseTensor.
"""
+ keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims,
+ "keep_dims", keep_dims)
+ if keepdims is None:
+ keepdims = False
+
output_ind, output_val, output_shape = (
gen_sparse_ops.sparse_reduce_max_sparse(
sp_input.indices, sp_input.values, sp_input.dense_shape,
- math_ops._ReductionDims(sp_input, axis, reduction_axes), keep_dims))
+ math_ops._ReductionDims(sp_input, axis, reduction_axes), keepdims))
return sparse_tensor.SparseTensor(output_ind, output_val, output_shape)
@tf_export("sparse_reduce_sum")
-def sparse_reduce_sum(sp_input, axis=None, keep_dims=False,
- reduction_axes=None):
+@deprecation.deprecated_args(
+ None, "keep_dims is deprecated, use keepdims instead", "keep_dims")
+def sparse_reduce_sum(sp_input, axis=None, keepdims=None,
+ reduction_axes=None, keep_dims=None):
"""Computes the sum of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to
@@ -870,8 +902,8 @@ def sparse_reduce_sum(sp_input, axis=None, keep_dims=False,
instead of a sparse one.
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless
- `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
- `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained
+ `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in
+ `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained
with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor
@@ -887,7 +919,7 @@ def sparse_reduce_sum(sp_input, axis=None, keep_dims=False,
tf.sparse_reduce_sum(x) ==> 3
tf.sparse_reduce_sum(x, 0) ==> [1, 1, 1]
tf.sparse_reduce_sum(x, 1) ==> [2, 1] # Can also use -1 as the axis.
- tf.sparse_reduce_sum(x, 1, keep_dims=True) ==> [[2], [1]]
+ tf.sparse_reduce_sum(x, 1, keepdims=True) ==> [[2], [1]]
tf.sparse_reduce_sum(x, [0, 1]) ==> 3
```
@@ -895,22 +927,31 @@ def sparse_reduce_sum(sp_input, axis=None, keep_dims=False,
sp_input: The SparseTensor to reduce. Should have numeric type.
axis: The dimensions to reduce; list or scalar. If `None` (the
default), reduces all dimensions.
- keep_dims: If true, retain reduced dimensions with length 1.
+ keepdims: If true, retain reduced dimensions with length 1.
reduction_axes: Deprecated name of axis.
+ keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced Tensor.
"""
+ keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims,
+ "keep_dims", keep_dims)
+ if keepdims is None:
+ keepdims = False
+
return gen_sparse_ops.sparse_reduce_sum(
sp_input.indices, sp_input.values, sp_input.dense_shape,
- math_ops._ReductionDims(sp_input, axis, reduction_axes), keep_dims)
+ math_ops._ReductionDims(sp_input, axis, reduction_axes), keepdims)
@tf_export("sparse_reduce_sum_sparse")
+@deprecation.deprecated_args(
+ None, "keep_dims is deprecated, use keepdims instead", "keep_dims")
def sparse_reduce_sum_sparse(sp_input,
axis=None,
- keep_dims=False,
- reduction_axes=None):
+ keepdims=None,
+ reduction_axes=None,
+ keep_dims=None):
"""Computes the sum of elements across dimensions of a SparseTensor.
This Op takes a SparseTensor and is the sparse counterpart to
@@ -918,8 +959,8 @@ def sparse_reduce_sum_sparse(sp_input,
SparseTensor.
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless
- `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
- `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained
+ `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in
+ `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained
with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor
@@ -930,16 +971,22 @@ def sparse_reduce_sum_sparse(sp_input,
sp_input: The SparseTensor to reduce. Should have numeric type.
axis: The dimensions to reduce; list or scalar. If `None` (the
default), reduces all dimensions.
- keep_dims: If true, retain reduced dimensions with length 1.
- reduction_axes: Deprecated name of axis
+ keepdims: If true, retain reduced dimensions with length 1.
+ reduction_axes: Deprecated name of axis.
+ keep_dims: Deprecated alias for `keepdims`.
Returns:
The reduced SparseTensor.
"""
+ keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims,
+ "keep_dims", keep_dims)
+ if keepdims is None:
+ keepdims = False
+
output_ind, output_val, output_shape = (
gen_sparse_ops.sparse_reduce_sum_sparse(
sp_input.indices, sp_input.values, sp_input.dense_shape,
- math_ops._ReductionDims(sp_input, axis, reduction_axes), keep_dims))
+ math_ops._ReductionDims(sp_input, axis, reduction_axes), keepdims))
return sparse_tensor.SparseTensor(output_ind, output_val, output_shape)
diff --git a/tensorflow/python/ops/spectral_ops.py b/tensorflow/python/ops/spectral_ops.py
index 293aace728..da5884e746 100644
--- a/tensorflow/python/ops/spectral_ops.py
+++ b/tensorflow/python/ops/spectral_ops.py
@@ -180,9 +180,9 @@ def dct(input, type=2, n=None, axis=-1, norm=None, name=None): # pylint: disabl
"""Computes the 1D [Discrete Cosine Transform (DCT)][dct] of `input`.
Currently only Types II and III are supported. Type II is implemented using a
- length `2N` padded @{tf.spectral.rfft}, as described here:
+ length `2N` padded `tf.spectral.rfft`, as described here:
https://dsp.stackexchange.com/a/10606. Type III is a fairly straightforward
- inverse of Type II (i.e. using a length `2N` padded @{tf.spectral.irfft}).
+ inverse of Type II (i.e. using a length `2N` padded `tf.spectral.irfft`).
@compatibility(scipy)
Equivalent to scipy.fftpack.dct for Type-II and Type-III DCT.
diff --git a/tensorflow/python/ops/state_ops.py b/tensorflow/python/ops/state_ops.py
index 2c93cf72c7..125e6c8dbf 100644
--- a/tensorflow/python/ops/state_ops.py
+++ b/tensorflow/python/ops/state_ops.py
@@ -13,7 +13,10 @@
# limitations under the License.
# ==============================================================================
-"""Variables. See the @{$python/state_ops} guide."""
+"""Variables.
+
+See the [Variables](https://tensorflow.org/api_guides/python/state_ops) guide.
+"""
from __future__ import absolute_import
from __future__ import division
@@ -329,7 +332,7 @@ def scatter_nd_update(ref, indices, updates, use_locking=True, name=None):
[1, 11, 3, 10, 9, 6, 7, 12]
- See @{tf.scatter_nd} for more details about how to make updates to
+ See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
@@ -443,7 +446,7 @@ def scatter_nd_add(ref, indices, updates, use_locking=False, name=None):
[1, 13, 3, 14, 14, 6, 7, 20]
- See @{tf.scatter_nd} for more details about how to make updates to
+ See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
@@ -470,3 +473,57 @@ def scatter_nd_add(ref, indices, updates, use_locking=False, name=None):
return ref._lazy_read(gen_state_ops.resource_scatter_nd_add( # pylint: disable=protected-access
ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype),
name=name))
+
+
+@tf_export("scatter_sub")
+def scatter_sub(ref, indices, updates, use_locking=False, name=None):
+ r"""Subtracts sparse updates to a variable reference.
+
+ ```python
+ # Scalar indices
+ ref[indices, ...] -= updates[...]
+
+ # Vector indices (for each i)
+ ref[indices[i], ...] -= updates[i, ...]
+
+ # High rank indices (for each i, ..., j)
+ ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...]
+ ```
+
+ This operation outputs `ref` after the update is done.
+ This makes it easier to chain operations that need to use the reset value.
+
+ Duplicate entries are handled correctly: if multiple `indices` reference
+ the same location, their (negated) contributions add.
+
+ Requires `updates.shape = indices.shape + ref.shape[1:]` or
+ `updates.shape = []`.
+
+ <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;">
+ <img style="width:100%"
+ src="https://www.tensorflow.org/images/ScatterSub.png" alt>
+ </div>
+
+ Args:
+ ref: A mutable `Tensor`. Must be one of the following types: `float32`,
+ `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`,
+ `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`,
+ `uint32`, `uint64`. Should be from a `Variable` node.
+ indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.
+ A tensor of indices into the first dimension of `ref`.
+ updates: A `Tensor`. Must have the same type as `ref`.
+ A tensor of updated values to subtract from `ref`.
+ use_locking: An optional `bool`. Defaults to `False`.
+ If True, the subtraction will be protected by a lock;
+ otherwise the behavior is undefined, but may exhibit less contention.
+ name: A name for the operation (optional).
+
+ Returns:
+ A mutable `Tensor`. Has the same type as `ref`.
+ """
+ if ref.dtype._is_ref_dtype:
+ return gen_state_ops.scatter_sub(ref, indices, updates,
+ use_locking=use_locking, name=name)
+ return ref._lazy_read(gen_resource_variable_ops.resource_scatter_sub( # pylint: disable=protected-access
+ ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype),
+ name=name))
diff --git a/tensorflow/python/ops/string_ops.py b/tensorflow/python/ops/string_ops.py
index 0280c89c10..c832ba4e2a 100644
--- a/tensorflow/python/ops/string_ops.py
+++ b/tensorflow/python/ops/string_ops.py
@@ -15,7 +15,7 @@
"""Operations for working with string Tensors.
-See the @{$python/string_ops} guide.
+See the [Strings](https://tensorflow.org/api_guides/python/string_ops) guide.
"""
from __future__ import absolute_import
@@ -24,6 +24,7 @@ from __future__ import print_function
import numpy as np
+from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
@@ -31,6 +32,7 @@ from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_string_ops
from tensorflow.python.ops import math_ops
+from tensorflow.python.util import compat as util_compat
# go/tf-wildcard-import
# pylint: disable=wildcard-import
@@ -42,6 +44,41 @@ from tensorflow.python.util.tf_export import tf_export
# Expose regex_full_match in strings namespace
tf_export("strings.regex_full_match")(regex_full_match)
+
+def regex_replace(source, pattern, rewrite, replace_global=True):
+ r"""Replace elements of `source` matching regex `pattern with `rewrite`.
+
+ Args:
+ source: string `Tensor`, the source strings to process.
+ pattern: string or scalar string `Tensor`, regular expression to use,
+ see more details at https://github.com/google/re2/wiki/Syntax
+ rewrite: string or scalar string `Tensor`, value to use in match
+ replacement, supports backslash-escaped digits (\1 to \9) can be to insert
+ text matching corresponding parenthesized group.
+ replace_global: `bool`, if `True` replace all non-overlapping matches,
+ else replace only the first match.
+
+ Returns:
+ string `Tensor` of the same shape as `source` with specified replacements.
+ """
+ # TODO(b/112455102): Remove compat.forward_compatible once past the horizon.
+ if not compat.forward_compatible(2018, 10, 10):
+ return gen_string_ops.regex_replace(
+ input=source, pattern=pattern,
+ rewrite=rewrite, replace_global=replace_global)
+ if (isinstance(pattern, util_compat.bytes_or_text_types) and
+ isinstance(rewrite, util_compat.bytes_or_text_types)):
+ # When `pattern` and `rewrite` are static through the life of the op we can
+ # use a version which performs the expensive regex compilation once at
+ # creation time.
+ return gen_string_ops.static_regex_replace(
+ input=source, pattern=pattern,
+ rewrite=rewrite, replace_global=replace_global)
+ return gen_string_ops.regex_replace(
+ input=source, pattern=pattern,
+ rewrite=rewrite, replace_global=replace_global)
+
+
@tf_export("string_split")
def string_split(source, delimiter=" ", skip_empty=True): # pylint: disable=invalid-name
"""Split elements of `source` based on `delimiter` into a `SparseTensor`.
diff --git a/tensorflow/python/ops/summary_op_util.py b/tensorflow/python/ops/summary_op_util.py
index a793f634bd..b382c3b7ce 100644
--- a/tensorflow/python/ops/summary_op_util.py
+++ b/tensorflow/python/ops/summary_op_util.py
@@ -23,7 +23,7 @@ import re
from tensorflow.python.framework import ops
from tensorflow.python.platform import tf_logging
-from tensorflow.python.training import distribute
+from tensorflow.python.training import distribution_strategy_context
def collect(val, collections, default_collections):
@@ -49,7 +49,7 @@ def skip_summary():
# TODO(priyag): Add a new optional argument that will provide multiple
# alternatives to override default behavior. (e.g. run on last tower,
# compute sum or mean across towers).
- tower_context = distribute.get_tower_context()
+ tower_context = distribution_strategy_context.get_tower_context()
return tower_context and tower_context.tower_id > 0
diff --git a/tensorflow/python/ops/summary_ops_v2.py b/tensorflow/python/ops/summary_ops_v2.py
index 00150fe688..94c7d88b5c 100644
--- a/tensorflow/python/ops/summary_ops_v2.py
+++ b/tensorflow/python/ops/summary_ops_v2.py
@@ -110,8 +110,8 @@ class SummaryWriter(object):
"""Encapsulates a stateful summary writer resource.
See also:
- - @{tf.contrib.summary.create_file_writer}
- - @{tf.contrib.summary.create_db_writer}
+ - `tf.contrib.summary.create_file_writer`
+ - `tf.contrib.summary.create_db_writer`
"""
def __init__(self, resource, init_op_fn):
@@ -174,22 +174,22 @@ def initialize(
"""Initializes summary writing for graph execution mode.
This helper method provides a higher-level alternative to using
- @{tf.contrib.summary.summary_writer_initializer_op} and
- @{tf.contrib.summary.graph}.
+ `tf.contrib.summary.summary_writer_initializer_op` and
+ `tf.contrib.summary.graph`.
- Most users will also want to call @{tf.train.create_global_step}
+ Most users will also want to call `tf.train.create_global_step`
which can happen before or after this function is called.
Args:
- graph: A @{tf.Graph} or @{tf.GraphDef} to output to the writer.
+ graph: A `tf.Graph` or `tf.GraphDef` to output to the writer.
This function will not write the default graph by default. When
writing to an event log file, the associated step will be zero.
- session: So this method can call @{tf.Session.run}. This defaults
- to @{tf.get_default_session}.
+ session: So this method can call `tf.Session.run`. This defaults
+ to `tf.get_default_session`.
Raises:
RuntimeError: If the current thread has no default
- @{tf.contrib.summary.SummaryWriter}.
+ `tf.contrib.summary.SummaryWriter`.
ValueError: If session wasn't passed and no default session.
"""
if context.executing_eagerly():
@@ -278,10 +278,10 @@ def create_db_writer(db_uri,
Experiment will not be associated with a User. Must be valid as
both a DNS label and Linux username.
name: Shared name for this SummaryWriter resource stored to default
- @{tf.Graph}.
+ `tf.Graph`.
Returns:
- A @{tf.contrib.summary.SummaryWriter} instance.
+ A `tf.contrib.summary.SummaryWriter` instance.
"""
with ops.device("cpu:0"):
if experiment_name is None:
@@ -328,7 +328,7 @@ def _nothing():
def all_summary_ops():
"""Graph-mode only. Returns all summary ops.
- Please note this excludes @{tf.contrib.summary.graph} ops.
+ Please note this excludes `tf.contrib.summary.graph` ops.
Returns:
The summary ops.
@@ -410,20 +410,20 @@ def generic(name, tensor, metadata=None, family=None, step=None):
def scalar(name, tensor, family=None, step=None):
"""Writes a scalar summary if possible.
- Unlike @{tf.contrib.summary.generic} this op may change the dtype
+ Unlike `tf.contrib.summary.generic` this op may change the dtype
depending on the writer, for both practical and efficiency concerns.
Args:
name: An arbitrary name for this summary.
- tensor: A @{tf.Tensor} Must be one of the following types:
+ tensor: A `tf.Tensor` Must be one of the following types:
`float32`, `float64`, `int32`, `int64`, `uint8`, `int16`,
`int8`, `uint16`, `half`, `uint32`, `uint64`.
family: Optional, the summary's family.
step: The `int64` monotonic step variable, which defaults
- to @{tf.train.get_global_step}.
+ to `tf.train.get_global_step`.
Returns:
- The created @{tf.Operation} or a @{tf.no_op} if summary writing has
+ The created `tf.Operation` or a `tf.no_op` if summary writing has
not been enabled for this context.
"""
@@ -494,31 +494,31 @@ def graph(param, step=None, name=None):
"""Writes a TensorFlow graph to the summary interface.
The graph summary is, strictly speaking, not a summary. Conditions
- like @{tf.contrib.summary.never_record_summaries} do not apply. Only
+ like `tf.contrib.summary.never_record_summaries` do not apply. Only
a single graph can be associated with a particular run. If multiple
graphs are written, then only the last one will be considered by
TensorBoard.
When not using eager execution mode, the user should consider passing
- the `graph` parameter to @{tf.contrib.summary.initialize} instead of
+ the `graph` parameter to `tf.contrib.summary.initialize` instead of
calling this function. Otherwise special care needs to be taken when
using the graph to record the graph.
Args:
- param: A @{tf.Tensor} containing a serialized graph proto. When
+ param: A `tf.Tensor` containing a serialized graph proto. When
eager execution is enabled, this function will automatically
- coerce @{tf.Graph}, @{tf.GraphDef}, and string types.
+ coerce `tf.Graph`, `tf.GraphDef`, and string types.
step: The global step variable. This doesn't have useful semantics
for graph summaries, but is used anyway, due to the structure of
event log files. This defaults to the global step.
name: A name for the operation (optional).
Returns:
- The created @{tf.Operation} or a @{tf.no_op} if summary writing has
+ The created `tf.Operation` or a `tf.no_op` if summary writing has
not been enabled for this context.
Raises:
- TypeError: If `param` isn't already a @{tf.Tensor} in graph mode.
+ TypeError: If `param` isn't already a `tf.Tensor` in graph mode.
"""
if not context.executing_eagerly() and not isinstance(param, ops.Tensor):
raise TypeError("graph() needs a tf.Tensor (e.g. tf.placeholder) in graph "
@@ -539,21 +539,21 @@ _graph = graph # for functions with a graph parameter
def import_event(tensor, name=None):
- """Writes a @{tf.Event} binary proto.
+ """Writes a `tf.Event` binary proto.
When using create_db_writer(), this can be used alongside
- @{tf.TFRecordReader} to load event logs into the database. Please
+ `tf.TFRecordReader` to load event logs into the database. Please
note that this is lower level than the other summary functions and
will ignore any conditions set by methods like
- @{tf.contrib.summary.should_record_summaries}.
+ `tf.contrib.summary.should_record_summaries`.
Args:
- tensor: A @{tf.Tensor} of type `string` containing a serialized
- @{tf.Event} proto.
+ tensor: A `tf.Tensor` of type `string` containing a serialized
+ `tf.Event` proto.
name: A name for the operation (optional).
Returns:
- The created @{tf.Operation}.
+ The created `tf.Operation`.
"""
return gen_summary_ops.import_event(
context.context().summary_writer_resource, tensor, name=name)
@@ -565,13 +565,13 @@ def flush(writer=None, name=None):
This operation blocks until that finishes.
Args:
- writer: The @{tf.contrib.summary.SummaryWriter} resource to flush.
+ writer: The `tf.contrib.summary.SummaryWriter` resource to flush.
The thread default will be used if this parameter is None.
- Otherwise a @{tf.no_op} is returned.
+ Otherwise a `tf.no_op` is returned.
name: A name for the operation (optional).
Returns:
- The created @{tf.Operation}.
+ The created `tf.Operation`.
"""
if writer is None:
writer = context.context().summary_writer_resource
@@ -593,7 +593,7 @@ def eval_dir(model_dir, name=None):
def create_summary_file_writer(*args, **kwargs):
- """Please use @{tf.contrib.summary.create_file_writer}."""
+ """Please use `tf.contrib.summary.create_file_writer`."""
logging.warning("Deprecation Warning: create_summary_file_writer was renamed "
"to create_file_writer")
return create_file_writer(*args, **kwargs)
diff --git a/tensorflow/python/ops/template.py b/tensorflow/python/ops/template.py
index da9b64fe34..e7ad261615 100644
--- a/tensorflow/python/ops/template.py
+++ b/tensorflow/python/ops/template.py
@@ -128,7 +128,7 @@ def make_template(name_, func_, create_scope_now_=False, unique_name_=None,
template of the same scope/unique_name already exists and reuse is false,
an error is raised. Defaults to None.
custom_getter_: Optional custom getter for variables used in `func_`. See
- the @{tf.get_variable} `custom_getter` documentation for
+ the `tf.get_variable` `custom_getter` documentation for
more information.
**kwargs: Keyword arguments to apply to `func_`.
@@ -176,7 +176,7 @@ def make_template_internal(name_,
template of the same scope/unique_name already exists and reuse is false,
an error is raised. Defaults to None. If executing eagerly, must be None.
custom_getter_: Optional custom getter for variables used in `func_`. See
- the @{tf.get_variable} `custom_getter` documentation for
+ the `tf.get_variable` `custom_getter` documentation for
more information.
create_graph_function_: When True, `func_` will be executed as a graph
function. This implies that `func_` must satisfy the properties that
diff --git a/tensorflow/python/ops/variable_scope.py b/tensorflow/python/ops/variable_scope.py
index aca44bcd44..46bcd68f1a 100644
--- a/tensorflow/python/ops/variable_scope.py
+++ b/tensorflow/python/ops/variable_scope.py
@@ -42,6 +42,7 @@ from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import function_utils
from tensorflow.python.util import tf_contextlib
+from tensorflow.python.util import tf_inspect
from tensorflow.python.util.tf_export import tf_export
__all__ = [
@@ -314,13 +315,13 @@ class _VariableStore(object):
use when doing asynchronous distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
Returns:
The created or existing `Variable` (or `PartitionedVariable`, if a
@@ -837,9 +838,6 @@ class _VariableStore(object):
raise ValueError("Variable %s does not exist, or was not created with "
"tf.get_variable(). Did you mean to set "
"reuse=tf.AUTO_REUSE in VarScope?" % name)
- if not shape.is_fully_defined() and not initializing_from_value:
- raise ValueError("Shape of a new variable (%s) must be fully defined, "
- "but instead was %s." % (name, shape))
# Create the tensor to initialize the variable with default value.
if initializer is None:
@@ -854,8 +852,17 @@ class _VariableStore(object):
# Instantiate initializer if provided initializer is a type object.
if isinstance(initializer, type(init_ops.Initializer)):
initializer = initializer(dtype=dtype)
- init_val = lambda: initializer( # pylint: disable=g-long-lambda
- shape.as_list(), dtype=dtype, partition_info=partition_info)
+ if shape and shape.is_fully_defined():
+ init_val = lambda: initializer( # pylint: disable=g-long-lambda
+ shape.as_list(), dtype=dtype, partition_info=partition_info)
+ elif not tf_inspect.getargspec(initializer).args:
+ init_val = initializer
+ else:
+ raise ValueError("You can only pass an initializer function that"
+ "expects no arguments to its callable when the "
+ "shape is not fully defined. The given initializer "
+ "function expects the following args %s" %
+ tf_inspect.getargspec(initializer).args)
variable_dtype = dtype.base_dtype
# Create the variable.
@@ -1440,12 +1447,11 @@ def get_variable(name,
aggregation=aggregation)
-get_variable_or_local_docstring = (
- """%s
+get_variable_or_local_docstring = ("""%s
%sThis function prefixes the name with the current variable scope
and performs reuse checks. See the
-@{$variables$Variable Scope How To}
+[Variable Scope How To](https://tensorflow.org/guide/variables)
for an extensive description of how reusing works. Here is a basic example:
```python
@@ -1484,7 +1490,7 @@ Args:
unless validate_shape is False.
regularizer: A (Tensor -> Tensor or None) function; the result of
applying it on a newly created variable will be added to the collection
- @{tf.GraphKeys.REGULARIZATION_LOSSES} and can be used for regularization.
+ `tf.GraphKeys.REGULARIZATION_LOSSES` and can be used for regularization.
%scollections: List of graph collections keys to add the Variable to.
Defaults to `[%s]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
@@ -1895,8 +1901,8 @@ class variable_scope(object):
Variable scope allows you to create new variables and to share already created
ones while providing checks to not create or share by accident. For details,
- see the @{$variables$Variable Scope How To}, here we present only a few basic
- examples.
+ see the [Variable Scope How To](https://tensorflow.org/guide/variables), here
+ we present only a few basic examples.
Simple example of how to create a new variable:
@@ -2445,13 +2451,13 @@ def variable_creator_scope(variable_creator):
use_resource: if True, a ResourceVariable is always created.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
This set may grow over time, so it's important the signature of creators is as
mentioned above.
diff --git a/tensorflow/python/ops/variables.py b/tensorflow/python/ops/variables.py
index fc00ce68ae..7a28615ba9 100644
--- a/tensorflow/python/ops/variables.py
+++ b/tensorflow/python/ops/variables.py
@@ -135,7 +135,7 @@ class VariableMetaclass(type):
@tf_export("Variable")
class Variable(six.with_metaclass(VariableMetaclass,
checkpointable.CheckpointableBase)):
- """See the @{$variables$Variables How To} for a high level overview.
+ """See the [Variables Guide](https://tensorflow.org/guide/variables).
A variable maintains state in the graph across calls to `run()`. You add a
variable to the graph by constructing an instance of the class `Variable`.
@@ -320,13 +320,13 @@ class Variable(six.with_metaclass(VariableMetaclass,
a resource variable is always created.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
- @{tf.VariableSynchronization}. By default the synchronization is set to
+ `tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
- @{tf.VariableAggregation}.
+ `tf.VariableAggregation`.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
@@ -388,7 +388,7 @@ class Variable(six.with_metaclass(VariableMetaclass,
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
- passed, the default session is used. See @{tf.Session} for more
+ passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
@@ -551,7 +551,7 @@ class Variable(six.with_metaclass(VariableMetaclass,
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
- passed, the default session is used. See @{tf.Session} for more
+ passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
@@ -1106,7 +1106,7 @@ class RefVariable(Variable):
def _AsTensor(self): # pylint: disable=invalid-name
"""Converts this variable to a Tensor.
- See @{tf.Variable.value}.
+ See `tf.Variable.value`.
Returns:
A `Tensor` containing the value of the variable.
@@ -1163,7 +1163,7 @@ class RefVariable(Variable):
Returns is a `Tensor` which holds a reference to the variable. You can
assign a new value to the variable by passing the tensor to an assign op.
- See @{tf.Variable.value} if you want to get the value of the
+ See `tf.Variable.value` if you want to get the value of the
variable.
Returns:
@@ -1191,7 +1191,7 @@ class RefVariable(Variable):
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
- passed, the default session is used. See @{tf.Session} for more
+ passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
@@ -1386,7 +1386,7 @@ class RefVariable(Variable):
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
- passed, the default session is used. See @{tf.Session} for more
+ passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
@@ -1917,15 +1917,10 @@ class PartitionedVariable(object):
def as_tensor(self):
"""Returns the overall concatenated value as a `Tensor`.
- The returned tensor will not inherit the control dependencies from the scope
- where the value is used, which is similar to getting the value of
- `Variable`.
-
Returns:
`Tensor` containing the concatenated value.
"""
- with ops.control_dependencies(None):
- return self._concat()
+ return self._concat()
@staticmethod
def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False):
@@ -1979,7 +1974,7 @@ def global_variables(scope=None):
This convenience function returns the contents of that collection.
An alternative to global variables are local variables. See
- @{tf.local_variables}
+ `tf.local_variables`
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
@@ -2032,7 +2027,7 @@ def local_variables(scope=None):
This convenience function returns the contents of that collection.
An alternative to local variables are global variables. See
- @{tf.global_variables}
+ `tf.global_variables`
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
diff --git a/tensorflow/python/platform/test.py b/tensorflow/python/platform/test.py
index 9ffb48c4a5..5dc4037d62 100644
--- a/tensorflow/python/platform/test.py
+++ b/tensorflow/python/platform/test.py
@@ -15,7 +15,7 @@
"""Testing.
-See the @{$python/test} guide.
+See the [Testing](https://tensorflow.org/api_guides/python/test) guide.
Note: `tf.test.mock` is an alias to the python `mock` or `unittest.mock`
depending on the python version.
diff --git a/tensorflow/python/saved_model/BUILD b/tensorflow/python/saved_model/BUILD
index 076f2d8760..7a37eda5ea 100644
--- a/tensorflow/python/saved_model/BUILD
+++ b/tensorflow/python/saved_model/BUILD
@@ -62,6 +62,7 @@ py_library(
srcs_version = "PY2AND3",
deps = [
":constants",
+ ":utils",
"//tensorflow/core:protos_all_py",
"//tensorflow/python:framework_for_generated_wrappers",
"//tensorflow/python:lib",
@@ -81,6 +82,7 @@ py_library(
srcs_version = "PY2AND3",
deps = [
":constants",
+ ":utils",
"//tensorflow/core:protos_all_py",
"//tensorflow/python:framework_for_generated_wrappers",
"//tensorflow/python:lib",
@@ -187,8 +189,10 @@ py_library(
],
srcs_version = "PY2AND3",
deps = [
+ ":constants",
"//tensorflow/core:protos_all_py",
"//tensorflow/python:framework_for_generated_wrappers",
+ "//tensorflow/python:lib",
"//tensorflow/python:sparse_tensor",
"//tensorflow/python:util",
],
diff --git a/tensorflow/python/saved_model/builder_impl.py b/tensorflow/python/saved_model/builder_impl.py
index 8c985a7c2f..8e7f123a85 100644
--- a/tensorflow/python/saved_model/builder_impl.py
+++ b/tensorflow/python/saved_model/builder_impl.py
@@ -32,6 +32,7 @@ from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging
from tensorflow.python.saved_model import constants
+from tensorflow.python.saved_model import utils_impl as saved_model_utils
from tensorflow.python.training import saver as tf_saver
from tensorflow.python.util import compat
from tensorflow.python.util.deprecation import deprecated_args
@@ -112,12 +113,8 @@ class SavedModelBuilder(object):
tf_logging.info("No assets to write.")
return
- assets_destination_dir = os.path.join(
- compat.as_bytes(self._export_dir),
- compat.as_bytes(constants.ASSETS_DIRECTORY))
-
- if not file_io.file_exists(assets_destination_dir):
- file_io.recursive_create_dir(assets_destination_dir)
+ assets_destination_dir = saved_model_utils.get_or_create_assets_dir(
+ self._export_dir)
# Copy each asset from source path to destination path.
for asset_basename, asset_source_filepath in asset_filename_map.items():
@@ -409,16 +406,8 @@ class SavedModelBuilder(object):
# Add assets and ops
self._add_collections(assets_collection, main_op, None)
- # Create the variables sub-directory, if it does not exist.
- variables_dir = os.path.join(
- compat.as_text(self._export_dir),
- compat.as_text(constants.VARIABLES_DIRECTORY))
- if not file_io.file_exists(variables_dir):
- file_io.recursive_create_dir(variables_dir)
-
- variables_path = os.path.join(
- compat.as_text(variables_dir),
- compat.as_text(constants.VARIABLES_FILENAME))
+ saved_model_utils.get_or_create_variables_dir(self._export_dir)
+ variables_path = saved_model_utils.get_variables_path(self._export_dir)
saver = self._maybe_create_saver(saver)
diff --git a/tensorflow/python/saved_model/loader_impl.py b/tensorflow/python/saved_model/loader_impl.py
index 16077f52fa..e8536108e8 100644
--- a/tensorflow/python/saved_model/loader_impl.py
+++ b/tensorflow/python/saved_model/loader_impl.py
@@ -31,6 +31,7 @@ from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging
from tensorflow.python.saved_model import constants
+from tensorflow.python.saved_model import utils_impl as saved_model_utils
from tensorflow.python.training import saver as tf_saver
from tensorflow.python.util import compat
from tensorflow.python.util.tf_export import tf_export
@@ -203,10 +204,7 @@ class SavedModelLoader(object):
variables to be loaded are located.
"""
self._export_dir = export_dir
- self._variables_path = os.path.join(
- compat.as_bytes(export_dir),
- compat.as_bytes(constants.VARIABLES_DIRECTORY),
- compat.as_bytes(constants.VARIABLES_FILENAME))
+ self._variables_path = saved_model_utils.get_variables_path(export_dir)
self._saved_model = _parse_saved_model(export_dir)
@property
diff --git a/tensorflow/python/saved_model/utils_impl.py b/tensorflow/python/saved_model/utils_impl.py
index cddce29a08..20ff34fd8e 100644
--- a/tensorflow/python/saved_model/utils_impl.py
+++ b/tensorflow/python/saved_model/utils_impl.py
@@ -18,10 +18,15 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import os
+
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
+from tensorflow.python.lib.io import file_io
+from tensorflow.python.saved_model import constants
+from tensorflow.python.util import compat
from tensorflow.python.util.tf_export import tf_export
@@ -84,3 +89,45 @@ def get_tensor_from_tensor_info(tensor_info, graph=None, import_scope=None):
_get_tensor(tensor_info.coo_sparse.dense_shape_tensor_name))
else:
raise ValueError("Invalid TensorInfo.encoding: %s" % encoding)
+
+
+# Path helpers.
+
+
+def get_or_create_variables_dir(export_dir):
+ """Return variables sub-directory, or create one if it doesn't exist."""
+ variables_dir = get_variables_dir(export_dir)
+ if not file_io.file_exists(variables_dir):
+ file_io.recursive_create_dir(variables_dir)
+ return variables_dir
+
+
+def get_variables_dir(export_dir):
+ """Return variables sub-directory in the SavedModel."""
+ return os.path.join(
+ compat.as_text(export_dir),
+ compat.as_text(constants.VARIABLES_DIRECTORY))
+
+
+def get_variables_path(export_dir):
+ """Return the variables path, used as the prefix for checkpoint files."""
+ return os.path.join(
+ compat.as_text(get_variables_dir(export_dir)),
+ compat.as_text(constants.VARIABLES_FILENAME))
+
+
+def get_or_create_assets_dir(export_dir):
+ """Return assets sub-directory, or create one if it doesn't exist."""
+ assets_destination_dir = get_assets_dir(export_dir)
+
+ if not file_io.file_exists(assets_destination_dir):
+ file_io.recursive_create_dir(assets_destination_dir)
+
+ return assets_destination_dir
+
+
+def get_assets_dir(export_dir):
+ """Return path to asset directory in the SavedModel."""
+ return os.path.join(
+ compat.as_text(export_dir),
+ compat.as_text(constants.ASSETS_DIRECTORY))
diff --git a/tensorflow/python/summary/summary.py b/tensorflow/python/summary/summary.py
index 1421d2772f..fbae2b77fa 100644
--- a/tensorflow/python/summary/summary.py
+++ b/tensorflow/python/summary/summary.py
@@ -15,7 +15,7 @@
"""Tensor summaries for exporting information about a model.
-See the @{$python/summary} guide.
+See the [Summary](https://tensorflow.org/api_guides/python/summary) guide.
"""
from __future__ import absolute_import
@@ -268,7 +268,7 @@ def merge(inputs, collections=None, name=None):
@compatibility(eager)
Not compatible with eager execution. To write TensorBoard
summaries under eager execution, use `tf.contrib.summary` instead.
- @end_compatbility
+ @end_compatibility
"""
# pylint: enable=line-too-long
if _context.executing_eagerly():
@@ -285,7 +285,7 @@ def merge(inputs, collections=None, name=None):
@tf_export('summary.merge_all')
-def merge_all(key=_ops.GraphKeys.SUMMARIES, scope=None):
+def merge_all(key=_ops.GraphKeys.SUMMARIES, scope=None, name=None):
"""Merges all summaries collected in the default graph.
Args:
@@ -304,7 +304,7 @@ def merge_all(key=_ops.GraphKeys.SUMMARIES, scope=None):
@compatibility(eager)
Not compatible with eager execution. To write TensorBoard
summaries under eager execution, use `tf.contrib.summary` instead.
- @end_compatbility
+ @end_compatibility
"""
if _context.executing_eagerly():
raise RuntimeError(
@@ -314,7 +314,7 @@ def merge_all(key=_ops.GraphKeys.SUMMARIES, scope=None):
if not summary_ops:
return None
else:
- return merge(summary_ops)
+ return merge(summary_ops, name=name)
@tf_export('summary.get_summary_description')
@@ -336,7 +336,7 @@ def get_summary_description(node_def):
@compatibility(eager)
Not compatible with eager execution. To write TensorBoard
summaries under eager execution, use `tf.contrib.summary` instead.
- @end_compatbility
+ @end_compatibility
"""
if node_def.op != 'TensorSummary':
diff --git a/tensorflow/python/summary/writer/writer.py b/tensorflow/python/summary/writer/writer.py
index 60e96ee947..16b8626476 100644
--- a/tensorflow/python/summary/writer/writer.py
+++ b/tensorflow/python/summary/writer/writer.py
@@ -104,8 +104,8 @@ class SummaryToEventTransformer(object):
and adds it to the event file.
You can pass the result of evaluating any summary op, using
- @{tf.Session.run} or
- @{tf.Tensor.eval}, to this
+ `tf.Session.run` or
+ `tf.Tensor.eval`, to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
@@ -352,7 +352,7 @@ class FileWriter(SummaryToEventTransformer):
@compatibility(eager)
`FileWriter` is not compatible with eager execution. To write TensorBoard
summaries under eager execution, use `tf.contrib.summary` instead.
- @end_compatbility
+ @end_compatibility
"""
if context.executing_eagerly():
raise RuntimeError(
diff --git a/tensorflow/python/tools/BUILD b/tensorflow/python/tools/BUILD
index 222f856511..01d43e09d1 100644
--- a/tensorflow/python/tools/BUILD
+++ b/tensorflow/python/tools/BUILD
@@ -114,6 +114,12 @@ py_library(
],
)
+py_library(
+ name = "component_api_helper",
+ srcs = ["component_api_helper.py"],
+ srcs_version = "PY2AND3",
+)
+
py_binary(
name = "strip_unused",
srcs = ["strip_unused.py"],
diff --git a/tensorflow/python/tools/api/generator/api_init_files.bzl b/tensorflow/python/tools/api/generator/api_init_files.bzl
index 64f0469482..7001e566ce 100644
--- a/tensorflow/python/tools/api/generator/api_init_files.bzl
+++ b/tensorflow/python/tools/api/generator/api_init_files.bzl
@@ -25,7 +25,6 @@ TENSORFLOW_API_INIT_FILES = [
"keras/applications/inception_resnet_v2/__init__.py",
"keras/applications/inception_v3/__init__.py",
"keras/applications/mobilenet/__init__.py",
- "keras/applications/mobilenet_v2/__init__.py",
"keras/applications/nasnet/__init__.py",
"keras/applications/resnet50/__init__.py",
"keras/applications/vgg16/__init__.py",
diff --git a/tensorflow/python/tools/api/generator/api_init_files_v1.bzl b/tensorflow/python/tools/api/generator/api_init_files_v1.bzl
index bc2f3516d1..73d11199d9 100644
--- a/tensorflow/python/tools/api/generator/api_init_files_v1.bzl
+++ b/tensorflow/python/tools/api/generator/api_init_files_v1.bzl
@@ -25,7 +25,6 @@ TENSORFLOW_API_INIT_FILES_V1 = [
"keras/applications/inception_resnet_v2/__init__.py",
"keras/applications/inception_v3/__init__.py",
"keras/applications/mobilenet/__init__.py",
- "keras/applications/mobilenet_v2/__init__.py",
"keras/applications/nasnet/__init__.py",
"keras/applications/resnet50/__init__.py",
"keras/applications/vgg16/__init__.py",
diff --git a/tensorflow/python/tools/component_api_helper.py b/tensorflow/python/tools/component_api_helper.py
new file mode 100644
index 0000000000..988ecc61f0
--- /dev/null
+++ b/tensorflow/python/tools/component_api_helper.py
@@ -0,0 +1,85 @@
+# 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.
+# ==============================================================================
+"""Helper functions to help integrate TensorFlow components into TF API.
+"""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import importlib
+import os
+
+
+def package_hook(parent_package_str, child_package_str, error_msg=None):
+ """Used to hook in an external package into the TensorFlow namespace.
+
+ Example usage:
+ ### tensorflow/__init__.py
+ from tensorflow.python.tools import component_api_helper
+ component_api_helper.package_hook(
+ 'tensorflow', 'tensorflow_estimator.python')
+ component_api_helper(
+ 'tensorflow.contrib', 'tensorflow_estimator.contrib.python')
+ del component_api_helper
+
+ TODO(mikecase): This function has a minor issue, where if the child package
+ does not exist alone in its directory, sibling packages to it will also be
+ accessible from the parent. This is because we just add
+ `child_pkg.__file__/..` to the subpackage search path. This should not be
+ a big issue because of how our API generation scripts work (the child package
+ we are hooking up should always be alone). But there might be a better way
+ of doing this.
+
+ Args:
+ parent_package_str: Parent package name as a string such as 'tensorflow' or
+ 'tensorflow.contrib'. This will become the parent package for the
+ component package being hooked in.
+ child_package_str: Child package name as a string such as
+ 'tensorflow_estimator.python'. This package will be added as a subpackage
+ of the parent.
+ error_msg: Message to print if child package cannot be found.
+ """
+ parent_pkg = importlib.import_module(parent_package_str)
+ try:
+ child_pkg = importlib.import_module(child_package_str)
+ except ImportError:
+ if error_msg:
+ print(error_msg)
+ return
+
+ def set_child_as_subpackage():
+ """Sets child package as a subpackage of parent package.
+
+ Will allow the following import statement to work.
+ >>> import parent.child
+ """
+ child_pkg_path = [os.path.join(os.path.dirname(child_pkg.__file__), "..")]
+ try:
+ parent_pkg.__path__ += child_pkg_path
+ except AttributeError:
+ parent_pkg.__path__ = child_pkg_path
+
+ def set_child_as_attr():
+ """Sets child package as a attr of the parent package.
+
+ Will allow for the following.
+ >>> import parent
+ >>> parent.child
+ """
+ child_pkg_attr_name = child_pkg.__name__.split(".")[-1]
+ setattr(parent_pkg, child_pkg_attr_name, child_pkg)
+
+ set_child_as_subpackage()
+ set_child_as_attr()
diff --git a/tensorflow/python/tools/freeze_graph.py b/tensorflow/python/tools/freeze_graph.py
index 130fe70beb..c7f414c5dc 100644
--- a/tensorflow/python/tools/freeze_graph.py
+++ b/tensorflow/python/tools/freeze_graph.py
@@ -59,6 +59,21 @@ from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import saver as saver_lib
+def _has_no_variables(sess):
+ """Determines if the graph has any variables.
+
+ Args:
+ sess: TensorFlow Session.
+
+ Returns:
+ Bool.
+ """
+ for op in sess.graph.get_operations():
+ if op.type.startswith("Variable") or op.type.endswith("VariableOp"):
+ return False
+ return True
+
+
def freeze_graph_with_def_protos(input_graph_def,
input_saver_def,
input_checkpoint,
@@ -152,6 +167,11 @@ def freeze_graph_with_def_protos(input_graph_def,
"from checkpoint files. Please pass in a SavedModel using "
"the flag --input_saved_model_dir.")
return -1
+ # Models that have been frozen previously do not contain Variables.
+ elif _has_no_variables(sess):
+ print("No variables were found in this model. It is likely the model "
+ "was frozen previously. You cannot freeze a graph twice.")
+ return 0
else:
raise e
diff --git a/tensorflow/python/training/adagrad.py b/tensorflow/python/training/adagrad.py
index 6778f3c735..3508b98475 100644
--- a/tensorflow/python/training/adagrad.py
+++ b/tensorflow/python/training/adagrad.py
@@ -70,20 +70,24 @@ class AdagradOptimizer(optimizer.Optimizer):
def _create_slots(self, var_list):
for v in var_list:
- with ops.colocate_with(v):
- dtype = v.dtype.base_dtype
- if v.get_shape().is_fully_defined():
- init = init_ops.constant_initializer(self._initial_accumulator_value,
- dtype=dtype)
- else:
- # Use a Tensor instead of initializer if variable does not have static
- # shape.
- init_constant = gen_array_ops.fill(array_ops.shape(v),
- self._initial_accumulator_value)
- init = math_ops.cast(init_constant, dtype)
+ dtype = v.dtype.base_dtype
+ if v.get_shape().is_fully_defined():
+ init = init_ops.constant_initializer(self._initial_accumulator_value,
+ dtype=dtype)
+ else:
+ init = self._init_constant_op(v, dtype)
self._get_or_make_slot_with_initializer(v, init, v.get_shape(), dtype,
"accumulator", self._name)
+ def _init_constant_op(self, v, dtype):
+ def init():
+ # Use a Tensor instead of initializer if variable does not have
+ # static shape.
+ init_constant = gen_array_ops.fill(array_ops.shape(v),
+ self._initial_accumulator_value)
+ return math_ops.cast(init_constant, dtype)
+ return init
+
def _prepare(self):
learning_rate = self._call_if_callable(self._learning_rate)
self._learning_rate_tensor = ops.convert_to_tensor(
diff --git a/tensorflow/python/training/adagrad_test.py b/tensorflow/python/training/adagrad_test.py
index c9aec33d09..4e634fff84 100644
--- a/tensorflow/python/training/adagrad_test.py
+++ b/tensorflow/python/training/adagrad_test.py
@@ -302,6 +302,39 @@ class AdagradOptimizerTest(test.TestCase):
# Creating optimizer should cause no exception.
adagrad.AdagradOptimizer(3.0, initial_accumulator_value=0.1)
+ def testDynamicShapeVariableWithCallableInit(self):
+ var0 = variable_scope.get_variable("var0",
+ initializer=constant_op.constant(1.),
+ validate_shape=False)
+ self.assertFalse(var0.shape.is_fully_defined())
+
+ grads0 = constant_op.constant(0.1, dtype=dtypes.float32)
+ learning_rate = lambda: 3.0
+
+ ada_opt = adagrad.AdagradOptimizer(
+ learning_rate, initial_accumulator_value=0.1, use_locking=True)
+
+ if not context.executing_eagerly():
+ ada_update = ada_opt.apply_gradients(
+ zip([grads0], [var0]))
+ self.evaluate(variables.global_variables_initializer())
+
+ # Fetch params to validate initial values
+ v0_val = self.evaluate([var0])
+ self.assertAllClose([1.0], v0_val)
+
+ # Run 3 steps of adagrad
+ for _ in range(3):
+ if not context.executing_eagerly():
+ self.evaluate(ada_update)
+ else:
+ ada_opt.apply_gradients(zip([grads0], [var0]))
+
+ # Validate updated params
+ v0_val = self.evaluate([var0])
+ self.assertAllCloseAccordingToType(
+ np.array([-1.6026098728179932]), v0_val)
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/training/basic_session_run_hooks.py b/tensorflow/python/training/basic_session_run_hooks.py
index 4e8e505549..76625624e4 100644
--- a/tensorflow/python/training/basic_session_run_hooks.py
+++ b/tensorflow/python/training/basic_session_run_hooks.py
@@ -28,9 +28,12 @@ from tensorflow.core.framework.summary_pb2 import Summary
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.util.event_pb2 import SessionLog
from tensorflow.python.client import timeline
+from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import meta_graph
from tensorflow.python.framework import ops
+from tensorflow.python.ops import init_ops
+from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import session_run_hook
@@ -40,6 +43,10 @@ from tensorflow.python.training.summary_io import SummaryWriterCache
from tensorflow.python.util.tf_export import tf_export
+_HOOKS = "hooks"
+_STEPS_PER_RUN_VAR = "steps_per_run"
+
+
class _HookTimer(object):
"""Base timer for determining when Hooks should trigger.
@@ -255,6 +262,116 @@ class LoggingTensorHook(session_run_hook.SessionRunHook):
self._log_tensors(values)
+def get_or_create_steps_per_run_variable():
+ """Gets or creates the steps_per_run variable.
+
+ In Estimator, the user provided computation, the model_fn, is wrapped
+ inside a tf.while_loop for peak performance. The iterations of the loop are
+ specified by this variable, which adjusts its value on the CPU after each
+ device program execution and before the next execution.
+
+ The purpose of using a variable, rather than a constant, is to allow
+ Estimator adapt the device training iterations according to the final steps
+ specified by users. For example, if the user sets the steps_per_run as
+ 4 and steps as 10 in Estimator.train(), the steps_per_run
+ variable will have the following value before each training run.
+
+ - 1-st execution: steps_per_run = 4
+ - 2-nd execution: steps_per_run = 4
+ - 3-rd execution: steps_per_run = 2
+
+ As model_fn increases the global step once per train_op invocation, the global
+ step is 10 after all executions, matching the steps=10 inputs passed in by
+ users.
+
+ Returns:
+ A TF non-trainable resource variable.
+
+ Raises:
+ RuntimeError: If multi steps_per_run variables were found.
+ """
+ graph = ops.get_default_graph()
+ collection_name = "{}_{}".format(_HOOKS, _STEPS_PER_RUN_VAR)
+ steps_per_run_vars = graph.get_collection(collection_name)
+ if len(steps_per_run_vars) == 1:
+ return steps_per_run_vars[0]
+ elif len(steps_per_run_vars) > 1:
+ raise RuntimeError("Multiple steps_per_run_var in collection.")
+
+ with variable_scope.variable_scope(_HOOKS, reuse=variable_scope.AUTO_REUSE):
+ return variable_scope.get_variable(
+ _STEPS_PER_RUN_VAR,
+ initializer=init_ops.ones_initializer(),
+ shape=[],
+ dtype=dtypes.int32,
+ trainable=False,
+ collections=[collection_name, ops.GraphKeys.LOCAL_VARIABLES],
+ use_resource=True)
+
+
+class _MultiStepStopAtStepHook(session_run_hook.SessionRunHook):
+ """Hook that requests stop at a specified step."""
+
+ def __init__(self, num_steps=None, last_step=None, steps_per_run=1):
+ """Initializes a `MultiStepStopAtStepHook`.
+
+ This hook requests stop after either a number of steps have been
+ executed or a last step has been reached. Only one of the two options can be
+ specified.
+
+ if `num_steps` is specified, it indicates the number of steps to execute
+ after `begin()` is called. If instead `last_step` is specified, it
+ indicates the last step we want to execute, as passed to the `after_run()`
+ call.
+
+ In Estimator, the user provided computation, the model_fn, is wrapped
+ inside a tf.while_loop for peak performance. The steps_per_run variable
+ determines the number of iterations of the loop before returning to the CPU.
+
+ Args:
+ num_steps: Number of steps to execute.
+ last_step: Step after which to stop.
+ steps_per_run: Number of steps executed per run call.
+
+ Raises:
+ ValueError: If one of the arguments is invalid.
+ """
+ if num_steps is None and last_step is None:
+ raise ValueError("One of num_steps or last_step must be specified.")
+ if num_steps is not None and last_step is not None:
+ raise ValueError("Only one of num_steps or last_step can be specified.")
+ if steps_per_run is None or steps_per_run < 1:
+ raise ValueError("steps_per_run should be greater than 0")
+ self._num_steps = num_steps
+ self._last_step = last_step
+ self._steps_per_run = steps_per_run
+
+ def begin(self):
+ self._global_step_tensor = training_util.get_global_step()
+ if self._global_step_tensor is None:
+ raise RuntimeError("Global step should be created to use StopAtStepHook.")
+ self._steps_per_run_variable = get_or_create_steps_per_run_variable()
+
+ def _update_steps_per_run_variable(self, global_step, session):
+ steps = min(self._last_step - global_step, self._steps_per_run)
+ self._steps_per_run_variable.load(steps, session=session)
+
+ def after_create_session(self, session, coord):
+ global_step = session.run(self._global_step_tensor)
+ if self._last_step is None:
+ self._last_step = global_step + self._num_steps
+ self._update_steps_per_run_variable(global_step, session)
+
+ def after_run(self, run_context, run_values):
+ # Global step cannot be retrieved via SessionRunArgs and before_run due to
+ # race condition in hook execution.
+ global_step = run_context.session.run(self._global_step_tensor)
+ if global_step >= self._last_step:
+ run_context.request_stop()
+ else:
+ self._update_steps_per_run_variable(global_step, run_context.session)
+
+
@tf_export("train.StopAtStepHook")
class StopAtStepHook(session_run_hook.SessionRunHook):
"""Hook that requests stop at a specified step."""
diff --git a/tensorflow/python/training/checkpoint_management.py b/tensorflow/python/training/checkpoint_management.py
index aaddc015ed..85f2904318 100644
--- a/tensorflow/python/training/checkpoint_management.py
+++ b/tensorflow/python/training/checkpoint_management.py
@@ -19,16 +19,23 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import collections
import os.path
import re
+import time
from google.protobuf import text_format
from tensorflow.core.protobuf import saver_pb2
+from tensorflow.python.eager import context
from tensorflow.python.framework import errors
+from tensorflow.python.framework import ops
from tensorflow.python.lib.io import file_io
+from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
+from tensorflow.python.training import training_util
from tensorflow.python.training.checkpoint_state_pb2 import CheckpointState
+from tensorflow.python.util import compat
from tensorflow.python.util.tf_export import tf_export
@@ -51,7 +58,9 @@ def _GetCheckpointFilename(save_dir, latest_filename):
@tf_export("train.generate_checkpoint_state_proto")
def generate_checkpoint_state_proto(save_dir,
model_checkpoint_path,
- all_model_checkpoint_paths=None):
+ all_model_checkpoint_paths=None,
+ all_model_checkpoint_timestamps=None,
+ last_preserved_timestamp=None):
"""Generates a checkpoint state proto.
Args:
@@ -61,11 +70,20 @@ def generate_checkpoint_state_proto(save_dir,
checkpoints, sorted from oldest to newest. If this is a non-empty list,
the last element must be equal to model_checkpoint_path. These paths
are also saved in the CheckpointState proto.
-
+ all_model_checkpoint_timestamps: A list of floats, indicating the number of
+ seconds since the Epoch when each checkpoint was generated.
+ last_preserved_timestamp: A float, indicating the number of seconds since
+ the Epoch when the last preserved checkpoint was written, e.g. due to a
+ `keep_checkpoint_every_n_hours` parameter (see
+ `tf.contrib.checkpoint.CheckpointManager` for an implementation).
Returns:
CheckpointState proto with model_checkpoint_path and
all_model_checkpoint_paths updated to either absolute paths or
relative paths to the current save_dir.
+
+ Raises:
+ ValueError: If `all_model_checkpoint_timestamps` was provided but its length
+ does not match `all_model_checkpoint_paths`.
"""
if all_model_checkpoint_paths is None:
all_model_checkpoint_paths = []
@@ -76,6 +94,14 @@ def generate_checkpoint_state_proto(save_dir,
model_checkpoint_path)
all_model_checkpoint_paths.append(model_checkpoint_path)
+ if (all_model_checkpoint_timestamps
+ and (len(all_model_checkpoint_timestamps)
+ != len(all_model_checkpoint_paths))):
+ raise ValueError(
+ ("Checkpoint timestamps, if provided, must match checkpoint paths (got "
+ "paths %s and timestamps %s)")
+ % (all_model_checkpoint_paths, all_model_checkpoint_timestamps))
+
# Relative paths need to be rewritten to be relative to the "save_dir"
# if model_checkpoint_path already contains "save_dir".
if not os.path.isabs(save_dir):
@@ -88,7 +114,9 @@ def generate_checkpoint_state_proto(save_dir,
coord_checkpoint_proto = CheckpointState(
model_checkpoint_path=model_checkpoint_path,
- all_model_checkpoint_paths=all_model_checkpoint_paths)
+ all_model_checkpoint_paths=all_model_checkpoint_paths,
+ all_model_checkpoint_timestamps=all_model_checkpoint_timestamps,
+ last_preserved_timestamp=last_preserved_timestamp)
return coord_checkpoint_proto
@@ -97,7 +125,9 @@ def generate_checkpoint_state_proto(save_dir,
def update_checkpoint_state(save_dir,
model_checkpoint_path,
all_model_checkpoint_paths=None,
- latest_filename=None):
+ latest_filename=None,
+ all_model_checkpoint_timestamps=None,
+ last_preserved_timestamp=None):
"""Updates the content of the 'checkpoint' file.
This updates the checkpoint file containing a CheckpointState
@@ -112,7 +142,13 @@ def update_checkpoint_state(save_dir,
are also saved in the CheckpointState proto.
latest_filename: Optional name of the checkpoint file. Default to
'checkpoint'.
-
+ all_model_checkpoint_timestamps: Optional list of timestamps (floats,
+ seconds since the Epoch) indicating when the checkpoints in
+ `all_model_checkpoint_paths` were created.
+ last_preserved_timestamp: A float, indicating the number of seconds since
+ the Epoch when the last preserved checkpoint was written, e.g. due to a
+ `keep_checkpoint_every_n_hours` parameter (see
+ `tf.contrib.checkpoint.CheckpointManager` for an implementation).
Raises:
RuntimeError: If any of the model checkpoint paths conflict with the file
containing CheckpointSate.
@@ -122,14 +158,18 @@ def update_checkpoint_state(save_dir,
model_checkpoint_path=model_checkpoint_path,
all_model_checkpoint_paths=all_model_checkpoint_paths,
latest_filename=latest_filename,
- save_relative_paths=False)
+ save_relative_paths=False,
+ all_model_checkpoint_timestamps=all_model_checkpoint_timestamps,
+ last_preserved_timestamp=last_preserved_timestamp)
def update_checkpoint_state_internal(save_dir,
model_checkpoint_path,
all_model_checkpoint_paths=None,
latest_filename=None,
- save_relative_paths=False):
+ save_relative_paths=False,
+ all_model_checkpoint_timestamps=None,
+ last_preserved_timestamp=None):
"""Updates the content of the 'checkpoint' file.
This updates the checkpoint file containing a CheckpointState
@@ -146,6 +186,13 @@ def update_checkpoint_state_internal(save_dir,
'checkpoint'.
save_relative_paths: If `True`, will write relative paths to the checkpoint
state file.
+ all_model_checkpoint_timestamps: Optional list of timestamps (floats,
+ seconds since the Epoch) indicating when the checkpoints in
+ `all_model_checkpoint_paths` were created.
+ last_preserved_timestamp: A float, indicating the number of seconds since
+ the Epoch when the last preserved checkpoint was written, e.g. due to a
+ `keep_checkpoint_every_n_hours` parameter (see
+ `tf.contrib.checkpoint.CheckpointManager` for an implementation).
Raises:
RuntimeError: If any of the model checkpoint paths conflict with the file
@@ -168,12 +215,16 @@ def update_checkpoint_state_internal(save_dir,
ckpt = generate_checkpoint_state_proto(
save_dir,
rel_model_checkpoint_path,
- all_model_checkpoint_paths=rel_all_model_checkpoint_paths)
+ all_model_checkpoint_paths=rel_all_model_checkpoint_paths,
+ all_model_checkpoint_timestamps=all_model_checkpoint_timestamps,
+ last_preserved_timestamp=last_preserved_timestamp)
else:
ckpt = generate_checkpoint_state_proto(
save_dir,
model_checkpoint_path,
- all_model_checkpoint_paths=all_model_checkpoint_paths)
+ all_model_checkpoint_paths=all_model_checkpoint_paths,
+ all_model_checkpoint_timestamps=all_model_checkpoint_timestamps,
+ last_preserved_timestamp=last_preserved_timestamp)
if coord_checkpoint_filename == ckpt.model_checkpoint_path:
raise RuntimeError("Save path '%s' conflicts with path used for "
@@ -404,3 +455,227 @@ def meta_graph_filename(checkpoint_filename, meta_graph_suffix="meta"):
basename = re.sub(r"-[\d\?]+-of-\d+$", "", checkpoint_filename)
suffixed_filename = ".".join([basename, meta_graph_suffix])
return suffixed_filename
+
+
+# TODO(allenl): Allow tf.keras.Model instances in the constructor directly?
+class CheckpointManager(object):
+ """Deletes old checkpoints.
+
+ Example usage:
+ ```python
+ import tensorflow as tf
+ checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
+ manager = tf.contrib.checkpoint.CheckpointManager(
+ checkpoint, directory="/tmp/model", max_to_keep=5)
+ status = checkpoint.restore(manager.latest_checkpoint)
+ while True:
+ # train
+ manager.save()
+ ```
+
+ `CheckpointManager` preserves its own state across instantiations (see the
+ `__init__` documentation for details). Only one should be active in a
+ particular directory at a time.
+ """
+
+ def __init__(self, checkpoint, directory,
+ max_to_keep, keep_checkpoint_every_n_hours=None):
+ """Configure a `CheckpointManager` for use in `directory`.
+
+ If a `CheckpointManager` was previously used in `directory`, its
+ state will be restored. This includes the list of managed checkpoints and
+ the timestamp bookkeeping necessary to support
+ `keep_checkpoint_every_n_hours`. The behavior of the new `CheckpointManager`
+ will be the same as the previous `CheckpointManager`, including cleaning up
+ existing checkpoints if appropriate.
+
+ Checkpoints are only considered for deletion just after a new checkpoint has
+ been added. At that point, `max_to_keep` checkpoints will remain in an
+ "active set". Once a checkpoint is preserved by
+ `keep_checkpoint_every_n_hours` it will not be deleted by this
+ `CheckpointManager` or any future `CheckpointManager` instantiated in
+ `directory` (regardless of the new setting of
+ `keep_checkpoint_every_n_hours`). The `max_to_keep` checkpoints in the
+ active set may be deleted by this `CheckpointManager` or a future
+ `CheckpointManager` instantiated in `directory` (subject to its
+ `max_to_keep` and `keep_checkpoint_every_n_hours` settings).
+
+ Args:
+ checkpoint: The `tf.train.Checkpoint` instance to save and manage
+ checkpoints for.
+ directory: The path to a directory in which to write checkpoints. A
+ special file named "checkpoint" is also written to this directory (in a
+ human-readable text format) which contains the state of the
+ `CheckpointManager`.
+ max_to_keep: An integer, the number of checkpoints to keep. Unless
+ preserved by `keep_checkpoint_every_n_hours`, checkpoints will be
+ deleted from the active set, oldest first, until only `max_to_keep`
+ checkpoints remain.
+ keep_checkpoint_every_n_hours: Upon removal from the active set, a
+ checkpoint will be preserved if it has been at least
+ `keep_checkpoint_every_n_hours` since the last preserved checkpoint. The
+ default setting of `None` does not preserve any checkpoints in this way.
+
+ Raises:
+ ValueError: If `max_to_keep` is not a positive integer.
+ """
+ self._checkpoint = checkpoint
+ self._save_counter_assign = None
+ if not max_to_keep or max_to_keep < 0:
+ raise ValueError(
+ "Expected a positive integer for `max_to_max_to_keep`, got %d."
+ % (max_to_keep,))
+ self._max_to_keep = max_to_keep
+ self._keep_checkpoint_every_n_hours = keep_checkpoint_every_n_hours
+ self._directory = directory
+ self._checkpoint_prefix = os.path.join(directory, "ckpt")
+ recovered_state = get_checkpoint_state(directory)
+ current_clock = time.time()
+ self._maybe_delete = collections.OrderedDict()
+ if recovered_state is None:
+ self._latest_checkpoint = None
+ self._last_preserved_timestamp = current_clock
+ else:
+ self._latest_checkpoint = recovered_state.model_checkpoint_path
+ self._last_preserved_timestamp = recovered_state.last_preserved_timestamp
+ if current_clock < self._last_preserved_timestamp:
+ # Time seems to have reversed itself. In addition to this warning, we'll
+ # min() saved checkpoint timestamps with the current time to ensure that
+ # old checkpoints don't get deleted accidentally.
+ logging.warning(
+ ("time.time() returned a value %f seconds behind the last "
+ "preserved checkpoint timestamp.")
+ % (self._last_preserved_timestamp - current_clock,))
+ self._last_preserved_timestamp = current_clock
+ all_timestamps = recovered_state.all_model_checkpoint_timestamps
+ all_paths = recovered_state.all_model_checkpoint_paths
+ del recovered_state # Uses modified values from now on
+ if not all_timestamps:
+ all_timestamps = [self._last_preserved_timestamp] * len(all_paths)
+
+ for filename, timestamp in zip(all_paths, all_timestamps):
+ timestamp = min(timestamp, current_clock)
+ if timestamp > self._last_preserved_timestamp:
+ self._maybe_delete[filename] = timestamp
+
+ @property
+ def latest_checkpoint(self):
+ """The prefix of the most recent checkpoint in `directory`.
+
+ Equivalent to `tf.train.latest_checkpoint(directory)` where `directory` is
+ the constructor argument to `CheckpointManager`.
+
+ Suitable for passing to `tf.train.Checkpoint.restore` to resume training.
+
+ Returns:
+ The checkpoint prefix. If there are no checkpoints, returns `None`.
+ """
+ return self._latest_checkpoint
+
+ @property
+ def checkpoints(self):
+ """A list of managed checkpoints.
+
+ Note that checkpoints saved due to `keep_checkpoint_every_n_hours` will not
+ show up in this list (to avoid ever-growing filename lists).
+
+ Returns:
+ A list of filenames, sorted from oldest to newest.
+ """
+ return list(self._maybe_delete.keys())
+
+ def _sweep(self):
+ """Deletes or preserves managed checkpoints."""
+ while len(self._maybe_delete) > self._max_to_keep:
+ filename, timestamp = self._maybe_delete.popitem(last=False)
+ # Even if we're keeping this checkpoint due to
+ # keep_checkpoint_every_n_hours, we won't reference it to avoid
+ # infinitely-growing CheckpointState protos.
+ if (self._keep_checkpoint_every_n_hours
+ and (timestamp - self._keep_checkpoint_every_n_hours * 3600.
+ >= self._last_preserved_timestamp)):
+ self._last_preserved_timestamp = timestamp
+ continue
+ remove_checkpoint(filename)
+
+ def _record_state(self):
+ """Saves the `CheckpointManager`'s state in `directory`."""
+ filenames, timestamps = zip(*self._maybe_delete.items())
+ update_checkpoint_state_internal(
+ self._directory,
+ model_checkpoint_path=self.latest_checkpoint,
+ all_model_checkpoint_paths=filenames,
+ all_model_checkpoint_timestamps=timestamps,
+ last_preserved_timestamp=self._last_preserved_timestamp,
+ save_relative_paths=True)
+
+ @property
+ def _prefix(self):
+ """A common prefix for all checkpoints saved with this manager.
+
+ For example, if `directory` (a constructor argument) were `"/tmp/tf-model"`,
+ `prefix` would be `"/tmp/tf-model/ckpt"` and checkpoints would generally be
+ numbered `"/tmp/tf-model/ckpt-1"`, `"/tmp/tf-model/ckpt-2"`, and so on. Each
+ checkpoint has several associated files
+ (e.g. `"/tmp/tf-model/ckpt-2.index"`).
+
+ Returns:
+ A string prefix.
+ """
+ return self._checkpoint_prefix
+
+ def save(self, session=None, checkpoint_number=None):
+ """Creates a new checkpoint and manages it.
+
+ Args:
+ session: The session to evaluate variables in. Ignored when executing
+ eagerly. If not provided when graph building, the default session is
+ used.
+ checkpoint_number: An optional integer, or an integer-dtype `Variable` or
+ `Tensor`, used to number the checkpoint. If `None` (default),
+ checkpoints are numbered using `checkpoint.save_counter`. Even if
+ `checkpoint_number` is provided, `save_counter` is still incremented. A
+ user-provided `checkpoint_number` is not incremented even if it is a
+ `Variable`.
+
+ Returns:
+ The path to the new checkpoint. It is also recorded in the `checkpoints`
+ and `latest_checkpoint` properies.
+ """
+ # Save counter logic duplicated from tf.train.Checkpoint, soon to diverge
+ # slightly with a custom numbering option.
+ if context.executing_eagerly():
+ save_counter = self._checkpoint.save_counter
+ save_counter.assign_add(1)
+ else:
+ if session is None:
+ session = ops.get_default_session()
+
+ def _initializing_creator(next_creator, **kwargs):
+ """Initialize the save counter if it has been newly created."""
+ v = next_creator(**kwargs)
+ session.run(v.initializer)
+ return v
+
+ with variable_scope.variable_creator_scope(_initializing_creator):
+ save_counter = self._checkpoint.save_counter
+ if self._save_counter_assign is None:
+ self._save_counter_assign = save_counter.assign_add(1, read_value=False)
+ session.run(self._save_counter_assign)
+ if checkpoint_number is None:
+ checkpoint_number = save_counter
+ if not isinstance(checkpoint_number, compat.integral_types):
+ checkpoint_number = training_util.global_step(
+ sess=session, global_step_tensor=checkpoint_number)
+ prefix = "%s-%d" % (self._prefix, checkpoint_number)
+ save_path = self._checkpoint.write(prefix)
+ timestamp = time.time()
+ # If this is an overwritten checkpoint we were previously tracking, delete
+ # and reinsert it to make sure it goes to the end of the queue.
+ if save_path in self._maybe_delete:
+ del self._maybe_delete[save_path]
+ self._maybe_delete[save_path] = timestamp
+ self._latest_checkpoint = save_path
+ self._sweep()
+ self._record_state()
+ return save_path
diff --git a/tensorflow/python/training/checkpoint_management_test.py b/tensorflow/python/training/checkpoint_management_test.py
index 4b31d0c613..1e2827d0a4 100644
--- a/tensorflow/python/training/checkpoint_management_test.py
+++ b/tensorflow/python/training/checkpoint_management_test.py
@@ -26,14 +26,18 @@ import tempfile
from google.protobuf import text_format
from tensorflow.core.protobuf import saver_pb2
+from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops as ops_lib
+from tensorflow.python.framework import test_util
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
+from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import saver as saver_module
from tensorflow.python.training.checkpoint_state_pb2 import CheckpointState
+from tensorflow.python.training.checkpointable import util
class LatestCheckpointWithRelativePaths(test.TestCase):
@@ -312,5 +316,202 @@ class SaverUtilsTest(test.TestCase):
self.assertFalse(checkpoint_management.checkpoint_exists(ckpt_prefix))
+class CheckpointManagerTest(test.TestCase):
+
+ @test_util.run_in_graph_and_eager_modes
+ def testDeletion(self):
+ checkpoint = util.Checkpoint()
+ manager = checkpoint_management.CheckpointManager(
+ checkpoint, self.get_temp_dir(), max_to_keep=3)
+ first_path = manager.save()
+ second_path = manager.save()
+ third_path = manager.save()
+ fourth_path = manager.save()
+ self.assertTrue(checkpoint_management.checkpoint_exists(fourth_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(third_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_path))
+ self.assertFalse(checkpoint_management.checkpoint_exists(first_path))
+
+ @test_util.run_in_graph_and_eager_modes
+ @test.mock.patch.object(checkpoint_management, "time")
+ def testSaveRestoreState(self, mock_time):
+ directory = self.get_temp_dir()
+ mock_time.time.return_value = 3.
+ checkpoint = util.Checkpoint()
+ first_manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory, max_to_keep=2)
+ first_time = 10000.
+ first_name = os.path.join(directory, "ckpt-1")
+ mock_time.time.return_value = first_time
+ first_manager.save()
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual([first_time], state.all_model_checkpoint_timestamps)
+ self.assertEqual(3., state.last_preserved_timestamp)
+ second_time = first_time + 3610.
+ second_name = os.path.join(directory, "ckpt-2")
+ mock_time.time.return_value = second_time
+ first_manager.save()
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual([first_time, second_time],
+ state.all_model_checkpoint_timestamps)
+ self.assertEqual(3., state.last_preserved_timestamp)
+ self.assertEqual([first_name, second_name], first_manager.checkpoints)
+ self.assertEqual(second_name, first_manager.latest_checkpoint)
+ del first_manager
+
+ second_manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory,
+ max_to_keep=2, keep_checkpoint_every_n_hours=1.5)
+ self.assertEqual([first_name, second_name], second_manager.checkpoints)
+ self.assertEqual(second_name, second_manager.latest_checkpoint)
+ third_name = os.path.join(directory, "ckpt-3")
+ third_time = second_time + 3600. * 0.2
+ mock_time.time.return_value = third_time
+ second_manager.save()
+ self.assertTrue(checkpoint_management.checkpoint_exists(first_name))
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_name))
+ self.assertEqual([second_name, third_name],
+ second_manager.checkpoints)
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual(first_time, state.last_preserved_timestamp)
+ fourth_time = third_time + 3600. * 0.5
+ mock_time.time.return_value = fourth_time
+ fourth_name = os.path.join(directory, "ckpt-4")
+ second_manager.save()
+ self.assertTrue(checkpoint_management.checkpoint_exists(first_name))
+ self.assertFalse(checkpoint_management.checkpoint_exists(second_name))
+ self.assertEqual([third_name, fourth_name],
+ second_manager.checkpoints)
+ fifth_time = fourth_time + 3600. * 0.5
+ mock_time.time.return_value = fifth_time
+ fifth_name = os.path.join(directory, "ckpt-5")
+ second_manager.save()
+ self.assertEqual([fourth_name, fifth_name],
+ second_manager.checkpoints)
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual(first_time, state.last_preserved_timestamp)
+ del second_manager
+ third_manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory,
+ max_to_keep=2, keep_checkpoint_every_n_hours=1.5)
+ self.assertEqual(fifth_name, third_manager.latest_checkpoint)
+ mock_time.time.return_value += 10.
+ third_manager.save()
+ sixth_name = os.path.join(directory, "ckpt-6")
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual(fourth_time, state.last_preserved_timestamp)
+ self.assertTrue(checkpoint_management.checkpoint_exists(first_name))
+ self.assertTrue(checkpoint_management.checkpoint_exists(fourth_name))
+ self.assertTrue(checkpoint_management.checkpoint_exists(fifth_name))
+ self.assertTrue(checkpoint_management.checkpoint_exists(sixth_name))
+ self.assertFalse(checkpoint_management.checkpoint_exists(second_name))
+ self.assertFalse(checkpoint_management.checkpoint_exists(third_name))
+ self.assertEqual([fifth_name, sixth_name],
+ third_manager.checkpoints)
+
+ @test_util.run_in_graph_and_eager_modes
+ def testContinueFromUnmanaged(self):
+ directory = self.get_temp_dir()
+ prefix = os.path.join(directory, "unusual_prefix")
+ checkpoint = util.Checkpoint()
+ first_path = checkpoint.save(prefix)
+ second_path = checkpoint.save(prefix)
+ del checkpoint
+ checkpoint = util.Checkpoint()
+ manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory, max_to_keep=2)
+ checkpoint.restore(manager.latest_checkpoint).run_restore_ops()
+ self.assertEqual(2, self.evaluate(checkpoint.save_counter))
+ third_path = manager.save()
+ self.assertEqual([third_path], manager.checkpoints)
+ fourth_path = manager.save()
+ self.assertEqual([third_path, fourth_path],
+ manager.checkpoints)
+ fifth_path = manager.save()
+ self.assertEqual([fourth_path, fifth_path],
+ manager.checkpoints)
+ self.assertTrue(checkpoint_management.checkpoint_exists(first_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_path))
+ self.assertFalse(checkpoint_management.checkpoint_exists(third_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(fourth_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(fifth_path))
+
+ @test_util.run_in_graph_and_eager_modes
+ @test.mock.patch.object(checkpoint_management, "time")
+ def testClockReset(self, mock_time):
+ directory = self.get_temp_dir()
+ mock_time.time.return_value = 10000.
+ checkpoint = util.Checkpoint()
+ first_manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory, max_to_keep=1, keep_checkpoint_every_n_hours=1.)
+ first_path = first_manager.save()
+ mock_time.time.return_value += 3600.
+ second_path = first_manager.save()
+ mock_time.time.return_value += 3600.
+ third_path = first_manager.save()
+ self.assertFalse(checkpoint_management.checkpoint_exists(first_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(third_path))
+ self.assertEqual([third_path], first_manager.checkpoints)
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual(13600., state.last_preserved_timestamp)
+ # Set the clock back in time
+ mock_time.time.return_value = 5000.
+ del first_manager
+ with test.mock.patch.object(logging, "warning") as mock_log:
+ second_manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory, max_to_keep=1)
+ self.assertRegexpMatches(
+ str(mock_log.call_args),
+ "behind the last preserved checkpoint timestamp")
+ # We should err on the side of keeping checkpoints around when we're not
+ # sure whether they were preserved or not due to clock funkiness.
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_path))
+ # We know about the existing checkpoints, but they'll never be deleted and
+ # so won't go in the CheckpointState proto on save.
+ self.assertEqual(third_path, second_manager.latest_checkpoint)
+ self.assertEqual([], second_manager.checkpoints)
+ mock_time.time.return_value += 10.
+ fourth_path = second_manager.save()
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(third_path))
+ self.assertEqual(fourth_path, second_manager.latest_checkpoint)
+ self.assertEqual([fourth_path], second_manager.checkpoints)
+ mock_time.time.return_value += 10.
+ fifth_path = second_manager.save()
+ self.assertTrue(checkpoint_management.checkpoint_exists(second_path))
+ self.assertTrue(checkpoint_management.checkpoint_exists(third_path))
+ self.assertEqual([fifth_path], second_manager.checkpoints)
+ state = checkpoint_management.get_checkpoint_state(directory)
+ self.assertEqual(5000., state.last_preserved_timestamp)
+ self.assertEqual([5020.],
+ state.all_model_checkpoint_timestamps)
+
+ @test_util.run_in_graph_and_eager_modes
+ def testCustomNumbering(self):
+ directory = self.get_temp_dir()
+ step = variables.Variable(0, dtype=dtypes.int64)
+ checkpoint = util.Checkpoint(step=step)
+ manager = checkpoint_management.CheckpointManager(
+ checkpoint, directory, max_to_keep=2)
+ self.evaluate(step.initializer)
+ for i in range(5):
+ path = manager.save(checkpoint_number=step)
+ expected_suffix = "-%d" % (2 * i,)
+ if not path.endswith(expected_suffix):
+ self.fail("%s should have suffix %s" % (path, expected_suffix))
+ self.evaluate(step.assign_add(2))
+ self.assertEqual(5, self.evaluate(checkpoint.save_counter))
+ # Test regular integers
+ last_path = manager.save(checkpoint_number=32)
+ self.assertIn("-32", last_path)
+ self.assertEqual(last_path, manager.latest_checkpoint)
+ self.assertEqual(
+ last_path, checkpoint_management.latest_checkpoint(directory))
+ state = checkpoint_management.get_checkpoint_state(directory)
+ # Only the most recent two checkpoints are saved
+ self.assertEqual([path, last_path], state.all_model_checkpoint_paths)
+
+
if __name__ == "__main__":
test.main()
diff --git a/tensorflow/python/training/checkpoint_state.proto b/tensorflow/python/training/checkpoint_state.proto
index 9172a5c331..704f7fdc88 100644
--- a/tensorflow/python/training/checkpoint_state.proto
+++ b/tensorflow/python/training/checkpoint_state.proto
@@ -4,8 +4,6 @@ package tensorflow;
option cc_enable_arenas = true;
// Protocol buffer representing the checkpoint state.
-//
-// TODO(touts): Add other attributes as needed.
message CheckpointState {
// Path to the most-recent model checkpoint.
string model_checkpoint_path = 1;
@@ -15,4 +13,10 @@ message CheckpointState {
// Note that the value of model_checkpoint_path should be the last item in
// this list.
repeated string all_model_checkpoint_paths = 2;
+ // Unix timestamps corresponding to all_model_checkpoint_paths, indicating
+ // when each checkpoint was created.
+ repeated double all_model_checkpoint_timestamps = 3;
+ // Unix timestamp indicating the creation time for the last preserved
+ // checkpoint.
+ double last_preserved_timestamp = 4;
}
diff --git a/tensorflow/python/training/checkpoint_utils.py b/tensorflow/python/training/checkpoint_utils.py
index 9b72b09f08..e6118177fd 100644
--- a/tensorflow/python/training/checkpoint_utils.py
+++ b/tensorflow/python/training/checkpoint_utils.py
@@ -29,7 +29,7 @@ from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import checkpoint_management
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import saver
from tensorflow.python.util.tf_export import tf_export
@@ -180,10 +180,10 @@ def init_from_checkpoint(ckpt_dir_or_file, assignment_map):
tf.errors.OpError: If missing checkpoints or tensors in checkpoints.
ValueError: If missing variables in current graph.
"""
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
_init_from_checkpoint(None, ckpt_dir_or_file, assignment_map)
else:
- distribute_lib.get_tower_context().merge_call(
+ distribution_strategy_context.get_tower_context().merge_call(
_init_from_checkpoint, ckpt_dir_or_file, assignment_map)
diff --git a/tensorflow/python/training/checkpointable/BUILD b/tensorflow/python/training/checkpointable/BUILD
index 8a289b31b5..d26932c1aa 100644
--- a/tensorflow/python/training/checkpointable/BUILD
+++ b/tensorflow/python/training/checkpointable/BUILD
@@ -101,15 +101,26 @@ py_library(
srcs_version = "PY2AND3",
deps = [
":base",
+ ":data_structures",
":tracking",
+ "//tensorflow/core:protos_all_py",
"//tensorflow/python:array_ops",
+ "//tensorflow/python:checkpoint_management",
"//tensorflow/python:constant_op",
"//tensorflow/python:control_flow_ops",
"//tensorflow/python:dtypes",
+ "//tensorflow/python:errors",
+ "//tensorflow/python:framework_ops",
+ "//tensorflow/python:init_ops",
"//tensorflow/python:io_ops_gen",
- "//tensorflow/python:ops",
+ "//tensorflow/python:pywrap_tensorflow",
"//tensorflow/python:saveable_object",
+ "//tensorflow/python:saver",
+ "//tensorflow/python:session",
+ "//tensorflow/python:tensor_shape",
"//tensorflow/python:util",
+ "//tensorflow/python:variable_scope",
+ "//tensorflow/python:variables",
"//tensorflow/python/eager:context",
],
)
@@ -118,10 +129,7 @@ py_test(
name = "util_test",
srcs = ["util_test.py"],
srcs_version = "PY2AND3",
- tags = [
- "no_windows", # TODO: needs investigation on Windows
- "notsan", # b/74395663
- ],
+ tags = ["notsan"], # b/74395663
deps = [
":base",
":tracking",
diff --git a/tensorflow/python/training/checkpointable/base.py b/tensorflow/python/training/checkpointable/base.py
index 66837ee52f..9189d8f3e8 100644
--- a/tensorflow/python/training/checkpointable/base.py
+++ b/tensorflow/python/training/checkpointable/base.py
@@ -22,6 +22,7 @@ import functools
import json
import weakref
+from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
@@ -79,10 +80,6 @@ class CheckpointInitialValue(ops.Tensor):
self.wrapped_value.set_shape(shape)
self._checkpoint_position = checkpoint_position
- @property
- def __class__(self):
- return (self.wrapped_value.__class__, CheckpointInitialValue)
-
def __getattr__(self, attr):
try:
return getattr(self.wrapped_value, attr)
@@ -97,14 +94,17 @@ class CheckpointInitialValue(ops.Tensor):
class PythonStringStateSaveable(saveable_object.SaveableObject):
"""Saves Python state in a checkpoint."""
- def __init__(self, name, state_callback):
+ def __init__(self, name, state_callback, restore_callback=None):
"""Configure saving.
Args:
name: The checkpoint key to write to.
state_callback: A function taking no arguments which returns a
string. This function is run every time a checkpoint is written.
+ restore_callback: A function taking a Python string, used to restore
+ state. Optional; defaults to doing nothing.
"""
+ self._restore_callback = restore_callback
if context.executing_eagerly():
self._save_string = (
lambda: constant_op.constant(state_callback(), dtype=dtypes.string))
@@ -117,9 +117,14 @@ class PythonStringStateSaveable(saveable_object.SaveableObject):
super(PythonStringStateSaveable, self).__init__(
self._save_string, [spec], name)
+ def python_restore(self, restored_strings):
+ """Called to restore Python state."""
+ if self._restore_callback:
+ restored, = restored_strings
+ self._restore_callback(restored)
+
def restore(self, restored_tensors, restored_shapes):
- # TODO(allenl): Add a Python hook for state coming out of a checkpoint
- # (currently PythonStringStateSaveable is write-only).
+ """Called to restore TensorFlow state (nothing to do)."""
return control_flow_ops.no_op()
@@ -231,7 +236,7 @@ class _CheckpointPosition(object):
with ops.device("/cpu:0"):
# Run the restore itself on the CPU.
value, = io_ops.restore_v2(
- prefix=self._checkpoint.save_path,
+ prefix=self._checkpoint.save_path_tensor,
tensor_names=[checkpoint_key],
shape_and_slices=[""],
dtypes=[base_type],
@@ -240,42 +245,99 @@ class _CheckpointPosition(object):
value_tensors[serialized_tensor.name] = array_ops.identity(value)
return value_tensors
- def restore_ops(self):
- """Create or fetch restore ops for this object's attributes.
-
- Requires that the `Checkpointable` Python object has been bound to an object
- ID in the checkpoint.
-
- Returns:
- A list of operations when graph building, or an empty list when executing
- eagerly.
- """
+ def _gather_ops_or_named_saveables(self):
+ """Looks up or creates SaveableObjects which don't have cached ops."""
saveables = self.checkpointable._gather_saveables_for_checkpoint() # pylint: disable=protected-access
# Name saveables based on the name this object had when it was checkpointed.
named_saveables = {}
- restore_ops = []
- building_graph = not context.executing_eagerly()
+ python_saveables = []
+ existing_restore_ops = []
for serialized_tensor in self.object_proto.attributes:
- saveable_factory = saveables.get(serialized_tensor.name, None)
- if saveable_factory is None:
- # Purposefully does not throw an exception if attributes have been added
- # or deleted. Stores unused attributes so an exception can be raised if
- # the user decides to check that everything in the checkpoint was
- # loaded.
- self._checkpoint.unused_attributes.setdefault(
- self.checkpointable, []).append(serialized_tensor.name)
+ if context.executing_eagerly():
+ existing_op = None
+ else:
+ existing_op = self._checkpoint.restore_ops_by_name.get(
+ serialized_tensor.checkpoint_key, None)
+ if existing_op is not None:
+ existing_restore_ops.append(existing_op)
continue
- if building_graph:
- existing_ops = self._checkpoint.restore_ops_by_name.get(
- serialized_tensor.name, None)
+
+ # Only if we don't have cached ops for this SaveableObject, we'll see if
+ # the SaveableObject itself has been cached. If not, we'll make it, and
+ # either way we'll extract new ops from it (or if it has Python state to
+ # restore, we'll run that).
+ if self._checkpoint.saveable_object_cache is None:
+ # No SaveableObject caching when executing eagerly.
+ saveable = None
else:
- existing_ops = None
- if existing_ops is None:
+ # If we've already created and cached a SaveableObject for this
+ # attribute, we can re-use it to avoid re-creating some ops when graph
+ # building.
+ saveable_list = self._checkpoint.saveable_object_cache.get(
+ self.checkpointable, {}).get(serialized_tensor.name, (None,))
+ if len(saveable_list) == 1:
+ # Almost every attribute will have exactly one SaveableObject.
+ saveable, = saveable_list
+ else:
+ # Don't use cached SaveableObjects for partitioned variables, which is
+ # the only case where we'd have a list of SaveableObjects. Op caching
+ # will catch them.
+ saveable = None
+ if saveable is not None:
+ # The name of this attribute has changed, so we need to re-generate
+ # the SaveableObject.
+ if serialized_tensor.checkpoint_key not in saveable.name:
+ saveable = None
+ del self._checkpoint.saveable_object_cache[self.checkpointable]
+ break
+ if saveable is None:
+ # If there was no cached SaveableObject, we should check if the Python
+ # object has the attribute.
+ saveable_factory = saveables.get(serialized_tensor.name, None)
+ if saveable_factory is None:
+ # Purposefully does not throw an exception if attributes have been
+ # added or deleted. Stores unused attributes so an exception can be
+ # raised if the user decides to check that everything in the
+ # checkpoint was loaded.
+ self._checkpoint.unused_attributes.setdefault(
+ self.checkpointable, []).append(serialized_tensor.name)
+ continue
if callable(saveable_factory):
saveable = saveable_factory(name=serialized_tensor.checkpoint_key)
else:
saveable = saveable_factory
+ if self._checkpoint.saveable_object_cache is not None:
+ self._checkpoint.saveable_object_cache.setdefault(
+ self.checkpointable, {})[serialized_tensor.name] = [saveable]
+ if isinstance(saveable, PythonStringStateSaveable):
+ python_saveables.append(saveable)
+ else:
named_saveables[serialized_tensor.checkpoint_key] = saveable
+ return existing_restore_ops, named_saveables, python_saveables
+
+ def restore_ops(self):
+ """Create or fetch restore ops for this object's attributes.
+
+ Requires that the `Checkpointable` Python object has been bound to an object
+ ID in the checkpoint.
+
+ Returns:
+ A list of operations when graph building, or an empty list when executing
+ eagerly.
+ """
+ (restore_ops,
+ named_saveables,
+ python_saveables) = self._gather_ops_or_named_saveables()
+
+ # Eagerly run restorations for Python state.
+ reader = pywrap_tensorflow.NewCheckpointReader(
+ self._checkpoint.save_path_string)
+ for saveable in python_saveables:
+ spec_names = [spec.name for spec in saveable.specs]
+ saveable.python_restore(
+ [reader.get_tensor(name) for name in spec_names])
+
+ # If we have new SaveableObjects, extract and cache restore ops.
if named_saveables:
validated_saveables = (
self._checkpoint.builder._ValidateAndSliceInputs(named_saveables)) # pylint: disable=protected-access
@@ -285,7 +347,7 @@ class _CheckpointPosition(object):
("Saveable keys changed when validating. Got back %s, was "
"expecting %s") % (named_saveables.keys(), validated_names))
all_tensors = self._checkpoint.builder.bulk_restore(
- filename_tensor=self._checkpoint.save_path,
+ filename_tensor=self._checkpoint.save_path_tensor,
saveables=validated_saveables, preferred_shard=-1,
restore_sequentially=False)
saveable_index = 0
@@ -295,7 +357,7 @@ class _CheckpointPosition(object):
saveable_index:saveable_index + num_specs]
saveable_index += num_specs
restore_op = saveable.restore(saveable_tensors, restored_shapes=None)
- if building_graph:
+ if not context.executing_eagerly():
assert saveable.name not in self._checkpoint.restore_ops_by_name
self._checkpoint.restore_ops_by_name[saveable.name] = restore_op
restore_ops.append(restore_op)
diff --git a/tensorflow/python/training/checkpointable/data_structures.py b/tensorflow/python/training/checkpointable/data_structures.py
index 507cda8734..f06cbbfa15 100644
--- a/tensorflow/python/training/checkpointable/data_structures.py
+++ b/tensorflow/python/training/checkpointable/data_structures.py
@@ -128,7 +128,8 @@ class CheckpointableDataStructure(base.CheckpointableBase):
"stored in a List object. Got %s, which does not inherit from "
"CheckpointableBase.") % (value,))
if (isinstance(value, CheckpointableDataStructure)
- or layer_utils.is_layer(value)):
+ or layer_utils.is_layer(value)
+ or layer_utils.has_weights(value)):
# Check for object-identity rather than with __eq__ to avoid
# de-duplicating empty container types. Automatically generated list
# wrappers keep things like "[] == []" true, which means "[] in [[]]" is
@@ -149,14 +150,14 @@ class CheckpointableDataStructure(base.CheckpointableBase):
def trainable_weights(self):
return layer_utils.gather_trainable_weights(
trainable=self.trainable,
- sub_layers=self.layers,
+ sub_layers=self._layers,
extra_variables=self._extra_variables)
@property
def non_trainable_weights(self):
return layer_utils.gather_non_trainable_weights(
trainable=self.trainable,
- sub_layers=self.layers,
+ sub_layers=self._layers,
extra_variables=self._extra_variables)
@property
@@ -183,7 +184,8 @@ class CheckpointableDataStructure(base.CheckpointableBase):
# have any inputs.
aggregated = []
for layer in self.layers:
- aggregated += layer.updates
+ if hasattr(layer, "updates"):
+ aggregated += layer.updates
return aggregated
@property
@@ -191,7 +193,8 @@ class CheckpointableDataStructure(base.CheckpointableBase):
"""Aggregate losses from any `Layer` instances."""
aggregated = []
for layer in self.layers:
- aggregated += layer.losses
+ if hasattr(layer, "losses"):
+ aggregated += layer.losses
return aggregated
def __hash__(self):
diff --git a/tensorflow/python/training/checkpointable/data_structures_test.py b/tensorflow/python/training/checkpointable/data_structures_test.py
index 472b7c32b4..4638917b4c 100644
--- a/tensorflow/python/training/checkpointable/data_structures_test.py
+++ b/tensorflow/python/training/checkpointable/data_structures_test.py
@@ -31,6 +31,7 @@ from tensorflow.python.layers import core as non_keras_core
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
+from tensorflow.python.ops import variables
from tensorflow.python.training.checkpointable import data_structures
from tensorflow.python.training.checkpointable import tracking
from tensorflow.python.training.checkpointable import util
@@ -96,6 +97,11 @@ class ListTests(test.TestCase):
model.load_weights(save_path)
self.assertAllEqual([[1., 2., 3.], [4., 5., 6.]],
self.evaluate(model.variables[0]))
+ v = variables.Variable(1.)
+ model.var_list = [v]
+ self.assertIn(v, model.variables)
+ self.assertIn(v, model.trainable_variables)
+ self.assertNotIn(v, model.non_trainable_variables)
def testUpdatesForwarded(self):
with context.graph_mode():
diff --git a/tensorflow/python/training/checkpointable/layer_utils.py b/tensorflow/python/training/checkpointable/layer_utils.py
index d65b631fe9..ec764bca89 100644
--- a/tensorflow/python/training/checkpointable/layer_utils.py
+++ b/tensorflow/python/training/checkpointable/layer_utils.py
@@ -30,13 +30,20 @@ def is_layer(obj):
and hasattr(obj, "variables"))
+def has_weights(obj):
+ """Implicit check for Layer-like objects."""
+ # TODO(b/110718070): Replace with isinstance(obj, base_layer.Layer).
+ return (hasattr(obj, "trainable_weights")
+ and hasattr(obj, "non_trainable_weights"))
+
+
def filter_empty_layer_containers(layer_list):
"""Filter out empty Layer-like containers."""
filtered = []
for obj in layer_list:
if is_layer(obj):
filtered.append(obj)
- else:
+ elif hasattr(obj, "layers"):
# Checkpointable data structures will not show up in ".layers" lists, but
# the layers they contain will.
filtered.extend(obj.layers)
diff --git a/tensorflow/python/training/checkpointable/util.py b/tensorflow/python/training/checkpointable/util.py
index 3cdaedce98..f49ed5c9ff 100644
--- a/tensorflow/python/training/checkpointable/util.py
+++ b/tensorflow/python/training/checkpointable/util.py
@@ -19,6 +19,7 @@ from __future__ import print_function
import abc
import collections
+import os
import weakref
from tensorflow.core.protobuf import checkpointable_object_graph_pb2
@@ -34,8 +35,9 @@ from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_io_ops as io_ops
from tensorflow.python.ops import init_ops
-from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
+from tensorflow.python.ops import variables
+from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import optimizer as optimizer_lib
from tensorflow.python.training import saveable_object as saveable_object_lib
from tensorflow.python.training import saver as saver_lib
@@ -66,16 +68,25 @@ _OBJECT_ATTRIBUTES_NAME = _ESCAPE_CHAR + "ATTRIBUTES"
class _CheckpointRestoreCoordinator(object):
"""Holds the status of an object-based checkpoint load."""
- def __init__(self, object_graph_proto, save_path, dtype_map=None):
+ def __init__(self, object_graph_proto, save_path, save_path_tensor,
+ restore_op_cache, saveable_object_cache):
"""Specify the checkpoint being loaded.
Args:
object_graph_proto: The CheckpointableObjectGraph protocol buffer
associated with this checkpoint.
- save_path: A string `Tensor`. The path to the checkpoint, as returned by
+ save_path: A string, the path to the checkpoint, as returned by
`tf.train.latest_checkpoint`.
- dtype_map: When executing eagerly, specifies dtypes for creating slot
- variables. None when graph building.
+ save_path_tensor: A string `Tensor` which contains or will be fed the save
+ path.
+ restore_op_cache: A dictionary shared between
+ `_CheckpointRestoreCoordinator`s for the same Python objects, used to
+ look up restore ops by name to avoid re-creating them across multiple
+ `restore()` calls.
+ saveable_object_cache: A mapping of checkpointable objects -> attribute
+ names -> list(`SaveableObject`s), used when `SaveableObjects` must be
+ referenced every restore (e.g. for Python state); otherwise they would
+ create their own ops every restore.
"""
self.builder = saver_lib.BulkSaverBuilder()
self.object_graph_proto = object_graph_proto
@@ -95,12 +106,17 @@ class _CheckpointRestoreCoordinator(object):
# loading). Used to make status assertions fail when loading checkpoints
# that don't quite match.
self.all_python_objects = _ObjectIdentityWeakSet()
- self.save_path = save_path
- self.dtype_map = dtype_map
+ self.save_path_tensor = save_path_tensor
+ self.save_path_string = save_path
+ self.dtype_map = pywrap_tensorflow.NewCheckpointReader(
+ save_path).get_variable_to_dtype_map()
+ # A NewCheckpointReader for the most recent checkpoint, for streaming Python
+ # state restoration.
# When graph building, contains a list of ops to run to restore objects from
# this checkpoint.
self.restore_ops = []
- self.restore_ops_by_name = {}
+ self.restore_ops_by_name = restore_op_cache
+ self.saveable_object_cache = saveable_object_cache
self.new_restore_ops_callback = None
# A mapping from optimizer proto ids to lists of slot variables to be
# restored when the optimizer is tracked. Only includes slot variables whose
@@ -225,10 +241,11 @@ def _default_getter(name, shape, dtype, initializer=None,
def initial_value():
return initializer(
shape_object.as_list(), dtype=dtype, partition_info=partition_info)
- return resource_variable_ops.ResourceVariable(
+ return variables.Variable(
initial_value=initial_value,
name=name,
dtype=variable_dtype,
+ use_resource=True,
**kwargs
)
@@ -1100,7 +1117,7 @@ class _SessionWithFeedDictAdditions(session_lib.SessionInterface):
def _copy_saver_with_new_var_list(old_saver, new_var_list):
"""Copy a `tf.train.Saver`'s state to a new Saver with different variables."""
- new_saver = saver_lib.Saver(var_list=new_var_list)
+ new_saver = saver_lib.Saver(var_list=new_var_list, max_to_keep=None)
# TODO(allenl): Move to copying functionality to Saver?
# pylint: disable=protected-access
new_saver._last_checkpoints = old_saver._last_checkpoints
@@ -1150,16 +1167,15 @@ class CheckpointableSaver(object):
self._last_save_object_graph = None
self._last_save_saver = None
- # Op caching for restore
- self._last_restore_object_graph = None
- self._last_restore_checkpoint = None
+ # Op caching for restore, shared between _CheckpointRestoreCoordinators
+ self._restore_op_cache = {}
if context.executing_eagerly():
# SaveableObjects are always recreated when executing eagerly.
self._saveable_object_cache = None
else:
- # Maps Checkpointable objects -> attribute names -> SaveableObjects, to
- # avoid re-creating SaveableObjects when graph building.
+ # Maps Checkpointable objects -> attribute names -> list(SaveableObjects),
+ # to avoid re-creating SaveableObjects when graph building.
self._saveable_object_cache = _ObjectIdentityWeakKeyDictionary()
@property
@@ -1226,7 +1242,8 @@ class CheckpointableSaver(object):
self._last_save_saver = _copy_saver_with_new_var_list(
old_saver=self._last_save_saver, new_var_list=named_variables)
else:
- self._last_save_saver = saver_lib.Saver(var_list=named_variables)
+ self._last_save_saver = saver_lib.Saver(
+ var_list=named_variables, max_to_keep=None)
self._last_save_object_graph = graph_proto
with ops.device("/cpu:0"):
save_path = self._last_save_saver.save(
@@ -1234,6 +1251,7 @@ class CheckpointableSaver(object):
session=session, feed_additions=feed_additions),
save_path=file_prefix,
write_meta_graph=False,
+ write_state=False,
global_step=checkpoint_number)
return save_path
@@ -1335,22 +1353,12 @@ class CheckpointableSaver(object):
object_graph_proto = (
checkpointable_object_graph_pb2.CheckpointableObjectGraph())
object_graph_proto.ParseFromString(object_graph_string)
- if graph_building and object_graph_proto == self._last_restore_object_graph:
- checkpoint = self._last_restore_checkpoint
- else:
- checkpoint = _CheckpointRestoreCoordinator(
- object_graph_proto=object_graph_proto,
- save_path=file_prefix_tensor,
- dtype_map=dtype_map)
- if graph_building:
- if self._last_restore_object_graph is not None:
- raise NotImplementedError(
- "Using a single Saver to restore different object graphs is not "
- "currently supported when graph building. Use a different Saver "
- "for each object graph (restore ops will be duplicated), or "
- "file a feature request if this limitation bothers you.")
- self._last_restore_checkpoint = checkpoint
- self._last_restore_object_graph = object_graph_proto
+ checkpoint = _CheckpointRestoreCoordinator(
+ object_graph_proto=object_graph_proto,
+ save_path=save_path,
+ save_path_tensor=file_prefix_tensor,
+ restore_op_cache=self._restore_op_cache,
+ saveable_object_cache=self._saveable_object_cache)
base._CheckpointPosition( # pylint: disable=protected-access
checkpoint=checkpoint, proto_id=0).restore(self._root_checkpointable)
load_status = CheckpointLoadStatus(
@@ -1486,6 +1494,32 @@ class Checkpoint(tracking.Checkpointable):
add_variable(self, name="save_counter", initializer=0,
dtype=dtypes.int64))
+ def write(self, file_prefix, session=None):
+ """Writes a training checkpoint.
+
+ The checkpoint includes variables created by this object and any
+ checkpointable objects it depends on at the time `Checkpoint.write()` is
+ called.
+
+ `write` does not number checkpoints, increment `save_counter`, or update the
+ metadata used by `tf.train.latest_checkpoint`. It is primarily intended for
+ use by higher level checkpoint management utilities. `save` provides a very
+ basic implementation of these features.
+
+ Args:
+ file_prefix: A prefix to use for the checkpoint filenames
+ (/path/to/directory/and_a_prefix).
+ session: The session to evaluate variables in. Ignored when executing
+ eagerly. If not provided when graph building, the default session is
+ used.
+
+ Returns:
+ The full path to the checkpoint (i.e. `file_prefix`).
+ """
+ return self._saver.save(
+ file_prefix=file_prefix,
+ session=session)
+
@property
def save_counter(self):
"""An integer variable which starts at zero and is incremented on save.
@@ -1499,12 +1533,19 @@ class Checkpoint(tracking.Checkpointable):
return self._save_counter
def save(self, file_prefix, session=None):
- """Save a training checkpoint.
+ """Saves a training checkpoint and provides basic checkpoint management.
The saved checkpoint includes variables created by this object and any
checkpointable objects it depends on at the time `Checkpoint.save()` is
called.
+ `save` is a basic convenience wrapper around the `write` method,
+ sequentially numbering checkpoints using `save_counter` and updating the
+ metadata used by `tf.train.latest_checkpoint`. More advanced checkpoint
+ management, for example garbage collection and custom numbering, may be
+ provided by other utilities which also wrap `write`
+ (`tf.contrib.checkpoint.CheckpointManager` for example).
+
Args:
file_prefix: A prefix to use for the checkpoint filenames
(/path/to/directory/and_a_prefix). Names are generated based on this
@@ -1527,15 +1568,20 @@ class Checkpoint(tracking.Checkpointable):
session.run(self.save_counter.initializer)
if not graph_building or self._save_assign_op is None:
with ops.colocate_with(self.save_counter):
- assign_op = self.save_counter.assign_add(1, read_value=False)
+ assign_op = self.save_counter.assign_add(1, read_value=True)
if graph_building:
- self._save_assign_op = assign_op
+ self._save_assign_op = data_structures.NoDependency(assign_op)
if graph_building:
- session.run(self._save_assign_op)
- return self._saver.save(
- file_prefix=file_prefix,
- checkpoint_number=self.save_counter,
- session=session)
+ checkpoint_number = session.run(self._save_assign_op)
+ else:
+ checkpoint_number = assign_op.numpy()
+ file_path = self.write("%s-%d" % (file_prefix, checkpoint_number),
+ session=session)
+ checkpoint_management.update_checkpoint_state(
+ save_dir=os.path.dirname(file_prefix),
+ model_checkpoint_path=file_path,
+ all_model_checkpoint_paths=[file_path])
+ return file_path
def restore(self, save_path):
"""Restore a training checkpoint.
diff --git a/tensorflow/python/training/checkpointable/util_test.py b/tensorflow/python/training/checkpointable/util_test.py
index 5506e6bc4e..cac293e916 100644
--- a/tensorflow/python/training/checkpointable/util_test.py
+++ b/tensorflow/python/training/checkpointable/util_test.py
@@ -522,7 +522,6 @@ class CheckpointingTests(test.TestCase):
# Does create garbage when executing eagerly due to ops.Graph() creation.
num_training_steps = 10
checkpoint_directory = self.get_temp_dir()
- checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
for training_continuation in range(3):
with ops.Graph().as_default(), self.test_session(
graph=ops.get_default_graph()), test_util.device(use_gpu=True):
@@ -531,9 +530,9 @@ class CheckpointingTests(test.TestCase):
root = checkpointable_utils.Checkpoint(
optimizer=optimizer, model=model,
global_step=training_util.get_or_create_global_step())
- checkpoint_path = checkpoint_management.latest_checkpoint(
- checkpoint_directory)
- status = root.restore(save_path=checkpoint_path)
+ manager = checkpoint_management.CheckpointManager(
+ root, checkpoint_directory, max_to_keep=1)
+ status = root.restore(save_path=manager.latest_checkpoint)
input_value = constant_op.constant([[3.]])
train_fn = functools.partial(
optimizer.minimize,
@@ -544,12 +543,26 @@ class CheckpointingTests(test.TestCase):
status.initialize_or_restore()
for _ in range(num_training_steps):
train_fn()
- root.save(file_prefix=checkpoint_prefix)
+ manager.save()
self.assertEqual((training_continuation + 1) * num_training_steps,
self.evaluate(root.global_step))
self.assertEqual(training_continuation + 1,
self.evaluate(root.save_counter))
+ @test_util.run_in_graph_and_eager_modes
+ def testCustomNumbering(self):
+ directory = self.get_temp_dir()
+ prefix = os.path.join(directory, "ckpt")
+ step = resource_variable_ops.ResourceVariable(0, dtype=dtypes.int64)
+ checkpoint = checkpointable_utils.Checkpoint(step=step)
+ self.evaluate(step.initializer)
+ for i in range(5):
+ path = checkpoint.write("%s-%d" % (prefix, self.evaluate(step)))
+ expected_suffix = "-%d" % (2 * i,)
+ if not path.endswith(expected_suffix):
+ self.fail("%s should have suffix %s" % (path, expected_suffix))
+ self.evaluate(step.assign_add(2))
+
# pylint: disable=cell-var-from-loop
@test_util.run_in_graph_and_eager_modes
def testWithDefun(self):
@@ -996,7 +1009,8 @@ class CheckpointingTests(test.TestCase):
self.assertEqual(before_ops, graph.get_operations())
@test_util.run_in_graph_and_eager_modes
- def testCheckpointCleanup(self):
+ def testCheckpointState(self):
+ # No checkpoints are deleted by default
checkpoint_directory = self.get_temp_dir()
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
obj = tracking.Checkpointable()
@@ -1006,7 +1020,7 @@ class CheckpointingTests(test.TestCase):
for _ in range(10):
saver.save(checkpoint_prefix)
expected_filenames = ["checkpoint"]
- for checkpoint_number in range(6, 11):
+ for checkpoint_number in range(1, 11):
expected_filenames.append("ckpt-%d.index" % (checkpoint_number,))
expected_filenames.append(
"ckpt-%d.data-00000-of-00001" % (checkpoint_number,))
@@ -1016,7 +1030,7 @@ class CheckpointingTests(test.TestCase):
os.listdir(checkpoint_directory))
@test_util.run_in_graph_and_eager_modes
- def testCheckpointCleanupChangingVarList(self):
+ def testCheckpointStateChangingVarList(self):
checkpoint_directory = self.get_temp_dir()
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
obj = tracking.Checkpointable()
@@ -1032,8 +1046,8 @@ class CheckpointingTests(test.TestCase):
looped_variables.append(new_variable)
expected_filenames = ["checkpoint"]
# We've copied the saver each time, but checkpoint management should still
- # be consistent.
- for checkpoint_number in range(6, 11):
+ # be consistent. Nothing gets deleted.
+ for checkpoint_number in range(1, 11):
expected_filenames.append("ckpt-%d.index" % (checkpoint_number,))
expected_filenames.append(
"ckpt-%d.data-00000-of-00001" % (checkpoint_number,))
@@ -1041,6 +1055,15 @@ class CheckpointingTests(test.TestCase):
self,
expected_filenames,
os.listdir(checkpoint_directory))
+ self.assertEqual(
+ checkpoint_prefix + "-10",
+ checkpoint_management.latest_checkpoint(checkpoint_directory))
+ # The checkpoint list only contains the most recent checkpoint, but they're
+ # all on disk. This means we won't eventually run into proto size limits.
+ self.assertEqual(
+ [checkpoint_prefix + "-10"],
+ (checkpoint_management.get_checkpoint_state(checkpoint_directory)
+ .all_model_checkpoint_paths))
for v in looped_variables:
self.evaluate(v.assign(314))
checkpoint.restore(checkpoint_prefix + "-6").run_restore_ops()
@@ -1050,16 +1073,11 @@ class CheckpointingTests(test.TestCase):
self.assertEqual(5, self.evaluate(checkpoint.var_5))
self.assertEqual(1, self.evaluate(checkpoint.var_1))
self.assertEqual(0, self.evaluate(checkpoint.var_0))
- if context.executing_eagerly():
- checkpoint.restore(checkpoint_prefix + "-10").run_restore_ops()
- self.assertEqual(9, self.evaluate(checkpoint.var_9))
- self.assertEqual(8, self.evaluate(checkpoint.var_8))
- self.assertEqual(1, self.evaluate(checkpoint.var_1))
- self.assertEqual(0, self.evaluate(checkpoint.var_0))
- else:
- # Restoring into modified graphs is an error while graph building.
- with self.assertRaises(NotImplementedError):
- checkpoint.restore(checkpoint_prefix + "-10").run_restore_ops()
+ checkpoint.restore(checkpoint_prefix + "-10").run_restore_ops()
+ self.assertEqual(9, self.evaluate(checkpoint.var_9))
+ self.assertEqual(8, self.evaluate(checkpoint.var_8))
+ self.assertEqual(1, self.evaluate(checkpoint.var_1))
+ self.assertEqual(0, self.evaluate(checkpoint.var_0))
def testManyRestoresGraph(self):
"""Restores after the first should not modify the graph."""
diff --git a/tensorflow/python/training/distribute.py b/tensorflow/python/training/distribute.py
index 5f7a53e186..1ac7c39872 100644
--- a/tensorflow/python/training/distribute.py
+++ b/tensorflow/python/training/distribute.py
@@ -21,7 +21,7 @@ from __future__ import print_function
import threading
from tensorflow.python.data.ops import dataset_ops
-from tensorflow.python.eager import context
+from tensorflow.python.eager import context as eager_context
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
@@ -31,71 +31,11 @@ from tensorflow.python.ops import variable_scope
from tensorflow.python.ops.losses import losses_impl
from tensorflow.python.platform import tf_logging
from tensorflow.python.training import device_util
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.util import nest
# ------------------------------------------------------------------------------
-# Internal API for setting the current thread mode as being either in a
-# tower or cross-tower context for a particular distribution strategy.
-
-
-class _ThreadMode(object):
-
- def __init__(self, dist, cross, tower):
- self.distribution_strategy = dist
- self.cross_tower_context = cross
- self.tower_context = tower
-
-
-class _CrossTowerThreadMode(_ThreadMode):
-
- def __init__(self, distribution_strategy):
- _ThreadMode.__init__(
- self, distribution_strategy, distribution_strategy, None)
-
-
-class _InTowerThreadMode(_ThreadMode):
-
- def __init__(self, tower_ctx):
- _ThreadMode.__init__(
- self, tower_ctx.distribution_strategy, None, tower_ctx)
-
-
-_per_thread_mode = threading.local()
-
-
-def _push_per_thread_mode(context):
- if not hasattr(_per_thread_mode, "stack"):
- _per_thread_mode.stack = []
- _per_thread_mode.stack.append(context)
-
-
-def _pop_per_thread_mode():
- _per_thread_mode.stack.pop(-1)
-
-
-class _DefaultTowerThreadMode(_ThreadMode):
- """Type of default value returned by `_get_per_thread_mode()`.
-
- Used when the thread-local stack is empty.
- """
-
- def __init__(self):
- # _default_distribution_strategy and _default_tower_context are
- # defined at the bottom of this file.
- _ThreadMode.__init__(
- self, _default_distribution_strategy, None, _default_tower_context)
-
-
-def _get_per_thread_mode():
- try:
- return _per_thread_mode.stack[-1]
- except (AttributeError, IndexError):
- # _default_tower_mode is defined at the bottom of this file.
- return _default_tower_mode
-
-
-# ------------------------------------------------------------------------------
# Context tracking whether in a distribution.update() or .update_non_slot()
# call.
@@ -128,96 +68,6 @@ class UpdateContext(object):
# ------------------------------------------------------------------------------
-# Public API for accessing the current thread mode
-
-
-def get_tower_context():
- """Returns the current TowerContext or None if in a cross-tower context.
-
- Note that execution:
- 1. starts in the default (single-tower) tower context (this function
- will return the default TowerContext object);
- 2. switches to cross-tower context (in which case this will return
- None) when entering a `with DistributionStrategy.scope():` block;
- 3. switches to a (non-default) tower context inside
- `call_for_each_tower(fn, ...)`;
- 4. if `fn` calls `get_tower_context()->merge_call(merge_fn, ...)`, then
- inside `merge_fn` you are back in the cross-tower context (and again
- this function will return None).
-
- Note that you can also go directly from step 1 to 4 to switch to a
- cross-tower context for the default `DistributionStrategy`. You may
- also switch from the cross-tower context of 4 to a tower context by
- calling `call_for_each_tower()`, jumping back to step 3.
-
- Most `DistributionStrategy` methods may only be executed in
- a cross-tower context, in a tower context you should use the
- `TowerContext` API instead.
-
- Returns:
- The current `TowerContext` object when in a tower context scope, else None.
-
- Exactly one of `get_tower_context()` and `get_cross_tower_context()`
- will return None in a particular block.
- """
- return _get_per_thread_mode().tower_context
-
-
-def get_cross_tower_context():
- """Returns the current DistributionStrategy if in a cross-tower context.
-
- Note that execution:
- 1. starts in the default (single-tower) tower context;
- 2. switches to cross-tower context when entering a
- `with DistributionStrategy.scope():` block;
- 3. switches to a (non-default) tower context inside
- `call_for_each_tower(fn, ...)`;
- 4. if `fn` calls `get_tower_context()->merge_call(merge_fn, ...)`, then
- inside `merge_fn` you are back in the cross-tower context.
-
- Note that you can also go directly from step 1 to 4 to switch to a
- cross-tower context for the default `DistributionStrategy`. You may
- also switch from the cross-tower context of 4 to a tower context by
- calling `call_for_each_tower()`, jumping back to step 3.
-
- Most `DistributionStrategy` methods may only be executed in
- a cross-tower context.
-
- Returns:
- Returns the current `DistributionStrategy` object in a cross-tower
- context, or None.
-
- Exactly one of `get_tower_context()` and `get_cross_tower_context()`
- will return None in a particular block.
- """
- return _get_per_thread_mode().cross_tower_context
-
-
-def get_distribution_strategy():
- """Returns the current `DistributionStrategy` object.
-
- Prefer to use `get_tower_context()` or `get_cross_tower_context()`
- instead when possible.
-
- Returns:
- A `DistributionStrategy` object. Inside a
- `with distribution_strategy.scope()` block, it returns
- `distribution_strategy`, otherwise it returns the default
- (single-tower) `DistributionStrategy` object.
- """
- return _get_per_thread_mode().distribution_strategy
-
-
-def has_distribution_strategy():
- """Return if there is a current non-default `DistributionStrategy`.
-
- Returns:
- True if inside a `with distribution_strategy.scope():`.
- """
- return get_distribution_strategy() is not _default_distribution_strategy
-
-
-# ------------------------------------------------------------------------------
# Public utility functions.
@@ -239,7 +89,8 @@ def _require_cross_tower_context(distribution_strategy):
if context.cross_tower_context is distribution_strategy: return
# We have an error to report, figure out the right message.
if context.distribution_strategy is not distribution_strategy:
- if context.distribution_strategy is _default_distribution_strategy:
+ if (context.distribution_strategy is
+ distribution_strategy_context._get_default_distribution_strategy()): # pylint: disable=protected-access
raise RuntimeError(
'Need to be inside "with distribution_strategy.scope()" for %s' %
(distribution_strategy,))
@@ -272,7 +123,8 @@ def _require_distribution_strategy_scope(distribution_strategy):
context = _get_per_thread_mode()
if context.distribution_strategy is distribution_strategy: return
# We have an error to report, figure out the right message.
- if context.distribution_strategy is _default_distribution_strategy:
+ if (context.distribution_strategy is
+ distribution_strategy_context._get_default_distribution_strategy()): # pylint: disable=protected-access
raise RuntimeError(
'Need to be inside "with distribution_strategy.scope()" for %s' %
(distribution_strategy,))
@@ -295,7 +147,8 @@ class _CurrentDistributionContext(object):
var_creator_scope,
var_scope=None,
default_device=None):
- self._context = _CrossTowerThreadMode(distribution_strategy)
+ self._context = distribution_strategy_context._CrossTowerThreadMode( # pylint: disable=protected-access
+ distribution_strategy)
self._var_creator_scope = var_creator_scope
self._var_scope = var_scope
if default_device:
@@ -395,6 +248,7 @@ class DistributionStrategy(object):
devices.
We have then a few approaches we want to support:
+
* Code written (as if) with no knowledge of class `DistributionStrategy`.
This code should work as before, even if some of the layers, etc.
used by that code are written to be distribution-aware. This is done
@@ -588,7 +442,7 @@ class DistributionStrategy(object):
Returns:
A context manager.
"""
- if has_distribution_strategy():
+ if distribution_strategy_context.has_distribution_strategy():
_require_cross_tower_context(self)
return _SameScopeAgainContext(self)
@@ -740,7 +594,7 @@ class DistributionStrategy(object):
In eager mode, returns `None`.
In graph mode, a list of ops to execute. Empty list if nothing to be done.
"""
- if context.executing_eagerly():
+ if eager_context.executing_eagerly():
return
else:
return []
@@ -757,7 +611,7 @@ class DistributionStrategy(object):
In eager mode, returns `None`.
In graph mode, a list of ops to execute. Empty list if nothing to be done.
"""
- if context.executing_eagerly():
+ if eager_context.executing_eagerly():
return
else:
return []
@@ -771,13 +625,18 @@ class DistributionStrategy(object):
Args:
fn: function to run using this distribution strategy. The function must
- have the following signature: def fn(context, inputs).
+ have the following signature: def fn(context, *inputs).
`context` is an instance of `MultiStepContext` that will be passed when
`fn` is run. `context` can be used to specify the outputs to be returned
from `fn` by calling `context.set_last_step_output`. It can also be used
to capture non tensor outputs by `context.set_non_tensor_output`.
See `MultiStepContext` documentation for more information.
- `inputs` will have same type/structure as `iterator.get_next()`.
+ `inputs` will have same type/structure as `iterator.get_next()`. If the
+ `iterator.get_next()` returns a tuple say `return x, y` then whose will
+ be unpacked and passed to the `step_fn`; and step_fn signature would
+ look like `def step_fn(context, x, y)`. If the iterator returns a single
+ value say `return x` then the value is passed as is; the step_fn
+ signature would look like `def step_fn(context, x)`.
Typically, `fn` will use `call_for_each_tower` method of the strategy
to distribute the computation over multiple towers.
iterator: Iterator of a dataset that represents the input for `fn`. The
@@ -864,7 +723,7 @@ class DistributionStrategy(object):
Args:
aggregation: Indicates how a variable will be aggregated. Accepted values
- are @{tf.VariableAggregation.SUM}, @{tf.VariableAggregation.MEAN}.
+ are `tf.VariableAggregation.SUM`, `tf.VariableAggregation.MEAN`.
value: A per-device value with one value per tower.
destinations: An optional mirrored variable, a device string,
list of device strings. The return value will be copied to all
@@ -893,7 +752,7 @@ class DistributionStrategy(object):
Args:
aggregation: Indicates how a variable will be aggregated. Accepted values
- are @{tf.VariableAggregation.SUM}, @{tf.VariableAggregation.MEAN}.
+ are `tf.VariableAggregation.SUM`, `tf.VariableAggregation.MEAN`.
value_destination_pairs: A sequence of (value, destinations)
pairs. See `reduce()` for a description.
@@ -1077,9 +936,37 @@ class DistributionStrategy(object):
def _worker_device_index(self):
raise NotImplementedError("must be implemented in descendants")
- def configure(self, session_config=None):
- """Find the best configuration given a tensorflow session config."""
- del session_config
+ @property
+ def between_graph(self):
+ """Whether the strategy uses between-graph replication or not.
+
+ This is expected to return a constant value that will not be changed
+ throughout its life cycle.
+ """
+ raise NotImplementedError("must be implemented in descendants")
+
+ def configure(self,
+ session_config=None,
+ cluster_spec=None,
+ task_type=None,
+ task_id=None):
+ """Configures the strategy class."""
+ del session_config, cluster_spec, task_type, task_id
+
+ @property
+ def should_init(self):
+ """Whether initialization is needed."""
+ raise NotImplementedError("must be implemented in descendants")
+
+ @property
+ def should_checkpoint(self):
+ """Whether checkpointing is needed."""
+ raise NotImplementedError("must be implemented in descendants")
+
+ @property
+ def should_save_summary(self):
+ """Whether saving summaries is needed."""
+ raise NotImplementedError("must be implemented in descendants")
# A note about the difference between the context managers
@@ -1106,7 +993,8 @@ class TowerContext(object):
def __init__(self, distribution_strategy, tower_id):
self._distribution_strategy = distribution_strategy
- self._thread_context = _InTowerThreadMode(self)
+ self._thread_context = distribution_strategy_context._InTowerThreadMode( # pylint: disable=protected-access
+ self)
self._tower_id = tower_id
def __enter__(self):
@@ -1149,7 +1037,8 @@ class TowerContext(object):
def _merge_call(self, merge_fn, *args, **kwargs):
"""Default implementation for single tower."""
_push_per_thread_mode( # thread-local, so not needed with multiple threads
- _CrossTowerThreadMode(self._distribution_strategy))
+ distribution_strategy_context._CrossTowerThreadMode( # pylint: disable=protected-access
+ self._distribution_strategy))
try:
return merge_fn(self._distribution_strategy, *args, **kwargs)
finally:
@@ -1196,7 +1085,7 @@ class _DefaultDistributionStrategy(DistributionStrategy):
def scope(self):
"""Context manager setting a variable creator and `self` as current."""
- if has_distribution_strategy():
+ if distribution_strategy_context.has_distribution_strategy():
raise RuntimeError("Must not nest DistributionStrategy scopes.")
def creator(next_creator, *args, **kwargs):
@@ -1277,6 +1166,7 @@ class _DefaultDistributionStrategy(DistributionStrategy):
raise RuntimeError("worker_device_index() method unsupported by "
"_DefaultDistributionStrategy.")
+
# ------------------------------------------------------------------------------
# Common operations
@@ -1292,20 +1182,11 @@ def increment_var(v, amount=1):
def merge_fn(dist, vm):
return dist.group(dist.update(vm, update))
- tower_context = get_tower_context()
+ tower_context = distribution_strategy_context.get_tower_context()
return tower_context.merge_call(merge_fn, v)
# ------------------------------------------------------------------------------
-# Singletons
-
-_default_distribution_strategy = _DefaultDistributionStrategy()
-_default_tower_context = TowerContext(
- _default_distribution_strategy, tower_id=0)
-_default_tower_mode = _DefaultTowerThreadMode()
-
-
-# ------------------------------------------------------------------------------
# We haven't yet implemented deserialization for DistributedVariables.
# So here we catch any attempts to deserialize variables
# when using distribution strategies.
@@ -1314,7 +1195,7 @@ _original_from_proto = resource_variable_ops._from_proto_fn
def _from_proto_fn(v, import_scope=None):
- if has_distribution_strategy():
+ if distribution_strategy_context.has_distribution_strategy():
raise NotImplementedError(
"Deserialization of variables is not yet supported when using"
"distributed strategies.")
@@ -1323,3 +1204,10 @@ def _from_proto_fn(v, import_scope=None):
resource_variable_ops._from_proto_fn = _from_proto_fn
# pylint: enable=protected-access
+
+
+#-------------------------------------------------------------------------------
+# Shorthand for some methods from distribution_strategy_context.
+_push_per_thread_mode = distribution_strategy_context._push_per_thread_mode # pylint: disable=protected-access
+_get_per_thread_mode = distribution_strategy_context._get_per_thread_mode # pylint: disable=protected-access
+_pop_per_thread_mode = distribution_strategy_context._pop_per_thread_mode # pylint: disable=protected-access
diff --git a/tensorflow/python/training/distribute_test.py b/tensorflow/python/training/distribute_test.py
index 694145ede7..f03bd39100 100644
--- a/tensorflow/python/training/distribute_test.py
+++ b/tensorflow/python/training/distribute_test.py
@@ -21,6 +21,7 @@ from __future__ import print_function
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import test
from tensorflow.python.training import distribute
+from tensorflow.python.training import distribution_strategy_context
class _TestTowerContext(distribute.TowerContext):
@@ -49,12 +50,12 @@ class _TestStrategy(distribute.DistributionStrategy):
def _assert_in_default_state(t):
- t.assertIs(distribute._default_tower_context,
- distribute.get_tower_context())
- t.assertIs(None, distribute.get_cross_tower_context())
- t.assertIs(distribute._default_distribution_strategy,
- distribute.get_distribution_strategy())
- t.assertFalse(distribute.has_distribution_strategy())
+ t.assertIs(distribution_strategy_context._get_default_tower_context(),
+ distribution_strategy_context.get_tower_context())
+ t.assertIs(None, distribution_strategy_context.get_cross_tower_context())
+ t.assertIs(distribution_strategy_context._get_default_distribution_strategy(),
+ distribution_strategy_context.get_distribution_strategy())
+ t.assertFalse(distribution_strategy_context.has_distribution_strategy())
class TestStrategyTest(test.TestCase):
@@ -64,11 +65,13 @@ class TestStrategyTest(test.TestCase):
dist = _TestStrategy()
def run_fn():
- tower_context = distribute.get_tower_context()
+ tower_context = distribution_strategy_context.get_tower_context()
self.assertTrue(tower_context is not None)
- self.assertIs(None, distribute.get_cross_tower_context())
- self.assertTrue(distribute.has_distribution_strategy())
- self.assertIs(dist, distribute.get_distribution_strategy())
+ self.assertIs(None,
+ distribution_strategy_context.get_cross_tower_context())
+ self.assertTrue(distribution_strategy_context.has_distribution_strategy())
+ self.assertIs(dist,
+ distribution_strategy_context.get_distribution_strategy())
self.assertEqual("foo", tower_context.merge_call(None, test_arg="foo"))
expected_value = _get_test_variable(
"bar", variable_scope.VariableSynchronization.AUTO,
@@ -86,10 +89,12 @@ class TestStrategyTest(test.TestCase):
_assert_in_default_state(self)
dist = _TestStrategy()
with dist.scope():
- self.assertIs(None, distribute.get_tower_context())
- self.assertIs(dist, distribute.get_cross_tower_context())
- self.assertTrue(distribute.has_distribution_strategy())
- self.assertIs(dist, distribute.get_distribution_strategy())
+ self.assertIs(None, distribution_strategy_context.get_tower_context())
+ self.assertIs(dist,
+ distribution_strategy_context.get_cross_tower_context())
+ self.assertTrue(distribution_strategy_context.has_distribution_strategy())
+ self.assertIs(dist,
+ distribution_strategy_context.get_distribution_strategy())
expected_value = _get_test_variable(
"baz", variable_scope.VariableSynchronization.AUTO,
variable_scope.VariableAggregation.NONE)
@@ -120,15 +125,21 @@ class DefaultDistributionStrategyTest(test.TestCase):
_assert_in_default_state(self)
def merge_fn(dist, s):
- self.assertIs(distribute._default_distribution_strategy, dist)
- self.assertIs(None, distribute.get_tower_context())
- self.assertIs(dist, distribute.get_cross_tower_context())
- self.assertIs(dist, distribute.get_distribution_strategy())
- self.assertFalse(distribute.has_distribution_strategy())
+ self.assertIs(
+ distribution_strategy_context._get_default_distribution_strategy(),
+ dist)
+ self.assertIs(None, distribution_strategy_context.get_tower_context())
+ self.assertIs(dist,
+ distribution_strategy_context.get_cross_tower_context())
+ self.assertIs(dist,
+ distribution_strategy_context.get_distribution_strategy())
+ self.assertFalse(
+ distribution_strategy_context.has_distribution_strategy())
return "foo_" + s
- tower_ctx = distribute.get_tower_context()
- self.assertIs(distribute._default_tower_context, tower_ctx)
+ tower_ctx = distribution_strategy_context.get_tower_context()
+ self.assertIs(distribution_strategy_context._get_default_tower_context(),
+ tower_ctx)
self.assertEqual("foo_bar", tower_ctx.merge_call(merge_fn, "bar"))
_assert_in_default_state(self)
diff --git a/tensorflow/python/training/distribution_strategy_context.py b/tensorflow/python/training/distribution_strategy_context.py
new file mode 100644
index 0000000000..998b5c35ce
--- /dev/null
+++ b/tensorflow/python/training/distribution_strategy_context.py
@@ -0,0 +1,203 @@
+# 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.
+# ==============================================================================
+"""Utility to get distribution strategy related contexts."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.python.framework import ops
+from tensorflow.python.util.lazy_loader import LazyLoader
+
+
+# There is a circular dependency between this and `distribute` module. So we
+# load it lazily to workaround this.
+distribute_lib = LazyLoader(
+ "distribute_lib", globals(),
+ "tensorflow.python.training.distribute")
+
+# ------------------------------------------------------------------------------
+# Internal API for setting the current thread mode as being either in a
+# tower or cross-tower context for a particular distribution strategy.
+
+
+class _ThreadMode(object):
+
+ def __init__(self, dist, cross, tower):
+ self.distribution_strategy = dist
+ self.cross_tower_context = cross
+ self.tower_context = tower
+
+
+class _CrossTowerThreadMode(_ThreadMode):
+
+ def __init__(self, distribution_strategy):
+ _ThreadMode.__init__(
+ self, distribution_strategy, distribution_strategy, None)
+
+
+class _InTowerThreadMode(_ThreadMode):
+
+ def __init__(self, tower_ctx):
+ _ThreadMode.__init__(
+ self, tower_ctx.distribution_strategy, None, tower_ctx)
+
+
+def _push_per_thread_mode(context):
+ ops.get_default_graph()._distribution_strategy_stack.append(context) # pylint: disable=protected-access
+
+
+def _pop_per_thread_mode():
+ ops.get_default_graph()._distribution_strategy_stack.pop(-1) # pylint: disable=protected-access
+
+
+class _DefaultTowerThreadMode(_ThreadMode):
+ """Type of default value returned by `_get_per_thread_mode()`.
+
+ Used when the thread-local stack is empty.
+ """
+
+ def __init__(self):
+ _ThreadMode.__init__(self, _get_default_distribution_strategy(), None,
+ _get_default_tower_context())
+
+
+def _get_per_thread_mode():
+ try:
+ return ops.get_default_graph()._distribution_strategy_stack[-1] # pylint: disable=protected-access
+ except (AttributeError, IndexError):
+ return _get_default_tower_mode()
+
+
+# ------------------------------------------------------------------------------
+# Public API for accessing the current thread mode
+
+
+def get_tower_context():
+ """Returns the current TowerContext or None if in a cross-tower context.
+
+ Note that execution:
+ 1. starts in the default (single-tower) tower context (this function
+ will return the default TowerContext object);
+ 2. switches to cross-tower context (in which case this will return
+ None) when entering a `with DistributionStrategy.scope():` block;
+ 3. switches to a (non-default) tower context inside
+ `call_for_each_tower(fn, ...)`;
+ 4. if `fn` calls `get_tower_context()->merge_call(merge_fn, ...)`, then
+ inside `merge_fn` you are back in the cross-tower context (and again
+ this function will return None).
+
+ Note that you can also go directly from step 1 to 4 to switch to a
+ cross-tower context for the default `DistributionStrategy`. You may
+ also switch from the cross-tower context of 4 to a tower context by
+ calling `call_for_each_tower()`, jumping back to step 3.
+
+ Most `DistributionStrategy` methods may only be executed in
+ a cross-tower context, in a tower context you should use the
+ `TowerContext` API instead.
+
+ Returns:
+ The current `TowerContext` object when in a tower context scope, else None.
+
+ Exactly one of `get_tower_context()` and `get_cross_tower_context()`
+ will return None in a particular block.
+ """
+ return _get_per_thread_mode().tower_context
+
+
+def get_cross_tower_context():
+ """Returns the current DistributionStrategy if in a cross-tower context.
+
+ Note that execution:
+ 1. starts in the default (single-tower) tower context;
+ 2. switches to cross-tower context when entering a
+ `with DistributionStrategy.scope():` block;
+ 3. switches to a (non-default) tower context inside
+ `call_for_each_tower(fn, ...)`;
+ 4. if `fn` calls `get_tower_context()->merge_call(merge_fn, ...)`, then
+ inside `merge_fn` you are back in the cross-tower context.
+
+ Note that you can also go directly from step 1 to 4 to switch to a
+ cross-tower context for the default `DistributionStrategy`. You may
+ also switch from the cross-tower context of 4 to a tower context by
+ calling `call_for_each_tower()`, jumping back to step 3.
+
+ Most `DistributionStrategy` methods may only be executed in
+ a cross-tower context.
+
+ Returns:
+ Returns the current `DistributionStrategy` object in a cross-tower
+ context, or None.
+
+ Exactly one of `get_tower_context()` and `get_cross_tower_context()`
+ will return None in a particular block.
+ """
+ return _get_per_thread_mode().cross_tower_context
+
+
+def get_distribution_strategy():
+ """Returns the current `DistributionStrategy` object.
+
+ Prefer to use `get_tower_context()` or `get_cross_tower_context()`
+ instead when possible.
+
+ Returns:
+ A `DistributionStrategy` object. Inside a
+ `with distribution_strategy.scope()` block, it returns
+ `distribution_strategy`, otherwise it returns the default
+ (single-tower) `DistributionStrategy` object.
+ """
+ return _get_per_thread_mode().distribution_strategy
+
+
+def has_distribution_strategy():
+ """Return if there is a current non-default `DistributionStrategy`.
+
+ Returns:
+ True if inside a `with distribution_strategy.scope():`.
+ """
+ return get_distribution_strategy() is not _get_default_distribution_strategy()
+
+
+# ------------------------------------------------------------------------------
+# Defaults that are used when no distribution strategy is explicitly created.
+# We create them lazily in a function so that we can workaround the circular
+# dependency on distribute_lib. See lazy loader at the top of this file.
+
+_defaults = {
+ "distribution_strategy": None,
+ "tower_context": None,
+ "tower_mode": None
+}
+
+
+def _get_default_distribution_strategy():
+ if _defaults["distribution_strategy"] is None:
+ _defaults["distribution_strategy"] = (
+ distribute_lib._DefaultDistributionStrategy()) # pylint: disable=protected-access
+ return _defaults["distribution_strategy"]
+
+
+def _get_default_tower_context():
+ if _defaults["tower_context"] is None:
+ _defaults["tower_context"] = distribute_lib.TowerContext(
+ _get_default_distribution_strategy(), tower_id=0)
+ return _defaults["tower_context"]
+
+
+def _get_default_tower_mode():
+ if _defaults["tower_mode"] is None:
+ _defaults["tower_mode"] = _DefaultTowerThreadMode()
+ return _defaults["tower_mode"]
diff --git a/tensorflow/python/training/ftrl.py b/tensorflow/python/training/ftrl.py
index 4fa081fab7..832c10d454 100644
--- a/tensorflow/python/training/ftrl.py
+++ b/tensorflow/python/training/ftrl.py
@@ -86,7 +86,7 @@ class FtrlOptimizer(optimizer.Optimizer):
if initial_accumulator_value < 0.0:
raise ValueError(
- "initial_accumulator_value %f needs to be be positive or zero" %
+ "initial_accumulator_value %f needs to be positive or zero" %
initial_accumulator_value)
if learning_rate_power > 0.0:
raise ValueError("learning_rate_power %f needs to be negative or zero" %
diff --git a/tensorflow/python/training/input.py b/tensorflow/python/training/input.py
index caa26581e8..0d6207f8c4 100644
--- a/tensorflow/python/training/input.py
+++ b/tensorflow/python/training/input.py
@@ -15,7 +15,8 @@
"""Input pipeline.
-Please see the @{$reading_data$reading data how-to}
+Please see the [reading data
+how-to](https://tensorflow.org/api_guides/python/reading_data)
for context.
"""
diff --git a/tensorflow/python/training/monitored_session.py b/tensorflow/python/training/monitored_session.py
index 7b06bffa4b..c077630de2 100644
--- a/tensorflow/python/training/monitored_session.py
+++ b/tensorflow/python/training/monitored_session.py
@@ -25,6 +25,7 @@ import sys
import six
from tensorflow.core.protobuf import config_pb2
+from tensorflow.python.distribute import distribute_coordinator_context
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
@@ -284,6 +285,63 @@ class Scaffold(object):
resources.initialize_resources(resources.local_resources()))
+def _create_monitored_session_with_worker_context(worker_context, # pylint: disable=missing-docstring
+ scaffold,
+ checkpoint_dir=None,
+ hooks=None,
+ chief_only_hooks=None,
+ save_checkpoint_secs=None,
+ save_summaries_steps=None,
+ save_summaries_secs=None,
+ config=None,
+ stop_grace_period_secs=120,
+ log_step_count_steps=100,
+ max_wait_secs=7200,
+ save_checkpoint_steps=None,
+ summary_dir=None):
+ all_hooks = []
+ if hooks:
+ all_hooks.extend(hooks)
+ if chief_only_hooks and worker_context.is_chief:
+ all_hooks.extend(chief_only_hooks)
+
+ summary_dir = summary_dir or checkpoint_dir
+ if summary_dir and worker_context.should_save_summary:
+ if log_step_count_steps and log_step_count_steps > 0:
+ all_hooks.append(
+ basic_session_run_hooks.StepCounterHook(
+ output_dir=summary_dir, every_n_steps=log_step_count_steps))
+
+ if (save_summaries_steps and save_summaries_steps > 0) or (
+ save_summaries_secs and save_summaries_secs > 0):
+ all_hooks.append(
+ basic_session_run_hooks.SummarySaverHook(
+ scaffold=scaffold,
+ save_steps=save_summaries_steps,
+ save_secs=save_summaries_secs,
+ output_dir=summary_dir))
+
+ if checkpoint_dir and worker_context.should_checkpoint:
+ if (save_checkpoint_secs and save_checkpoint_secs > 0) or (
+ save_checkpoint_steps and save_checkpoint_steps > 0):
+ all_hooks.append(
+ basic_session_run_hooks.CheckpointSaverHook(
+ checkpoint_dir,
+ save_steps=save_checkpoint_steps,
+ save_secs=save_checkpoint_secs,
+ scaffold=scaffold))
+
+ session_creator = worker_context.session_creator(
+ scaffold,
+ config=config,
+ checkpoint_dir=checkpoint_dir,
+ max_wait_secs=max_wait_secs)
+ return MonitoredSession(
+ session_creator=session_creator,
+ hooks=all_hooks,
+ stop_grace_period_secs=stop_grace_period_secs)
+
+
@tf_export('train.MonitoredTrainingSession')
def MonitoredTrainingSession(master='', # pylint: disable=invalid-name
is_chief=True,
@@ -373,14 +431,35 @@ def MonitoredTrainingSession(master='', # pylint: disable=invalid-name
save_checkpoint_steps = None
scaffold = scaffold or Scaffold()
+ worker_context = distribute_coordinator_context.get_current_worker_context()
+
+ if worker_context:
+ return _create_monitored_session_with_worker_context(
+ worker_context,
+ scaffold,
+ checkpoint_dir=checkpoint_dir,
+ hooks=hooks,
+ chief_only_hooks=chief_only_hooks,
+ save_checkpoint_secs=save_checkpoint_secs,
+ save_summaries_steps=save_summaries_steps,
+ save_summaries_secs=save_summaries_secs,
+ config=config,
+ stop_grace_period_secs=stop_grace_period_secs,
+ log_step_count_steps=log_step_count_steps,
+ max_wait_secs=max_wait_secs,
+ save_checkpoint_steps=save_checkpoint_steps,
+ summary_dir=summary_dir)
+
if not is_chief:
session_creator = WorkerSessionCreator(
scaffold=scaffold,
master=master,
config=config,
max_wait_secs=max_wait_secs)
- return MonitoredSession(session_creator=session_creator, hooks=hooks or [],
- stop_grace_period_secs=stop_grace_period_secs)
+ return MonitoredSession(
+ session_creator=session_creator,
+ hooks=hooks or [],
+ stop_grace_period_secs=stop_grace_period_secs)
all_hooks = []
if chief_only_hooks:
@@ -400,25 +479,29 @@ def MonitoredTrainingSession(master='', # pylint: disable=invalid-name
if (save_summaries_steps and save_summaries_steps > 0) or (
save_summaries_secs and save_summaries_secs > 0):
- all_hooks.append(basic_session_run_hooks.SummarySaverHook(
- scaffold=scaffold,
- save_steps=save_summaries_steps,
- save_secs=save_summaries_secs,
- output_dir=summary_dir))
+ all_hooks.append(
+ basic_session_run_hooks.SummarySaverHook(
+ scaffold=scaffold,
+ save_steps=save_summaries_steps,
+ save_secs=save_summaries_secs,
+ output_dir=summary_dir))
if checkpoint_dir:
if (save_checkpoint_secs and save_checkpoint_secs > 0) or (
save_checkpoint_steps and save_checkpoint_steps > 0):
- all_hooks.append(basic_session_run_hooks.CheckpointSaverHook(
- checkpoint_dir,
- save_steps=save_checkpoint_steps,
- save_secs=save_checkpoint_secs,
- scaffold=scaffold))
+ all_hooks.append(
+ basic_session_run_hooks.CheckpointSaverHook(
+ checkpoint_dir,
+ save_steps=save_checkpoint_steps,
+ save_secs=save_checkpoint_secs,
+ scaffold=scaffold))
if hooks:
all_hooks.extend(hooks)
- return MonitoredSession(session_creator=session_creator, hooks=all_hooks,
- stop_grace_period_secs=stop_grace_period_secs)
+ return MonitoredSession(
+ session_creator=session_creator,
+ hooks=all_hooks,
+ stop_grace_period_secs=stop_grace_period_secs)
@tf_export('train.SessionCreator')
@@ -546,6 +629,11 @@ class _MonitoredSession(object):
self._hooks = hooks or []
for h in self._hooks:
h.begin()
+
+ worker_context = distribute_coordinator_context.get_current_worker_context()
+ if not session_creator and worker_context:
+ session_creator = worker_context.session_creator()
+
# Create the session.
self._coordinated_creator = self._CoordinatedSessionCreator(
session_creator=session_creator or ChiefSessionCreator(),
diff --git a/tensorflow/python/training/monitored_session_test.py b/tensorflow/python/training/monitored_session_test.py
index 92533ca4f3..ff586b6c03 100644
--- a/tensorflow/python/training/monitored_session_test.py
+++ b/tensorflow/python/training/monitored_session_test.py
@@ -32,6 +32,7 @@ from tensorflow.contrib.testing.python.framework import util_test
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import debug_pb2
from tensorflow.python.client import session as session_lib
+from tensorflow.python.distribute import distribute_coordinator
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
@@ -381,6 +382,119 @@ class MonitoredTrainingSessionTest(test.TestCase):
self.assertEqual(0, session.run(gstep))
+class MockStrategy(object):
+
+ def __init__(self,
+ between_graph=False,
+ should_init=True,
+ should_checkpoint=None,
+ should_save_summary=None):
+ self._between_graph = between_graph
+ self._should_init = should_init
+ self._should_checkpoint = should_checkpoint
+ self._should_save_summary = should_save_summary
+
+ @property
+ def between_graph(self):
+ return self._between_graph
+
+ @property
+ def should_init(self):
+ return self._should_init
+
+ @property
+ def should_checkpoint(self):
+ return self._should_checkpoint
+
+ @property
+ def should_save_summary(self):
+ return self._should_save_summary
+
+
+class MonitoredTrainingSessionWithDistributeCoordinatorTest(test.TestCase):
+ """Test distribute coordinator controls summary saving and checkpointing."""
+
+ def test_summary_hook_enabled(self):
+ context = distribute_coordinator._WorkerContext(
+ MockStrategy(should_save_summary=True), None, None, None)
+
+ logdir = _test_dir(self.get_temp_dir(), 'test_summaries_enabled')
+ with ops.Graph().as_default():
+ gstep = variables_lib.get_or_create_global_step()
+ new_gstep = state_ops.assign_add(gstep, 1)
+ summary.scalar('my_summary_tag', new_gstep * 2)
+ with context, monitored_session.MonitoredTrainingSession(
+ checkpoint_dir=logdir,
+ save_summaries_steps=100,
+ log_step_count_steps=10) as session:
+ for _ in range(101):
+ session.run(new_gstep)
+
+ summaries = util_test.latest_summaries(logdir)
+ tags = [s.summary.value[0].tag for s in summaries]
+ self.assertIn('my_summary_tag', tags)
+ self.assertIn('global_step/sec', tags)
+
+ def test_summary_hook_disabled(self):
+ context = distribute_coordinator._WorkerContext(
+ MockStrategy(should_save_summary=False), None, None, None)
+
+ logdir = _test_dir(self.get_temp_dir(), 'test_summaries_disabled')
+ with ops.Graph().as_default():
+ gstep = variables_lib.get_or_create_global_step()
+ new_gstep = state_ops.assign_add(gstep, 1)
+ summary.scalar('my_summary_tag', new_gstep * 2)
+ with context, monitored_session.MonitoredTrainingSession(
+ checkpoint_dir=logdir,
+ save_summaries_steps=100,
+ log_step_count_steps=10) as session:
+ for _ in range(101):
+ session.run(new_gstep)
+
+ # No summary is saved.
+ summaries = util_test.latest_summaries(logdir)
+ self.assertEqual(len(summaries), 0)
+
+ def test_checkpoint_hook_enabled(self):
+ context = distribute_coordinator._WorkerContext(
+ MockStrategy(should_checkpoint=True), None, None, None)
+
+ logdir = _test_dir(self.get_temp_dir(), 'test_save_checkpoint_enabled')
+ with ops.Graph().as_default():
+ gstep = variables_lib.get_or_create_global_step()
+ new_gstep = state_ops.assign_add(gstep, 1)
+ with context, monitored_session.MonitoredTrainingSession(
+ checkpoint_dir=logdir,
+ save_checkpoint_steps=100,
+ log_step_count_steps=10) as session:
+ for _ in range(100):
+ session.run(new_gstep)
+
+ # A restart will find the checkpoint and recover automatically.
+ with monitored_session.MonitoredTrainingSession(
+ is_chief=True, checkpoint_dir=logdir) as session:
+ self.assertEqual(100, session.run(gstep))
+
+ def test_checkpoint_hook_disabled(self):
+ context = distribute_coordinator._WorkerContext(
+ MockStrategy(should_checkpoint=False), None, None, None)
+
+ logdir = _test_dir(self.get_temp_dir(), 'test_save_checkpoint_disabled')
+ with ops.Graph().as_default():
+ gstep = variables_lib.get_or_create_global_step()
+ new_gstep = state_ops.assign_add(gstep, 1)
+ with context, monitored_session.MonitoredTrainingSession(
+ checkpoint_dir=logdir,
+ save_checkpoint_steps=100,
+ log_step_count_steps=10) as session:
+ for _ in range(100):
+ session.run(new_gstep)
+
+ # No checkpoint is saved.
+ checkpoint = checkpoint_management.latest_checkpoint(logdir)
+ self.assertIsNone(checkpoint)
+
+
class StopAtNSession(monitored_session._WrappedSession):
"""A wrapped session that stops at the N-th call to _check_stop."""
@@ -1365,8 +1479,8 @@ class MonitoredSessionTest(test.TestCase):
with monitored_session.MonitoredSession(
session_creator=monitored_session.ChiefSessionCreator(
scaffold,
- checkpoint_filename_with_path=
- checkpoint_management.latest_checkpoint(logdir))) as session:
+ checkpoint_filename_with_path=checkpoint_management.
+ latest_checkpoint(logdir))) as session:
self.assertEqual(2, session.run(gstep))
def test_retry_initialization_on_aborted_error(self):
diff --git a/tensorflow/python/training/moving_averages.py b/tensorflow/python/training/moving_averages.py
index 60cc54c264..4b91d1e963 100644
--- a/tensorflow/python/training/moving_averages.py
+++ b/tensorflow/python/training/moving_averages.py
@@ -300,7 +300,7 @@ class ExponentialMovingAverage(object):
for a given variable.
* Build a model normally but load the checkpoint files to evaluate by using
the shadow variable names. For this use the `average_name()` method. See
- the @{tf.train.Saver} for more
+ the `tf.train.Saver` for more
information on restoring saved variables.
Example of restoring the shadow variable values:
diff --git a/tensorflow/python/training/optimizer.py b/tensorflow/python/training/optimizer.py
index f75db08059..1b6bce2865 100644
--- a/tensorflow/python/training/optimizer.py
+++ b/tensorflow/python/training/optimizer.py
@@ -35,6 +35,7 @@ from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
from tensorflow.python.training import slot_creator
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.util import nest
@@ -51,8 +52,8 @@ def get_filtered_grad_fn(grad_fn):
# those variables are accessed in another thread during the gradient
# computation. To get a consistent set of variables, we filter out
# those with `None` gradients.
- def filtered_grad_fn(x=None):
- return [(g, v) for g, v in grad_fn(x) if g is not None]
+ def filtered_grad_fn(*args, **kwargs):
+ return [(g, v) for g, v in grad_fn(*args, **kwargs) if g is not None]
return filtered_grad_fn
@@ -464,7 +465,8 @@ class Optimizer(
# TODO(josh11b): Test that we handle weight decay in a reasonable way.
if (distribute_lib.get_loss_reduction() ==
variable_scope.VariableAggregation.MEAN):
- num_towers = distribute_lib.get_distribution_strategy().num_towers
+ num_towers = distribution_strategy_context.get_distribution_strategy(
+ ).num_towers
if num_towers > 1:
loss_value *= (1. / num_towers)
@@ -482,7 +484,8 @@ class Optimizer(
# Scale loss if using a "mean" loss reduction and multiple towers.
if (distribute_lib.get_loss_reduction() ==
variable_scope.VariableAggregation.MEAN):
- num_towers = distribute_lib.get_distribution_strategy().num_towers
+ num_towers = distribution_strategy_context.get_distribution_strategy(
+ ).num_towers
if num_towers > 1:
loss *= (1. / num_towers)
@@ -548,15 +551,15 @@ class Optimizer(
# methods: _create_slots(), _prepare(), _apply_dense(), and _apply_sparse().
# Handle DistributionStrategy case.
- if distribute_lib.get_cross_tower_context():
+ if distribution_strategy_context.get_cross_tower_context():
raise RuntimeError("Use `_distributed_apply()` instead of "
"`apply_gradients()` in a cross-tower context.")
# TODO(isaprykin): Get rid of `has_distribution_strategy()` check by
# always calling _distributed_apply(), using the default distribution
# as needed.
- if distribute_lib.has_distribution_strategy():
- grads_and_vars = get_filtered_grad_fn(lambda _: grads_and_vars)()
- return distribute_lib.get_tower_context().merge_call(
+ if distribution_strategy_context.has_distribution_strategy():
+ grads_and_vars = get_filtered_grad_fn(lambda: grads_and_vars)()
+ return distribution_strategy_context.get_tower_context().merge_call(
self._distributed_apply, grads_and_vars, global_step, name)
# No DistributionStrategy case.
@@ -799,7 +802,8 @@ class Optimizer(
v = self._non_slot_dict.get(key, None)
if v is None:
self._maybe_initialize_checkpointable()
- distribution_strategy = distribute_lib.get_distribution_strategy()
+ distribution_strategy = (
+ distribution_strategy_context.get_distribution_strategy())
with distribution_strategy.colocate_vars_with(colocate_with):
if eager:
restored_initial_value = self._preload_simple_restoration(
diff --git a/tensorflow/python/training/quantize_training.i b/tensorflow/python/training/quantize_training.i
index 54d6789616..41e62e0252 100644
--- a/tensorflow/python/training/quantize_training.i
+++ b/tensorflow/python/training/quantize_training.i
@@ -56,7 +56,7 @@ PyObject* DoQuantizeTrainingOnGraphDefHelper(
%insert("python") %{
def do_quantize_training_on_graphdef(input_graph, num_bits):
- """A general quantization scheme is being developed in @{tf.contrib.quantize}.
+ """A general quantization scheme is being developed in `tf.contrib.quantize`.
Consider using that instead, though since it is in the tf.contrib namespace,
it is not subject to backward compatibility guarantees.
diff --git a/tensorflow/python/training/saver.py b/tensorflow/python/training/saver.py
index 213c11c50d..274c856686 100644
--- a/tensorflow/python/training/saver.py
+++ b/tensorflow/python/training/saver.py
@@ -809,6 +809,22 @@ class BaseSaverBuilder(object):
keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours,
version=self._write_version)
else:
+ graph = ops.get_default_graph()
+ # Do some sanity checking on collections containing
+ # PartitionedVariables. If a saved collection has a PartitionedVariable,
+ # the GraphDef needs to include concat ops to get the value (or there'll
+ # be a lookup error on load).
+ check_collection_list = graph.get_all_collection_keys()
+ for collection_type in check_collection_list:
+ for element in graph.get_collection(collection_type):
+ if isinstance(element, variables.PartitionedVariable):
+ try:
+ graph.get_operation_by_name(element.name)
+ except KeyError:
+ # Create a concat op for this PartitionedVariable. The user may
+ # not need it, but we'll try looking it up on MetaGraph restore
+ # since it's in a collection.
+ element.as_tensor()
return saver_pb2.SaverDef(
filename_tensor_name=filename_tensor.name,
save_tensor_name=save_tensor.name,
@@ -869,7 +885,7 @@ def _get_saver_or_default():
class Saver(object):
"""Saves and restores variables.
- See @{$variables$Variables}
+ See [Variables](https://tensorflow.org/guide/variables)
for an overview of variables, saving and restoring.
The `Saver` class adds ops to save and restore variables to and from
@@ -1529,9 +1545,7 @@ class Saver(object):
# 1. The checkpoint would not be loaded successfully as is. Try to parse
# it as an object-based checkpoint.
try:
- reader = pywrap_tensorflow.NewCheckpointReader(save_path)
- object_graph_string = reader.get_tensor(
- checkpointable.OBJECT_GRAPH_PROTO_KEY)
+ names_to_keys = object_graph_key_mapping(save_path)
except errors.NotFoundError:
# 2. This is not an object-based checkpoint, which likely means there
# is a graph mismatch. Re-raise the original error with
@@ -1546,42 +1560,19 @@ class Saver(object):
"may be somewhat fragile, and will re-build the Saver. Instead, "
"consider loading object-based checkpoints using "
"tf.train.Checkpoint().")
- self._restore_from_object_based_checkpoint(
- sess=sess, save_path=save_path,
- object_graph_string=object_graph_string)
+ self._object_restore_saver = saver_from_object_based_checkpoint(
+ checkpoint_path=save_path,
+ var_list=self._var_list,
+ builder=self._builder,
+ names_to_keys=names_to_keys,
+ cached_saver=self._object_restore_saver)
+ self._object_restore_saver.restore(sess=sess, save_path=save_path)
except errors.InvalidArgumentError as err:
# There is a mismatch between the graph and the checkpoint being loaded.
# We add a more reasonable error message here to help users (b/110263146)
raise _wrap_restore_error_with_msg(
err, "a mismatch between the current graph and the graph")
- def _restore_from_object_based_checkpoint(self, sess, save_path,
- object_graph_string):
- """A compatibility mode for reading object-based checkpoints."""
- object_graph_proto = (
- checkpointable_object_graph_pb2.CheckpointableObjectGraph())
- object_graph_proto.ParseFromString(object_graph_string)
- names_to_keys = {}
- for node in object_graph_proto.nodes:
- for attribute in node.attributes:
- names_to_keys[attribute.full_name] = attribute.checkpoint_key
- saveables = self._builder._ValidateAndSliceInputs(self._var_list) # pylint: disable=protected-access
- for saveable in saveables:
- for spec in saveable.specs:
- if spec.name not in names_to_keys:
- raise errors.NotFoundError(
- None, None,
- message=("Attempting to load an object-based checkpoint using "
- "variable names, but could not find %s in the "
- "checkpoint.") % spec.name)
- spec.name = names_to_keys[spec.name]
- if self._object_restore_saver is None:
- # Cache the Saver so multiple restore() calls don't pollute the graph when
- # graph building. This assumes keys are consistent (i.e. this is the same
- # type of object-based checkpoint we saw previously).
- self._object_restore_saver = Saver(saveables)
- self._object_restore_saver.restore(sess=sess, save_path=save_path)
-
@staticmethod
def _add_collection_def(meta_graph_def, key, export_scope=None):
"""Adds a collection to MetaGraphDef protocol buffer.
@@ -1815,3 +1806,92 @@ ops.register_proto_function(
proto_type=saver_pb2.SaverDef,
to_proto=Saver.to_proto,
from_proto=Saver.from_proto)
+
+
+def object_graph_key_mapping(checkpoint_path):
+ """Return name to key mappings from the checkpoint.
+
+ Args:
+ checkpoint_path: string, path to object-based checkpoint
+
+ Returns:
+ Dictionary mapping tensor names to checkpoint keys.
+ """
+ reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
+ object_graph_string = reader.get_tensor(
+ checkpointable.OBJECT_GRAPH_PROTO_KEY)
+ object_graph_proto = (
+ checkpointable_object_graph_pb2.CheckpointableObjectGraph())
+ object_graph_proto.ParseFromString(object_graph_string)
+ names_to_keys = {}
+ for node in object_graph_proto.nodes:
+ for attribute in node.attributes:
+ names_to_keys[attribute.full_name] = attribute.checkpoint_key
+ return names_to_keys
+
+
+def saver_from_object_based_checkpoint(
+ checkpoint_path, var_list=None, builder=None, names_to_keys=None,
+ cached_saver=None):
+ """Return a `Saver` which reads from an object-based checkpoint.
+
+ This function validates that all variables in the variables list are remapped
+ in the object-based checkpoint (or `names_to_keys` dict if provided). A
+ saver will be created with the list of remapped variables.
+
+ The `cached_saver` argument allows the user to pass in a previously created
+ saver, so multiple `saver.restore()` calls don't pollute the graph when graph
+ building. This assumes that keys are consistent, meaning that the
+ 1) `checkpoint_path` checkpoint, and
+ 2) checkpoint used to create the `cached_saver`
+ are the same type of object-based checkpoint. If this argument is set, this
+ function will simply validate that all variables have been remapped by the
+ checkpoint at `checkpoint_path`.
+
+ Note that in general, `tf.train.Checkpoint` should be used to restore/save an
+ object-based checkpoint.
+
+ Args:
+ checkpoint_path: string, path to object-based checkpoint
+ var_list: list of `Variables` that appear in the checkpoint. If `None`,
+ `var_list` will be set to all saveable objects.
+ builder: a `BaseSaverBuilder` instance. If `None`, a new `BulkSaverBuilder`
+ will be created.
+ names_to_keys: dict mapping string tensor names to checkpooint keys. If
+ `None`, this dict will be generated from the checkpoint file.
+ cached_saver: Cached `Saver` object with remapped variables.
+
+ Returns:
+ `Saver` with remapped variables for reading from an object-based checkpoint.
+
+ Raises:
+ ValueError if the checkpoint provided is not an object-based checkpoint.
+ NotFoundError: If one of the variables in `var_list` can not be found in the
+ checkpoint. This could mean the checkpoint or `names_to_keys` mapping is
+ missing the variable.
+ """
+ if names_to_keys is None:
+ try:
+ names_to_keys = object_graph_key_mapping(checkpoint_path)
+ except errors.NotFoundError:
+ raise ValueError("Checkpoint in %s not an object-based checkpoint."
+ % checkpoint_path)
+ if var_list is None:
+ var_list = variables._all_saveable_objects() # pylint: disable=protected-access
+ if builder is None:
+ builder = BulkSaverBuilder()
+
+ saveables = builder._ValidateAndSliceInputs(var_list) # pylint: disable=protected-access
+ for saveable in saveables:
+ for spec in saveable.specs:
+ if spec.name not in names_to_keys:
+ raise errors.NotFoundError(
+ None, None,
+ message=("Attempting to load an object-based checkpoint using "
+ "variable names, but could not find %s in the "
+ "checkpoint.") % spec.name)
+ spec.name = names_to_keys[spec.name]
+
+ if cached_saver is None:
+ return Saver(saveables)
+ return cached_saver
diff --git a/tensorflow/python/training/saver_test.py b/tensorflow/python/training/saver_test.py
index 941aafc780..b55e64122a 100644
--- a/tensorflow/python/training/saver_test.py
+++ b/tensorflow/python/training/saver_test.py
@@ -784,6 +784,32 @@ class SaverTest(test.TestCase):
self.assertEqual(20.0, v1.eval())
save.save(sess, save_path)
+ def testSaveRestoreAndValidateVariableDtype(self):
+ for variable_op in [
+ variables.Variable, resource_variable_ops.ResourceVariable
+ ]:
+ save_path = os.path.join(self.get_temp_dir(), "basic_save_restore")
+
+ # Build the first session.
+ with self.test_session(graph=ops_lib.Graph()) as sess:
+ v0 = variable_op(10.0, name="v0", dtype=dtypes.float32)
+
+ if not context.executing_eagerly():
+ self.evaluate([variables.global_variables_initializer()])
+
+ save = saver_module.Saver({"v0": v0})
+ save.save(sess, save_path)
+
+ # Start a second session.
+ with self.test_session(graph=ops_lib.Graph()) as sess:
+ v0_wrong_dtype = variable_op(1, name="v0", dtype=dtypes.int32)
+ # Restore the saved value with different dtype
+ # in the parameter nodes.
+ save = saver_module.Saver({"v0": v0_wrong_dtype})
+ with self.assertRaisesRegexp(errors.InvalidArgumentError,
+ "original dtype"):
+ save.restore(sess, save_path)
+
# Test restoring large tensors (triggers a thread pool)
def testRestoreLargeTensors(self):
save_dir = self.get_temp_dir()
diff --git a/tensorflow/python/training/server_lib.py b/tensorflow/python/training/server_lib.py
index 58cf5277fe..46543413e4 100644
--- a/tensorflow/python/training/server_lib.py
+++ b/tensorflow/python/training/server_lib.py
@@ -98,9 +98,9 @@ class Server(object):
"""An in-process TensorFlow server, for use in distributed training.
A `tf.train.Server` instance encapsulates a set of devices and a
- @{tf.Session} target that
+ `tf.Session` target that
can participate in distributed training. A server belongs to a
- cluster (specified by a @{tf.train.ClusterSpec}), and
+ cluster (specified by a `tf.train.ClusterSpec`), and
corresponds to a particular task in a named job. The server can
communicate with any other server in the same cluster.
"""
@@ -186,7 +186,7 @@ class Server(object):
"""Returns the target for a `tf.Session` to connect to this server.
To create a
- @{tf.Session} that
+ `tf.Session` that
connects to this server, use the following snippet:
```python
@@ -230,7 +230,7 @@ class ClusterSpec(object):
A `tf.train.ClusterSpec` represents the set of processes that
participate in a distributed TensorFlow computation. Every
- @{tf.train.Server} is constructed in a particular cluster.
+ `tf.train.Server` is constructed in a particular cluster.
To create a cluster with two jobs and five tasks, you specify the
mapping from job names to lists of network addresses (typically
@@ -421,7 +421,7 @@ class ClusterSpec(object):
NOTE: For backwards compatibility, this method returns a list. If
the given job was defined with a sparse set of task indices, the
length of this list may not reflect the number of tasks defined in
- this job. Use the @{tf.train.ClusterSpec.num_tasks} method
+ this job. Use the `tf.train.ClusterSpec.num_tasks` method
to find the number of tasks defined in a particular job.
Args:
diff --git a/tensorflow/python/training/slot_creator.py b/tensorflow/python/training/slot_creator.py
index 258a6f045d..d76b22acd8 100644
--- a/tensorflow/python/training/slot_creator.py
+++ b/tensorflow/python/training/slot_creator.py
@@ -45,7 +45,7 @@ from tensorflow.python.ops import init_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
-from tensorflow.python.training import distribute as distribute_lib
+from tensorflow.python.training import distribution_strategy_context
def _create_slot_var(primary, val, scope, validate_shape, shape, dtype):
@@ -112,7 +112,8 @@ def create_slot(primary, val, name, colocate_with_primary=True):
prefix = primary.op.name
with variable_scope.variable_scope(None, prefix + "/" + name):
if colocate_with_primary:
- distribution_strategy = distribute_lib.get_distribution_strategy()
+ distribution_strategy = (
+ distribution_strategy_context.get_distribution_strategy())
with distribution_strategy.colocate_vars_with(primary):
return _create_slot_var(primary, val, "", validate_shape, None, None)
else:
@@ -149,7 +150,8 @@ def create_slot_with_initializer(primary, initializer, shape, dtype, name,
prefix = primary.op.name
with variable_scope.variable_scope(None, prefix + "/" + name):
if colocate_with_primary:
- distribution_strategy = distribute_lib.get_distribution_strategy()
+ distribution_strategy = (
+ distribution_strategy_context.get_distribution_strategy())
with distribution_strategy.colocate_vars_with(primary):
return _create_slot_var(primary, initializer, "", validate_shape, shape,
dtype)
diff --git a/tensorflow/python/training/supervisor.py b/tensorflow/python/training/supervisor.py
index 372ea415df..0755364bbe 100644
--- a/tensorflow/python/training/supervisor.py
+++ b/tensorflow/python/training/supervisor.py
@@ -45,7 +45,7 @@ class Supervisor(object):
"""A training helper that checkpoints models and computes summaries.
This class is deprecated. Please use
- @{tf.train.MonitoredTrainingSession} instead.
+ `tf.train.MonitoredTrainingSession` instead.
The Supervisor is a small wrapper around a `Coordinator`, a `Saver`,
and a `SessionManager` that takes care of common needs of TensorFlow
@@ -134,7 +134,7 @@ class Supervisor(object):
* Specifying `'local'` requests a session that uses the RPC-based
"Master interface" to run TensorFlow programs. See
- @{tf.train.Server.create_local_server} for
+ `tf.train.Server.create_local_server` for
details.
* Specifying `'grpc://hostname:port'` requests a session that uses
diff --git a/tensorflow/python/training/sync_replicas_optimizer.py b/tensorflow/python/training/sync_replicas_optimizer.py
index 0c6cf910d1..7afaa92699 100644
--- a/tensorflow/python/training/sync_replicas_optimizer.py
+++ b/tensorflow/python/training/sync_replicas_optimizer.py
@@ -53,7 +53,7 @@ class SyncReplicasOptimizer(optimizer.Optimizer):
which replicas can fetch the new variables and continue.
The following accumulators/queue are created:
- <empty line>
+
* N `gradient accumulators`, one per variable to train. Gradients are pushed
to them and the chief worker will wait until enough gradients are collected
and then average them before applying to variables. The accumulator will
@@ -68,7 +68,7 @@ class SyncReplicasOptimizer(optimizer.Optimizer):
The optimizer adds nodes to the graph to collect gradients and pause the
trainers until variables are updated.
For the Parameter Server job:
- <empty line>
+
1. An accumulator is created for each variable, and each replica pushes the
gradients into the accumulators instead of directly applying them to the
variables.
@@ -81,7 +81,7 @@ class SyncReplicasOptimizer(optimizer.Optimizer):
update its local_step variable and start the next batch.
For the replicas:
- <empty line>
+
1. Start a step: fetch variables and compute gradients.
2. Once the gradients have been computed, push them into gradient
accumulators. Each accumulator will check the staleness and drop the stale.
diff --git a/tensorflow/python/training/training.py b/tensorflow/python/training/training.py
index 544010afbe..686c4be31a 100644
--- a/tensorflow/python/training/training.py
+++ b/tensorflow/python/training/training.py
@@ -15,7 +15,7 @@
"""Support for training models.
-See the @{$python/train} guide.
+See the [Training](https://tensorflow.org/api_guides/python/train) guide.
"""
# Optimizers.
@@ -53,6 +53,7 @@ from tensorflow.python.training import input as _input
from tensorflow.python.training.input import * # pylint: disable=redefined-builtin
# pylint: enable=wildcard-import
+from tensorflow.python.training.basic_session_run_hooks import get_or_create_steps_per_run_variable
from tensorflow.python.training.basic_session_run_hooks import SecondOrStepTimer
from tensorflow.python.training.basic_session_run_hooks import LoggingTensorHook
from tensorflow.python.training.basic_session_run_hooks import StopAtStepHook
diff --git a/tensorflow/python/training/warm_starting_util.py b/tensorflow/python/training/warm_starting_util.py
index b1a7cfab83..0ba7ba983d 100644
--- a/tensorflow/python/training/warm_starting_util.py
+++ b/tensorflow/python/training/warm_starting_util.py
@@ -44,7 +44,7 @@ class VocabInfo(
])):
"""Vocabulary information for warm-starting.
- See @{tf.estimator.WarmStartSettings$WarmStartSettings} for examples of using
+ See `tf.estimator.WarmStartSettings` for examples of using
VocabInfo to warm-start.
Attributes:
diff --git a/tensorflow/python/util/deprecation.py b/tensorflow/python/util/deprecation.py
index 74e1fb227f..c43589f5c4 100644
--- a/tensorflow/python/util/deprecation.py
+++ b/tensorflow/python/util/deprecation.py
@@ -393,8 +393,8 @@ def deprecated_args(date, instructions, *deprecated_arg_names_or_tuples,
Returns:
Dictionary from arg_name to DeprecatedArgSpec.
"""
- arg_name_to_pos = dict(
- (name, pos) for (pos, name) in enumerate(arg_spec.args))
+ arg_name_to_pos = {
+ name: pos for pos, name in enumerate(arg_spec.args)}
deprecated_positional_args = {}
for arg_name, spec in iter(names_to_ok_vals.items()):
if arg_name in arg_name_to_pos:
diff --git a/tensorflow/python/util/nest.py b/tensorflow/python/util/nest.py
index faae0d89c3..2968ca9c07 100644
--- a/tensorflow/python/util/nest.py
+++ b/tensorflow/python/util/nest.py
@@ -62,6 +62,10 @@ def _is_namedtuple(instance, strict=False):
return _pywrap_tensorflow.IsNamedtuple(instance, strict)
+# See the swig file (util.i) for documentation.
+_is_mapping = _pywrap_tensorflow.IsMapping
+
+
def _sequence_like(instance, args):
"""Converts the sequence `args` to the same type as `instance`.
@@ -73,7 +77,7 @@ def _sequence_like(instance, args):
Returns:
`args` with the type of `instance`.
"""
- if isinstance(instance, (dict, _collections.Mapping)):
+ if _is_mapping(instance):
# Pack dictionaries in a deterministic order by sorting the keys.
# Notice this means that we ignore the original order of `OrderedDict`
# instances. This is intentional, to avoid potential bugs caused by mixing
@@ -89,7 +93,7 @@ def _sequence_like(instance, args):
def _yield_value(iterable):
- if isinstance(iterable, (dict, _collections.Mapping)):
+ if _is_mapping(iterable):
# Iterate through dictionaries in a deterministic order by sorting the
# keys. Notice this means that we ignore the original order of `OrderedDict`
# instances. This is intentional, to avoid potential bugs caused by mixing
@@ -102,53 +106,16 @@ def _yield_value(iterable):
yield value
-def is_sequence(seq):
- """Returns a true if its input is a collections.Sequence (except strings).
+# See the swig file (util.i) for documentation.
+is_sequence = _pywrap_tensorflow.IsSequence
- Args:
- seq: an input sequence.
- Returns:
- True if the sequence is a not a string and is a collections.Sequence or a
- dict.
- """
- return _pywrap_tensorflow.IsSequence(seq)
+# See the swig file (util.i) for documentation.
+flatten = _pywrap_tensorflow.Flatten
-def flatten(nest):
- """Returns a flat list from a given nested structure.
-
- If `nest` is not a sequence, tuple, or dict, then returns a single-element
- list: `[nest]`.
-
- In the case of dict instances, the sequence consists of the values, sorted by
- key to ensure deterministic behavior. This is true also for `OrderedDict`
- instances: their sequence order is ignored, the sorting order of keys is
- used instead. The same convention is followed in `pack_sequence_as`. This
- correctly repacks dicts and `OrderedDict`s after they have been flattened,
- and also allows flattening an `OrderedDict` and then repacking it back using
- a corresponding plain dict, or vice-versa.
- Dictionaries with non-sortable keys cannot be flattened.
-
- Users must not modify any collections used in `nest` while this function is
- running.
-
- Args:
- nest: an arbitrarily nested structure or a scalar object. Note, numpy
- arrays are considered scalars.
-
- Returns:
- A Python list, the flattened version of the input.
-
- Raises:
- TypeError: The nest is or contains a dict with non-sortable keys.
- """
- return _pywrap_tensorflow.Flatten(nest)
-
-
-def _same_namedtuples(nest1, nest2):
- """Returns True if the two namedtuples have the same name and fields."""
- return _pywrap_tensorflow.SameNamedtuples(nest1, nest2)
+# See the swig file (util.i) for documentation.
+_same_namedtuples = _pywrap_tensorflow.SameNamedtuples
def assert_same_structure(nest1, nest2, check_types=True):
@@ -311,14 +278,17 @@ def pack_sequence_as(structure, flat_sequence):
% len(flat_sequence))
return flat_sequence[0]
- flat_structure = flatten(structure)
- if len(flat_structure) != len(flat_sequence):
- raise ValueError(
- "Could not pack sequence. Structure had %d elements, but flat_sequence "
- "had %d elements. Structure: %s, flat_sequence: %s."
- % (len(flat_structure), len(flat_sequence), structure, flat_sequence))
-
- _, packed = _packed_nest_with_indices(structure, flat_sequence, 0)
+ try:
+ final_index, packed = _packed_nest_with_indices(structure, flat_sequence, 0)
+ if final_index < len(flat_sequence):
+ raise IndexError
+ except IndexError:
+ flat_structure = flatten(structure)
+ if len(flat_structure) != len(flat_sequence):
+ raise ValueError(
+ "Could not pack sequence. Structure had %d elements, but "
+ "flat_sequence had %d elements. Structure: %s, flat_sequence: %s." %
+ (len(flat_structure), len(flat_sequence), structure, flat_sequence))
return _sequence_like(structure, packed)
diff --git a/tensorflow/python/util/tf_should_use.py b/tensorflow/python/util/tf_should_use.py
index 28e49afa02..ca6710bcf2 100644
--- a/tensorflow/python/util/tf_should_use.py
+++ b/tensorflow/python/util/tf_should_use.py
@@ -17,23 +17,124 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
-import functools
-import types
+import copy
+import sys
+import traceback
import six # pylint: disable=unused-import
-from tensorflow.python.eager import context
+from tensorflow.python.platform import tf_logging
from tensorflow.python.util import tf_decorator
# pylint: enable=g-bad-import-order,g-import-not-at-top
-# TODO(b/65412899): Re-implement to avoid leaking python objects.
-# This function / class remains since the API is public (mark_used()).
+class _TFShouldUseHelper(object):
+ """Object stored in TFShouldUse-wrapped objects.
+
+ When it is deleted it will emit a warning or error if its `sate` method
+ has not been called by time of deletion.
+ """
+
+ def __init__(self, type_, repr_, stack_frame, fatal_error_if_unsated):
+ self._type = type_
+ self._repr = repr_
+ self._stack_frame = stack_frame
+ self._fatal_error_if_unsated = fatal_error_if_unsated
+ self._sated = False
+
+ def sate(self):
+ self._sated = True
+ self._type = None
+ self._repr = None
+ self._stack_frame = None
+ self._logging_module = None
+
+ def __del__(self):
+ if self._sated:
+ return
+ if self._fatal_error_if_unsated:
+ logger = tf_logging.fatal
+ else:
+ logger = tf_logging.error
+ creation_stack = ''.join(
+ [line.rstrip() for line in traceback.format_stack(self._stack_frame)])
+ logger(
+ '==================================\n'
+ 'Object was never used (type %s):\n%s\nIf you want to mark it as '
+ 'used call its "mark_used()" method.\nIt was originally created '
+ 'here:\n%s\n'
+ '==================================' %
+ (self._type, self._repr, creation_stack))
+
+
+def _new__init__(self, true_value, tf_should_use_helper):
+ # pylint: disable=protected-access
+ self._tf_should_use_helper = tf_should_use_helper
+ self._true_value = true_value
+
+
+def _new__setattr__(self, key, value):
+ if key in ('_tf_should_use_helper', '_true_value'):
+ return object.__setattr__(self, key, value)
+ return setattr(
+ object.__getattribute__(self, '_true_value'),
+ key, value)
+
+
+def _new__getattribute__(self, key):
+ if key not in ('_tf_should_use_helper', '_true_value'):
+ object.__getattribute__(self, '_tf_should_use_helper').sate()
+ if key in ('_tf_should_use_helper', 'mark_used', '__setatt__'):
+ return object.__getattribute__(self, key)
+ return getattr(object.__getattribute__(self, '_true_value'), key)
+
+
+def _new_mark_used(self, *args, **kwargs):
+ object.__getattribute__(self, '_tf_should_use_helper').sate()
+ try:
+ mu = object.__getattribute__(
+ object.__getattribute__(self, '_true_value'),
+ 'mark_used')
+ return mu(*args, **kwargs)
+ except AttributeError:
+ pass
+
+
+_WRAPPERS = dict()
+
+
+def _get_wrapper(x, tf_should_use_helper):
+ """Create a wrapper for object x, whose class subclasses type(x).
+
+ The wrapper will emit a warning if it is deleted without any of its
+ properties being accessed or methods being called.
+
+ Args:
+ x: The instance to wrap.
+ tf_should_use_helper: The object that tracks usage.
+
+ Returns:
+ An object wrapping `x`, of type `type(x)`.
+ """
+ type_x = type(x)
+ memoized = _WRAPPERS.get(type_x, None)
+ if memoized:
+ return memoized(x, tf_should_use_helper)
+
+ tx = copy.deepcopy(type_x)
+ copy_tx = type(tx.__name__, tx.__bases__, dict(tx.__dict__))
+ copy_tx.__init__ = _new__init__
+ copy_tx.__getattribute__ = _new__getattribute__
+ copy_tx.mark_used = _new_mark_used
+ copy_tx.__setattr__ = _new__setattr__
+ _WRAPPERS[type_x] = copy_tx
+
+ return copy_tx(x, tf_should_use_helper)
+
+
def _add_should_use_warning(x, fatal_error=False):
"""Wraps object x so that if it is never used, a warning is logged.
- Does nothing when executing eagerly.
-
Args:
x: Python object.
fatal_error: Python bool. If `True`, tf.logging.fatal is raised
@@ -43,50 +144,22 @@ def _add_should_use_warning(x, fatal_error=False):
An instance of `TFShouldUseWarningWrapper` which subclasses `type(x)`
and is a very shallow wrapper for `x` which logs access into `x`.
"""
- del fatal_error
if x is None or x == []: # pylint: disable=g-explicit-bool-comparison
return x
- if context.executing_eagerly():
- # Typically not needed when executing eagerly (the main use case is for ops
- # which need to be incorporated into the graph), and even the no-op wrapper
- # creates reference cycles which require garbage collection.
- return x
-
- def override_method(method):
- def fn(self, *args, **kwargs):
- return method(self, *args, **kwargs)
- return fn
-
- class TFShouldUseWarningWrapper(type(x)):
- """Wrapper for objects that keeps track of their use."""
-
- def __init__(self, true_self):
- self.__dict__ = true_self.__dict__
+ # Extract the current frame for later use by traceback printing.
+ try:
+ raise ValueError()
+ except ValueError:
+ stack_frame = sys.exc_info()[2].tb_frame.f_back
- # Not sure why this pylint warning is being used; this is not an
- # old class form.
- # pylint: disable=super-on-old-class
- def __getattribute__(self, name):
- return super(TFShouldUseWarningWrapper, self).__getattribute__(name)
-
- def mark_used(self, *args, **kwargs):
- return
+ tf_should_use_helper = _TFShouldUseHelper(
+ type_=type(x),
+ repr_=repr(x),
+ stack_frame=stack_frame,
+ fatal_error_if_unsated=fatal_error)
- # pylint: enable=super-on-old-class
-
- for name in dir(TFShouldUseWarningWrapper):
- method = getattr(TFShouldUseWarningWrapper, name)
- if not isinstance(method, types.FunctionType):
- continue
- if name in ('__init__', '__getattribute__', '__del__', 'mark_used'):
- continue
- setattr(TFShouldUseWarningWrapper, name,
- functools.wraps(method)(override_method(method)))
-
- wrapped = TFShouldUseWarningWrapper(x)
- wrapped.__doc__ = x.__doc__ # functools.wraps fails on some objects.
- return wrapped
+ return _get_wrapper(x, tf_should_use_helper)
def should_use_result(fn):
@@ -106,8 +179,6 @@ def should_use_result(fn):
- `t != 0`. In this case, comparison is done on types / ids.
- `isinstance(t, tf.Tensor)`. Similar to above.
- Does nothing when executing eagerly.
-
Args:
fn: The function to wrap.
@@ -142,8 +213,6 @@ def must_use_result_or_fatal(fn):
- `t != 0`. In this case, comparison is done on types / ids.
- `isinstance(t, tf.Tensor)`. Similar to above.
- Does nothing when executing eagerly.
-
Args:
fn: The function to wrap.
diff --git a/tensorflow/python/util/tf_should_use_test.py b/tensorflow/python/util/tf_should_use_test.py
index 4c6e48b11c..16fa1f547d 100644
--- a/tensorflow/python/util/tf_should_use_test.py
+++ b/tensorflow/python/util/tf_should_use_test.py
@@ -30,48 +30,51 @@ from tensorflow.python.util import tf_should_use
@contextlib.contextmanager
-def reroute_error(captured):
+def reroute_error():
"""Temporarily reroute errors written to tf_logging.error into `captured`."""
- del captured[:]
- true_logger = tf_logging.error
- def capture_errors(*args, **unused_kwargs):
- captured.extend(args)
- tf_logging.error = capture_errors
- try:
- yield
- finally:
- tf_logging.error = true_logger
+ with test.mock.patch.object(tf_should_use.tf_logging, 'error') as error:
+ with test.mock.patch.object(tf_should_use.tf_logging, 'fatal') as fatal:
+ yield error, fatal
class TfShouldUseTest(test.TestCase):
def testAddShouldUseWarningWhenNotUsed(self):
- self.skipTest('b/65412899')
c = constant_op.constant(0, name='blah0')
- captured = []
- with reroute_error(captured):
- def in_this_function():
- h = tf_should_use._add_should_use_warning(c)
- del h
+ def in_this_function():
+ h = tf_should_use._add_should_use_warning(c)
+ del h
+ with reroute_error() as (error, _):
in_this_function()
- self.assertIn('Object was never used', '\n'.join(captured))
- self.assertIn('blah0:0', '\n'.join(captured))
- self.assertIn('in_this_function', '\n'.join(captured))
- gc.collect()
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ self.assertIn('blah0:0', msg)
+ self.assertIn('in_this_function', msg)
+ self.assertFalse(gc.garbage)
+
+ def testAddShouldUseFatalWhenNotUsed(self):
+ c = constant_op.constant(0, name='blah0')
+ def in_this_function():
+ h = tf_should_use._add_should_use_warning(c, fatal_error=True)
+ del h
+ with reroute_error() as (_, fatal):
+ in_this_function()
+ msg = '\n'.join(fatal.call_args[0])
+ self.assertIn('Object was never used', msg)
+ self.assertIn('blah0:0', msg)
+ self.assertIn('in_this_function', msg)
self.assertFalse(gc.garbage)
def _testAddShouldUseWarningWhenUsed(self, fn, name):
c = constant_op.constant(0, name=name)
- captured = []
- with reroute_error(captured):
+ with reroute_error() as (error, fatal):
h = tf_should_use._add_should_use_warning(c)
fn(h)
del h
- self.assertNotIn('Object was never used', '\n'.join(captured))
- self.assertNotIn('%s:0' % name, '\n'.join(captured))
+ error.assert_not_called()
+ fatal.assert_not_called()
def testAddShouldUseWarningWhenUsedWithAdd(self):
- self.skipTest('b/65412899')
def add(h):
_ = h + 1
self._testAddShouldUseWarningWhenUsed(add, name='blah_add')
@@ -79,7 +82,6 @@ class TfShouldUseTest(test.TestCase):
self.assertFalse(gc.garbage)
def testAddShouldUseWarningWhenUsedWithGetName(self):
- self.skipTest('b/65412899')
def get_name(h):
_ = h.name
self._testAddShouldUseWarningWhenUsed(get_name, name='blah_get_name')
@@ -87,35 +89,33 @@ class TfShouldUseTest(test.TestCase):
self.assertFalse(gc.garbage)
def testShouldUseResult(self):
- self.skipTest('b/65412899')
@tf_should_use.should_use_result
def return_const(value):
return constant_op.constant(value, name='blah2')
- captured = []
- with reroute_error(captured):
+ with reroute_error() as (error, _):
return_const(0.0)
- self.assertIn('Object was never used', '\n'.join(captured))
- self.assertIn('blah2:0', '\n'.join(captured))
- self.assertIn('return_const', '\n'.join(captured))
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ self.assertIn('blah2:0', msg)
+ self.assertIn('return_const', msg)
gc.collect()
self.assertFalse(gc.garbage)
def testShouldUseResultWhenNotReallyUsed(self):
- self.skipTest('b/65412899')
@tf_should_use.should_use_result
def return_const(value):
return constant_op.constant(value, name='blah3')
- captured = []
- with reroute_error(captured):
+ with reroute_error() as (error, _):
with self.test_session():
return_const(0.0)
# Creating another op and executing it does not mark the
# unused op as being "used".
v = constant_op.constant(1.0, name='meh')
v.eval()
- self.assertIn('Object was never used', '\n'.join(captured))
- self.assertIn('blah3:0', '\n'.join(captured))
- self.assertIn('return_const', '\n'.join(captured))
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ self.assertIn('blah3:0', msg)
+ self.assertIn('return_const', msg)
gc.collect()
self.assertFalse(gc.garbage)
diff --git a/tensorflow/python/util/util.cc b/tensorflow/python/util/util.cc
index ebb72079ef..61249d664b 100644
--- a/tensorflow/python/util/util.cc
+++ b/tensorflow/python/util/util.cc
@@ -647,6 +647,7 @@ void RegisterSparseTensorValueClass(PyObject* sparse_tensor_value_class) {
}
bool IsSequence(PyObject* o) { return IsSequenceHelper(o) == 1; }
+bool IsMapping(PyObject* o) { return IsMappingHelper(o) == 1; }
PyObject* Flatten(PyObject* nested) {
PyObject* list = PyList_New(0);
diff --git a/tensorflow/python/util/util.h b/tensorflow/python/util/util.h
index 41dcc969f8..f15ebb6efe 100644
--- a/tensorflow/python/util/util.h
+++ b/tensorflow/python/util/util.h
@@ -47,6 +47,15 @@ bool IsSequence(PyObject* o);
// True if `instance` is a `namedtuple`.
PyObject* IsNamedtuple(PyObject* o, bool strict);
+// Returns a true if its input is a collections.Mapping.
+//
+// Args:
+// seq: the input to be checked.
+//
+// Returns:
+// True if the sequence subclasses mapping.
+bool IsMapping(PyObject* o);
+
// Implements the same interface as tensorflow.util.nest._same_namedtuples
// Returns Py_True iff the two namedtuples have the same name and fields.
// Raises RuntimeError if `o1` or `o2` don't look like namedtuples (don't have
diff --git a/tensorflow/python/util/util.i b/tensorflow/python/util/util.i
index 6ad1484295..8d9f9615d7 100644
--- a/tensorflow/python/util/util.i
+++ b/tensorflow/python/util/util.i
@@ -37,18 +37,70 @@ limitations under the License.
%unignore tensorflow::swig::RegisterSparseTensorValueClass;
%noexception tensorflow::swig::RegisterSparseTensorValueClass;
+%feature("docstring") tensorflow::swig::IsSequence
+"""Returns a true if its input is a collections.Sequence (except strings).
+
+Args:
+ seq: an input sequence.
+
+Returns:
+ True if the sequence is a not a string and is a collections.Sequence or a
+ dict.
+"""
%unignore tensorflow::swig::IsSequence;
%noexception tensorflow::swig::IsSequence;
%unignore tensorflow::swig::IsNamedtuple;
%noexception tensorflow::swig::IsNamedtuple;
+%feature("docstring") tensorflow::swig::IsMapping
+"""Returns True iff `instance` is a `collections.Mapping`.
+
+Args:
+ instance: An instance of a Python object.
+
+Returns:
+ True if `instance` is a `collections.Mapping`.
+"""
+%unignore tensorflow::swig::IsMapping;
+%noexception tensorflow::swig::IsMapping;
+
+%feature("docstring") tensorflow::swig::SameNamedtuples
+"Returns True if the two namedtuples have the same name and fields."
%unignore tensorflow::swig::SameNamedtuples;
%noexception tensorflow::swig::SameNamedtuples;
%unignore tensorflow::swig::AssertSameStructure;
%noexception tensorflow::swig::AssertSameStructure;
+%feature("docstring") tensorflow::swig::Flatten
+"""Returns a flat list from a given nested structure.
+
+If `nest` is not a sequence, tuple, or dict, then returns a single-element
+list: `[nest]`.
+
+In the case of dict instances, the sequence consists of the values, sorted by
+key to ensure deterministic behavior. This is true also for `OrderedDict`
+instances: their sequence order is ignored, the sorting order of keys is
+used instead. The same convention is followed in `pack_sequence_as`. This
+correctly repacks dicts and `OrderedDict`s after they have been flattened,
+and also allows flattening an `OrderedDict` and then repacking it back using
+a corresponding plain dict, or vice-versa.
+Dictionaries with non-sortable keys cannot be flattened.
+
+Users must not modify any collections used in `nest` while this function is
+running.
+
+Args:
+ nest: an arbitrarily nested structure or a scalar object. Note, numpy
+ arrays are considered scalars.
+
+Returns:
+ A Python list, the flattened version of the input.
+
+Raises:
+ TypeError: The nest is or contains a dict with non-sortable keys.
+"""
%unignore tensorflow::swig::Flatten;
%noexception tensorflow::swig::Flatten;
diff --git a/tensorflow/stream_executor/BUILD b/tensorflow/stream_executor/BUILD
index e742f8e8d5..d4d97087ba 100644
--- a/tensorflow/stream_executor/BUILD
+++ b/tensorflow/stream_executor/BUILD
@@ -30,6 +30,7 @@ cc_library(
hdrs = STREAM_EXECUTOR_HEADERS,
linkopts = select({
"//tensorflow:freebsd": [],
+ "//tensorflow:windows": [],
"//conditions:default": ["-ldl"],
}),
visibility = ["//visibility:public"],
@@ -79,6 +80,7 @@ cc_library(
}),
linkopts = select({
"//tensorflow:freebsd": [],
+ "//tensorflow:windows": [],
"//conditions:default": ["-ldl"],
}),
visibility = ["//visibility:public"],
diff --git a/tensorflow/stream_executor/host/host_gpu_executor.h b/tensorflow/stream_executor/host/host_gpu_executor.h
index 858396ef96..7ba1f18101 100644
--- a/tensorflow/stream_executor/host/host_gpu_executor.h
+++ b/tensorflow/stream_executor/host/host_gpu_executor.h
@@ -88,7 +88,7 @@ class HostExecutor : public internal::StreamExecutorInterface {
uint64 size) override;
// No "synchronize all activity" implemented for this platform at the moment.
- bool SynchronizeAllActivity() override { return false; }
+ bool SynchronizeAllActivity() override { return true; }
bool SynchronousMemZero(DeviceMemoryBase *location, uint64 size) override;
bool SynchronousMemSet(DeviceMemoryBase *location, int value,
diff --git a/tensorflow/stream_executor/host/host_stream.cc b/tensorflow/stream_executor/host/host_stream.cc
index 5a7d3b3dd4..bfbfb56cd7 100644
--- a/tensorflow/stream_executor/host/host_stream.cc
+++ b/tensorflow/stream_executor/host/host_stream.cc
@@ -28,18 +28,28 @@ HostStream::HostStream()
HostStream::~HostStream() {}
bool HostStream::EnqueueTask(std::function<void()> task) {
+ struct NotifiedTask {
+ HostStream* stream;
+ std::function<void()> task;
+
+ void operator()() {
+ task();
+ // Destroy the task before unblocking its waiters, as BlockHostUntilDone()
+ // should guarantee that all tasks are destroyed.
+ task = std::function<void()>();
+ {
+ mutex_lock lock(stream->mu_);
+ --stream->pending_tasks_;
+ }
+ stream->completion_condition_.notify_all();
+ }
+ };
+
{
mutex_lock lock(mu_);
++pending_tasks_;
}
- host_executor_->Schedule([this, task]() {
- task();
- {
- mutex_lock lock(mu_);
- --pending_tasks_;
- }
- completion_condition_.notify_all();
- });
+ host_executor_->Schedule(NotifiedTask{this, std::move(task)});
return true;
}
diff --git a/tensorflow/stream_executor/stream_executor_internal.h b/tensorflow/stream_executor/stream_executor_internal.h
index 92e5376835..59a477b5c9 100644
--- a/tensorflow/stream_executor/stream_executor_internal.h
+++ b/tensorflow/stream_executor/stream_executor_internal.h
@@ -236,7 +236,7 @@ class StreamExecutorInterface {
virtual bool Memcpy(Stream *stream, DeviceMemoryBase *gpu_dst,
const void *host_src, uint64 size) = 0;
virtual bool MemcpyDeviceToDevice(Stream *stream, DeviceMemoryBase *gpu_dst,
- const DeviceMemoryBase &host_src,
+ const DeviceMemoryBase &gpu_src,
uint64 size) = 0;
virtual bool HostCallback(Stream *stream, std::function<void()> callback) = 0;
virtual bool HostCallback(Stream *stream,
diff --git a/tensorflow/tensorflow.bzl b/tensorflow/tensorflow.bzl
index 39db840884..c7766f384e 100644
--- a/tensorflow/tensorflow.bzl
+++ b/tensorflow/tensorflow.bzl
@@ -4,12 +4,12 @@
# Uses the ":optmode" config_setting to pick the options.
load(
"//tensorflow/core:platform/default/build_config_root.bzl",
- "tf_cuda_tests_tags",
- "tf_sycl_tests_tags",
+ "if_dynamic_kernels",
+ "if_static",
"tf_additional_grpc_deps_py",
"tf_additional_xla_deps_py",
- "if_static",
- "if_dynamic_kernels",
+ "tf_cuda_tests_tags",
+ "tf_sycl_tests_tags",
)
load(
"@local_config_tensorrt//:build_defs.bzl",
@@ -17,13 +17,15 @@ load(
)
load(
"@local_config_cuda//cuda:build_defs.bzl",
- "if_cuda",
"cuda_default_copts",
+ "if_cuda",
)
load(
"//third_party/mkl:build_defs.bzl",
"if_mkl",
- "if_mkl_lnx_x64"
+ "if_mkl_lnx_x64",
+ "if_mkl_ml",
+ "mkl_deps",
)
load(
"//third_party/mkl_dnn:build_defs.bzl",
@@ -36,155 +38,154 @@ def register_extension_info(**kwargs):
# i.e. "common_runtime/direct_session_test.cc" becomes
# "common_runtime_direct_session_test"
def src_to_test_name(src):
- return src.replace("/", "_").split(".")[0]
+ return src.replace("/", "_").split(".")[0]
def full_path(relative_paths):
- return [native.package_name() + "/" + relative for relative in relative_paths]
+ return [native.package_name() + "/" + relative for relative in relative_paths]
def _add_tfcore_prefix(src):
- if src.startswith("//"):
- return src
- return "//tensorflow/core:" + src
+ if src.startswith("//"):
+ return src
+ return "//tensorflow/core:" + src
# List of proto files for android builds
def tf_android_core_proto_sources(core_proto_sources_relative):
- return [
- _add_tfcore_prefix(p) for p in core_proto_sources_relative
- ]
+ return [
+ _add_tfcore_prefix(p)
+ for p in core_proto_sources_relative
+ ]
# Returns the list of pb.h and proto.h headers that are generated for
# tf_android_core_proto_sources().
def tf_android_core_proto_headers(core_proto_sources_relative):
- return ([
- _add_tfcore_prefix(p).replace(":", "/").replace(".proto", ".pb.h")
- for p in core_proto_sources_relative
- ] + [
- _add_tfcore_prefix(p).replace(":", "/").replace(".proto", ".proto.h")
- for p in core_proto_sources_relative
- ])
+ return ([
+ _add_tfcore_prefix(p).replace(":", "/").replace(".proto", ".pb.h")
+ for p in core_proto_sources_relative
+ ] + [
+ _add_tfcore_prefix(p).replace(":", "/").replace(".proto", ".proto.h")
+ for p in core_proto_sources_relative
+ ])
# Sanitize a dependency so that it works correctly from code that includes
# TensorFlow as a submodule.
def clean_dep(dep):
- return str(Label(dep))
+ return str(Label(dep))
def if_android_x86(a):
- return select({
- clean_dep("//tensorflow:android_x86"): a,
- clean_dep("//tensorflow:android_x86_64"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:android_x86"): a,
+ clean_dep("//tensorflow:android_x86_64"): a,
+ "//conditions:default": [],
+ })
def if_android_arm(a):
- return select({
- clean_dep("//tensorflow:android_arm"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:android_arm"): a,
+ "//conditions:default": [],
+ })
def if_android_arm64(a):
- return select({
- clean_dep("//tensorflow:android_arm64"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:android_arm64"): a,
+ "//conditions:default": [],
+ })
def if_android_mips(a):
- return select({
- clean_dep("//tensorflow:android_mips"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:android_mips"): a,
+ "//conditions:default": [],
+ })
def if_not_android(a):
- return select({
- clean_dep("//tensorflow:android"): [],
- "//conditions:default": a,
- })
+ return select({
+ clean_dep("//tensorflow:android"): [],
+ "//conditions:default": a,
+ })
def if_not_android_mips_and_mips64(a):
- return select({
- clean_dep("//tensorflow:android_mips"): [],
- clean_dep("//tensorflow:android_mips64"): [],
- "//conditions:default": a,
- })
+ return select({
+ clean_dep("//tensorflow:android_mips"): [],
+ clean_dep("//tensorflow:android_mips64"): [],
+ "//conditions:default": a,
+ })
def if_android(a):
- return select({
- clean_dep("//tensorflow:android"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:android"): a,
+ "//conditions:default": [],
+ })
def if_ios(a):
- return select({
- clean_dep("//tensorflow:ios"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:ios"): a,
+ "//conditions:default": [],
+ })
def if_ios_x86_64(a):
- return select({
- clean_dep("//tensorflow:ios_x86_64"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:ios_x86_64"): a,
+ "//conditions:default": [],
+ })
def if_mobile(a):
- return select({
- clean_dep("//tensorflow:android"): a,
- clean_dep("//tensorflow:ios"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:android"): a,
+ clean_dep("//tensorflow:ios"): a,
+ "//conditions:default": [],
+ })
def if_not_mobile(a):
- return select({
- clean_dep("//tensorflow:android"): [],
- clean_dep("//tensorflow:ios"): [],
- "//conditions:default": a,
- })
+ return select({
+ clean_dep("//tensorflow:android"): [],
+ clean_dep("//tensorflow:ios"): [],
+ "//conditions:default": a,
+ })
# Config setting selector used when building for products
# which requires restricted licenses to be avoided.
def if_not_lgpl_restricted(a):
- _ = (a,)
- return select({
- "//conditions:default": [],
- })
+ _ = (a,)
+ return select({
+ "//conditions:default": [],
+ })
def if_not_windows(a):
- return select({
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- "//conditions:default": a,
- })
+ return select({
+ clean_dep("//tensorflow:windows"): [],
+ "//conditions:default": a,
+ })
def if_windows(a):
- return select({
- clean_dep("//tensorflow:windows"): a,
- clean_dep("//tensorflow:windows_msvc"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:windows"): a,
+ "//conditions:default": [],
+ })
def if_not_windows_cuda(a):
- return select({
- clean_dep("//tensorflow:with_cuda_support_windows_override"): [],
- "//conditions:default": a,
- })
+ return select({
+ clean_dep("//tensorflow:with_cuda_support_windows_override"): [],
+ "//conditions:default": a,
+ })
def if_linux_x86_64(a):
- return select({
- clean_dep("//tensorflow:linux_x86_64"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:linux_x86_64"): a,
+ "//conditions:default": [],
+ })
def if_darwin(a):
- return select({
- clean_dep("//tensorflow:darwin"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:darwin"): a,
+ "//conditions:default": [],
+ })
def if_override_eigen_strong_inline(a):
- return select({
- clean_dep("//tensorflow:override_eigen_strong_inline"): a,
- "//conditions:default": [],
- })
+ return select({
+ clean_dep("//tensorflow:override_eigen_strong_inline"): a,
+ "//conditions:default": [],
+ })
-def get_win_copts(is_external=False):
+def get_win_copts(is_external = False):
WINDOWS_COPTS = [
"/DPLATFORM_WINDOWS",
"/DEIGEN_HAS_C99_MATH",
@@ -202,163 +203,169 @@ def get_win_copts(is_external=False):
"/DNOGDI",
]
if is_external:
- return WINDOWS_COPTS + ["/UTF_COMPILE_LIBRARY"]
+ return WINDOWS_COPTS + ["/UTF_COMPILE_LIBRARY"]
else:
- return WINDOWS_COPTS + ["/DTF_COMPILE_LIBRARY"]
+ return WINDOWS_COPTS + ["/DTF_COMPILE_LIBRARY"]
# LINT.IfChange
-def tf_copts(android_optimization_level_override="-O2", is_external=False):
- # For compatibility reasons, android_optimization_level_override
- # is currently only being set for Android.
- # To clear this value, and allow the CROSSTOOL default
- # to be used, pass android_optimization_level_override=None
- android_copts = [
- "-std=c++11",
- "-DTF_LEAN_BINARY",
- "-Wno-narrowing",
- "-fomit-frame-pointer",
- ]
- if android_optimization_level_override:
- android_copts.append(android_optimization_level_override)
- return (
- if_not_windows([
- "-DEIGEN_AVOID_STL_ARRAY",
- "-Iexternal/gemmlowp",
- "-Wno-sign-compare",
- "-fno-exceptions",
- "-ftemplate-depth=900"])
- + if_cuda(["-DGOOGLE_CUDA=1"])
- + if_tensorrt(["-DGOOGLE_TENSORRT=1"])
- + if_mkl(["-DINTEL_MKL=1", "-DEIGEN_USE_VML"])
- + if_mkl_open_source_only(["-DDO_NOT_USE_ML"])
- + if_mkl_lnx_x64(["-fopenmp"])
- + if_android_arm(["-mfpu=neon"])
- + if_linux_x86_64(["-msse3"])
- + if_ios_x86_64(["-msse4.1"])
- + select({
+def tf_copts(android_optimization_level_override = "-O2", is_external = False):
+ # For compatibility reasons, android_optimization_level_override
+ # is currently only being set for Android.
+ # To clear this value, and allow the CROSSTOOL default
+ # to be used, pass android_optimization_level_override=None
+ android_copts = [
+ "-std=c++11",
+ "-DTF_LEAN_BINARY",
+ "-Wno-narrowing",
+ "-fomit-frame-pointer",
+ ]
+ if android_optimization_level_override:
+ android_copts.append(android_optimization_level_override)
+ return (
+ if_not_windows([
+ "-DEIGEN_AVOID_STL_ARRAY",
+ "-Iexternal/gemmlowp",
+ "-Wno-sign-compare",
+ "-fno-exceptions",
+ "-ftemplate-depth=900",
+ ]) +
+ if_cuda(["-DGOOGLE_CUDA=1"]) +
+ if_tensorrt(["-DGOOGLE_TENSORRT=1"]) +
+ if_mkl(["-DINTEL_MKL=1", "-DEIGEN_USE_VML"]) +
+ if_mkl_open_source_only(["-DINTEL_MKL_DNN_ONLY"]) +
+ if_mkl_lnx_x64(["-fopenmp"]) +
+ if_android_arm(["-mfpu=neon"]) +
+ if_linux_x86_64(["-msse3"]) +
+ if_ios_x86_64(["-msse4.1"]) +
+ select({
clean_dep("//tensorflow:framework_shared_object"): [],
"//conditions:default": ["-DTENSORFLOW_MONOLITHIC_BUILD"],
- })
- + select({
+ }) +
+ select({
clean_dep("//tensorflow:android"): android_copts,
clean_dep("//tensorflow:darwin"): [],
clean_dep("//tensorflow:windows"): get_win_copts(is_external),
- clean_dep("//tensorflow:windows_msvc"): get_win_copts(is_external),
clean_dep("//tensorflow:ios"): ["-std=c++11"],
clean_dep("//tensorflow:no_lgpl_deps"): ["-D__TENSORFLOW_NO_LGPL_DEPS__", "-pthread"],
- "//conditions:default": ["-pthread"]
- }))
-
+ "//conditions:default": ["-pthread"],
+ })
+ )
def tfe_xla_copts():
- return select({
- "//tensorflow:with_xla_support": ["-DTENSORFLOW_EAGER_USE_XLA"],
- "//conditions:default": [],
- })
+ return select({
+ "//tensorflow:with_xla_support": ["-DTENSORFLOW_EAGER_USE_XLA"],
+ "//conditions:default": [],
+ })
def tf_opts_nortti_if_android():
- return if_android([
- "-fno-rtti",
- "-DGOOGLE_PROTOBUF_NO_RTTI",
- "-DGOOGLE_PROTOBUF_NO_STATIC_INITIALIZER",
- ])
+ return if_android([
+ "-fno-rtti",
+ "-DGOOGLE_PROTOBUF_NO_RTTI",
+ "-DGOOGLE_PROTOBUF_NO_STATIC_INITIALIZER",
+ ])
# LINT.ThenChange(//tensorflow/contrib/android/cmake/CMakeLists.txt)
def tf_features_nomodules_if_android():
- return if_android(["-use_header_modules"])
+ return if_android(["-use_header_modules"])
# Given a list of "op_lib_names" (a list of files in the ops directory
# without their .cc extensions), generate a library for that file.
-def tf_gen_op_libs(op_lib_names, deps=None, is_external=True):
- # Make library out of each op so it can also be used to generate wrappers
- # for various languages.
- if not deps:
- deps = []
- for n in op_lib_names:
- native.cc_library(
- name=n + "_op_lib",
- copts=tf_copts(is_external=is_external),
- srcs=["ops/" + n + ".cc"],
- deps=deps + [clean_dep("//tensorflow/core:framework")],
- visibility=["//visibility:public"],
- alwayslink=1,
- linkstatic=1,)
+def tf_gen_op_libs(op_lib_names, deps = None, is_external = True):
+ # Make library out of each op so it can also be used to generate wrappers
+ # for various languages.
+ if not deps:
+ deps = []
+ for n in op_lib_names:
+ native.cc_library(
+ name = n + "_op_lib",
+ copts = tf_copts(is_external = is_external),
+ srcs = ["ops/" + n + ".cc"],
+ deps = deps + [clean_dep("//tensorflow/core:framework")],
+ visibility = ["//visibility:public"],
+ alwayslink = 1,
+ linkstatic = 1,
+ )
def _make_search_paths(prefix, levels_to_root):
- return ",".join(
- ["-rpath,%s/%s" % (prefix, "/".join([".."] * search_level))
- for search_level in range(levels_to_root + 1)])
+ return ",".join(
+ [
+ "-rpath,%s/%s" % (prefix, "/".join([".."] * search_level))
+ for search_level in range(levels_to_root + 1)
+ ],
+ )
def _rpath_linkopts(name):
- # Search parent directories up to the TensorFlow root directory for shared
- # object dependencies, even if this op shared object is deeply nested
- # (e.g. tensorflow/contrib/package:python/ops/_op_lib.so). tensorflow/ is then
- # the root and tensorflow/libtensorflow_framework.so should exist when
- # deployed. Other shared object dependencies (e.g. shared between contrib/
- # ops) are picked up as long as they are in either the same or a parent
- # directory in the tensorflow/ tree.
- levels_to_root = native.package_name().count("/") + name.count("/")
- return select({
- clean_dep("//tensorflow:darwin"): [
- "-Wl,%s" % (_make_search_paths("@loader_path", levels_to_root),),
- ],
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- "//conditions:default": [
- "-Wl,%s" % (_make_search_paths("$$ORIGIN", levels_to_root),),
- ],
- })
+ # Search parent directories up to the TensorFlow root directory for shared
+ # object dependencies, even if this op shared object is deeply nested
+ # (e.g. tensorflow/contrib/package:python/ops/_op_lib.so). tensorflow/ is then
+ # the root and tensorflow/libtensorflow_framework.so should exist when
+ # deployed. Other shared object dependencies (e.g. shared between contrib/
+ # ops) are picked up as long as they are in either the same or a parent
+ # directory in the tensorflow/ tree.
+ levels_to_root = native.package_name().count("/") + name.count("/")
+ return select({
+ clean_dep("//tensorflow:darwin"): [
+ "-Wl,%s" % (_make_search_paths("@loader_path", levels_to_root),),
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ "//conditions:default": [
+ "-Wl,%s" % (_make_search_paths("$$ORIGIN", levels_to_root),),
+ ],
+ })
# Bazel-generated shared objects which must be linked into TensorFlow binaries
# to define symbols from //tensorflow/core:framework and //tensorflow/core:lib.
def tf_binary_additional_srcs():
- return if_static(
- extra_deps=[],
- otherwise=[
- clean_dep("//tensorflow:libtensorflow_framework.so"),
- ])
-
+ return if_static(
+ extra_deps = [],
+ otherwise = [
+ clean_dep("//tensorflow:libtensorflow_framework.so"),
+ ],
+ )
# Helper functions to add kernel dependencies to tf binaries when using dynamic
# kernel linking.
def tf_binary_dynamic_kernel_dsos(kernels):
- return if_dynamic_kernels(
- extra_deps=["libtfkernel_%s.so" % clean_dep(k) for k in kernels],
- otherwise=[])
+ return if_dynamic_kernels(
+ extra_deps = ["libtfkernel_%s.so" % clean_dep(k) for k in kernels],
+ otherwise = [],
+ )
# Helper functions to add kernel dependencies to tf binaries when using static
# kernel linking.
def tf_binary_dynamic_kernel_deps(kernels):
- return if_dynamic_kernels(
- extra_deps=[],
- otherwise=kernels)
+ return if_dynamic_kernels(
+ extra_deps = [],
+ otherwise = kernels,
+ )
def tf_cc_shared_object(
- name,
- srcs=[],
- deps=[],
- data=[],
- linkopts=[],
- framework_so=tf_binary_additional_srcs(),
- kernels=[],
- **kwargs):
- native.cc_binary(
- name=name,
- srcs=srcs + framework_so,
- deps=deps + tf_binary_dynamic_kernel_deps(kernels),
- linkshared = 1,
- data = data + tf_binary_dynamic_kernel_dsos(kernels),
- linkopts=linkopts + _rpath_linkopts(name) + select({
- clean_dep("//tensorflow:darwin"): [
- "-Wl,-install_name,@rpath/" + name.split("/")[-1],
- ],
- clean_dep("//tensorflow:windows"): [],
- "//conditions:default": [
- "-Wl,-soname," + name.split("/")[-1],
- ],
- }),
- **kwargs)
+ name,
+ srcs = [],
+ deps = [],
+ data = [],
+ linkopts = [],
+ framework_so = tf_binary_additional_srcs(),
+ kernels = [],
+ **kwargs):
+ native.cc_binary(
+ name = name,
+ srcs = srcs + framework_so,
+ deps = deps + tf_binary_dynamic_kernel_deps(kernels),
+ linkshared = 1,
+ data = data + tf_binary_dynamic_kernel_dsos(kernels),
+ linkopts = linkopts + _rpath_linkopts(name) + select({
+ clean_dep("//tensorflow:darwin"): [
+ "-Wl,-install_name,@rpath/" + name.split("/")[-1],
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ "//conditions:default": [
+ "-Wl,-soname," + name.split("/")[-1],
+ ],
+ }),
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_cc_shared_object",
@@ -369,26 +376,28 @@ register_extension_info(
# (//third_party/tensorflow:libtensorflow_framework.so) when not building
# statically. Also adds linker options (rpaths) so that the framework shared
# object can be found.
-def tf_cc_binary(name,
- srcs=[],
- deps=[],
- data=[],
- linkopts=[],
- copts=tf_copts(),
- kernels=[],
- **kwargs):
- native.cc_binary(
- name=name,
- copts=copts,
- srcs=srcs + tf_binary_additional_srcs(),
- deps=deps + tf_binary_dynamic_kernel_deps(kernels) + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- ],
- ),
- data=data + tf_binary_dynamic_kernel_dsos(kernels),
- linkopts=linkopts + _rpath_linkopts(name),
- **kwargs)
+def tf_cc_binary(
+ name,
+ srcs = [],
+ deps = [],
+ data = [],
+ linkopts = [],
+ copts = tf_copts(),
+ kernels = [],
+ **kwargs):
+ native.cc_binary(
+ name = name,
+ copts = copts,
+ srcs = srcs + tf_binary_additional_srcs(),
+ deps = deps + tf_binary_dynamic_kernel_deps(kernels) + if_mkl_ml(
+ [
+ "//third_party/mkl:intel_binary_blob",
+ ],
+ ),
+ data = data + tf_binary_dynamic_kernel_dsos(kernels),
+ linkopts = linkopts + _rpath_linkopts(name),
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_cc_binary",
@@ -398,64 +407,72 @@ register_extension_info(
# A simple wrap around native.cc_binary rule.
# When using this rule, you should realize it doesn't link to any tensorflow
# dependencies by default.
-def tf_native_cc_binary(name,
- copts=tf_copts(),
- **kwargs):
- native.cc_binary(
- name=name,
- copts=copts,
- **kwargs)
+def tf_native_cc_binary(
+ name,
+ copts = tf_copts(),
+ **kwargs):
+ native.cc_binary(
+ name = name,
+ copts = copts,
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_native_cc_binary",
label_regex_for_dep = "{extension_name}.*",
)
-def tf_gen_op_wrapper_cc(name,
- out_ops_file,
- pkg="",
- op_gen=clean_dep("//tensorflow/cc:cc_op_gen_main"),
- deps=None,
- include_internal_ops=0,
- # ApiDefs will be loaded in the order specified in this list.
- api_def_srcs=[]):
- # Construct an op generator binary for these ops.
- tool = out_ops_file + "_gen_cc"
- if deps == None:
- deps = [pkg + ":" + name + "_op_lib"]
- tf_cc_binary(
- name=tool,
- copts=tf_copts(),
- linkopts=if_not_windows(["-lm"]),
- linkstatic=1, # Faster to link this one-time-use binary dynamically
- deps=[op_gen] + deps)
-
- srcs = api_def_srcs[:]
-
- if not api_def_srcs:
- api_def_args_str = ","
- else:
- api_def_args = []
- for api_def_src in api_def_srcs:
- # Add directory of the first ApiDef source to args.
- # We are assuming all ApiDefs in a single api_def_src are in the
- # same directory.
- api_def_args.append(
- " $$(dirname $$(echo $(locations " + api_def_src +
- ") | cut -d\" \" -f1))")
- api_def_args_str = ",".join(api_def_args)
-
- native.genrule(
- name=name + "_genrule",
- outs=[
- out_ops_file + ".h", out_ops_file + ".cc",
- out_ops_file + "_internal.h", out_ops_file + "_internal.cc"
- ],
- srcs=srcs,
- tools=[":" + tool] + tf_binary_additional_srcs(),
- cmd=("$(location :" + tool + ") $(location :" + out_ops_file + ".h) " +
- "$(location :" + out_ops_file + ".cc) " +
- str(include_internal_ops) + " " + api_def_args_str))
+def tf_gen_op_wrapper_cc(
+ name,
+ out_ops_file,
+ pkg = "",
+ op_gen = clean_dep("//tensorflow/cc:cc_op_gen_main"),
+ deps = None,
+ include_internal_ops = 0,
+ # ApiDefs will be loaded in the order specified in this list.
+ api_def_srcs = []):
+ # Construct an op generator binary for these ops.
+ tool = out_ops_file + "_gen_cc"
+ if deps == None:
+ deps = [pkg + ":" + name + "_op_lib"]
+ tf_cc_binary(
+ name = tool,
+ copts = tf_copts(),
+ linkopts = if_not_windows(["-lm"]),
+ linkstatic = 1, # Faster to link this one-time-use binary dynamically
+ deps = [op_gen] + deps,
+ )
+
+ srcs = api_def_srcs[:]
+
+ if not api_def_srcs:
+ api_def_args_str = ","
+ else:
+ api_def_args = []
+ for api_def_src in api_def_srcs:
+ # Add directory of the first ApiDef source to args.
+ # We are assuming all ApiDefs in a single api_def_src are in the
+ # same directory.
+ api_def_args.append(
+ " $$(dirname $$(echo $(locations " + api_def_src +
+ ") | cut -d\" \" -f1))",
+ )
+ api_def_args_str = ",".join(api_def_args)
+
+ native.genrule(
+ name = name + "_genrule",
+ outs = [
+ out_ops_file + ".h",
+ out_ops_file + ".cc",
+ out_ops_file + "_internal.h",
+ out_ops_file + "_internal.cc",
+ ],
+ srcs = srcs,
+ tools = [":" + tool] + tf_binary_additional_srcs(),
+ cmd = ("$(location :" + tool + ") $(location :" + out_ops_file + ".h) " +
+ "$(location :" + out_ops_file + ".cc) " +
+ str(include_internal_ops) + " " + api_def_args_str),
+ )
# Given a list of "op_lib_names" (a list of files in the ops directory
# without their .cc extensions), generate individual C++ .cc and .h
@@ -484,68 +501,72 @@ def tf_gen_op_wrapper_cc(name,
# "ops/math_ops_internal.h" ],
# deps = [ ... ])
# TODO(joshl): Cleaner approach for hidden ops.
-def tf_gen_op_wrappers_cc(name,
- op_lib_names=[],
- other_srcs=[],
- other_hdrs=[],
- pkg="",
- deps=[
- clean_dep("//tensorflow/cc:ops"),
- clean_dep("//tensorflow/cc:scope"),
- clean_dep("//tensorflow/cc:const_op"),
- ],
- op_gen=clean_dep("//tensorflow/cc:cc_op_gen_main"),
- include_internal_ops=0,
- visibility=None,
- # ApiDefs will be loaded in the order apecified in this list.
- api_def_srcs=[]):
- subsrcs = other_srcs[:]
- subhdrs = other_hdrs[:]
- internalsrcs = []
- internalhdrs = []
- for n in op_lib_names:
- tf_gen_op_wrapper_cc(
- n,
- "ops/" + n,
- pkg=pkg,
- op_gen=op_gen,
- include_internal_ops=include_internal_ops,
- api_def_srcs=api_def_srcs)
- subsrcs += ["ops/" + n + ".cc"]
- subhdrs += ["ops/" + n + ".h"]
- internalsrcs += ["ops/" + n + "_internal.cc"]
- internalhdrs += ["ops/" + n + "_internal.h"]
-
- native.cc_library(
- name=name,
- srcs=subsrcs,
- hdrs=subhdrs,
- deps=deps + if_not_android([
- clean_dep("//tensorflow/core:core_cpu"),
- clean_dep("//tensorflow/core:framework"),
- clean_dep("//tensorflow/core:lib"),
- clean_dep("//tensorflow/core:protos_all_cc"),
- ]) + if_android([
- clean_dep("//tensorflow/core:android_tensorflow_lib"),
- ]),
- copts=tf_copts(),
- alwayslink=1,
- visibility=visibility)
- native.cc_library(
- name=name + "_internal",
- srcs=internalsrcs,
- hdrs=internalhdrs,
- deps=deps + if_not_android([
- clean_dep("//tensorflow/core:core_cpu"),
- clean_dep("//tensorflow/core:framework"),
- clean_dep("//tensorflow/core:lib"),
- clean_dep("//tensorflow/core:protos_all_cc"),
- ]) + if_android([
- clean_dep("//tensorflow/core:android_tensorflow_lib"),
- ]),
- copts=tf_copts(),
- alwayslink=1,
- visibility=[clean_dep("//tensorflow:internal")])
+def tf_gen_op_wrappers_cc(
+ name,
+ op_lib_names = [],
+ other_srcs = [],
+ other_hdrs = [],
+ pkg = "",
+ deps = [
+ clean_dep("//tensorflow/cc:ops"),
+ clean_dep("//tensorflow/cc:scope"),
+ clean_dep("//tensorflow/cc:const_op"),
+ ],
+ op_gen = clean_dep("//tensorflow/cc:cc_op_gen_main"),
+ include_internal_ops = 0,
+ visibility = None,
+ # ApiDefs will be loaded in the order apecified in this list.
+ api_def_srcs = []):
+ subsrcs = other_srcs[:]
+ subhdrs = other_hdrs[:]
+ internalsrcs = []
+ internalhdrs = []
+ for n in op_lib_names:
+ tf_gen_op_wrapper_cc(
+ n,
+ "ops/" + n,
+ pkg = pkg,
+ op_gen = op_gen,
+ include_internal_ops = include_internal_ops,
+ api_def_srcs = api_def_srcs,
+ )
+ subsrcs += ["ops/" + n + ".cc"]
+ subhdrs += ["ops/" + n + ".h"]
+ internalsrcs += ["ops/" + n + "_internal.cc"]
+ internalhdrs += ["ops/" + n + "_internal.h"]
+
+ native.cc_library(
+ name = name,
+ srcs = subsrcs,
+ hdrs = subhdrs,
+ deps = deps + if_not_android([
+ clean_dep("//tensorflow/core:core_cpu"),
+ clean_dep("//tensorflow/core:framework"),
+ clean_dep("//tensorflow/core:lib"),
+ clean_dep("//tensorflow/core:protos_all_cc"),
+ ]) + if_android([
+ clean_dep("//tensorflow/core:android_tensorflow_lib"),
+ ]),
+ copts = tf_copts(),
+ alwayslink = 1,
+ visibility = visibility,
+ )
+ native.cc_library(
+ name = name + "_internal",
+ srcs = internalsrcs,
+ hdrs = internalhdrs,
+ deps = deps + if_not_android([
+ clean_dep("//tensorflow/core:core_cpu"),
+ clean_dep("//tensorflow/core:framework"),
+ clean_dep("//tensorflow/core:lib"),
+ clean_dep("//tensorflow/core:protos_all_cc"),
+ ]) + if_android([
+ clean_dep("//tensorflow/core:android_tensorflow_lib"),
+ ]),
+ copts = tf_copts(),
+ alwayslink = 1,
+ visibility = [clean_dep("//tensorflow:internal")],
+ )
# Generates a Python library target wrapping the ops registered in "deps".
#
@@ -571,96 +592,102 @@ def tf_gen_op_wrappers_cc(name,
# is invalid to specify both "hidden" and "op_whitelist".
# cc_linkopts: Optional linkopts to be added to tf_cc_binary that contains the
# specified ops.
-def tf_gen_op_wrapper_py(name,
- out=None,
- hidden=None,
- visibility=None,
- deps=[],
- require_shape_functions=False,
- hidden_file=None,
- generated_target_name=None,
- op_whitelist=[],
- cc_linkopts=[],
- api_def_srcs=[]):
- if (hidden or hidden_file) and op_whitelist:
- fail('Cannot pass specify both hidden and op_whitelist.')
-
- # Construct a cc_binary containing the specified ops.
- tool_name = "gen_" + name + "_py_wrappers_cc"
- if not deps:
- deps = [str(Label("//tensorflow/core:" + name + "_op_lib"))]
- tf_cc_binary(
- name=tool_name,
- linkopts=if_not_windows(["-lm"]) + cc_linkopts,
- copts=tf_copts(),
- linkstatic=1, # Faster to link this one-time-use binary dynamically
- deps=([
- clean_dep("//tensorflow/core:framework"),
- clean_dep("//tensorflow/python:python_op_gen_main")
- ] + deps),
- visibility=[clean_dep("//tensorflow:internal")],)
-
- # Invoke the previous cc_binary to generate a python file.
- if not out:
- out = "ops/gen_" + name + ".py"
-
- if hidden:
- op_list_arg = ",".join(hidden)
- op_list_is_whitelist = False
- elif op_whitelist:
- op_list_arg = ",".join(op_whitelist)
- op_list_is_whitelist = True
- else:
- op_list_arg = "''"
- op_list_is_whitelist = False
-
- # Prepare ApiDef directories to pass to the genrule.
- if not api_def_srcs:
- api_def_args_str = ","
- else:
- api_def_args = []
- for api_def_src in api_def_srcs:
- # Add directory of the first ApiDef source to args.
- # We are assuming all ApiDefs in a single api_def_src are in the
- # same directory.
- api_def_args.append(
- "$$(dirname $$(echo $(locations " + api_def_src +
- ") | cut -d\" \" -f1))")
- api_def_args_str = ",".join(api_def_args)
-
- if hidden_file:
- # `hidden_file` is file containing a list of op names to be hidden in the
- # generated module.
- native.genrule(
- name=name + "_pygenrule",
- outs=[out],
- srcs=api_def_srcs + [hidden_file],
- tools=[tool_name] + tf_binary_additional_srcs(),
- cmd=("$(location " + tool_name + ") " + api_def_args_str +
- " @$(location " + hidden_file + ") " +
- ("1" if require_shape_functions else "0") + " > $@"))
- else:
- native.genrule(
- name=name + "_pygenrule",
- outs=[out],
- srcs=api_def_srcs,
- tools=[tool_name] + tf_binary_additional_srcs(),
- cmd=("$(location " + tool_name + ") " + api_def_args_str + " " +
- op_list_arg + " " +
- ("1" if require_shape_functions else "0") + " " +
- ("1" if op_list_is_whitelist else "0") + " > $@"))
-
- # Make a py_library out of the generated python file.
- if not generated_target_name:
- generated_target_name = name
- native.py_library(
- name=generated_target_name,
- srcs=[out],
- srcs_version="PY2AND3",
- visibility=visibility,
- deps=[
- clean_dep("//tensorflow/python:framework_for_generated_wrappers_v2"),
- ],)
+def tf_gen_op_wrapper_py(
+ name,
+ out = None,
+ hidden = None,
+ visibility = None,
+ deps = [],
+ require_shape_functions = False,
+ hidden_file = None,
+ generated_target_name = None,
+ op_whitelist = [],
+ cc_linkopts = [],
+ api_def_srcs = []):
+ if (hidden or hidden_file) and op_whitelist:
+ fail("Cannot pass specify both hidden and op_whitelist.")
+
+ # Construct a cc_binary containing the specified ops.
+ tool_name = "gen_" + name + "_py_wrappers_cc"
+ if not deps:
+ deps = [str(Label("//tensorflow/core:" + name + "_op_lib"))]
+ tf_cc_binary(
+ name = tool_name,
+ linkopts = if_not_windows(["-lm"]) + cc_linkopts,
+ copts = tf_copts(),
+ linkstatic = 1, # Faster to link this one-time-use binary dynamically
+ deps = ([
+ clean_dep("//tensorflow/core:framework"),
+ clean_dep("//tensorflow/python:python_op_gen_main"),
+ ] + deps),
+ visibility = [clean_dep("//tensorflow:internal")],
+ )
+
+ # Invoke the previous cc_binary to generate a python file.
+ if not out:
+ out = "ops/gen_" + name + ".py"
+
+ if hidden:
+ op_list_arg = ",".join(hidden)
+ op_list_is_whitelist = False
+ elif op_whitelist:
+ op_list_arg = ",".join(op_whitelist)
+ op_list_is_whitelist = True
+ else:
+ op_list_arg = "''"
+ op_list_is_whitelist = False
+
+ # Prepare ApiDef directories to pass to the genrule.
+ if not api_def_srcs:
+ api_def_args_str = ","
+ else:
+ api_def_args = []
+ for api_def_src in api_def_srcs:
+ # Add directory of the first ApiDef source to args.
+ # We are assuming all ApiDefs in a single api_def_src are in the
+ # same directory.
+ api_def_args.append(
+ "$$(dirname $$(echo $(locations " + api_def_src +
+ ") | cut -d\" \" -f1))",
+ )
+ api_def_args_str = ",".join(api_def_args)
+
+ if hidden_file:
+ # `hidden_file` is file containing a list of op names to be hidden in the
+ # generated module.
+ native.genrule(
+ name = name + "_pygenrule",
+ outs = [out],
+ srcs = api_def_srcs + [hidden_file],
+ tools = [tool_name] + tf_binary_additional_srcs(),
+ cmd = ("$(location " + tool_name + ") " + api_def_args_str +
+ " @$(location " + hidden_file + ") " +
+ ("1" if require_shape_functions else "0") + " > $@"),
+ )
+ else:
+ native.genrule(
+ name = name + "_pygenrule",
+ outs = [out],
+ srcs = api_def_srcs,
+ tools = [tool_name] + tf_binary_additional_srcs(),
+ cmd = ("$(location " + tool_name + ") " + api_def_args_str + " " +
+ op_list_arg + " " +
+ ("1" if require_shape_functions else "0") + " " +
+ ("1" if op_list_is_whitelist else "0") + " > $@"),
+ )
+
+ # Make a py_library out of the generated python file.
+ if not generated_target_name:
+ generated_target_name = name
+ native.py_library(
+ name = generated_target_name,
+ srcs = [out],
+ srcs_version = "PY2AND3",
+ visibility = visibility,
+ deps = [
+ clean_dep("//tensorflow/python:framework_for_generated_wrappers_v2"),
+ ],
+ )
# Define a bazel macro that creates cc_test for tensorflow.
#
@@ -671,53 +698,54 @@ def tf_gen_op_wrapper_py(name,
#
# TODO(opensource): we need to enable this to work around the hidden symbol
# __cudaRegisterFatBinary error. Need more investigations.
-def tf_cc_test(name,
- srcs,
- deps,
- data=[],
- linkstatic=0,
- extra_copts=[],
- suffix="",
- linkopts=[],
- nocopts=None,
- kernels=[],
- **kwargs):
- native.cc_test(
- name="%s%s" % (name, suffix),
- srcs=srcs + tf_binary_additional_srcs(),
- copts=tf_copts() + extra_copts,
- linkopts=select({
- clean_dep("//tensorflow:android"): [
- "-pie",
- ],
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- clean_dep("//tensorflow:darwin"): [
- "-lm",
- ],
- "//conditions:default": [
- "-lpthread",
- "-lm"
- ],
- }) + linkopts + _rpath_linkopts(name),
- deps=deps + tf_binary_dynamic_kernel_deps(kernels) + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- ],
- ),
- data=data + tf_binary_dynamic_kernel_dsos(kernels),
- # Nested select() statements seem not to be supported when passed to
- # linkstatic, and we already have a cuda select() passed in to this
- # function.
- linkstatic=linkstatic or select({
- # cc_tests with ".so"s in srcs incorrectly link on Darwin unless
- # linkstatic=1 (https://github.com/bazelbuild/bazel/issues/3450).
- # TODO(allenl): Remove Mac static linking when Bazel 0.6 is out.
- clean_dep("//tensorflow:darwin"): 1,
- "//conditions:default": 0,
- }),
- nocopts=nocopts,
- **kwargs)
+def tf_cc_test(
+ name,
+ srcs,
+ deps,
+ data = [],
+ linkstatic = 0,
+ extra_copts = [],
+ suffix = "",
+ linkopts = [],
+ nocopts = None,
+ kernels = [],
+ **kwargs):
+ native.cc_test(
+ name = "%s%s" % (name, suffix),
+ srcs = srcs + tf_binary_additional_srcs(),
+ copts = tf_copts() + extra_copts,
+ linkopts = select({
+ clean_dep("//tensorflow:android"): [
+ "-pie",
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ clean_dep("//tensorflow:darwin"): [
+ "-lm",
+ ],
+ "//conditions:default": [
+ "-lpthread",
+ "-lm",
+ ],
+ }) + linkopts + _rpath_linkopts(name),
+ deps = deps + tf_binary_dynamic_kernel_deps(kernels) + if_mkl_ml(
+ [
+ "//third_party/mkl:intel_binary_blob",
+ ],
+ ),
+ data = data + tf_binary_dynamic_kernel_dsos(kernels),
+ # Nested select() statements seem not to be supported when passed to
+ # linkstatic, and we already have a cuda select() passed in to this
+ # function.
+ linkstatic = linkstatic or select({
+ # cc_tests with ".so"s in srcs incorrectly link on Darwin unless
+ # linkstatic=1 (https://github.com/bazelbuild/bazel/issues/3450).
+ # TODO(allenl): Remove Mac static linking when Bazel 0.6 is out.
+ clean_dep("//tensorflow:darwin"): 1,
+ "//conditions:default": 0,
+ }),
+ nocopts = nocopts,
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_cc_test",
@@ -726,107 +754,115 @@ register_extension_info(
# Part of the testing workflow requires a distinguishable name for the build
# rules that involve a GPU, even if otherwise identical to the base rule.
-def tf_cc_test_gpu(name,
- srcs,
- deps,
- linkstatic=0,
- tags=[],
- data=[],
- size="medium",
- suffix="",
- args=None):
- tf_cc_test(
- name,
- srcs,
- deps,
- linkstatic=linkstatic,
- tags=tags,
- data=data,
- size=size,
- suffix=suffix,
- args=args)
+def tf_cc_test_gpu(
+ name,
+ srcs,
+ deps,
+ linkstatic = 0,
+ tags = [],
+ data = [],
+ size = "medium",
+ suffix = "",
+ args = None):
+ tf_cc_test(
+ name,
+ srcs,
+ deps,
+ linkstatic = linkstatic,
+ tags = tags,
+ data = data,
+ size = size,
+ suffix = suffix,
+ args = args,
+ )
register_extension_info(
extension_name = "tf_cc_test_gpu",
label_regex_for_dep = "{extension_name}",
)
-def tf_cuda_cc_test(name,
- srcs=[],
- deps=[],
- tags=[],
- data=[],
- size="medium",
- extra_copts=[],
- linkstatic=0,
- args=[],
- linkopts=[]):
- tf_cc_test(
- name=name,
- srcs=srcs,
- deps=deps,
- tags=tags + ["manual"],
- data=data,
- size=size,
- extra_copts=extra_copts,
- linkstatic=linkstatic,
- linkopts=linkopts,
- args=args)
- tf_cc_test(
- name=name,
- srcs=srcs,
- suffix="_gpu",
- deps=deps + if_cuda([
- clean_dep("//tensorflow/core:gpu_runtime"),
- ]),
- linkstatic=select({
- # TODO(allenl): Remove Mac static linking when Bazel 0.6 is out.
- clean_dep("//tensorflow:darwin"): 1,
- "@local_config_cuda//cuda:using_nvcc": 1,
- "@local_config_cuda//cuda:using_clang": 1,
- "//conditions:default": 0,
- }),
- tags=tags + tf_cuda_tests_tags(),
- data=data,
- size=size,
- extra_copts=extra_copts,
- linkopts=linkopts,
- args=args)
+def tf_cuda_cc_test(
+ name,
+ srcs = [],
+ deps = [],
+ tags = [],
+ data = [],
+ size = "medium",
+ extra_copts = [],
+ linkstatic = 0,
+ args = [],
+ linkopts = []):
+ tf_cc_test(
+ name = name,
+ srcs = srcs,
+ deps = deps,
+ tags = tags + ["manual"],
+ data = data,
+ size = size,
+ extra_copts = extra_copts,
+ linkstatic = linkstatic,
+ linkopts = linkopts,
+ args = args,
+ )
+ tf_cc_test(
+ name = name,
+ srcs = srcs,
+ suffix = "_gpu",
+ deps = deps + if_cuda([
+ clean_dep("//tensorflow/core:gpu_runtime"),
+ ]),
+ linkstatic = select({
+ # TODO(allenl): Remove Mac static linking when Bazel 0.6 is out.
+ clean_dep("//tensorflow:darwin"): 1,
+ "@local_config_cuda//cuda:using_nvcc": 1,
+ "@local_config_cuda//cuda:using_clang": 1,
+ "//conditions:default": 0,
+ }),
+ tags = tags + tf_cuda_tests_tags(),
+ data = data,
+ size = size,
+ extra_copts = extra_copts,
+ linkopts = linkopts,
+ args = args,
+ )
register_extension_info(
extension_name = "tf_cuda_cc_test",
label_regex_for_dep = "{extension_name}",
)
-def tf_cuda_only_cc_test(name,
- srcs=[],
- deps=[],
- tags=[],
- data=[],
- size="medium",
- linkstatic=0,
- args=[],
- kernels=[],
- linkopts=[]):
- native.cc_test(
- name="%s%s" % (name, "_gpu"),
- srcs=srcs + tf_binary_additional_srcs(),
- size=size,
- args=args,
- copts= _cuda_copts() + tf_copts(),
- data=data + tf_binary_dynamic_kernel_dsos(kernels),
- deps=deps + tf_binary_dynamic_kernel_deps(kernels) + if_cuda([
- clean_dep("//tensorflow/core:cuda"),
- clean_dep("//tensorflow/core:gpu_lib")]),
- linkopts=if_not_windows(["-lpthread", "-lm"]) + linkopts + _rpath_linkopts(name),
- linkstatic=linkstatic or select({
- # cc_tests with ".so"s in srcs incorrectly link on Darwin
- # unless linkstatic=1.
- # TODO(allenl): Remove Mac static linking when Bazel 0.6 is out.
- clean_dep("//tensorflow:darwin"): 1,
- "//conditions:default": 0,
- }),
- tags=tags + tf_cuda_tests_tags())
+def tf_cuda_only_cc_test(
+ name,
+ srcs = [],
+ deps = [],
+ tags = [],
+ data = [],
+ size = "medium",
+ linkstatic = 0,
+ args = [],
+ kernels = [],
+ linkopts = []):
+ native.cc_test(
+ name = "%s%s" % (name, "_gpu"),
+ srcs = srcs + tf_binary_additional_srcs(),
+ size = size,
+ args = args,
+ copts = _cuda_copts() + tf_copts(),
+ data = data + tf_binary_dynamic_kernel_dsos(kernels),
+ deps = deps + tf_binary_dynamic_kernel_deps(kernels) + if_cuda([
+ clean_dep("//tensorflow/core:cuda"),
+ clean_dep("//tensorflow/core:gpu_lib"),
+ ]),
+ linkopts = if_not_windows(["-lpthread", "-lm"]) + linkopts + _rpath_linkopts(name),
+ linkstatic = linkstatic or select({
+ # cc_tests with ".so"s in srcs incorrectly link on Darwin
+ # unless linkstatic=1.
+ # TODO(allenl): Remove Mac static linking when Bazel 0.6 is out.
+ clean_dep("//tensorflow:darwin"): 1,
+ "//conditions:default": 0,
+ }),
+ tags = tags + tf_cuda_tests_tags(),
+ )
register_extension_info(
extension_name = "tf_cuda_only_cc_test",
@@ -834,109 +870,112 @@ register_extension_info(
)
# Create a cc_test for each of the tensorflow tests listed in "tests"
-def tf_cc_tests(srcs,
- deps,
- name="",
- linkstatic=0,
- tags=[],
- size="medium",
- args=None,
- linkopts=[],
- nocopts=None):
- for src in srcs:
- tf_cc_test(
- name=src_to_test_name(src),
- srcs=[src],
- deps=deps,
- linkstatic=linkstatic,
- tags=tags,
- size=size,
- args=args,
- linkopts=linkopts,
- nocopts=nocopts)
-
-def tf_cc_test_mkl(srcs,
- deps,
- name="",
- data=[],
- linkstatic=0,
- tags=[],
- size="medium",
- kernels=[],
- args=None):
- # -fno-exceptions in nocopts breaks compilation if header modules are enabled.
- disable_header_modules = ["-use_header_modules"]
-
- for src in srcs:
- native.cc_test(
- name=src_to_test_name(src),
- srcs=if_mkl([src]) + tf_binary_additional_srcs(),
- copts=tf_copts(),
- linkopts=select({
- clean_dep("//tensorflow:android"): [
- "-pie",
- ],
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- "//conditions:default": [
- "-lpthread",
- "-lm"
- ],
- }) + _rpath_linkopts(src_to_test_name(src)),
- deps=deps + tf_binary_dynamic_kernel_deps(kernels) + if_mkl(
- [
- "//third_party/mkl:intel_binary_blob",
- ],
- ),
- data=data + tf_binary_dynamic_kernel_dsos(kernels),
- linkstatic=linkstatic,
- tags=tags,
- size=size,
- args=args,
- features=disable_header_modules,
- nocopts="-fno-exceptions")
-
-
-def tf_cc_tests_gpu(srcs,
- deps,
- name="",
- linkstatic=0,
- tags=[],
- size="medium",
- args=None):
- tf_cc_tests(srcs, deps, linkstatic, tags=tags, size=size, args=args)
-
-def tf_cuda_cc_tests(srcs,
- deps,
- name="",
- tags=[],
- size="medium",
- linkstatic=0,
- args=None,
- linkopts=[]):
- for src in srcs:
- tf_cuda_cc_test(
- name=src_to_test_name(src),
- srcs=[src],
- deps=deps,
- tags=tags,
- size=size,
- linkstatic=linkstatic,
- args=args,
- linkopts=linkopts)
-
-def tf_java_test(name,
- srcs=[],
- deps=[],
- kernels=[],
- *args,
- **kwargs):
- native.java_test(
- name=name,
- srcs=srcs,
- deps=deps + tf_binary_additional_srcs() + tf_binary_dynamic_kernel_dsos(kernels) + tf_binary_dynamic_kernel_deps(kernels),
- *args,
- **kwargs)
+def tf_cc_tests(
+ srcs,
+ deps,
+ name = "",
+ linkstatic = 0,
+ tags = [],
+ size = "medium",
+ args = None,
+ linkopts = [],
+ nocopts = None):
+ for src in srcs:
+ tf_cc_test(
+ name = src_to_test_name(src),
+ srcs = [src],
+ deps = deps,
+ linkstatic = linkstatic,
+ tags = tags,
+ size = size,
+ args = args,
+ linkopts = linkopts,
+ nocopts = nocopts,
+ )
+
+def tf_cc_test_mkl(
+ srcs,
+ deps,
+ name = "",
+ data = [],
+ linkstatic = 0,
+ tags = [],
+ size = "medium",
+ kernels = [],
+ args = None):
+ # -fno-exceptions in nocopts breaks compilation if header modules are enabled.
+ disable_header_modules = ["-use_header_modules"]
+
+ for src in srcs:
+ native.cc_test(
+ name = src_to_test_name(src),
+ srcs = if_mkl([src]) + tf_binary_additional_srcs(),
+ copts = tf_copts(),
+ linkopts = select({
+ clean_dep("//tensorflow:android"): [
+ "-pie",
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ "//conditions:default": [
+ "-lpthread",
+ "-lm",
+ ],
+ }) + _rpath_linkopts(src_to_test_name(src)),
+ deps = deps + tf_binary_dynamic_kernel_deps(kernels) + mkl_deps(),
+ data = data + tf_binary_dynamic_kernel_dsos(kernels),
+ linkstatic = linkstatic,
+ tags = tags,
+ size = size,
+ args = args,
+ features = disable_header_modules,
+ nocopts = "-fno-exceptions",
+ )
+
+def tf_cc_tests_gpu(
+ srcs,
+ deps,
+ name = "",
+ linkstatic = 0,
+ tags = [],
+ size = "medium",
+ args = None):
+ tf_cc_tests(srcs, deps, linkstatic, tags = tags, size = size, args = args)
+
+def tf_cuda_cc_tests(
+ srcs,
+ deps,
+ name = "",
+ tags = [],
+ size = "medium",
+ linkstatic = 0,
+ args = None,
+ linkopts = []):
+ for src in srcs:
+ tf_cuda_cc_test(
+ name = src_to_test_name(src),
+ srcs = [src],
+ deps = deps,
+ tags = tags,
+ size = size,
+ linkstatic = linkstatic,
+ args = args,
+ linkopts = linkopts,
+ )
+
+def tf_java_test(
+ name,
+ srcs = [],
+ deps = [],
+ kernels = [],
+ *args,
+ **kwargs):
+ native.java_test(
+ name = name,
+ srcs = srcs,
+ deps = deps + tf_binary_additional_srcs() + tf_binary_dynamic_kernel_dsos(kernels) + tf_binary_dynamic_kernel_deps(kernels),
+ *args,
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_java_test",
@@ -944,85 +983,89 @@ register_extension_info(
)
def _cuda_copts():
- """Gets the appropriate set of copts for (maybe) CUDA compilation.
-
- If we're doing CUDA compilation, returns copts for our particular CUDA
- compiler. If we're not doing CUDA compilation, returns an empty list.
-
- """
- return cuda_default_copts() + select({
- "//conditions:default": [],
- "@local_config_cuda//cuda:using_nvcc": ([
- "-nvcc_options=relaxed-constexpr",
- "-nvcc_options=ftz=true",
- ]),
- "@local_config_cuda//cuda:using_clang": ([
- "-fcuda-flush-denormals-to-zero",
- ]),
- })
+ """Gets the appropriate set of copts for (maybe) CUDA compilation.
+
+ If we're doing CUDA compilation, returns copts for our particular CUDA
+ compiler. If we're not doing CUDA compilation, returns an empty list.
+
+ """
+ return cuda_default_copts() + select({
+ "//conditions:default": [],
+ "@local_config_cuda//cuda:using_nvcc": ([
+ "-nvcc_options=relaxed-constexpr",
+ "-nvcc_options=ftz=true",
+ ]),
+ "@local_config_cuda//cuda:using_clang": ([
+ "-fcuda-flush-denormals-to-zero",
+ ]),
+ })
# Build defs for TensorFlow kernels
# When this target is built using --config=cuda, a cc_library is built
# that passes -DGOOGLE_CUDA=1 and '-x cuda', linking in additional
# libraries needed by GPU kernels.
-def tf_gpu_kernel_library(srcs,
- copts=[],
- cuda_copts=[],
- deps=[],
- hdrs=[],
- **kwargs):
- copts = copts + _cuda_copts() + if_cuda(cuda_copts) + tf_copts()
- kwargs["features"] = kwargs.get("features", []) + ["-use_header_modules"]
-
- native.cc_library(
- srcs=srcs,
- hdrs=hdrs,
- copts=copts,
- deps=deps + if_cuda([
- clean_dep("//tensorflow/core:cuda"),
- clean_dep("//tensorflow/core:gpu_lib"),
- ]),
- alwayslink=1,
- **kwargs)
+def tf_gpu_kernel_library(
+ srcs,
+ copts = [],
+ cuda_copts = [],
+ deps = [],
+ hdrs = [],
+ **kwargs):
+ copts = copts + _cuda_copts() + if_cuda(cuda_copts) + tf_copts()
+ kwargs["features"] = kwargs.get("features", []) + ["-use_header_modules"]
+
+ native.cc_library(
+ srcs = srcs,
+ hdrs = hdrs,
+ copts = copts,
+ deps = deps + if_cuda([
+ clean_dep("//tensorflow/core:cuda"),
+ clean_dep("//tensorflow/core:gpu_lib"),
+ ]),
+ alwayslink = 1,
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_gpu_kernel_library",
label_regex_for_dep = "{extension_name}",
)
-def tf_cuda_library(deps=None, cuda_deps=None, copts=tf_copts(), **kwargs):
- """Generate a cc_library with a conditional set of CUDA dependencies.
-
- When the library is built with --config=cuda:
-
- - Both deps and cuda_deps are used as dependencies.
- - The cuda runtime is added as a dependency (if necessary).
- - The library additionally passes -DGOOGLE_CUDA=1 to the list of copts.
- - In addition, when the library is also built with TensorRT enabled, it
- additionally passes -DGOOGLE_TENSORRT=1 to the list of copts.
-
- Args:
- - cuda_deps: BUILD dependencies which will be linked if and only if:
- '--config=cuda' is passed to the bazel command line.
- - deps: dependencies which will always be linked.
- - copts: copts always passed to the cc_library.
- - kwargs: Any other argument to cc_library.
- """
- if not deps:
- deps = []
- if not cuda_deps:
- cuda_deps = []
-
- kwargs["features"] = kwargs.get("features", []) + ["-use_header_modules"]
- native.cc_library(
- deps=deps + if_cuda(cuda_deps + [
- clean_dep("//tensorflow/core:cuda"),
- "@local_config_cuda//cuda:cuda_headers"
- ]),
- copts=(copts + if_cuda(["-DGOOGLE_CUDA=1"]) + if_mkl(["-DINTEL_MKL=1"]) +
- if_tensorrt(["-DGOOGLE_TENSORRT=1"])),
- **kwargs)
+def tf_cuda_library(deps = None, cuda_deps = None, copts = tf_copts(), **kwargs):
+ """Generate a cc_library with a conditional set of CUDA dependencies.
+
+ When the library is built with --config=cuda:
+
+ - Both deps and cuda_deps are used as dependencies.
+ - The cuda runtime is added as a dependency (if necessary).
+ - The library additionally passes -DGOOGLE_CUDA=1 to the list of copts.
+ - In addition, when the library is also built with TensorRT enabled, it
+ additionally passes -DGOOGLE_TENSORRT=1 to the list of copts.
+
+ Args:
+ - cuda_deps: BUILD dependencies which will be linked if and only if:
+ '--config=cuda' is passed to the bazel command line.
+ - deps: dependencies which will always be linked.
+ - copts: copts always passed to the cc_library.
+ - kwargs: Any other argument to cc_library.
+ """
+ if not deps:
+ deps = []
+ if not cuda_deps:
+ cuda_deps = []
+
+ kwargs["features"] = kwargs.get("features", []) + ["-use_header_modules"]
+ native.cc_library(
+ deps = deps + if_cuda(cuda_deps + [
+ clean_dep("//tensorflow/core:cuda"),
+ "@local_config_cuda//cuda:cuda_headers",
+ ]),
+ copts = (copts + if_cuda(["-DGOOGLE_CUDA=1"]) + if_mkl(["-DINTEL_MKL=1"]) +
+ if_mkl_open_source_only(["-DINTEL_MKL_DNN_ONLY"]) +
+ if_tensorrt(["-DGOOGLE_TENSORRT=1"])),
+ **kwargs
+ )
register_extension_info(
extension_name = "tf_cuda_library",
@@ -1040,126 +1083,138 @@ def tf_kernel_library(
copts = None,
is_external = False,
**kwargs):
- """A rule to build a TensorFlow OpKernel.
-
- May either specify srcs/hdrs or prefix. Similar to tf_cuda_library,
- but with alwayslink=1 by default. If prefix is specified:
- * prefix*.cc (except *.cu.cc) is added to srcs
- * prefix*.h (except *.cu.h) is added to hdrs
- * prefix*.cu.cc and prefix*.h (including *.cu.h) are added to gpu_srcs.
- With the exception that test files are excluded.
- For example, with prefix = "cast_op",
- * srcs = ["cast_op.cc"]
- * hdrs = ["cast_op.h"]
- * gpu_srcs = ["cast_op_gpu.cu.cc", "cast_op.h"]
- * "cast_op_test.cc" is excluded
- With prefix = "cwise_op"
- * srcs = ["cwise_op_abs.cc", ..., "cwise_op_tanh.cc"],
- * hdrs = ["cwise_ops.h", "cwise_ops_common.h"],
- * gpu_srcs = ["cwise_op_gpu_abs.cu.cc", ..., "cwise_op_gpu_tanh.cu.cc",
- "cwise_ops.h", "cwise_ops_common.h",
- "cwise_ops_gpu_common.cu.h"]
- * "cwise_ops_test.cc" is excluded
- """
- if not srcs:
- srcs = []
- if not hdrs:
- hdrs = []
- if not deps:
- deps = []
- if not copts:
- copts = []
- textual_hdrs = []
- copts = copts + tf_copts(is_external=is_external)
- if prefix:
- if native.glob([prefix + "*.cu.cc"], exclude=["*test*"]):
- if not gpu_srcs:
- gpu_srcs = []
- gpu_srcs = gpu_srcs + native.glob(
- [prefix + "*.cu.cc", prefix + "*.h"], exclude=[prefix + "*test*"])
- srcs = srcs + native.glob(
- [prefix + "*.cc"], exclude=[prefix + "*test*", prefix + "*.cu.cc"])
- hdrs = hdrs + native.glob(
+ """A rule to build a TensorFlow OpKernel.
+
+ May either specify srcs/hdrs or prefix. Similar to tf_cuda_library,
+ but with alwayslink=1 by default. If prefix is specified:
+ * prefix*.cc (except *.cu.cc) is added to srcs
+ * prefix*.h (except *.cu.h) is added to hdrs
+ * prefix*.cu.cc and prefix*.h (including *.cu.h) are added to gpu_srcs.
+ With the exception that test files are excluded.
+ For example, with prefix = "cast_op",
+ * srcs = ["cast_op.cc"]
+ * hdrs = ["cast_op.h"]
+ * gpu_srcs = ["cast_op_gpu.cu.cc", "cast_op.h"]
+ * "cast_op_test.cc" is excluded
+ With prefix = "cwise_op"
+ * srcs = ["cwise_op_abs.cc", ..., "cwise_op_tanh.cc"],
+ * hdrs = ["cwise_ops.h", "cwise_ops_common.h"],
+ * gpu_srcs = ["cwise_op_gpu_abs.cu.cc", ..., "cwise_op_gpu_tanh.cu.cc",
+ "cwise_ops.h", "cwise_ops_common.h",
+ "cwise_ops_gpu_common.cu.h"]
+ * "cwise_ops_test.cc" is excluded
+ """
+ if not srcs:
+ srcs = []
+ if not hdrs:
+ hdrs = []
+ if not deps:
+ deps = []
+ if not copts:
+ copts = []
+ textual_hdrs = []
+ copts = copts + tf_copts(is_external = is_external)
+ if prefix:
+ if native.glob([prefix + "*.cu.cc"], exclude = ["*test*"]):
+ if not gpu_srcs:
+ gpu_srcs = []
+ gpu_srcs = gpu_srcs + native.glob(
+ [prefix + "*.cu.cc", prefix + "*.h"],
+ exclude = [prefix + "*test*"],
+ )
+ srcs = srcs + native.glob(
+ [prefix + "*.cc"],
+ exclude = [prefix + "*test*", prefix + "*.cu.cc"],
+ )
+ hdrs = hdrs + native.glob(
[prefix + "*.h"],
exclude = [prefix + "*test*", prefix + "*.cu.h", prefix + "*impl.h"],
)
- textual_hdrs = native.glob(
+ textual_hdrs = native.glob(
[prefix + "*impl.h"],
exclude = [prefix + "*test*", prefix + "*.cu.h"],
)
- cuda_deps = [clean_dep("//tensorflow/core:gpu_lib")]
- if gpu_srcs:
- for gpu_src in gpu_srcs:
- if gpu_src.endswith(".cc") and not gpu_src.endswith(".cu.cc"):
- fail("{} not allowed in gpu_srcs. .cc sources must end with .cu.cc".
- format(gpu_src))
- tf_gpu_kernel_library(
- name=name + "_gpu", srcs=gpu_srcs, deps=deps, **kwargs)
- cuda_deps.extend([":" + name + "_gpu"])
- kwargs["tags"] = kwargs.get("tags", []) + [
- "req_dep=%s" % clean_dep("//tensorflow/core:gpu_lib"),
- "req_dep=@local_config_cuda//cuda:cuda_headers",
- ]
- tf_cuda_library(
- name=name,
- srcs=srcs,
- hdrs=hdrs,
- textual_hdrs = textual_hdrs,
- copts=copts,
- cuda_deps=cuda_deps,
- linkstatic=1, # Needed since alwayslink is broken in bazel b/27630669
- alwayslink=alwayslink,
- deps=deps,
- **kwargs)
-
- # TODO(gunan): CUDA dependency not clear here. Fix it.
- tf_cc_shared_object(
- name="libtfkernel_%s.so" % name,
- srcs=srcs + hdrs,
- copts=copts,
- deps=deps,
- tags=["manual", "notap"])
+ cuda_deps = [clean_dep("//tensorflow/core:gpu_lib")]
+ if gpu_srcs:
+ for gpu_src in gpu_srcs:
+ if gpu_src.endswith(".cc") and not gpu_src.endswith(".cu.cc"):
+ fail("{} not allowed in gpu_srcs. .cc sources must end with .cu.cc"
+ .format(gpu_src))
+ tf_gpu_kernel_library(
+ name = name + "_gpu",
+ srcs = gpu_srcs,
+ deps = deps,
+ **kwargs
+ )
+ cuda_deps.extend([":" + name + "_gpu"])
+ kwargs["tags"] = kwargs.get("tags", []) + [
+ "req_dep=%s" % clean_dep("//tensorflow/core:gpu_lib"),
+ "req_dep=@local_config_cuda//cuda:cuda_headers",
+ ]
+ tf_cuda_library(
+ name = name,
+ srcs = srcs,
+ hdrs = hdrs,
+ textual_hdrs = textual_hdrs,
+ copts = copts,
+ cuda_deps = cuda_deps,
+ linkstatic = 1, # Needed since alwayslink is broken in bazel b/27630669
+ alwayslink = alwayslink,
+ deps = deps,
+ **kwargs
+ )
+ # TODO(gunan): CUDA dependency not clear here. Fix it.
+ tf_cc_shared_object(
+ name = "libtfkernel_%s.so" % name,
+ srcs = srcs + hdrs,
+ copts = copts,
+ deps = deps,
+ tags = ["manual", "notap"],
+ )
register_extension_info(
extension_name = "tf_kernel_library",
label_regex_for_dep = "{extension_name}(_gpu)?",
)
-def tf_mkl_kernel_library(name,
- prefix=None,
- srcs=None,
- hdrs=None,
- deps=None,
- alwayslink=1,
- copts=tf_copts(),
- nocopts="-fno-exceptions"):
- """A rule to build MKL-based TensorFlow kernel libraries."""
-
- if not bool(srcs):
- srcs = []
- if not bool(hdrs):
- hdrs = []
-
- if prefix:
- srcs = srcs + native.glob(
- [prefix + "*.cc"])
- hdrs = hdrs + native.glob(
- [prefix + "*.h"])
-
- # -fno-exceptions in nocopts breaks compilation if header modules are enabled.
- disable_header_modules = ["-use_header_modules"]
-
- native.cc_library(
- name=name,
- srcs=if_mkl(srcs),
- hdrs=hdrs,
- deps=deps,
- alwayslink=alwayslink,
- copts=copts,
- nocopts=nocopts,
- features = disable_header_modules
- )
+def tf_mkl_kernel_library(
+ name,
+ prefix = None,
+ srcs = None,
+ hdrs = None,
+ deps = None,
+ alwayslink = 1,
+ copts = tf_copts(),
+ nocopts = "-fno-exceptions"):
+ """A rule to build MKL-based TensorFlow kernel libraries."""
+
+ if not bool(srcs):
+ srcs = []
+ if not bool(hdrs):
+ hdrs = []
+
+ if prefix:
+ srcs = srcs + native.glob(
+ [prefix + "*.cc"],
+ )
+ hdrs = hdrs + native.glob(
+ [prefix + "*.h"],
+ )
+
+ # -fno-exceptions in nocopts breaks compilation if header modules are enabled.
+ disable_header_modules = ["-use_header_modules"]
+
+ native.cc_library(
+ name = name,
+ srcs = if_mkl(srcs),
+ hdrs = hdrs,
+ deps = deps,
+ alwayslink = alwayslink,
+ copts = copts,
+ nocopts = nocopts,
+ features = disable_header_modules,
+ )
register_extension_info(
extension_name = "tf_mkl_kernel_library",
@@ -1168,35 +1223,42 @@ register_extension_info(
# Bazel rules for building swig files.
def _py_wrap_cc_impl(ctx):
- srcs = ctx.files.srcs
- if len(srcs) != 1:
- fail("Exactly one SWIG source file label must be specified.", "srcs")
- module_name = ctx.attr.module_name
- src = ctx.files.srcs[0]
- inputs = depset([src])
- inputs += ctx.files.swig_includes
- for dep in ctx.attr.deps:
- inputs += dep.cc.transitive_headers
- inputs += ctx.files._swiglib
- inputs += ctx.files.toolchain_deps
- swig_include_dirs = depset(_get_repository_roots(ctx, inputs))
- swig_include_dirs += sorted([f.dirname for f in ctx.files._swiglib])
- args = [
- "-c++", "-python", "-module", module_name, "-o", ctx.outputs.cc_out.path,
- "-outdir", ctx.outputs.py_out.dirname
- ]
- args += ["-l" + f.path for f in ctx.files.swig_includes]
- args += ["-I" + i for i in swig_include_dirs]
- args += [src.path]
- outputs = [ctx.outputs.cc_out, ctx.outputs.py_out]
- ctx.action(
- executable=ctx.executable._swig,
- arguments=args,
- inputs=list(inputs),
- outputs=outputs,
- mnemonic="PythonSwig",
- progress_message="SWIGing " + src.path)
- return struct(files=depset(outputs))
+ srcs = ctx.files.srcs
+ if len(srcs) != 1:
+ fail("Exactly one SWIG source file label must be specified.", "srcs")
+ module_name = ctx.attr.module_name
+ src = ctx.files.srcs[0]
+ inputs = depset([src])
+ inputs += ctx.files.swig_includes
+ for dep in ctx.attr.deps:
+ inputs += dep.cc.transitive_headers
+ inputs += ctx.files._swiglib
+ inputs += ctx.files.toolchain_deps
+ swig_include_dirs = depset(_get_repository_roots(ctx, inputs))
+ swig_include_dirs += sorted([f.dirname for f in ctx.files._swiglib])
+ args = [
+ "-c++",
+ "-python",
+ "-module",
+ module_name,
+ "-o",
+ ctx.outputs.cc_out.path,
+ "-outdir",
+ ctx.outputs.py_out.dirname,
+ ]
+ args += ["-l" + f.path for f in ctx.files.swig_includes]
+ args += ["-I" + i for i in swig_include_dirs]
+ args += [src.path]
+ outputs = [ctx.outputs.cc_out, ctx.outputs.py_out]
+ ctx.action(
+ executable = ctx.executable._swig,
+ arguments = args,
+ inputs = list(inputs),
+ outputs = outputs,
+ mnemonic = "PythonSwig",
+ progress_message = "SWIGing " + src.path,
+ )
+ return struct(files = depset(outputs))
_py_wrap_cc = rule(
attrs = {
@@ -1234,40 +1296,40 @@ _py_wrap_cc = rule(
)
def _get_repository_roots(ctx, files):
- """Returns abnormal root directories under which files reside.
-
- When running a ctx.action, source files within the main repository are all
- relative to the current directory; however, files that are generated or exist
- in remote repositories will have their root directory be a subdirectory,
- e.g. bazel-out/local-fastbuild/genfiles/external/jpeg_archive. This function
- returns the set of these devious directories, ranked and sorted by popularity
- in order to hopefully minimize the number of I/O system calls within the
- compiler, because includes have quadratic complexity.
- """
- result = {}
- for f in files:
- root = f.root.path
- if root:
- if root not in result:
- result[root] = 0
- result[root] -= 1
- work = f.owner.workspace_root
- if work:
- if root:
- root += "/"
- root += work
- if root:
- if root not in result:
- result[root] = 0
- result[root] -= 1
- return [k for v, k in sorted([(v, k) for k, v in result.items()])]
+ """Returns abnormal root directories under which files reside.
+
+ When running a ctx.action, source files within the main repository are all
+ relative to the current directory; however, files that are generated or exist
+ in remote repositories will have their root directory be a subdirectory,
+ e.g. bazel-out/local-fastbuild/genfiles/external/jpeg_archive. This function
+ returns the set of these devious directories, ranked and sorted by popularity
+ in order to hopefully minimize the number of I/O system calls within the
+ compiler, because includes have quadratic complexity.
+ """
+ result = {}
+ for f in files:
+ root = f.root.path
+ if root:
+ if root not in result:
+ result[root] = 0
+ result[root] -= 1
+ work = f.owner.workspace_root
+ if work:
+ if root:
+ root += "/"
+ root += work
+ if root:
+ if root not in result:
+ result[root] = 0
+ result[root] -= 1
+ return [k for v, k in sorted([(v, k) for k, v in result.items()])]
# Bazel rule for collecting the header files that a target depends on.
def _transitive_hdrs_impl(ctx):
- outputs = depset()
- for dep in ctx.attr.deps:
- outputs += dep.cc.transitive_headers
- return struct(files=outputs)
+ outputs = depset()
+ for dep in ctx.attr.deps:
+ outputs += dep.cc.transitive_headers
+ return struct(files = outputs)
_transitive_hdrs = rule(
attrs = {
@@ -1279,52 +1341,54 @@ _transitive_hdrs = rule(
implementation = _transitive_hdrs_impl,
)
-def transitive_hdrs(name, deps=[], **kwargs):
- _transitive_hdrs(name=name + "_gather", deps=deps)
- native.filegroup(name=name, srcs=[":" + name + "_gather"])
+def transitive_hdrs(name, deps = [], **kwargs):
+ _transitive_hdrs(name = name + "_gather", deps = deps)
+ native.filegroup(name = name, srcs = [":" + name + "_gather"])
# Create a header only library that includes all the headers exported by
# the libraries in deps.
-def cc_header_only_library(name, deps=[], includes=[], **kwargs):
- _transitive_hdrs(name=name + "_gather", deps=deps)
- native.cc_library(name=name,
- hdrs=[":" + name + "_gather"],
- includes=includes,
- **kwargs)
+def cc_header_only_library(name, deps = [], includes = [], **kwargs):
+ _transitive_hdrs(name = name + "_gather", deps = deps)
+ native.cc_library(
+ name = name,
+ hdrs = [":" + name + "_gather"],
+ includes = includes,
+ **kwargs
+ )
def tf_custom_op_library_additional_deps():
- return [
+ return [
"@protobuf_archive//:protobuf_headers",
- clean_dep("//third_party/eigen3"),
- clean_dep("//tensorflow/core:framework_headers_lib"),
- ] + if_windows(["//tensorflow/python:pywrap_tensorflow_import_lib"])
+ clean_dep("//third_party/eigen3"),
+ clean_dep("//tensorflow/core:framework_headers_lib"),
+ ] + if_windows(["//tensorflow/python:pywrap_tensorflow_import_lib"])
# A list of targets that contains the implemenation of
# tf_custom_op_library_additional_deps. It's used to generate a DEF file for
# exporting symbols from _pywrap_tensorflow.dll on Windows.
def tf_custom_op_library_additional_deps_impl():
- return [
+ return [
"@protobuf_archive//:protobuf",
"@nsync//:nsync_cpp",
- # for //third_party/eigen3
- clean_dep("//third_party/eigen3"),
- # for //tensorflow/core:framework_headers_lib
- clean_dep("//tensorflow/core:framework"),
- clean_dep("//tensorflow/core:reader_base"),
- ]
+ # for //third_party/eigen3
+ clean_dep("//third_party/eigen3"),
+ # for //tensorflow/core:framework_headers_lib
+ clean_dep("//tensorflow/core:framework"),
+ clean_dep("//tensorflow/core:reader_base"),
+ ]
# Traverse the dependency graph along the "deps" attribute of the
# target and return a struct with one field called 'tf_collected_deps'.
# tf_collected_deps will be the union of the deps of the current target
# and the tf_collected_deps of the dependencies of this target.
def _collect_deps_aspect_impl(target, ctx):
- alldeps = depset()
- if hasattr(ctx.rule.attr, "deps"):
- for dep in ctx.rule.attr.deps:
- alldeps = alldeps | depset([dep.label])
- if hasattr(dep, "tf_collected_deps"):
- alldeps = alldeps | dep.tf_collected_deps
- return struct(tf_collected_deps=alldeps)
+ alldeps = depset()
+ if hasattr(ctx.rule.attr, "deps"):
+ for dep in ctx.rule.attr.deps:
+ alldeps = alldeps | depset([dep.label])
+ if hasattr(dep, "tf_collected_deps"):
+ alldeps = alldeps | dep.tf_collected_deps
+ return struct(tf_collected_deps = alldeps)
collect_deps_aspect = aspect(
attr_aspects = ["deps"],
@@ -1332,24 +1396,26 @@ collect_deps_aspect = aspect(
)
def _dep_label(dep):
- label = dep.label
- return label.package + ":" + label.name
+ label = dep.label
+ return label.package + ":" + label.name
# This rule checks that the transitive dependencies of targets listed
# in the 'deps' attribute don't depend on the targets listed in
# the 'disallowed_deps' attribute.
def _check_deps_impl(ctx):
- disallowed_deps = ctx.attr.disallowed_deps
- for input_dep in ctx.attr.deps:
- if not hasattr(input_dep, "tf_collected_deps"):
- continue
- for dep in input_dep.tf_collected_deps:
- for disallowed_dep in disallowed_deps:
- if dep == disallowed_dep.label:
- fail(
- _dep_label(input_dep) + " cannot depend on " + _dep_label(
- disallowed_dep))
- return struct()
+ disallowed_deps = ctx.attr.disallowed_deps
+ for input_dep in ctx.attr.deps:
+ if not hasattr(input_dep, "tf_collected_deps"):
+ continue
+ for dep in input_dep.tf_collected_deps:
+ for disallowed_dep in disallowed_deps:
+ if dep == disallowed_dep.label:
+ fail(
+ _dep_label(input_dep) + " cannot depend on " + _dep_label(
+ disallowed_dep,
+ ),
+ )
+ return struct()
check_deps = rule(
_check_deps_impl,
@@ -1368,66 +1434,70 @@ check_deps = rule(
# Helper to build a dynamic library (.so) from the sources containing
# implementations of custom ops and kernels.
-def tf_custom_op_library(name, srcs=[], gpu_srcs=[], deps=[], linkopts=[]):
- cuda_deps = [
- clean_dep("//tensorflow/core:stream_executor_headers_lib"),
- "@local_config_cuda//cuda:cuda_headers",
- "@local_config_cuda//cuda:cudart_static",
- ]
- deps = deps + tf_custom_op_library_additional_deps()
- if gpu_srcs:
- basename = name.split(".")[0]
- native.cc_library(
- name=basename + "_gpu",
- srcs=gpu_srcs,
- copts=_cuda_copts() + if_tensorrt(["-DGOOGLE_TENSORRT=1"]),
- features = if_cuda(["-use_header_modules"]),
- deps=deps + if_cuda(cuda_deps))
- cuda_deps.extend([":" + basename + "_gpu"])
-
- check_deps(
- name=name + "_check_deps",
- deps=deps + if_cuda(cuda_deps),
- disallowed_deps=[
- clean_dep("//tensorflow/core:framework"),
- clean_dep("//tensorflow/core:lib")
- ])
- tf_cc_shared_object(
- name=name,
- srcs=srcs,
- deps=deps + if_cuda(cuda_deps),
- data=if_static([name + "_check_deps"]),
- copts=tf_copts(is_external=True),
- features = ["windows_export_all_symbols"],
- linkopts=linkopts + select({
- "//conditions:default": [
- "-lm",
- ],
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- clean_dep("//tensorflow:darwin"): [],
- }),)
+def tf_custom_op_library(name, srcs = [], gpu_srcs = [], deps = [], linkopts = []):
+ cuda_deps = [
+ clean_dep("//tensorflow/core:stream_executor_headers_lib"),
+ "@local_config_cuda//cuda:cuda_headers",
+ "@local_config_cuda//cuda:cudart_static",
+ ]
+ deps = deps + tf_custom_op_library_additional_deps()
+ if gpu_srcs:
+ basename = name.split(".")[0]
+ native.cc_library(
+ name = basename + "_gpu",
+ srcs = gpu_srcs,
+ copts = _cuda_copts() + if_tensorrt(["-DGOOGLE_TENSORRT=1"]),
+ features = if_cuda(["-use_header_modules"]),
+ deps = deps + if_cuda(cuda_deps),
+ )
+ cuda_deps.extend([":" + basename + "_gpu"])
+
+ check_deps(
+ name = name + "_check_deps",
+ deps = deps + if_cuda(cuda_deps),
+ disallowed_deps = [
+ clean_dep("//tensorflow/core:framework"),
+ clean_dep("//tensorflow/core:lib"),
+ ],
+ )
+ tf_cc_shared_object(
+ name = name,
+ srcs = srcs,
+ deps = deps + if_cuda(cuda_deps),
+ data = if_static([name + "_check_deps"]),
+ copts = tf_copts(is_external = True),
+ features = ["windows_export_all_symbols"],
+ linkopts = linkopts + select({
+ "//conditions:default": [
+ "-lm",
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ clean_dep("//tensorflow:darwin"): [],
+ }),
+ )
register_extension_info(
extension_name = "tf_custom_op_library",
label_regex_for_dep = "{extension_name}",
)
-def tf_custom_op_py_library(name,
- srcs=[],
- dso=[],
- kernels=[],
- srcs_version="PY2AND3",
- visibility=None,
- deps=[]):
- kernels = kernels # unused argument
- native.py_library(
- name=name,
- data=dso,
- srcs=srcs,
- srcs_version=srcs_version,
- visibility=visibility,
- deps=deps,)
+def tf_custom_op_py_library(
+ name,
+ srcs = [],
+ dso = [],
+ kernels = [],
+ srcs_version = "PY2AND3",
+ visibility = None,
+ deps = []):
+ kernels = kernels # unused argument
+ native.py_library(
+ name = name,
+ data = dso,
+ srcs = srcs,
+ srcs_version = srcs_version,
+ visibility = visibility,
+ deps = deps,
+ )
register_extension_info(
extension_name = "tf_custom_op_py_library",
@@ -1441,119 +1511,127 @@ register_extension_info(
# This function attempts to append init_module_name to list of
# exported functions in version script
def _append_init_to_versionscript_impl(ctx):
- mod_name = ctx.attr.module_name
- if ctx.attr.is_version_script:
- ctx.actions.expand_template(
- template=ctx.file.template_file,
- output=ctx.outputs.versionscript,
- substitutions={
- "global:":"global:\n init_%s;\n PyInit_*;"%(mod_name),
- },
- is_executable=False,
- )
- else:
- ctx.actions.expand_template(
- template=ctx.file.template_file,
- output=ctx.outputs.versionscript,
- substitutions={
- "*tensorflow*":"*tensorflow*\ninit_%s\nPyInit_*\n"%(mod_name),
- },
- is_executable=False,
- )
-
+ mod_name = ctx.attr.module_name
+ if ctx.attr.is_version_script:
+ ctx.actions.expand_template(
+ template = ctx.file.template_file,
+ output = ctx.outputs.versionscript,
+ substitutions = {
+ "global:": "global:\n init_%s;\n PyInit_*;" % (mod_name),
+ },
+ is_executable = False,
+ )
+ else:
+ ctx.actions.expand_template(
+ template = ctx.file.template_file,
+ output = ctx.outputs.versionscript,
+ substitutions = {
+ "*tensorflow*": "*tensorflow*\ninit_%s\nPyInit_*\n" % (mod_name),
+ },
+ is_executable = False,
+ )
-_append_init_to_versionscript= rule(
- implementation=_append_init_to_versionscript_impl,
- attrs={
- "module_name":attr.string(mandatory=True),
- "template_file":attr.label(allow_files=True,single_file=True,mandatory=True),
- "is_version_script":attr.bool(default=True,
- doc='whether target is a ld version script or exported symbol list',
- mandatory=False),
- },
- outputs={"versionscript":"%{name}.lds"},
+_append_init_to_versionscript = rule(
+ implementation = _append_init_to_versionscript_impl,
+ attrs = {
+ "module_name": attr.string(mandatory = True),
+ "template_file": attr.label(allow_files = True, single_file = True, mandatory = True),
+ "is_version_script": attr.bool(
+ default = True,
+ doc = "whether target is a ld version script or exported symbol list",
+ mandatory = False,
+ ),
+ },
+ outputs = {"versionscript": "%{name}.lds"},
)
-def tf_py_wrap_cc(name,
- srcs,
- swig_includes=[],
- deps=[],
- copts=[],
- **kwargs):
- module_name = name.split("/")[-1]
- # Convert a rule name such as foo/bar/baz to foo/bar/_baz.so
- # and use that as the name for the rule producing the .so file.
- cc_library_name = "/".join(name.split("/")[:-1] + ["_" + module_name + ".so"])
- cc_library_pyd_name = "/".join(
- name.split("/")[:-1] + ["_" + module_name + ".pyd"])
- extra_deps = []
- _py_wrap_cc(
- name=name + "_py_wrap",
- srcs=srcs,
- swig_includes=swig_includes,
- deps=deps + extra_deps,
- toolchain_deps=["@bazel_tools//tools/cpp:current_cc_toolchain"],
- module_name=module_name,
- py_module_name=name)
- vscriptname=name+"_versionscript"
- _append_init_to_versionscript(
- name=vscriptname,
- module_name=module_name,
- is_version_script=select({
- "@local_config_cuda//cuda:darwin":False,
- "//conditions:default":True,
- }),
- template_file=select({
- "@local_config_cuda//cuda:darwin":clean_dep("//tensorflow:tf_exported_symbols.lds"),
- "//conditions:default":clean_dep("//tensorflow:tf_version_script.lds")
- })
- )
- extra_linkopts = select({
- "@local_config_cuda//cuda:darwin": [
- "-Wl,-exported_symbols_list",
- "$(location %s.lds)"%vscriptname,
- ],
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- "//conditions:default": [
- "-Wl,--version-script",
- "$(location %s.lds)"%vscriptname,
- ]
- })
- extra_deps += select({
- "@local_config_cuda//cuda:darwin": [
- "%s.lds"%vscriptname,
- ],
- clean_dep("//tensorflow:windows"): [],
- clean_dep("//tensorflow:windows_msvc"): [],
- "//conditions:default": [
- "%s.lds"%vscriptname,
- ]
- })
-
- tf_cc_shared_object(
- name=cc_library_name,
- srcs=[module_name + ".cc"],
- copts=copts + if_not_windows([
- "-Wno-self-assign", "-Wno-sign-compare", "-Wno-write-strings"
- ]),
- linkopts=extra_linkopts,
- linkstatic=1,
- deps=deps + extra_deps,
- **kwargs)
- native.genrule(
- name="gen_" + cc_library_pyd_name,
- srcs=[":" + cc_library_name],
- outs=[cc_library_pyd_name],
- cmd="cp $< $@",)
- native.py_library(
- name=name,
- srcs=[":" + name + ".py"],
- srcs_version="PY2AND3",
- data=select({
- clean_dep("//tensorflow:windows"): [":" + cc_library_pyd_name],
- "//conditions:default": [":" + cc_library_name],
- }))
+def tf_py_wrap_cc(
+ name,
+ srcs,
+ swig_includes = [],
+ deps = [],
+ copts = [],
+ **kwargs):
+ module_name = name.split("/")[-1]
+
+ # Convert a rule name such as foo/bar/baz to foo/bar/_baz.so
+ # and use that as the name for the rule producing the .so file.
+ cc_library_name = "/".join(name.split("/")[:-1] + ["_" + module_name + ".so"])
+ cc_library_pyd_name = "/".join(
+ name.split("/")[:-1] + ["_" + module_name + ".pyd"],
+ )
+ extra_deps = []
+ _py_wrap_cc(
+ name = name + "_py_wrap",
+ srcs = srcs,
+ swig_includes = swig_includes,
+ deps = deps + extra_deps,
+ toolchain_deps = ["@bazel_tools//tools/cpp:current_cc_toolchain"],
+ module_name = module_name,
+ py_module_name = name,
+ )
+ vscriptname = name + "_versionscript"
+ _append_init_to_versionscript(
+ name = vscriptname,
+ module_name = module_name,
+ is_version_script = select({
+ "@local_config_cuda//cuda:darwin": False,
+ "//conditions:default": True,
+ }),
+ template_file = select({
+ "@local_config_cuda//cuda:darwin": clean_dep("//tensorflow:tf_exported_symbols.lds"),
+ "//conditions:default": clean_dep("//tensorflow:tf_version_script.lds"),
+ }),
+ )
+ extra_linkopts = select({
+ "@local_config_cuda//cuda:darwin": [
+ "-Wl,-exported_symbols_list",
+ "$(location %s.lds)" % vscriptname,
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ "//conditions:default": [
+ "-Wl,--version-script",
+ "$(location %s.lds)" % vscriptname,
+ ],
+ })
+ extra_deps += select({
+ "@local_config_cuda//cuda:darwin": [
+ "%s.lds" % vscriptname,
+ ],
+ clean_dep("//tensorflow:windows"): [],
+ "//conditions:default": [
+ "%s.lds" % vscriptname,
+ ],
+ })
+
+ tf_cc_shared_object(
+ name = cc_library_name,
+ srcs = [module_name + ".cc"],
+ copts = copts + if_not_windows([
+ "-Wno-self-assign",
+ "-Wno-sign-compare",
+ "-Wno-write-strings",
+ ]),
+ linkopts = extra_linkopts,
+ linkstatic = 1,
+ deps = deps + extra_deps,
+ **kwargs
+ )
+ native.genrule(
+ name = "gen_" + cc_library_pyd_name,
+ srcs = [":" + cc_library_name],
+ outs = [cc_library_pyd_name],
+ cmd = "cp $< $@",
+ )
+ native.py_library(
+ name = name,
+ srcs = [":" + name + ".py"],
+ srcs_version = "PY2AND3",
+ data = select({
+ clean_dep("//tensorflow:windows"): [":" + cc_library_pyd_name],
+ "//conditions:default": [":" + cc_library_name],
+ }),
+ )
# This macro is for running python tests against system installed pip package
# on Windows.
@@ -1571,246 +1649,263 @@ def tf_py_wrap_cc(name,
# Note that this only works on Windows. See the definition of
# //third_party/tensorflow/tools/pip_package:win_pip_package_marker for specific reasons.
# 2. When --define=no_tensorflow_py_deps=false (by default), it's a normal py_test.
-def py_test(deps=[], data=[], **kwargs):
- native.py_test(
- # TODO(jlebar): Ideally we'd use tcmalloc here.,
- deps=select({
- "//conditions:default": deps,
- clean_dep("//tensorflow:no_tensorflow_py_deps"): [],
- }),
- data = data + select({
- "//conditions:default": [],
- clean_dep("//tensorflow:no_tensorflow_py_deps"):
- ["//tensorflow/tools/pip_package:win_pip_package_marker"],
- }),
- **kwargs)
+def py_test(deps = [], data = [], **kwargs):
+ native.py_test(
+ # TODO(jlebar): Ideally we'd use tcmalloc here.,
+ deps = select({
+ "//conditions:default": deps,
+ clean_dep("//tensorflow:no_tensorflow_py_deps"): [],
+ }),
+ data = data + select({
+ "//conditions:default": [],
+ clean_dep("//tensorflow:no_tensorflow_py_deps"): ["//tensorflow/tools/pip_package:win_pip_package_marker"],
+ }),
+ **kwargs
+ )
register_extension_info(
extension_name = "py_test",
label_regex_for_dep = "{extension_name}",
)
-def tf_py_test(name,
- srcs,
- size="medium",
- data=[],
- main=None,
- args=[],
- tags=[],
- shard_count=1,
- additional_deps=[],
- flaky=0,
- xla_enabled=False,
- grpc_enabled=False):
- if xla_enabled:
- additional_deps = additional_deps + tf_additional_xla_deps_py()
- if grpc_enabled:
- additional_deps = additional_deps + tf_additional_grpc_deps_py()
- py_test(
- name=name,
- size=size,
- srcs=srcs,
- main=main,
- args=args,
- tags=tags,
- visibility=[clean_dep("//tensorflow:internal")],
- shard_count=shard_count,
- data=data,
- deps=[
+def tf_py_test(
+ name,
+ srcs,
+ size = "medium",
+ data = [],
+ main = None,
+ args = [],
+ tags = [],
+ shard_count = 1,
+ additional_deps = [],
+ flaky = 0,
+ xla_enabled = False,
+ grpc_enabled = False):
+ if xla_enabled:
+ additional_deps = additional_deps + tf_additional_xla_deps_py()
+ if grpc_enabled:
+ additional_deps = additional_deps + tf_additional_grpc_deps_py()
+ py_test(
+ name = name,
+ size = size,
+ srcs = srcs,
+ main = main,
+ args = args,
+ tags = tags,
+ visibility = [clean_dep("//tensorflow:internal")],
+ shard_count = shard_count,
+ data = data,
+ deps = [
clean_dep("//tensorflow/python:extra_py_tests_deps"),
clean_dep("//tensorflow/python:gradient_checker"),
- ] + additional_deps,
- flaky=flaky,
- srcs_version="PY2AND3")
+ ] + additional_deps,
+ flaky = flaky,
+ srcs_version = "PY2AND3",
+ )
register_extension_info(
extension_name = "tf_py_test",
label_regex_map = {"additional_deps": "deps:{extension_name}"},
)
-def cuda_py_test(name,
- srcs,
- size="medium",
- data=[],
- main=None,
- args=[],
- shard_count=1,
- additional_deps=[],
- tags=[],
- flaky=0,
- xla_enabled=False,
- grpc_enabled=False):
- test_tags = tags + tf_cuda_tests_tags()
- tf_py_test(
- name=name,
- size=size,
- srcs=srcs,
- data=data,
- main=main,
- args=args,
- tags=test_tags,
- shard_count=shard_count,
- additional_deps=additional_deps,
- flaky=flaky,
- xla_enabled=xla_enabled,
- grpc_enabled=grpc_enabled)
+def cuda_py_test(
+ name,
+ srcs,
+ size = "medium",
+ data = [],
+ main = None,
+ args = [],
+ shard_count = 1,
+ additional_deps = [],
+ tags = [],
+ flaky = 0,
+ xla_enabled = False,
+ grpc_enabled = False):
+ test_tags = tags + tf_cuda_tests_tags()
+ tf_py_test(
+ name = name,
+ size = size,
+ srcs = srcs,
+ data = data,
+ main = main,
+ args = args,
+ tags = test_tags,
+ shard_count = shard_count,
+ additional_deps = additional_deps,
+ flaky = flaky,
+ xla_enabled = xla_enabled,
+ grpc_enabled = grpc_enabled,
+ )
register_extension_info(
extension_name = "cuda_py_test",
label_regex_map = {"additional_deps": "additional_deps:{extension_name}"},
)
-def sycl_py_test(name,
- srcs,
- size="medium",
- data=[],
- main=None,
- args=[],
- shard_count=1,
- additional_deps=[],
- tags=[],
- flaky=0,
- xla_enabled=False,
- grpc_enabled=False):
- test_tags = tags + tf_sycl_tests_tags()
- tf_py_test(
- name=name,
- size=size,
- srcs=srcs,
- data=data,
- main=main,
- args=args,
- tags=test_tags,
- shard_count=shard_count,
- additional_deps=additional_deps,
- flaky=flaky,
- xla_enabled=xla_enabled,
- grpc_enabled=grpc_enabled)
+def sycl_py_test(
+ name,
+ srcs,
+ size = "medium",
+ data = [],
+ main = None,
+ args = [],
+ shard_count = 1,
+ additional_deps = [],
+ tags = [],
+ flaky = 0,
+ xla_enabled = False,
+ grpc_enabled = False):
+ test_tags = tags + tf_sycl_tests_tags()
+ tf_py_test(
+ name = name,
+ size = size,
+ srcs = srcs,
+ data = data,
+ main = main,
+ args = args,
+ tags = test_tags,
+ shard_count = shard_count,
+ additional_deps = additional_deps,
+ flaky = flaky,
+ xla_enabled = xla_enabled,
+ grpc_enabled = grpc_enabled,
+ )
register_extension_info(
extension_name = "sycl_py_test",
label_regex_map = {"additional_deps": "additional_deps:{extension_name}"},
)
-def py_tests(name,
- srcs,
- size="medium",
- additional_deps=[],
- data=[],
- tags=[],
- shard_count=1,
- prefix="",
- xla_enabled=False,
- grpc_enabled=False):
- for src in srcs:
- test_name = src.split("/")[-1].split(".")[0]
- if prefix:
- test_name = "%s_%s" % (prefix, test_name)
- tf_py_test(
- name=test_name,
- size=size,
- srcs=[src],
- main=src,
- tags=tags,
- shard_count=shard_count,
- data=data,
- additional_deps=additional_deps,
- xla_enabled=xla_enabled,
- grpc_enabled=grpc_enabled)
-
-def cuda_py_tests(name,
- srcs,
- size="medium",
- additional_deps=[],
- data=[],
- shard_count=1,
- tags=[],
- prefix="",
- xla_enabled=False,
- grpc_enabled=False):
- test_tags = tags + tf_cuda_tests_tags()
- py_tests(
- name=name,
- size=size,
- srcs=srcs,
- additional_deps=additional_deps,
- data=data,
- tags=test_tags,
- shard_count=shard_count,
- prefix=prefix,
- xla_enabled=xla_enabled,
- grpc_enabled=grpc_enabled)
+def py_tests(
+ name,
+ srcs,
+ size = "medium",
+ additional_deps = [],
+ data = [],
+ tags = [],
+ shard_count = 1,
+ prefix = "",
+ xla_enabled = False,
+ grpc_enabled = False):
+ for src in srcs:
+ test_name = src.split("/")[-1].split(".")[0]
+ if prefix:
+ test_name = "%s_%s" % (prefix, test_name)
+ tf_py_test(
+ name = test_name,
+ size = size,
+ srcs = [src],
+ main = src,
+ tags = tags,
+ shard_count = shard_count,
+ data = data,
+ additional_deps = additional_deps,
+ xla_enabled = xla_enabled,
+ grpc_enabled = grpc_enabled,
+ )
+
+def cuda_py_tests(
+ name,
+ srcs,
+ size = "medium",
+ additional_deps = [],
+ data = [],
+ shard_count = 1,
+ tags = [],
+ prefix = "",
+ xla_enabled = False,
+ grpc_enabled = False):
+ test_tags = tags + tf_cuda_tests_tags()
+ py_tests(
+ name = name,
+ size = size,
+ srcs = srcs,
+ additional_deps = additional_deps,
+ data = data,
+ tags = test_tags,
+ shard_count = shard_count,
+ prefix = prefix,
+ xla_enabled = xla_enabled,
+ grpc_enabled = grpc_enabled,
+ )
# Creates a genrule named <name> for running tools/proto_text's generator to
# make the proto_text functions, for the protos passed in <srcs>.
#
# Return a struct with fields (hdrs, srcs) containing the names of the
# generated files.
-def tf_generate_proto_text_sources(name, srcs_relative_dir, srcs, protodeps=[], deps=[], visibility=None):
- out_hdrs = (
- [p.replace(".proto", ".pb_text.h")
- for p in srcs] + [p.replace(".proto", ".pb_text-impl.h") for p in srcs])
- out_srcs = [p.replace(".proto", ".pb_text.cc") for p in srcs]
- native.genrule(
- name=name + "_srcs",
- srcs=srcs + protodeps + [clean_dep("//tensorflow/tools/proto_text:placeholder.txt")],
- outs=out_hdrs + out_srcs,
- visibility=visibility,
- cmd=
- "$(location //tensorflow/tools/proto_text:gen_proto_text_functions) "
- + "$(@D) " + srcs_relative_dir + " $(SRCS)",
- tools=[
- clean_dep("//tensorflow/tools/proto_text:gen_proto_text_functions")
- ],)
-
- native.filegroup(
- name=name + "_hdrs",
- srcs=out_hdrs,
- visibility=visibility,
- )
-
- native.cc_library(
- name=name,
- srcs=out_srcs,
- hdrs=out_hdrs,
- visibility=visibility,
- deps = deps,
- )
+def tf_generate_proto_text_sources(name, srcs_relative_dir, srcs, protodeps = [], deps = [], visibility = None):
+ out_hdrs = (
+ [
+ p.replace(".proto", ".pb_text.h")
+ for p in srcs
+ ] + [p.replace(".proto", ".pb_text-impl.h") for p in srcs]
+ )
+ out_srcs = [p.replace(".proto", ".pb_text.cc") for p in srcs]
+ native.genrule(
+ name = name + "_srcs",
+ srcs = srcs + protodeps + [clean_dep("//tensorflow/tools/proto_text:placeholder.txt")],
+ outs = out_hdrs + out_srcs,
+ visibility = visibility,
+ cmd =
+ "$(location //tensorflow/tools/proto_text:gen_proto_text_functions) " +
+ "$(@D) " + srcs_relative_dir + " $(SRCS)",
+ tools = [
+ clean_dep("//tensorflow/tools/proto_text:gen_proto_text_functions"),
+ ],
+ )
+
+ native.filegroup(
+ name = name + "_hdrs",
+ srcs = out_hdrs,
+ visibility = visibility,
+ )
+
+ native.cc_library(
+ name = name,
+ srcs = out_srcs,
+ hdrs = out_hdrs,
+ visibility = visibility,
+ deps = deps,
+ )
def tf_genrule_cmd_append_to_srcs(to_append):
- return ("cat $(SRCS) > $(@) && " + "echo >> $(@) && " + "echo " + to_append +
- " >> $(@)")
+ return ("cat $(SRCS) > $(@) && " + "echo >> $(@) && " + "echo " + to_append +
+ " >> $(@)")
def tf_version_info_genrule():
- native.genrule(
- name="version_info_gen",
- srcs=[
- clean_dep("@local_config_git//:gen/spec.json"),
- clean_dep("@local_config_git//:gen/head"),
- clean_dep("@local_config_git//:gen/branch_ref"),
- ],
- outs=["util/version_info.cc"],
- cmd=
- "$(location //tensorflow/tools/git:gen_git_source.py) --generate $(SRCS) \"$@\" --git_tag_override=$${GIT_TAG_OVERRIDE:-}",
- local=1,
- tools=[clean_dep("//tensorflow/tools/git:gen_git_source.py")],)
+ native.genrule(
+ name = "version_info_gen",
+ srcs = [
+ clean_dep("@local_config_git//:gen/spec.json"),
+ clean_dep("@local_config_git//:gen/head"),
+ clean_dep("@local_config_git//:gen/branch_ref"),
+ ],
+ outs = ["util/version_info.cc"],
+ cmd =
+ "$(location //tensorflow/tools/git:gen_git_source.py) --generate $(SRCS) \"$@\" --git_tag_override=$${GIT_TAG_OVERRIDE:-}",
+ local = 1,
+ tools = [clean_dep("//tensorflow/tools/git:gen_git_source.py")],
+ )
def tf_py_build_info_genrule():
- native.genrule(
- name="py_build_info_gen",
- outs=["platform/build_info.py"],
- cmd=
- "$(location //tensorflow/tools/build_info:gen_build_info.py) --raw_generate \"$@\" --build_config " + if_cuda("cuda", "cpu"),
- local=1,
- tools=[clean_dep("//tensorflow/tools/build_info:gen_build_info.py")],)
-
-def cc_library_with_android_deps(deps,
- android_deps=[],
- common_deps=[],
- copts=tf_copts(),
- **kwargs):
- deps = if_not_android(deps) + if_android(android_deps) + common_deps
- native.cc_library(deps=deps, copts=copts, **kwargs)
+ native.genrule(
+ name = "py_build_info_gen",
+ outs = ["platform/build_info.py"],
+ cmd =
+ "$(location //tensorflow/tools/build_info:gen_build_info.py) --raw_generate \"$@\" --build_config " + if_cuda("cuda", "cpu"),
+ local = 1,
+ tools = [clean_dep("//tensorflow/tools/build_info:gen_build_info.py")],
+ )
+
+def cc_library_with_android_deps(
+ deps,
+ android_deps = [],
+ common_deps = [],
+ copts = tf_copts(),
+ **kwargs):
+ deps = if_not_android(deps) + if_android(android_deps) + common_deps
+ native.cc_library(deps = deps, copts = copts, **kwargs)
register_extension_info(
extension_name = "cc_library_with_android_deps",
diff --git a/tensorflow/tools/api/golden/BUILD b/tensorflow/tools/api/golden/BUILD
index 1f041ef193..4389a999e7 100644
--- a/tensorflow/tools/api/golden/BUILD
+++ b/tensorflow/tools/api/golden/BUILD
@@ -13,5 +13,5 @@ filegroup(
filegroup(
name = "api_golden_v2",
- srcs = glob(["v1/*.pbtxt"]),
+ srcs = glob(["v2/*.pbtxt"]),
)
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected1-d.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected1-d.pbtxt
index f754fa1da8..ff19dcc3a3 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected1-d.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected1-d.pbtxt
@@ -82,7 +82,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\'], varargs=None, keywords=kwargs, defaults=[\'1\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\', \'implementation\'], varargs=None, keywords=kwargs, defaults=[\'1\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1\'], "
}
member_method {
name: "add_loss"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected2-d.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected2-d.pbtxt
index c9516b8f07..3c278fead6 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected2-d.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-locally-connected2-d.pbtxt
@@ -82,7 +82,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\'], varargs=None, keywords=kwargs, defaults=[\'(1, 1)\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\', \'implementation\'], varargs=None, keywords=kwargs, defaults=[\'(1, 1)\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1\'], "
}
member_method {
name: "add_loss"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt
index 1160d2840f..6718e36dc6 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt
@@ -61,6 +61,10 @@ tf_class {
mtype: "<type \'property\'>"
}
member {
+ name: "output_size"
+ mtype: "<type \'property\'>"
+ }
+ member {
name: "state_size"
mtype: "<type \'property\'>"
}
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt
index c74773000a..e606eab919 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt
index d251f54806..5deb02d569 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt
index d76eab7eb8..32fa151a8e 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'kernel_initializer\', \'bias_initializer\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'kernel_initializer\', \'bias_initializer\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt
index 944db6ac93..30c6c2ce3b 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'use_peepholes\', \'cell_clip\', \'initializer\', \'num_proj\', \'proj_clip\', \'num_unit_shards\', \'num_proj_shards\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'False\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'use_peepholes\', \'cell_clip\', \'initializer\', \'num_proj\', \'proj_clip\', \'num_unit_shards\', \'num_proj_shards\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'False\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.pbtxt
index 5eb42b4db3..8040eae01a 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.pbtxt
@@ -785,6 +785,10 @@ tf_module {
argspec: "args=[\'x\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
+ name: "batch_gather"
+ argspec: "args=[\'params\', \'indices\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
+ member_method {
name: "batch_to_space"
argspec: "args=[\'input\', \'crops\', \'block_size\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
@@ -1001,6 +1005,10 @@ tf_module {
argspec: "args=[\'x\', \'y\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
+ name: "div_no_nan"
+ argspec: "args=[\'x\', \'y\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
+ member_method {
name: "divide"
argspec: "args=[\'x\', \'y\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
@@ -1902,19 +1910,19 @@ tf_module {
}
member_method {
name: "sparse_reduce_max"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reduce_max_sparse"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reduce_sum"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reduce_sum_sparse"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reorder"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.strings.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.strings.pbtxt
index 9a831fed26..018be7b9f9 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.strings.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.strings.pbtxt
@@ -5,6 +5,10 @@ tf_module {
argspec: "args=[\'inputs\', \'separator\', \'name\'], varargs=None, keywords=None, defaults=[\'\', \'None\'], "
}
member_method {
+ name: "length"
+ argspec: "args=[\'input\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
+ member_method {
name: "regex_full_match"
argspec: "args=[\'input\', \'pattern\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.summary.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.summary.pbtxt
index 871ebb5247..7ed9cd77a0 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.summary.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.summary.pbtxt
@@ -50,7 +50,7 @@ tf_module {
}
member_method {
name: "merge_all"
- argspec: "args=[\'key\', \'scope\'], varargs=None, keywords=None, defaults=[\'summaries\', \'None\'], "
+ argspec: "args=[\'key\', \'scope\', \'name\'], varargs=None, keywords=None, defaults=[\'summaries\', \'None\', \'None\'], "
}
member_method {
name: "scalar"
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.train.-checkpoint.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.train.-checkpoint.pbtxt
index 2d067e4eff..5be37200f3 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.train.-checkpoint.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.train.-checkpoint.pbtxt
@@ -20,4 +20,8 @@ tf_class {
name: "save"
argspec: "args=[\'self\', \'file_prefix\', \'session\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
+ member_method {
+ name: "write"
+ argspec: "args=[\'self\', \'file_prefix\', \'session\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
}
diff --git a/tensorflow/tools/api/golden/v1/tensorflow.train.pbtxt b/tensorflow/tools/api/golden/v1/tensorflow.train.pbtxt
index b0fb04d7d4..9f35395284 100644
--- a/tensorflow/tools/api/golden/v1/tensorflow.train.pbtxt
+++ b/tensorflow/tools/api/golden/v1/tensorflow.train.pbtxt
@@ -298,7 +298,7 @@ tf_module {
}
member_method {
name: "generate_checkpoint_state_proto"
- argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\', \'all_model_checkpoint_timestamps\', \'last_preserved_timestamp\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\'], "
}
member_method {
name: "get_checkpoint_mtimes"
@@ -446,7 +446,7 @@ tf_module {
}
member_method {
name: "update_checkpoint_state"
- argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\', \'latest_filename\'], varargs=None, keywords=None, defaults=[\'None\', \'None\'], "
+ argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\', \'latest_filename\', \'all_model_checkpoint_timestamps\', \'last_preserved_timestamp\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "warm_start"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.-experimental.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.-experimental.pbtxt
index ef9fe096a1..eb41deee13 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.-experimental.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.-experimental.pbtxt
@@ -14,5 +14,11 @@ tf_proto {
label: LABEL_OPTIONAL
type: TYPE_BOOL
}
+ field {
+ name: "executor_type"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ }
}
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.pbtxt
index eeef15515d..e565b903d2 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.-config-proto.pbtxt
@@ -137,6 +137,12 @@ tf_proto {
label: LABEL_OPTIONAL
type: TYPE_BOOL
}
+ field {
+ name: "executor_type"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ }
}
}
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.data.-iterator.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.data.-iterator.pbtxt
index 1f9aeb6ad6..4f0147a523 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.data.-iterator.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.data.-iterator.pbtxt
@@ -1,6 +1,7 @@
path: "tensorflow.data.Iterator"
tf_class {
is_instance: "<class \'tensorflow.python.data.ops.iterator_ops.Iterator\'>"
+ is_instance: "<class \'tensorflow.python.training.checkpointable.base.CheckpointableBase\'>"
is_instance: "<type \'object\'>"
member {
name: "initializer"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-classifier.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-classifier.pbtxt
index 9dbb5d16a4..c23b04b4ef 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-classifier.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-classifier.pbtxt
@@ -21,7 +21,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'feature_columns\', \'n_batches_per_layer\', \'model_dir\', \'n_classes\', \'weight_column\', \'label_vocabulary\', \'n_trees\', \'max_depth\', \'learning_rate\', \'l1_regularization\', \'l2_regularization\', \'tree_complexity\', \'min_node_weight\', \'config\', \'center_bias\'], varargs=None, keywords=None, defaults=[\'None\', \'<object object instance>\', \'None\', \'None\', \'100\', \'6\', \'0.1\', \'0.0\', \'0.0\', \'0.0\', \'0.0\', \'None\', \'False\'], "
+ argspec: "args=[\'self\', \'feature_columns\', \'n_batches_per_layer\', \'model_dir\', \'n_classes\', \'weight_column\', \'label_vocabulary\', \'n_trees\', \'max_depth\', \'learning_rate\', \'l1_regularization\', \'l2_regularization\', \'tree_complexity\', \'min_node_weight\', \'config\', \'center_bias\', \'pruning_mode\'], varargs=None, keywords=None, defaults=[\'None\', \'<object object instance>\', \'None\', \'None\', \'100\', \'6\', \'0.1\', \'0.0\', \'0.0\', \'0.0\', \'0.0\', \'None\', \'False\', \'none\'], "
}
member_method {
name: "eval_dir"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-regressor.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-regressor.pbtxt
index 34a30c2874..6878d28fff 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-regressor.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.estimator.-boosted-trees-regressor.pbtxt
@@ -21,7 +21,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'feature_columns\', \'n_batches_per_layer\', \'model_dir\', \'label_dimension\', \'weight_column\', \'n_trees\', \'max_depth\', \'learning_rate\', \'l1_regularization\', \'l2_regularization\', \'tree_complexity\', \'min_node_weight\', \'config\', \'center_bias\'], varargs=None, keywords=None, defaults=[\'None\', \'<object object instance>\', \'None\', \'100\', \'6\', \'0.1\', \'0.0\', \'0.0\', \'0.0\', \'0.0\', \'None\', \'False\'], "
+ argspec: "args=[\'self\', \'feature_columns\', \'n_batches_per_layer\', \'model_dir\', \'label_dimension\', \'weight_column\', \'n_trees\', \'max_depth\', \'learning_rate\', \'l1_regularization\', \'l2_regularization\', \'tree_complexity\', \'min_node_weight\', \'config\', \'center_bias\', \'pruning_mode\'], varargs=None, keywords=None, defaults=[\'None\', \'<object object instance>\', \'None\', \'100\', \'6\', \'0.1\', \'0.0\', \'0.0\', \'0.0\', \'0.0\', \'None\', \'False\', \'none\'], "
}
member_method {
name: "eval_dir"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.estimator.-run-config.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.estimator.-run-config.pbtxt
index 5aa4b3d4fb..bf1f94b6ae 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.estimator.-run-config.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.estimator.-run-config.pbtxt
@@ -11,6 +11,10 @@ tf_class {
mtype: "<type \'property\'>"
}
member {
+ name: "eval_distribute"
+ mtype: "<type \'property\'>"
+ }
+ member {
name: "evaluation_master"
mtype: "<type \'property\'>"
}
@@ -92,7 +96,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'model_dir\', \'tf_random_seed\', \'save_summary_steps\', \'save_checkpoints_steps\', \'save_checkpoints_secs\', \'session_config\', \'keep_checkpoint_max\', \'keep_checkpoint_every_n_hours\', \'log_step_count_steps\', \'train_distribute\', \'device_fn\', \'protocol\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'100\', \'<object object instance>\', \'<object object instance>\', \'None\', \'5\', \'10000\', \'100\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'model_dir\', \'tf_random_seed\', \'save_summary_steps\', \'save_checkpoints_steps\', \'save_checkpoints_secs\', \'session_config\', \'keep_checkpoint_max\', \'keep_checkpoint_every_n_hours\', \'log_step_count_steps\', \'train_distribute\', \'device_fn\', \'protocol\', \'eval_distribute\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'100\', \'<object object instance>\', \'<object object instance>\', \'None\', \'5\', \'10000\', \'100\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "replace"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.image.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.image.pbtxt
index 6ec3aba775..5c46dc5ee7 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.image.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.image.pbtxt
@@ -125,6 +125,10 @@ tf_module {
argspec: "args=[\'overlaps\', \'scores\', \'max_output_size\', \'overlap_threshold\', \'score_threshold\', \'name\'], varargs=None, keywords=None, defaults=[\'0.5\', \'-inf\', \'None\'], "
}
member_method {
+ name: "non_max_suppression_padded"
+ argspec: "args=[\'boxes\', \'scores\', \'max_output_size\', \'iou_threshold\', \'score_threshold\', \'pad_to_max_output_size\', \'name\'], varargs=None, keywords=None, defaults=[\'0.5\', \'-inf\', \'False\', \'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"
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.-model.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.-model.pbtxt
index 40e82b18b6..e579fe6a1a 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.-model.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.-model.pbtxt
@@ -135,7 +135,7 @@ tf_class {
}
member_method {
name: "compile"
- argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\', \'distribute\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "compute_mask"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.-sequential.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.-sequential.pbtxt
index 65cfad77d1..97688fcb0f 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.-sequential.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.-sequential.pbtxt
@@ -140,7 +140,7 @@ tf_class {
}
member_method {
name: "compile"
- argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\', \'distribute\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "compute_mask"
@@ -267,10 +267,6 @@ tf_class {
argspec: "args=[\'self\', \'line_length\', \'positions\', \'print_fn\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\'], "
}
member_method {
- name: "symbolic_set_inputs"
- argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
name: "test_on_batch"
argspec: "args=[\'self\', \'x\', \'y\', \'sample_weight\'], varargs=None, keywords=None, defaults=[\'None\', \'None\'], "
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.activations.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.activations.pbtxt
index 2cd83baf65..2e9de9ebb2 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.activations.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.activations.pbtxt
@@ -22,7 +22,7 @@ tf_module {
}
member_method {
name: "relu"
- argspec: "args=[\'x\', \'alpha\', \'max_value\'], varargs=None, keywords=None, defaults=[\'0.0\', \'None\'], "
+ argspec: "args=[\'x\', \'alpha\', \'max_value\', \'threshold\'], varargs=None, keywords=None, defaults=[\'0.0\', \'None\', \'0\'], "
}
member_method {
name: "selu"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.densenet.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.densenet.pbtxt
deleted file mode 100644
index 42cb914450..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.densenet.pbtxt
+++ /dev/null
@@ -1,23 +0,0 @@
-path: "tensorflow.keras.applications.densenet"
-tf_module {
- member_method {
- name: "DenseNet121"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "DenseNet169"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "DenseNet201"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\', \'data_format\'], varargs=None, keywords=None, defaults=[\'None\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_resnet_v2.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_resnet_v2.pbtxt
deleted file mode 100644
index 211080c19b..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_resnet_v2.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.inception_resnet_v2"
-tf_module {
- member_method {
- name: "InceptionResNetV2"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_v3.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_v3.pbtxt
deleted file mode 100644
index b67cee80ab..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.inception_v3.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.inception_v3"
-tf_module {
- member_method {
- name: "InceptionV3"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.mobilenet.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.mobilenet.pbtxt
deleted file mode 100644
index ef774e1dd7..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.mobilenet.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.mobilenet"
-tf_module {
- member_method {
- name: "MobileNet"
- argspec: "args=[\'input_shape\', \'alpha\', \'depth_multiplier\', \'dropout\', \'include_top\', \'weights\', \'input_tensor\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'None\', \'1.0\', \'1\', \'0.001\', \'True\', \'imagenet\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.nasnet.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.nasnet.pbtxt
deleted file mode 100644
index cd75b87540..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.nasnet.pbtxt
+++ /dev/null
@@ -1,19 +0,0 @@
-path: "tensorflow.keras.applications.nasnet"
-tf_module {
- member_method {
- name: "NASNetLarge"
- argspec: "args=[\'input_shape\', \'include_top\', \'weights\', \'input_tensor\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'None\', \'True\', \'imagenet\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "NASNetMobile"
- argspec: "args=[\'input_shape\', \'include_top\', \'weights\', \'input_tensor\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'None\', \'True\', \'imagenet\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.pbtxt
deleted file mode 100644
index 9fc086eb8e..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.pbtxt
+++ /dev/null
@@ -1,87 +0,0 @@
-path: "tensorflow.keras.applications"
-tf_module {
- member {
- name: "densenet"
- mtype: "<type \'module\'>"
- }
- member {
- name: "inception_resnet_v2"
- mtype: "<type \'module\'>"
- }
- member {
- name: "inception_v3"
- mtype: "<type \'module\'>"
- }
- member {
- name: "mobilenet"
- mtype: "<type \'module\'>"
- }
- member {
- name: "nasnet"
- mtype: "<type \'module\'>"
- }
- member {
- name: "resnet50"
- mtype: "<type \'module\'>"
- }
- member {
- name: "vgg16"
- mtype: "<type \'module\'>"
- }
- member {
- name: "vgg19"
- mtype: "<type \'module\'>"
- }
- member {
- name: "xception"
- mtype: "<type \'module\'>"
- }
- member_method {
- name: "DenseNet121"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "DenseNet169"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "DenseNet201"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "InceptionResNetV2"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "InceptionV3"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "MobileNet"
- argspec: "args=[\'input_shape\', \'alpha\', \'depth_multiplier\', \'dropout\', \'include_top\', \'weights\', \'input_tensor\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'None\', \'1.0\', \'1\', \'0.001\', \'True\', \'imagenet\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "NASNetLarge"
- argspec: "args=[\'input_shape\', \'include_top\', \'weights\', \'input_tensor\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'None\', \'True\', \'imagenet\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "NASNetMobile"
- argspec: "args=[\'input_shape\', \'include_top\', \'weights\', \'input_tensor\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'None\', \'True\', \'imagenet\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "ResNet50"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "VGG16"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "VGG19"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "Xception"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.resnet50.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.resnet50.pbtxt
deleted file mode 100644
index 7385af064d..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.resnet50.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.resnet50"
-tf_module {
- member_method {
- name: "ResNet50"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\', \'data_format\', \'mode\'], varargs=None, keywords=None, defaults=[\'None\', \'caffe\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg16.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg16.pbtxt
deleted file mode 100644
index ba66fba8f3..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg16.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.vgg16"
-tf_module {
- member_method {
- name: "VGG16"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\', \'data_format\', \'mode\'], varargs=None, keywords=None, defaults=[\'None\', \'caffe\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg19.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg19.pbtxt
deleted file mode 100644
index e55a1345b6..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.vgg19.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.vgg19"
-tf_module {
- member_method {
- name: "VGG19"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\', \'data_format\', \'mode\'], varargs=None, keywords=None, defaults=[\'None\', \'caffe\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.xception.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.xception.pbtxt
deleted file mode 100644
index 59dd2108f2..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.applications.xception.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.applications.xception"
-tf_module {
- member_method {
- name: "Xception"
- argspec: "args=[\'include_top\', \'weights\', \'input_tensor\', \'input_shape\', \'pooling\', \'classes\'], varargs=None, keywords=None, defaults=[\'True\', \'imagenet\', \'None\', \'None\', \'None\', \'1000\'], "
- }
- member_method {
- name: "decode_predictions"
- argspec: "args=[\'preds\', \'top\'], varargs=None, keywords=None, defaults=[\'5\'], "
- }
- member_method {
- name: "preprocess_input"
- argspec: "args=[\'x\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.backend.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.backend.pbtxt
index fddac63b78..126ce8db6a 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.backend.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.backend.pbtxt
@@ -366,7 +366,7 @@ tf_module {
}
member_method {
name: "relu"
- argspec: "args=[\'x\', \'alpha\', \'max_value\'], varargs=None, keywords=None, defaults=[\'0.0\', \'None\'], "
+ argspec: "args=[\'x\', \'alpha\', \'max_value\', \'threshold\'], varargs=None, keywords=None, defaults=[\'0.0\', \'None\', \'0\'], "
}
member_method {
name: "repeat"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-lambda.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-lambda.pbtxt
index 5d05cf689f..2dff7a6de4 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-lambda.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-lambda.pbtxt
@@ -118,7 +118,7 @@ tf_class {
}
member_method {
name: "compute_output_shape"
- argspec: "args=[\'self\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "count_params"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected1-d.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected1-d.pbtxt
index f754fa1da8..ff19dcc3a3 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected1-d.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected1-d.pbtxt
@@ -82,7 +82,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\'], varargs=None, keywords=kwargs, defaults=[\'1\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\', \'implementation\'], varargs=None, keywords=kwargs, defaults=[\'1\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1\'], "
}
member_method {
name: "add_loss"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected2-d.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected2-d.pbtxt
index c9516b8f07..3c278fead6 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected2-d.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-locally-connected2-d.pbtxt
@@ -82,7 +82,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\'], varargs=None, keywords=kwargs, defaults=[\'(1, 1)\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'filters\', \'kernel_size\', \'strides\', \'padding\', \'data_format\', \'activation\', \'use_bias\', \'kernel_initializer\', \'bias_initializer\', \'kernel_regularizer\', \'bias_regularizer\', \'activity_regularizer\', \'kernel_constraint\', \'bias_constraint\', \'implementation\'], varargs=None, keywords=kwargs, defaults=[\'(1, 1)\', \'valid\', \'None\', \'None\', \'True\', \'glorot_uniform\', \'zeros\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1\'], "
}
member_method {
name: "add_loss"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-re-l-u.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-re-l-u.pbtxt
index c00fa79adf..4d3de58bd1 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-re-l-u.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-re-l-u.pbtxt
@@ -82,7 +82,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'max_value\'], varargs=None, keywords=kwargs, defaults=[\'None\'], "
+ argspec: "args=[\'self\', \'max_value\', \'negative_slope\', \'threshold\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'0\', \'0\'], "
}
member_method {
name: "add_loss"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt
index 1160d2840f..6718e36dc6 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.layers.-stacked-r-n-n-cells.pbtxt
@@ -61,6 +61,10 @@ tf_class {
mtype: "<type \'property\'>"
}
member {
+ name: "output_size"
+ mtype: "<type \'property\'>"
+ }
+ member {
name: "state_size"
mtype: "<type \'property\'>"
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-model.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-model.pbtxt
index 85f7c2bfed..56914e1746 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-model.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-model.pbtxt
@@ -135,7 +135,7 @@ tf_class {
}
member_method {
name: "compile"
- argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\', \'distribute\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "compute_mask"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-sequential.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-sequential.pbtxt
index 6a83129f7d..acfb3521c0 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-sequential.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.keras.models.-sequential.pbtxt
@@ -140,7 +140,7 @@ tf_class {
}
member_method {
name: "compile"
- argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'optimizer\', \'loss\', \'metrics\', \'loss_weights\', \'sample_weight_mode\', \'weighted_metrics\', \'target_tensors\', \'distribute\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "compute_mask"
@@ -267,10 +267,6 @@ tf_class {
argspec: "args=[\'self\', \'line_length\', \'positions\', \'print_fn\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\'], "
}
member_method {
- name: "symbolic_set_inputs"
- argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
name: "test_on_batch"
argspec: "args=[\'self\', \'x\', \'y\', \'sample_weight\'], varargs=None, keywords=None, defaults=[\'None\', \'None\'], "
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-directory-iterator.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-directory-iterator.pbtxt
deleted file mode 100644
index dddace87dc..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-directory-iterator.pbtxt
+++ /dev/null
@@ -1,23 +0,0 @@
-path: "tensorflow.keras.preprocessing.image.DirectoryIterator"
-tf_class {
- is_instance: "<class \'tensorflow.python.keras.preprocessing.image.DirectoryIterator\'>"
- is_instance: "<class \'tensorflow.python.keras.preprocessing.image.Iterator\'>"
- is_instance: "<class \'tensorflow.python.keras.utils.data_utils.Sequence\'>"
- is_instance: "<type \'object\'>"
- member_method {
- name: "__init__"
- argspec: "args=[\'self\', \'directory\', \'image_data_generator\', \'target_size\', \'color_mode\', \'classes\', \'class_mode\', \'batch_size\', \'shuffle\', \'seed\', \'data_format\', \'save_to_dir\', \'save_prefix\', \'save_format\', \'follow_links\', \'subset\', \'interpolation\'], varargs=None, keywords=None, defaults=[\'(256, 256)\', \'rgb\', \'None\', \'categorical\', \'32\', \'True\', \'None\', \'None\', \'None\', \'\', \'png\', \'False\', \'None\', \'nearest\'], "
- }
- member_method {
- name: "next"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "on_epoch_end"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "reset"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-image-data-generator.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-image-data-generator.pbtxt
deleted file mode 100644
index c1e2e94f0b..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-image-data-generator.pbtxt
+++ /dev/null
@@ -1,29 +0,0 @@
-path: "tensorflow.keras.preprocessing.image.ImageDataGenerator"
-tf_class {
- is_instance: "<class \'tensorflow.python.keras.preprocessing.image.ImageDataGenerator\'>"
- is_instance: "<type \'object\'>"
- member_method {
- name: "__init__"
- argspec: "args=[\'self\', \'featurewise_center\', \'samplewise_center\', \'featurewise_std_normalization\', \'samplewise_std_normalization\', \'zca_whitening\', \'zca_epsilon\', \'rotation_range\', \'width_shift_range\', \'height_shift_range\', \'brightness_range\', \'shear_range\', \'zoom_range\', \'channel_shift_range\', \'fill_mode\', \'cval\', \'horizontal_flip\', \'vertical_flip\', \'rescale\', \'preprocessing_function\', \'data_format\', \'validation_split\'], varargs=None, keywords=None, defaults=[\'False\', \'False\', \'False\', \'False\', \'False\', \'1e-06\', \'0.0\', \'0.0\', \'0.0\', \'None\', \'0.0\', \'0.0\', \'0.0\', \'nearest\', \'0.0\', \'False\', \'False\', \'None\', \'None\', \'None\', \'0.0\'], "
- }
- member_method {
- name: "fit"
- argspec: "args=[\'self\', \'x\', \'augment\', \'rounds\', \'seed\'], varargs=None, keywords=None, defaults=[\'False\', \'1\', \'None\'], "
- }
- member_method {
- name: "flow"
- argspec: "args=[\'self\', \'x\', \'y\', \'batch_size\', \'shuffle\', \'seed\', \'save_to_dir\', \'save_prefix\', \'save_format\', \'subset\'], varargs=None, keywords=None, defaults=[\'None\', \'32\', \'True\', \'None\', \'None\', \'\', \'png\', \'None\'], "
- }
- member_method {
- name: "flow_from_directory"
- argspec: "args=[\'self\', \'directory\', \'target_size\', \'color_mode\', \'classes\', \'class_mode\', \'batch_size\', \'shuffle\', \'seed\', \'save_to_dir\', \'save_prefix\', \'save_format\', \'follow_links\', \'subset\', \'interpolation\'], varargs=None, keywords=None, defaults=[\'(256, 256)\', \'rgb\', \'None\', \'categorical\', \'32\', \'True\', \'None\', \'None\', \'\', \'png\', \'False\', \'None\', \'nearest\'], "
- }
- member_method {
- name: "random_transform"
- argspec: "args=[\'self\', \'x\', \'seed\'], varargs=None, keywords=None, defaults=[\'None\'], "
- }
- member_method {
- name: "standardize"
- argspec: "args=[\'self\', \'x\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-iterator.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-iterator.pbtxt
deleted file mode 100644
index 825d9f1d1d..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-iterator.pbtxt
+++ /dev/null
@@ -1,18 +0,0 @@
-path: "tensorflow.keras.preprocessing.image.Iterator"
-tf_class {
- is_instance: "<class \'tensorflow.python.keras.preprocessing.image.Iterator\'>"
- is_instance: "<class \'tensorflow.python.keras.utils.data_utils.Sequence\'>"
- is_instance: "<type \'object\'>"
- member_method {
- name: "__init__"
- argspec: "args=[\'self\', \'n\', \'batch_size\', \'shuffle\', \'seed\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "on_epoch_end"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "reset"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-numpy-array-iterator.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-numpy-array-iterator.pbtxt
deleted file mode 100644
index 75924a254a..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.-numpy-array-iterator.pbtxt
+++ /dev/null
@@ -1,23 +0,0 @@
-path: "tensorflow.keras.preprocessing.image.NumpyArrayIterator"
-tf_class {
- is_instance: "<class \'tensorflow.python.keras.preprocessing.image.NumpyArrayIterator\'>"
- is_instance: "<class \'tensorflow.python.keras.preprocessing.image.Iterator\'>"
- is_instance: "<class \'tensorflow.python.keras.utils.data_utils.Sequence\'>"
- is_instance: "<type \'object\'>"
- member_method {
- name: "__init__"
- argspec: "args=[\'self\', \'x\', \'y\', \'image_data_generator\', \'batch_size\', \'shuffle\', \'seed\', \'data_format\', \'save_to_dir\', \'save_prefix\', \'save_format\', \'subset\'], varargs=None, keywords=None, defaults=[\'32\', \'False\', \'None\', \'None\', \'None\', \'\', \'png\', \'None\'], "
- }
- member_method {
- name: "next"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "on_epoch_end"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "reset"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.pbtxt
deleted file mode 100644
index 6b850dd6b7..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.image.pbtxt
+++ /dev/null
@@ -1,63 +0,0 @@
-path: "tensorflow.keras.preprocessing.image"
-tf_module {
- member {
- name: "DirectoryIterator"
- mtype: "<type \'type\'>"
- }
- member {
- name: "ImageDataGenerator"
- mtype: "<type \'type\'>"
- }
- member {
- name: "Iterator"
- mtype: "<type \'type\'>"
- }
- member {
- name: "NumpyArrayIterator"
- mtype: "<type \'type\'>"
- }
- member_method {
- name: "apply_transform"
- argspec: "args=[\'x\', \'transform_matrix\', \'channel_axis\', \'fill_mode\', \'cval\'], varargs=None, keywords=None, defaults=[\'0\', \'nearest\', \'0.0\'], "
- }
- member_method {
- name: "array_to_img"
- argspec: "args=[\'x\', \'data_format\', \'scale\'], varargs=None, keywords=None, defaults=[\'None\', \'True\'], "
- }
- member_method {
- name: "flip_axis"
- argspec: "args=[\'x\', \'axis\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "img_to_array"
- argspec: "args=[\'img\', \'data_format\'], varargs=None, keywords=None, defaults=[\'None\'], "
- }
- member_method {
- name: "load_img"
- argspec: "args=[\'path\', \'grayscale\', \'target_size\', \'interpolation\'], varargs=None, keywords=None, defaults=[\'False\', \'None\', \'nearest\'], "
- }
- member_method {
- name: "random_brightness"
- argspec: "args=[\'x\', \'brightness_range\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "random_channel_shift"
- argspec: "args=[\'x\', \'intensity\', \'channel_axis\'], varargs=None, keywords=None, defaults=[\'0\'], "
- }
- member_method {
- name: "random_rotation"
- argspec: "args=[\'x\', \'rg\', \'row_axis\', \'col_axis\', \'channel_axis\', \'fill_mode\', \'cval\'], varargs=None, keywords=None, defaults=[\'1\', \'2\', \'0\', \'nearest\', \'0.0\'], "
- }
- member_method {
- name: "random_shear"
- argspec: "args=[\'x\', \'intensity\', \'row_axis\', \'col_axis\', \'channel_axis\', \'fill_mode\', \'cval\'], varargs=None, keywords=None, defaults=[\'1\', \'2\', \'0\', \'nearest\', \'0.0\'], "
- }
- member_method {
- name: "random_shift"
- argspec: "args=[\'x\', \'wrg\', \'hrg\', \'row_axis\', \'col_axis\', \'channel_axis\', \'fill_mode\', \'cval\'], varargs=None, keywords=None, defaults=[\'1\', \'2\', \'0\', \'nearest\', \'0.0\'], "
- }
- member_method {
- name: "random_zoom"
- argspec: "args=[\'x\', \'zoom_range\', \'row_axis\', \'col_axis\', \'channel_axis\', \'fill_mode\', \'cval\'], varargs=None, keywords=None, defaults=[\'1\', \'2\', \'0\', \'nearest\', \'0.0\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.pbtxt
deleted file mode 100644
index 5a78581fc5..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.pbtxt
+++ /dev/null
@@ -1,15 +0,0 @@
-path: "tensorflow.keras.preprocessing"
-tf_module {
- member {
- name: "image"
- mtype: "<type \'module\'>"
- }
- member {
- name: "sequence"
- mtype: "<type \'module\'>"
- }
- member {
- name: "text"
- mtype: "<type \'module\'>"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.-timeseries-generator.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.-timeseries-generator.pbtxt
deleted file mode 100644
index 326b1fa4fd..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.-timeseries-generator.pbtxt
+++ /dev/null
@@ -1,14 +0,0 @@
-path: "tensorflow.keras.preprocessing.sequence.TimeseriesGenerator"
-tf_class {
- is_instance: "<class \'tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator\'>"
- is_instance: "<class \'tensorflow.python.keras.utils.data_utils.Sequence\'>"
- is_instance: "<type \'object\'>"
- member_method {
- name: "__init__"
- argspec: "args=[\'self\', \'data\', \'targets\', \'length\', \'sampling_rate\', \'stride\', \'start_index\', \'end_index\', \'shuffle\', \'reverse\', \'batch_size\'], varargs=None, keywords=None, defaults=[\'1\', \'1\', \'0\', \'None\', \'False\', \'False\', \'128\'], "
- }
- member_method {
- name: "on_epoch_end"
- argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.pbtxt
deleted file mode 100644
index cf59f8a272..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.sequence.pbtxt
+++ /dev/null
@@ -1,19 +0,0 @@
-path: "tensorflow.keras.preprocessing.sequence"
-tf_module {
- member {
- name: "TimeseriesGenerator"
- mtype: "<type \'type\'>"
- }
- member_method {
- name: "make_sampling_table"
- argspec: "args=[\'size\', \'sampling_factor\'], varargs=None, keywords=None, defaults=[\'1e-05\'], "
- }
- member_method {
- name: "pad_sequences"
- argspec: "args=[\'sequences\', \'maxlen\', \'dtype\', \'padding\', \'truncating\', \'value\'], varargs=None, keywords=None, defaults=[\'None\', \'int32\', \'pre\', \'pre\', \'0.0\'], "
- }
- member_method {
- name: "skipgrams"
- argspec: "args=[\'sequence\', \'vocabulary_size\', \'window_size\', \'negative_samples\', \'shuffle\', \'categorical\', \'sampling_table\', \'seed\'], varargs=None, keywords=None, defaults=[\'4\', \'1.0\', \'True\', \'False\', \'None\', \'None\'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.-tokenizer.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.-tokenizer.pbtxt
deleted file mode 100644
index b42b12b6c0..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.-tokenizer.pbtxt
+++ /dev/null
@@ -1,33 +0,0 @@
-path: "tensorflow.keras.preprocessing.text.Tokenizer"
-tf_class {
- is_instance: "<class \'tensorflow.python.keras.preprocessing.text.Tokenizer\'>"
- is_instance: "<type \'object\'>"
- member_method {
- name: "__init__"
- argspec: "args=[\'self\', \'num_words\', \'filters\', \'lower\', \'split\', \'char_level\', \'oov_token\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n\', \'True\', \' \', \'False\', \'None\'], "
- }
- member_method {
- name: "fit_on_sequences"
- argspec: "args=[\'self\', \'sequences\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "fit_on_texts"
- argspec: "args=[\'self\', \'texts\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "sequences_to_matrix"
- argspec: "args=[\'self\', \'sequences\', \'mode\'], varargs=None, keywords=None, defaults=[\'binary\'], "
- }
- member_method {
- name: "texts_to_matrix"
- argspec: "args=[\'self\', \'texts\', \'mode\'], varargs=None, keywords=None, defaults=[\'binary\'], "
- }
- member_method {
- name: "texts_to_sequences"
- argspec: "args=[\'self\', \'texts\'], varargs=None, keywords=None, defaults=None"
- }
- member_method {
- name: "texts_to_sequences_generator"
- argspec: "args=[\'self\', \'texts\'], varargs=None, keywords=None, defaults=None"
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.pbtxt
deleted file mode 100644
index 50b54fc7e1..0000000000
--- a/tensorflow/tools/api/golden/v2/tensorflow.keras.preprocessing.text.pbtxt
+++ /dev/null
@@ -1,19 +0,0 @@
-path: "tensorflow.keras.preprocessing.text"
-tf_module {
- member {
- name: "Tokenizer"
- mtype: "<type \'type\'>"
- }
- member_method {
- name: "hashing_trick"
- argspec: "args=[\'text\', \'n\', \'hash_function\', \'filters\', \'lower\', \'split\'], varargs=None, keywords=None, defaults=[\'None\', \'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n\', \'True\', \' \'], "
- }
- member_method {
- name: "one_hot"
- argspec: "args=[\'text\', \'n\', \'filters\', \'lower\', \'split\'], varargs=None, keywords=None, defaults=[\'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n\', \'True\', \' \'], "
- }
- member_method {
- name: "text_to_word_sequence"
- argspec: "args=[\'text\', \'filters\', \'lower\', \'split\'], varargs=None, keywords=None, defaults=[\'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n\', \'True\', \' \'], "
- }
-}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt
index c74773000a..e606eab919 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-l-s-t-m-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt
index d251f54806..5deb02d569 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-basic-r-n-n-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt
index d76eab7eb8..32fa151a8e 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-g-r-u-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'kernel_initializer\', \'bias_initializer\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'activation\', \'reuse\', \'kernel_initializer\', \'bias_initializer\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'None\', \'None\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt
index 944db6ac93..30c6c2ce3b 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.nn.rnn_cell.-l-s-t-m-cell.pbtxt
@@ -101,7 +101,7 @@ tf_class {
}
member_method {
name: "__init__"
- argspec: "args=[\'self\', \'num_units\', \'use_peepholes\', \'cell_clip\', \'initializer\', \'num_proj\', \'proj_clip\', \'num_unit_shards\', \'num_proj_shards\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'False\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
+ argspec: "args=[\'self\', \'num_units\', \'use_peepholes\', \'cell_clip\', \'initializer\', \'num_proj\', \'proj_clip\', \'num_unit_shards\', \'num_proj_shards\', \'forget_bias\', \'state_is_tuple\', \'activation\', \'reuse\', \'name\', \'dtype\'], varargs=None, keywords=kwargs, defaults=[\'False\', \'None\', \'None\', \'None\', \'None\', \'None\', \'None\', \'1.0\', \'True\', \'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "add_loss"
@@ -125,7 +125,7 @@ tf_class {
}
member_method {
name: "build"
- argspec: "args=[\'self\', \'inputs_shape\'], varargs=None, keywords=None, defaults=None"
+ argspec: "args=[\'instance\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.pbtxt
index 5eb42b4db3..8040eae01a 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.pbtxt
@@ -785,6 +785,10 @@ tf_module {
argspec: "args=[\'x\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
+ name: "batch_gather"
+ argspec: "args=[\'params\', \'indices\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
+ member_method {
name: "batch_to_space"
argspec: "args=[\'input\', \'crops\', \'block_size\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
@@ -1001,6 +1005,10 @@ tf_module {
argspec: "args=[\'x\', \'y\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
+ name: "div_no_nan"
+ argspec: "args=[\'x\', \'y\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
+ member_method {
name: "divide"
argspec: "args=[\'x\', \'y\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
@@ -1902,19 +1910,19 @@ tf_module {
}
member_method {
name: "sparse_reduce_max"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reduce_max_sparse"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reduce_sum"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reduce_sum_sparse"
- argspec: "args=[\'sp_input\', \'axis\', \'keep_dims\', \'reduction_axes\'], varargs=None, keywords=None, defaults=[\'None\', \'False\', \'None\'], "
+ argspec: "args=[\'sp_input\', \'axis\', \'keepdims\', \'reduction_axes\', \'keep_dims\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "sparse_reorder"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.strings.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.strings.pbtxt
index 9a831fed26..018be7b9f9 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.strings.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.strings.pbtxt
@@ -5,6 +5,10 @@ tf_module {
argspec: "args=[\'inputs\', \'separator\', \'name\'], varargs=None, keywords=None, defaults=[\'\', \'None\'], "
}
member_method {
+ name: "length"
+ argspec: "args=[\'input\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
+ member_method {
name: "regex_full_match"
argspec: "args=[\'input\', \'pattern\', \'name\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.summary.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.summary.pbtxt
index 871ebb5247..7ed9cd77a0 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.summary.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.summary.pbtxt
@@ -50,7 +50,7 @@ tf_module {
}
member_method {
name: "merge_all"
- argspec: "args=[\'key\', \'scope\'], varargs=None, keywords=None, defaults=[\'summaries\', \'None\'], "
+ argspec: "args=[\'key\', \'scope\', \'name\'], varargs=None, keywords=None, defaults=[\'summaries\', \'None\', \'None\'], "
}
member_method {
name: "scalar"
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.train.-checkpoint.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.train.-checkpoint.pbtxt
index 2d067e4eff..5be37200f3 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.train.-checkpoint.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.train.-checkpoint.pbtxt
@@ -20,4 +20,8 @@ tf_class {
name: "save"
argspec: "args=[\'self\', \'file_prefix\', \'session\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
+ member_method {
+ name: "write"
+ argspec: "args=[\'self\', \'file_prefix\', \'session\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ }
}
diff --git a/tensorflow/tools/api/golden/v2/tensorflow.train.pbtxt b/tensorflow/tools/api/golden/v2/tensorflow.train.pbtxt
index b0fb04d7d4..9f35395284 100644
--- a/tensorflow/tools/api/golden/v2/tensorflow.train.pbtxt
+++ b/tensorflow/tools/api/golden/v2/tensorflow.train.pbtxt
@@ -298,7 +298,7 @@ tf_module {
}
member_method {
name: "generate_checkpoint_state_proto"
- argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\'], varargs=None, keywords=None, defaults=[\'None\'], "
+ argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\', \'all_model_checkpoint_timestamps\', \'last_preserved_timestamp\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\'], "
}
member_method {
name: "get_checkpoint_mtimes"
@@ -446,7 +446,7 @@ tf_module {
}
member_method {
name: "update_checkpoint_state"
- argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\', \'latest_filename\'], varargs=None, keywords=None, defaults=[\'None\', \'None\'], "
+ argspec: "args=[\'save_dir\', \'model_checkpoint_path\', \'all_model_checkpoint_paths\', \'latest_filename\', \'all_model_checkpoint_timestamps\', \'last_preserved_timestamp\'], varargs=None, keywords=None, defaults=[\'None\', \'None\', \'None\', \'None\'], "
}
member_method {
name: "warm_start"
diff --git a/tensorflow/tools/api/tests/api_compatibility_test.py b/tensorflow/tools/api/tests/api_compatibility_test.py
index 12fe029ede..43d19bc99c 100644
--- a/tensorflow/tools/api/tests/api_compatibility_test.py
+++ b/tensorflow/tools/api/tests/api_compatibility_test.py
@@ -34,13 +34,6 @@ import sys
import unittest
import tensorflow as tf
-# pylint: disable=g-import-not-at-top
-try:
- from tensorflow.compat import v1 as tf_v1
- # We import compat.v1 as tf_v1 instead.
- del tf.compat.v1
-except ImportError:
- tf_v1 = None
from google.protobuf import message
from google.protobuf import text_format
@@ -53,8 +46,6 @@ from tensorflow.tools.api.lib import api_objects_pb2
from tensorflow.tools.api.lib import python_object_to_proto_visitor
from tensorflow.tools.common import public_api
from tensorflow.tools.common import traverse
-# pylint: enable=g-import-not-at-top
-
# FLAGS defined at the bottom:
FLAGS = None
@@ -88,7 +79,7 @@ def _KeyToFilePath(key, api_version):
case_insensitive_key = re.sub('([A-Z]{1})', _ReplaceCapsWithDash, key)
api_folder = (
_API_GOLDEN_FOLDER_V2 if api_version == 2 else _API_GOLDEN_FOLDER_V1)
- return os.path.join(_API_GOLDEN_FOLDER_V1, '%s.pbtxt' % case_insensitive_key)
+ return os.path.join(api_folder, '%s.pbtxt' % case_insensitive_key)
def _FileNameToKey(filename):
@@ -104,6 +95,21 @@ def _FileNameToKey(filename):
return api_object_key
+def _VerifyNoSubclassOfMessageVisitor(path, parent, unused_children):
+ """A Visitor that crashes on subclasses of generated proto classes."""
+ # If the traversed object is a proto Message class
+ if not (isinstance(parent, type) and
+ issubclass(parent, message.Message)):
+ return
+ if parent is message.Message:
+ return
+ # Check that it is a direct subclass of Message.
+ if message.Message not in parent.__bases__:
+ raise NotImplementedError(
+ 'Object tf.%s is a subclass of a generated proto Message. '
+ 'They are not yet supported by the API tools.' % path)
+
+
class ApiCompatibilityTest(test.TestCase):
def __init__(self, *args, **kwargs):
@@ -215,33 +221,40 @@ class ApiCompatibilityTest(test.TestCase):
logging.info('No differences found between API and golden.')
def testNoSubclassOfMessage(self):
-
- def Visit(path, parent, unused_children):
- """A Visitor that crashes on subclasses of generated proto classes."""
- # If the traversed object is a proto Message class
- if not (isinstance(parent, type) and
- issubclass(parent, message.Message)):
- return
- if parent is message.Message:
- return
- # Check that it is a direct subclass of Message.
- if message.Message not in parent.__bases__:
- raise NotImplementedError(
- 'Object tf.%s is a subclass of a generated proto Message. '
- 'They are not yet supported by the API tools.' % path)
- visitor = public_api.PublicAPIVisitor(Visit)
+ visitor = public_api.PublicAPIVisitor(_VerifyNoSubclassOfMessageVisitor)
visitor.do_not_descend_map['tf'].append('contrib')
+ # Skip compat.v1 and compat.v2 since they are validated in separate tests.
+ visitor.private_map['tf.compat'] = ['v1', 'v2']
traverse.traverse(tf, visitor)
- def checkBackwardsCompatibility(self, root, golden_file_pattern, api_version):
+ def testNoSubclassOfMessageV1(self):
+ if not hasattr(tf.compat, 'v1'):
+ return
+ visitor = public_api.PublicAPIVisitor(_VerifyNoSubclassOfMessageVisitor)
+ visitor.do_not_descend_map['tf'].append('contrib')
+ traverse.traverse(tf.compat.v1, visitor)
+
+ def testNoSubclassOfMessageV2(self):
+ if not hasattr(tf.compat, 'v2'):
+ return
+ visitor = public_api.PublicAPIVisitor(_VerifyNoSubclassOfMessageVisitor)
+ visitor.do_not_descend_map['tf'].append('contrib')
+ traverse.traverse(tf.compat.v2, visitor)
+
+ def _checkBackwardsCompatibility(
+ self, root, golden_file_pattern, api_version,
+ additional_private_map=None):
# Extract all API stuff.
visitor = python_object_to_proto_visitor.PythonObjectToProtoVisitor()
public_api_visitor = public_api.PublicAPIVisitor(visitor)
public_api_visitor.do_not_descend_map['tf'].append('contrib')
- public_api_visitor.do_not_descend_map['tf.GPUOptions'] = ['Experimental']
- traverse.traverse(root, public_api_visitor)
+ public_api_visitor.do_not_descend_map['tf.GPUOptions'] = [
+ 'Experimental']
+ if additional_private_map:
+ public_api_visitor.private_map.update(additional_private_map)
+ traverse.traverse(root, public_api_visitor)
proto_dict = visitor.GetProtos()
# Read all golden files.
@@ -271,23 +284,43 @@ class ApiCompatibilityTest(test.TestCase):
sys.version_info.major == 2,
'API compabitility test goldens are generated using python2.')
def testAPIBackwardsCompatibility(self):
- api_version = 2
+ api_version = 1
golden_file_pattern = os.path.join(
resource_loader.get_root_dir_with_all_resources(),
_KeyToFilePath('*', api_version))
- self.checkBackwardsCompatibility(tf, golden_file_pattern, api_version)
+ self._checkBackwardsCompatibility(
+ tf,
+ golden_file_pattern,
+ api_version,
+ # Skip compat.v1 and compat.v2 since they are validated
+ # in separate tests.
+ additional_private_map={'tf.compat': ['v1', 'v2']})
@unittest.skipUnless(
sys.version_info.major == 2,
'API compabitility test goldens are generated using python2.')
def testAPIBackwardsCompatibilityV1(self):
- if not tf_v1:
+ if not hasattr(tf.compat, 'v1'):
return
api_version = 1
golden_file_pattern = os.path.join(
resource_loader.get_root_dir_with_all_resources(),
_KeyToFilePath('*', api_version))
- self.checkBackwardsCompatibility(tf_v1, golden_file_pattern, api_version)
+ self._checkBackwardsCompatibility(
+ tf.compat.v1, golden_file_pattern, api_version)
+
+ @unittest.skipUnless(
+ sys.version_info.major == 2,
+ 'API compabitility test goldens are generated using python2.')
+ def testAPIBackwardsCompatibilityV2(self):
+ if not hasattr(tf.compat, 'v2'):
+ return
+ api_version = 2
+ golden_file_pattern = os.path.join(
+ resource_loader.get_root_dir_with_all_resources(),
+ _KeyToFilePath('*', api_version))
+ self._checkBackwardsCompatibility(
+ tf.compat.v2, golden_file_pattern, api_version)
if __name__ == '__main__':
diff --git a/tensorflow/tools/ci_build/Dockerfile.gpu.ppc64le b/tensorflow/tools/ci_build/Dockerfile.gpu.ppc64le
index a404f129ab..e026edb6bb 100644
--- a/tensorflow/tools/ci_build/Dockerfile.gpu.ppc64le
+++ b/tensorflow/tools/ci_build/Dockerfile.gpu.ppc64le
@@ -26,3 +26,6 @@ ENV LD_LIBRARY_PATH /usr/local/cuda/extras/CUPTI/lib64:$LD_LIBRARY_PATH
# Configure the build for our CUDA configuration.
ENV TF_NEED_CUDA 1
ENV TF_CUDA_COMPUTE_CAPABILITIES 3.0
+
+# TODO get NCCL 2 in the docker image
+ENV TF_NCCL_VERSION 1
diff --git a/tensorflow/tools/ci_build/linux/mkl/build-dev-container.sh b/tensorflow/tools/ci_build/linux/mkl/build-dev-container.sh
index a1d91a6123..b497326d98 100755
--- a/tensorflow/tools/ci_build/linux/mkl/build-dev-container.sh
+++ b/tensorflow/tools/ci_build/linux/mkl/build-dev-container.sh
@@ -57,6 +57,17 @@ TF_DOCKER_BUILD_TYPE="MKL" \
TF_BAZEL_BUILD_OPTIONS="${TF_BAZEL_BUILD_OPTIONS}" \
${WORKSPACE}/tensorflow/tools/docker/parameterized_docker_build.sh
+# build the python3.6 container and whl
+TF_DOCKER_BUILD_TYPE="MKL" \
+ TF_DOCKER_BUILD_IS_DEVEL="YES" \
+ TF_DOCKER_BUILD_DEVEL_BRANCH="${TF_DOCKER_BUILD_DEVEL_BRANCH}" \
+ TF_DOCKER_BUILD_IMAGE_NAME="${TF_DOCKER_BUILD_IMAGE_NAME}" \
+ TF_DOCKER_BUILD_VERSION="${TF_DOCKER_BUILD_VERSION}" \
+ TF_DOCKER_BUILD_PYTHON_VERSION="PYTHON3.6" \
+ TF_BAZEL_BUILD_OPTIONS="${TF_BAZEL_BUILD_OPTIONS}" \
+ ${WORKSPACE}/tensorflow/tools/docker/parameterized_docker_build.sh
+
+
# Build containers for AVX2
# Include the instructions for haswell and later, but tune for broadwell
TF_BAZEL_BUILD_OPTIONS="--config=mkl --copt=-march=haswell --copt=-mtune=broadwell --copt=-O3 --cxxopt=-D_GLIBCXX_USE_CXX11_ABI=0"
@@ -80,3 +91,13 @@ TF_DOCKER_BUILD_TYPE="MKL" \
TF_BAZEL_BUILD_OPTIONS="${TF_BAZEL_BUILD_OPTIONS}" \
${WORKSPACE}/tensorflow/tools/docker/parameterized_docker_build.sh
+# build the python3.6 container and whl
+TF_DOCKER_BUILD_TYPE="MKL" \
+ TF_DOCKER_BUILD_IS_DEVEL="YES" \
+ TF_DOCKER_BUILD_DEVEL_BRANCH="${TF_DOCKER_BUILD_DEVEL_BRANCH}" \
+ TF_DOCKER_BUILD_IMAGE_NAME="${TF_DOCKER_BUILD_IMAGE_NAME}" \
+ TF_DOCKER_BUILD_VERSION="${TF_DOCKER_BUILD_VERSION}-avx2" \
+ TF_DOCKER_BUILD_PYTHON_VERSION="PYTHON3.6" \
+ TF_BAZEL_BUILD_OPTIONS="${TF_BAZEL_BUILD_OPTIONS}" \
+ ${WORKSPACE}/tensorflow/tools/docker/parameterized_docker_build.sh
+
diff --git a/tensorflow/tools/ci_build/linux/ppc64le/cpu/run_py2.sh b/tensorflow/tools/ci_build/linux/ppc64le/cpu/run_py2.sh
new file mode 100755
index 0000000000..e13de35061
--- /dev/null
+++ b/tensorflow/tools/ci_build/linux/ppc64le/cpu/run_py2.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# 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.
+#
+# ==============================================================================
+
+set -e
+set -x
+
+N_JOBS=$(grep -c ^processor /proc/cpuinfo)
+
+echo ""
+echo "Bazel will use ${N_JOBS} concurrent job(s)."
+echo ""
+
+# Run configure.
+export TF_NEED_CUDA=0
+export CC_OPT_FLAGS='-mcpu=power8 -mtune=power8'
+export PYTHON_BIN_PATH=`which python2`
+yes "" | $PYTHON_BIN_PATH configure.py
+
+# Run bazel test command. Double test timeouts to avoid flakes.
+bazel test --test_tag_filters=-no_oss,-oss_serial,-gpu,-benchmark-test -k \
+ --jobs=${N_JOBS} --test_timeout 300,450,1200,3600 --build_tests_only --config=opt \
+ --test_output=errors --test_size_filters=small,medium -- \
+ //tensorflow/... -//tensorflow/compiler/...
diff --git a/tensorflow/tools/ci_build/linux/ppc64le/cpu/run_py3.sh b/tensorflow/tools/ci_build/linux/ppc64le/cpu/run_py3.sh
new file mode 100755
index 0000000000..a04ac158f5
--- /dev/null
+++ b/tensorflow/tools/ci_build/linux/ppc64le/cpu/run_py3.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# 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.
+#
+# ==============================================================================
+
+set -e
+set -x
+
+N_JOBS=$(grep -c ^processor /proc/cpuinfo)
+
+echo ""
+echo "Bazel will use ${N_JOBS} concurrent job(s)."
+echo ""
+
+# Run configure.
+export TF_NEED_CUDA=0
+export CC_OPT_FLAGS='-mcpu=power8 -mtune=power8'
+export PYTHON_BIN_PATH=`which python3`
+yes "" | $PYTHON_BIN_PATH configure.py
+
+# Run bazel test command. Double test timeouts to avoid flakes.
+bazel test --test_tag_filters=-no_oss,-oss_serial,-gpu,-benchmark-test -k \
+ --jobs=${N_JOBS} --test_timeout 300,450,1200,3600 --build_tests_only --config=opt \
+ --test_output=errors --test_size_filters=small,medium -- \
+ //tensorflow/... -//tensorflow/compiler/...
diff --git a/tensorflow/tools/ci_build/linux/ppc64le/gpu/run_py2.sh b/tensorflow/tools/ci_build/linux/ppc64le/gpu/run_py2.sh
new file mode 100755
index 0000000000..77286e8448
--- /dev/null
+++ b/tensorflow/tools/ci_build/linux/ppc64le/gpu/run_py2.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+# 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.
+#
+# ==============================================================================
+
+set -e
+set -x
+
+N_JOBS=$(grep -c ^processor /proc/cpuinfo)
+LT_JOBS=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader | wc -l)
+
+echo ""
+echo "Bazel will use ${N_JOBS} concurrent job(s)."
+echo "Bazel will use ${LT_JOBS} local test job(s)."
+echo ""
+
+# Run configure.
+export PYTHON_BIN_PATH=`which python2`
+export CC_OPT_FLAGS='-mcpu=power8 -mtune=power8'
+
+export TF_NEED_CUDA=1
+export TF_CUDA_COMPUTE_CAPABILITIES=3.7
+
+yes "" | $PYTHON_BIN_PATH configure.py
+
+# Run bazel test command. Double test timeouts to avoid flakes.
+bazel test --config=cuda --test_tag_filters=-no_oss,-oss_serial,-no_gpu,-benchmark-test -k \
+ --jobs=${N_JOBS} --test_timeout 300,450,1200,3600 \
+ --test_output=errors --local_test_jobs=${LT_JOBS} --build_tests_only --config=opt \
+ --test_size_filters=small,medium \
+ --run_under=//tensorflow/tools/ci_build/gpu_build:parallel_gpu_execute -- \
+ //tensorflow/... -//tensorflow/compiler/...
diff --git a/tensorflow/tools/ci_build/linux/ppc64le/gpu/run_py3.sh b/tensorflow/tools/ci_build/linux/ppc64le/gpu/run_py3.sh
new file mode 100755
index 0000000000..17aa52ee6b
--- /dev/null
+++ b/tensorflow/tools/ci_build/linux/ppc64le/gpu/run_py3.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+# 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.
+#
+# ==============================================================================
+
+set -e
+set -x
+
+N_JOBS=$(grep -c ^processor /proc/cpuinfo)
+LT_JOBS=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader | wc -l)
+
+echo ""
+echo "Bazel will use ${N_JOBS} concurrent job(s)."
+echo "Bazel will use ${LT_JOBS} local test job(s)."
+echo ""
+
+# Run configure.
+export PYTHON_BIN_PATH=`which python3`
+export CC_OPT_FLAGS='-mcpu=power8 -mtune=power8'
+
+export TF_NEED_CUDA=1
+export TF_CUDA_COMPUTE_CAPABILITIES=3.7
+
+yes "" | $PYTHON_BIN_PATH configure.py
+
+# Run bazel test command. Double test timeouts to avoid flakes.
+bazel test --config=cuda --test_tag_filters=-no_oss,-oss_serial,-no_gpu,-benchmark-test -k \
+ --jobs=${N_JOBS} --test_timeout 300,450,1200,3600 \
+ --test_output=errors --local_test_jobs=${LT_JOBS} --build_tests_only --config=opt \
+ --test_size_filters=small,medium \
+ --run_under=//tensorflow/tools/ci_build/gpu_build:parallel_gpu_execute -- \
+ //tensorflow/... -//tensorflow/compiler/...
diff --git a/tensorflow/tools/ci_build/windows/cpu/pip/build_tf_windows.sh b/tensorflow/tools/ci_build/windows/cpu/pip/build_tf_windows.sh
index 47e0e5dd59..5d0a8efc69 100644
--- a/tensorflow/tools/ci_build/windows/cpu/pip/build_tf_windows.sh
+++ b/tensorflow/tools/ci_build/windows/cpu/pip/build_tf_windows.sh
@@ -68,6 +68,7 @@ TEST_TARGET="//${PY_TEST_DIR}/tensorflow/python/... \
# --test_contrib_only Use tensorflow/contrib/... as test target
for ARG in "$@"; do
case "$ARG" in
+ --tf_nightly) TF_NIGHTLY=1 ;;
--skip_test) SKIP_TEST=1 ;;
--enable_remote_cache) set_remote_cache_options ;;
--release_build) RELEASE_BUILD=1 ;;
@@ -86,6 +87,11 @@ else
export TF_OVERRIDE_EIGEN_STRONG_INLINE=1
fi
+if [[ "$TF_NIGHTLY" == 1 ]]; then
+ python tensorflow/tools/ci_build/update_version.py --nightly
+ EXTRA_PIP_FLAG="--nightly_flag"
+fi
+
# Enable short object file path to avoid long path issue on Windows.
echo "startup --output_user_root=${TMPDIR}" >> "${TMP_BAZELRC}"
@@ -104,7 +110,11 @@ fi
# Create a python test directory to avoid package name conflict
create_python_test_dir "${PY_TEST_DIR}"
-./bazel-bin/tensorflow/tools/pip_package/build_pip_package "$PWD/${PY_TEST_DIR}"
+./bazel-bin/tensorflow/tools/pip_package/build_pip_package "$PWD/${PY_TEST_DIR}" "${EXTRA_PIP_FLAG}"
+
+if [[ "$TF_NIGHTLY" == 1 ]]; then
+ exit 0
+fi
# Running python tests on Windows needs pip package installed
PIP_NAME=$(ls ${PY_TEST_DIR}/tensorflow-*.whl)
diff --git a/tensorflow/tools/ci_build/windows/gpu/pip/build_tf_windows.sh b/tensorflow/tools/ci_build/windows/gpu/pip/build_tf_windows.sh
index e3eee11080..7ac07872e9 100644
--- a/tensorflow/tools/ci_build/windows/gpu/pip/build_tf_windows.sh
+++ b/tensorflow/tools/ci_build/windows/gpu/pip/build_tf_windows.sh
@@ -68,6 +68,7 @@ TEST_TARGET="//${PY_TEST_DIR}/tensorflow/python/... \
# --test_contrib_only Use tensorflow/contrib/... as test target
for ARG in "$@"; do
case "$ARG" in
+ --tf_nightly) TF_NIGHTLY=1 ;;
--skip_test) SKIP_TEST=1 ;;
--enable_remote_cache) set_remote_cache_options ;;
--release_build) RELEASE_BUILD=1 ;;
@@ -86,6 +87,11 @@ else
export TF_OVERRIDE_EIGEN_STRONG_INLINE=1
fi
+if [[ "$TF_NIGHTLY" == 1 ]]; then
+ python tensorflow/tools/ci_build/update_version.py --nightly
+ EXTRA_PIP_FLAG="--nightly_flag"
+fi
+
# Enable short object file path to avoid long path issue on Windows.
echo "startup --output_user_root=${TMPDIR}" >> "${TMP_BAZELRC}"
@@ -107,7 +113,11 @@ fi
# Create a python test directory to avoid package name conflict
create_python_test_dir "${PY_TEST_DIR}"
-./bazel-bin/tensorflow/tools/pip_package/build_pip_package "$PWD/${PY_TEST_DIR}"
+./bazel-bin/tensorflow/tools/pip_package/build_pip_package "$PWD/${PY_TEST_DIR}" --gpu "${EXTRA_PIP_FLAG}"
+
+if [[ "$TF_NIGHTLY" == 1 ]]; then
+ exit 0
+fi
# Running python tests on Windows needs pip package installed
PIP_NAME=$(ls ${PY_TEST_DIR}/tensorflow-*.whl)
diff --git a/tensorflow/tools/def_file_filter/def_file_filter.py.tpl b/tensorflow/tools/def_file_filter/def_file_filter.py.tpl
index 8bdc03eb0f..4bfcc2570c 100644
--- a/tensorflow/tools/def_file_filter/def_file_filter.py.tpl
+++ b/tensorflow/tools/def_file_filter/def_file_filter.py.tpl
@@ -48,6 +48,7 @@ EXCLUDE_RE = re.compile(r"RTTI|deleting destructor|::internal::")
INCLUDEPRE_RE = re.compile(r"google::protobuf::internal::ExplicitlyConstructed|"
r"google::protobuf::internal::ArenaImpl::AllocateAligned|" # for contrib/data/_prefetching_ops
r"google::protobuf::internal::ArenaImpl::AddCleanup|" # for contrib/data/_prefetching_ops
+ r"google::protobuf::internal::LogMessage|" # for contrib/data/_prefetching_ops
r"google::protobuf::Arena::OnArenaAllocation|" # for contrib/data/_prefetching_ops
r"tensorflow::internal::LogMessage|"
r"tensorflow::internal::LogString|"
diff --git a/tensorflow/tools/def_file_filter/def_file_filter_configure.bzl b/tensorflow/tools/def_file_filter/def_file_filter_configure.bzl
index f8f63e276c..df0fd05319 100644
--- a/tensorflow/tools/def_file_filter/def_file_filter_configure.bzl
+++ b/tensorflow/tools/def_file_filter/def_file_filter_configure.bzl
@@ -24,27 +24,27 @@ load("@bazel_tools//tools/cpp:windows_cc_configure.bzl", "find_msvc_tool")
load("@bazel_tools//tools/cpp:lib_cc_configure.bzl", "auto_configure_fail")
def _def_file_filter_configure_impl(repository_ctx):
- if repository_ctx.os.name.lower().find("windows") == -1:
+ if repository_ctx.os.name.lower().find("windows") == -1:
+ repository_ctx.symlink(Label("//tensorflow/tools/def_file_filter:BUILD.tpl"), "BUILD")
+ repository_ctx.file("def_file_filter.py", "")
+ return
+ vc_path = find_vc_path(repository_ctx)
+ if vc_path == None:
+ auto_configure_fail("Visual C++ build tools not found on your machine")
+
+ undname = find_msvc_tool(repository_ctx, vc_path, "undname.exe")
+ if undname == None:
+ auto_configure_fail("Couldn't find undname.exe under %s, please check your VC installation and set BAZEL_VC environment variable correctly." % vc_path)
+ undname_bin_path = undname.replace("\\", "\\\\")
+
+ repository_ctx.template(
+ "def_file_filter.py",
+ Label("//tensorflow/tools/def_file_filter:def_file_filter.py.tpl"),
+ {
+ "%{undname_bin_path}": undname_bin_path,
+ },
+ )
repository_ctx.symlink(Label("//tensorflow/tools/def_file_filter:BUILD.tpl"), "BUILD")
- repository_ctx.file("def_file_filter.py", "")
- return
- vc_path = find_vc_path(repository_ctx)
- if vc_path == "visual-studio-not-found":
- auto_configure_fail("Visual C++ build tools not found on your machine")
-
- undname = find_msvc_tool(repository_ctx, vc_path, "undname.exe")
- if undname == None:
- auto_configure_fail("Couldn't find undname.exe under %s, please check your VC installation and set BAZEL_VC environment variable correctly." % vc_path)
- undname_bin_path = undname.replace("\\", "\\\\")
-
- repository_ctx.template(
- "def_file_filter.py",
- Label("//tensorflow/tools/def_file_filter:def_file_filter.py.tpl"),
- {
- "%{undname_bin_path}": undname_bin_path,
- })
- repository_ctx.symlink(Label("//tensorflow/tools/def_file_filter:BUILD.tpl"), "BUILD")
-
def_file_filter_configure = repository_rule(
implementation = _def_file_filter_configure_impl,
@@ -55,6 +55,6 @@ def_file_filter_configure = repository_rule(
"VS100COMNTOOLS",
"VS110COMNTOOLS",
"VS120COMNTOOLS",
- "VS140COMNTOOLS"
+ "VS140COMNTOOLS",
],
)
diff --git a/tensorflow/tools/docker/Dockerfile b/tensorflow/tools/docker/Dockerfile
index bf06214009..2c31d784e5 100644
--- a/tensorflow/tools/docker/Dockerfile
+++ b/tensorflow/tools/docker/Dockerfile
@@ -29,6 +29,8 @@ RUN pip --no-cache-dir install \
h5py \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
numpy==1.14.5 \
pandas \
diff --git a/tensorflow/tools/docker/Dockerfile.devel b/tensorflow/tools/docker/Dockerfile.devel
index 6552588fac..bacdea72ce 100644
--- a/tensorflow/tools/docker/Dockerfile.devel
+++ b/tensorflow/tools/docker/Dockerfile.devel
@@ -33,6 +33,8 @@ RUN pip --no-cache-dir install \
h5py \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
mock \
numpy==1.14.5 \
diff --git a/tensorflow/tools/docker/Dockerfile.devel-gpu b/tensorflow/tools/docker/Dockerfile.devel-gpu
index f4c83f85d4..4f89e3f701 100644
--- a/tensorflow/tools/docker/Dockerfile.devel-gpu
+++ b/tensorflow/tools/docker/Dockerfile.devel-gpu
@@ -49,6 +49,8 @@ RUN pip --no-cache-dir install \
h5py \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
mock \
numpy==1.14.5 \
diff --git a/tensorflow/tools/docker/Dockerfile.devel-gpu-cuda9-cudnn7 b/tensorflow/tools/docker/Dockerfile.devel-gpu-cuda9-cudnn7
index 30bc2d2806..056b4755f4 100644
--- a/tensorflow/tools/docker/Dockerfile.devel-gpu-cuda9-cudnn7
+++ b/tensorflow/tools/docker/Dockerfile.devel-gpu-cuda9-cudnn7
@@ -37,6 +37,8 @@ RUN pip --no-cache-dir install --upgrade \
RUN pip --no-cache-dir install \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
numpy \
scipy \
diff --git a/tensorflow/tools/docker/Dockerfile.devel-mkl b/tensorflow/tools/docker/Dockerfile.devel-mkl
index f0c7118ecb..2df770e525 100755
--- a/tensorflow/tools/docker/Dockerfile.devel-mkl
+++ b/tensorflow/tools/docker/Dockerfile.devel-mkl
@@ -18,18 +18,29 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libhdf5-serial-dev \
libpng12-dev \
libzmq3-dev \
+ libssl-dev \
pkg-config \
- python-dev \
- ${PYTHON3_DEV} \
rsync \
software-properties-common \
unzip \
zip \
zlib1g-dev \
openjdk-8-jdk \
- openjdk-8-jre-headless \
- && \
- apt-get clean && \
+ openjdk-8-jre-headless
+
+#install Python 3
+RUN if [ ${PYTHON} = "python3.6" ]; then \
+ curl https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz -o /opt/python.tar.xz && \
+ cd /opt && tar xvf python.tar.xz && \
+ cd /opt/*/ && ./configure && \
+ make && make install; \
+ else \
+ apt-get install -y --no-install-recommends \
+ python-dev \
+ ${PYTHON3_DEV}; \
+ fi
+
+RUN apt-get clean && \
rm -rf /var/lib/apt/lists/*
RUN curl -fSsL -O https://bootstrap.pypa.io/get-pip.py && \
@@ -41,6 +52,8 @@ RUN ${PIP} --no-cache-dir install \
h5py \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
mock \
numpy \
@@ -51,7 +64,9 @@ RUN ${PIP} --no-cache-dir install \
${PYTHON} -m ipykernel.kernelspec
RUN if [ "${PYTHON}" = "python3" ]; then \
- ln -s -f /usr/bin/python3 /usr/bin/python; \
+ ln -s -f /usr/bin/python3 /usr/bin/python; \
+ elif [ "${PYTHON}" = "python3.6" ]; then \
+ ln -s -f /usr/local/bin/python3.6 /usr/bin/python; \
fi
# Set up our notebook config.
diff --git a/tensorflow/tools/docker/Dockerfile.devel-mkl-horovod b/tensorflow/tools/docker/Dockerfile.devel-mkl-horovod
new file mode 100755
index 0000000000..ab2eec1728
--- /dev/null
+++ b/tensorflow/tools/docker/Dockerfile.devel-mkl-horovod
@@ -0,0 +1,168 @@
+FROM ubuntu:16.04
+
+LABEL maintainer="Cong Xu <cong.xu@intel.com>"
+
+# These parameters can be overridden by parameterized_docker_build.sh
+ARG TF_BUILD_VERSION=r1.9
+ARG PYTHON="python"
+ARG PYTHON3_DEV=""
+ARG WHL_DIR="/tmp/pip"
+ARG PIP="pip"
+
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ build-essential \
+ curl \
+ git \
+ libcurl3-dev \
+ libfreetype6-dev \
+ libhdf5-serial-dev \
+ libpng12-dev \
+ libzmq3-dev \
+ pkg-config \
+ python-dev \
+ ${PYTHON3_DEV} \
+ rsync \
+ software-properties-common \
+ unzip \
+ zip \
+ zlib1g-dev \
+ openjdk-8-jdk \
+ openjdk-8-jre-headless \
+ wget \
+ numactl \
+ openssh-client \
+ openssh-server \
+ && \
+ apt-get clean && \
+ rm -rf /var/lib/apt/lists/*
+
+RUN curl -fSsL -O https://bootstrap.pypa.io/get-pip.py && \
+ ${PYTHON} get-pip.py && \
+ rm get-pip.py
+
+RUN ${PIP} --no-cache-dir install \
+ Pillow \
+ h5py \
+ ipykernel \
+ jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
+ matplotlib \
+ mock \
+ numpy \
+ scipy \
+ sklearn \
+ pandas \
+ && \
+ ${PYTHON} -m ipykernel.kernelspec
+
+RUN if [ "${PYTHON}" = "python3" ]; then \
+ ln -s -f /usr/bin/python3 /usr/bin/python; \
+ fi
+
+# Set up our notebook config.
+COPY jupyter_notebook_config.py /root/.jupyter/
+
+# Jupyter has issues with being run directly:
+# https://github.com/ipython/ipython/issues/7062
+# We just add a little wrapper script.
+COPY run_jupyter.sh /
+
+# Set up Bazel.
+
+# Running bazel inside a `docker build` command causes trouble, cf:
+# https://github.com/bazelbuild/bazel/issues/134
+# The easiest solution is to set up a bazelrc file forcing --batch.
+RUN echo "startup --batch" >>/etc/bazel.bazelrc
+# Similarly, we need to workaround sandboxing issues:
+# https://github.com/bazelbuild/bazel/issues/418
+RUN echo "build --spawn_strategy=standalone --genrule_strategy=standalone" \
+ >>/etc/bazel.bazelrc
+# Install the most recent bazel release.
+ENV BAZEL_VERSION 0.15.0
+WORKDIR /
+RUN mkdir /bazel && \
+ cd /bazel && \
+ curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -O https://github.com/bazelbuild/bazel/releases/download/$BAZEL_VERSION/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh && \
+ curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -o /bazel/LICENSE.txt https://raw.githubusercontent.com/bazelbuild/bazel/master/LICENSE && \
+ chmod +x bazel-*.sh && \
+ ./bazel-$BAZEL_VERSION-installer-linux-x86_64.sh && \
+ cd / && \
+ rm -f /bazel/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh
+
+# Download and build TensorFlow.
+WORKDIR /tensorflow
+
+# Download and build TensorFlow.
+# Enable checking out both tags and branches
+RUN export TAG_PREFIX="v" && \
+ echo ${TF_BUILD_VERSION} | grep -q ^${TAG_PREFIX}; \
+ if [ $? -eq 0 ]; then \
+ git clone --depth=1 https://github.com/tensorflow/tensorflow.git . && \
+ git fetch --tags && \
+ git checkout ${TF_BUILD_VERSION}; \
+ else \
+ git clone --depth=1 --branch=${TF_BUILD_VERSION} https://github.com/tensorflow/tensorflow.git . ; \
+ fi
+
+RUN yes "" | ${PYTHON} configure.py
+
+ENV CI_BUILD_PYTHON ${PYTHON}
+
+# Set bazel build parameters in .bazelrc in parameterized_docker_build.sh
+# Use --copt=-march values to get optimized builds appropriate for the hardware
+# platform of your choice.
+# For ivy-bridge or sandy-bridge
+# --copt=-march="avx" \
+# For haswell, broadwell, or skylake
+# --copt=-march="avx2" \
+COPY .bazelrc /root/.bazelrc
+
+RUN tensorflow/tools/ci_build/builds/configured CPU \
+ bazel --bazelrc=/root/.bazelrc build -c opt \
+ tensorflow/tools/pip_package:build_pip_package && \
+ bazel-bin/tensorflow/tools/pip_package/build_pip_package "${WHL_DIR}" && \
+ ${PIP} --no-cache-dir install --upgrade "${WHL_DIR}"/tensorflow-*.whl && \
+ rm -rf /root/.cache
+# Clean up Bazel cache when done.
+
+WORKDIR /root
+
+# Install Open MPI
+RUN mkdir /tmp/openmpi && \
+ cd /tmp/openmpi && \
+ wget https://www.open-mpi.org/software/ompi/v3.0/downloads/openmpi-3.0.0.tar.gz && \
+ tar zxf openmpi-3.0.0.tar.gz && \
+ cd openmpi-3.0.0 && \
+ ./configure --enable-orterun-prefix-by-default && \
+ make -j $(nproc) all && \
+ make install && \
+ ldconfig && \
+ rm -rf /tmp/openmpi
+
+# Create a wrapper for OpenMPI to allow running as root by default
+RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
+ echo '#!/bin/bash' > /usr/local/bin/mpirun && \
+ echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
+ chmod a+x /usr/local/bin/mpirun
+
+# Configure OpenMPI to run good defaults:
+RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
+
+# Install Horovod
+RUN ${PIP} install --no-cache-dir horovod
+
+# Install OpenSSH for MPI to communicate between containers
+RUN mkdir -p /var/run/sshd
+
+# Allow OpenSSH to talk to containers without asking for confirmation
+RUN cat /etc/ssh/ssh_config | grep -v StrictHostKeyChecking > /etc/ssh/ssh_config.new && \
+ echo " StrictHostKeyChecking no" >> /etc/ssh/ssh_config.new && \
+ mv /etc/ssh/ssh_config.new /etc/ssh/ssh_config
+
+# TensorBoard
+EXPOSE 6006
+# IPython
+EXPOSE 8888
+
+WORKDIR /root
diff --git a/tensorflow/tools/docker/Dockerfile.gpu b/tensorflow/tools/docker/Dockerfile.gpu
index 5ec1e60f00..aa0e0face1 100644
--- a/tensorflow/tools/docker/Dockerfile.gpu
+++ b/tensorflow/tools/docker/Dockerfile.gpu
@@ -37,6 +37,8 @@ RUN pip --no-cache-dir install \
h5py \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
numpy==1.14.5 \
pandas \
diff --git a/tensorflow/tools/docker/Dockerfile.mkl b/tensorflow/tools/docker/Dockerfile.mkl
index ad5109f26d..69553302d8 100755
--- a/tensorflow/tools/docker/Dockerfile.mkl
+++ b/tensorflow/tools/docker/Dockerfile.mkl
@@ -38,6 +38,8 @@ RUN ${PIP} --no-cache-dir install \
h5py \
ipykernel \
jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
matplotlib \
numpy \
pandas \
diff --git a/tensorflow/tools/docker/Dockerfile.mkl-horovod b/tensorflow/tools/docker/Dockerfile.mkl-horovod
new file mode 100755
index 0000000000..756716ee0e
--- /dev/null
+++ b/tensorflow/tools/docker/Dockerfile.mkl-horovod
@@ -0,0 +1,111 @@
+FROM ubuntu:16.04
+
+LABEL maintainer="Cong Xu <cong.xu@intel.com>"
+
+# This parameter MUST be set by parameterized_docker_build.sh
+ARG TF_WHL_URL
+
+# Optional parameters
+ARG TF_BUILD_VERSION=r1.9
+ARG PYTHON="python"
+ARG PYTHON_DEV="python-dev"
+ARG PIP="pip"
+
+# Pick up some TF dependencies
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ build-essential \
+ curl \
+ libfreetype6-dev \
+ libhdf5-serial-dev \
+ libpng12-dev \
+ libzmq3-dev \
+ pkg-config \
+ python \
+ ${PYTHON_DEV} \
+ rsync \
+ software-properties-common \
+ unzip \
+ && \
+ apt-get clean && \
+ rm -rf /var/lib/apt/lists/*
+
+RUN curl -O https://bootstrap.pypa.io/get-pip.py && \
+ python get-pip.py && \
+ rm get-pip.py
+
+RUN ${PIP} --no-cache-dir install \
+ Pillow \
+ h5py \
+ ipykernel \
+ jupyter \
+ keras_applications==1.0.4 \
+ keras_preprocessing==1.0.2 \
+ matplotlib \
+ numpy \
+ pandas \
+ scipy \
+ sklearn \
+ && \
+ python -m ipykernel.kernelspec
+
+COPY ${TF_WHL_URL} /
+RUN ${PIP} install --no-cache-dir --force-reinstall /${TF_WHL_URL} && \
+ rm -rf /${TF_WHL_URL}
+
+RUN if [ "${PYTHON}" = "python3" ]; then \
+ ln -s -f /usr/bin/python3 /usr/bin/python; \
+ fi
+
+# Set up our notebook config.
+COPY jupyter_notebook_config.py /root/.jupyter/
+
+# Copy sample notebooks.
+COPY notebooks /notebooks
+
+# Jupyter has issues with being run directly:
+# https://github.com/ipython/ipython/issues/7062
+# We just add a little wrapper script.
+COPY run_jupyter.sh /
+
+WORKDIR /root
+
+# Install Open MPI
+RUN mkdir /tmp/openmpi && \
+ cd /tmp/openmpi && \
+ wget https://www.open-mpi.org/software/ompi/v3.0/downloads/openmpi-3.0.0.tar.gz && \
+ tar zxf openmpi-3.0.0.tar.gz && \
+ cd openmpi-3.0.0 && \
+ ./configure --enable-orterun-prefix-by-default && \
+ make -j $(nproc) all && \
+ make install && \
+ ldconfig && \
+ rm -rf /tmp/openmpi
+
+# Create a wrapper for OpenMPI to allow running as root by default
+RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
+ echo '#!/bin/bash' > /usr/local/bin/mpirun && \
+ echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
+ chmod a+x /usr/local/bin/mpirun
+
+# Configure OpenMPI to run good defaults:
+RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
+
+# Install Horovod
+RUN ${PIP} install --no-cache-dir horovod
+
+# Install OpenSSH for MPI to communicate between containers
+RUN mkdir -p /var/run/sshd
+
+# Allow OpenSSH to talk to containers without asking for confirmation
+RUN cat /etc/ssh/ssh_config | grep -v StrictHostKeyChecking > /etc/ssh/ssh_config.new && \
+ echo " StrictHostKeyChecking no" >> /etc/ssh/ssh_config.new && \
+ mv /etc/ssh/ssh_config.new /etc/ssh/ssh_config
+
+# TensorBoard
+EXPOSE 6006
+# IPython
+EXPOSE 8888
+
+WORKDIR "/notebooks"
+
+CMD ["/run_jupyter.sh", "--allow-root"]
diff --git a/tensorflow/tools/docker/parameterized_docker_build.sh b/tensorflow/tools/docker/parameterized_docker_build.sh
index 4681c5fd61..448a3a7647 100755
--- a/tensorflow/tools/docker/parameterized_docker_build.sh
+++ b/tensorflow/tools/docker/parameterized_docker_build.sh
@@ -19,8 +19,8 @@
# parameterized_docker_build.sh
#
# The script obeys the following environment variables:
-# TF_DOCKER_BUILD_TYPE: (CPU | GPU | MKL)
-# CPU, GPU, or MKL image
+# TF_DOCKER_BUILD_TYPE: (CPU | GPU | MKL | MKL-HOROVOD)
+# CPU, GPU, MKL or MKL-HOROVOD image
#
# TF_DOCKER_BUILD_IS_DEVEL: (NO | YES)
# Is this developer image
@@ -169,6 +169,15 @@ elif [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]]; then
else
ORIG_DOCKERFILE="${ORIG_DOCKERFILE}.mkl"
fi
+elif [[ ${TF_DOCKER_BUILD_TYPE} == "mkl-horovod" ]]; then
+ DOCKER_BINARY="docker"
+ FINAL_TAG="${FINAL_TAG}-mkl-horovod"
+ if [[ ${ORIG_DOCKERFILE} == *"."* ]]; then
+ # There is already a dot in the tag, use "-"
+ ORIG_DOCKERFILE="${ORIG_DOCKERFILE}-mkl-horovod"
+ else
+ ORIG_DOCKERFILE="${ORIG_DOCKERFILE}.mkl-horovod"
+ fi
elif [[ ${TF_DOCKER_BUILD_TYPE} == "gpu" ]]; then
DOCKER_BINARY="nvidia-docker"
@@ -188,6 +197,8 @@ if [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python2" ]]; then
:
elif [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3" ]]; then
FINAL_TAG="${FINAL_TAG}-py3"
+elif [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3.6" ]]; then
+ FINAL_TAG="${FINAL_TAG}-py3.6"
else
die "Unrecognized value in TF_DOCKER_BUILD_PYTHON_VERSION: "\
"${TF_DOCKER_BUILD_PYTHON_VERSION}"
@@ -227,6 +238,10 @@ if [[ "${TF_DOCKER_BUILD_IS_DEVEL}" == "no" ]]; then
die "FAIL: Non-development MKL builds require a pre-built pip whl."
fi
+ if [[ "${TF_DOCKER_BUILD_TYPE}" == "mkl-horovod" ]]; then
+ die "FAIL: Non-development MKL-HOROVOD builds require a pre-built pip whl."
+ fi
+
if [[ "${TF_DOCKER_BUILD_TYPE}" == "gpu" ]]; then
export TF_BUILD_APPEND_CI_DOCKER_EXTRA_PARAMS=\
"${TF_BUILD_APPEND_CI_DOCKER_EXTRA_PARAMS} -e TF_CUDA_COMPUTE_CAPABILITIES=3.0,3.5,5.2"
@@ -279,7 +294,8 @@ if [[ "${TF_DOCKER_BUILD_IS_DEVEL}" == "no" ]]; then
# Use string replacement to put the correct file name into the Dockerfile
PIP_WHL=$(basename "${PIP_WHL}")
- if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]]; then
+ if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]] || \
+ [[ ${TF_DOCKER_BUILD_TYPE} == "mkl-horovod" ]]; then
TF_DOCKER_BUILD_ARGS+=("--build-arg TF_WHL_URL=${PIP_WHL}" )
cp "${ORIG_DOCKERFILE}" "${DOCKERFILE}"
else
@@ -295,7 +311,8 @@ if [[ "${TF_DOCKER_BUILD_IS_DEVEL}" == "no" ]]; then
echo
else
echo "Downloading pip wheel from: ${TF_DOCKER_BUILD_CENTRAL_PIP}"
- if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]]; then
+ if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]] || \
+ [[ ${TF_DOCKER_BUILD_TYPE} == "mkl-horovod" ]]; then
pushd "${TMP_DIR}/"
curl -O ${TF_DOCKER_BUILD_CENTRAL_PIP}
popd
@@ -319,7 +336,8 @@ if [[ "${TF_DOCKER_BUILD_IS_DEVEL}" == "no" ]]; then
# Modify python/pip version if necessary.
if [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3" ]]; then
- if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]]; then
+ if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]] || \
+ [[ ${TF_DOCKER_BUILD_TYPE} == "mkl-horovod" ]]; then
TF_DOCKER_BUILD_ARGS+=("--build-arg PYTHON=${TF_DOCKER_BUILD_PYTHON_VERSION}")
TF_DOCKER_BUILD_ARGS+=("--build-arg PYTHON_DEV=python3-dev")
TF_DOCKER_BUILD_ARGS+=("--build-arg PIP=pip3")
@@ -340,8 +358,9 @@ if [[ "${TF_DOCKER_BUILD_IS_DEVEL}" == "no" ]]; then
else # TF_DOCKER_BUILD_IS_DEVEL == 'yes'
DOCKERFILE="${TMP_DIR}/Dockerfile"
- # Set up Dockerfile ARGS for mkl build
- if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]]; then
+ # Set up Dockerfile ARGS for mkl and mkl-horovod build
+ if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]] || \
+ [[ ${TF_DOCKER_BUILD_TYPE} == "mkl-horovod" ]]; then
if [[ -z "${TF_BAZEL_BUILD_OPTIONS// }" ]]; then
TF_BAZEL_BUILD_OPTIONS=("--config=mkl --copt=-mavx --cxxopt=-D_GLIBCXX_USE_CXX11_ABI=0")
else
@@ -360,14 +379,17 @@ else # TF_DOCKER_BUILD_IS_DEVEL == 'yes'
fi
# Modify python/pip version if necessary.
- if [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3" ]]; then
- if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]]; then
+ if [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3" ]] || [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3.6" ]]; then
+ if [[ ${TF_DOCKER_BUILD_TYPE} == "mkl" ]] || [[ ${TF_DOCKER_BUILD_TYPE} == "mkl-horovod" ]]; then
TF_DOCKER_BUILD_ARGS+=("--build-arg PYTHON=${TF_DOCKER_BUILD_PYTHON_VERSION}")
TF_DOCKER_BUILD_ARGS+=("--build-arg PYTHON3_DEV=python3-dev")
TF_DOCKER_BUILD_ARGS+=("--build-arg WHL_DIR=/tmp/pip3")
TF_DOCKER_BUILD_ARGS+=("--build-arg PIP=pip3")
cp "${ORIG_DOCKERFILE}" "${DOCKERFILE}"
else
+ if [[ "${TF_DOCKER_BUILD_PYTHON_VERSION}" == "python3.6" ]] && [[ "${TF_DOCKER_BUILD_TYPE}" != "mkl" ]]; then
+ die "Python 3.6 build only supported for MKL builds."
+ fi
if sed -i -e 's/python-dev/python-dev python3-dev/g' "${DOCKERFILE}" && \
sed -i -e 's/python /python3 /g' "${DOCKERFILE}" && \
sed -i -e 's^/tmp/pip^/tmp/pip3^g' "${DOCKERFILE}" && \
diff --git a/tensorflow/tools/docs/BUILD b/tensorflow/tools/docs/BUILD
index cc7885ab1b..4f7efe193f 100644
--- a/tensorflow/tools/docs/BUILD
+++ b/tensorflow/tools/docs/BUILD
@@ -34,11 +34,29 @@ py_test(
)
py_library(
+ name = "doc_controls",
+ srcs = ["doc_controls.py"],
+ srcs_version = "PY2AND3",
+)
+
+py_test(
+ name = "doc_controls_test",
+ size = "small",
+ srcs = ["doc_controls_test.py"],
+ srcs_version = "PY2AND3",
+ deps = [
+ ":doc_controls",
+ "//tensorflow/python:platform_test",
+ ],
+)
+
+py_library(
name = "parser",
srcs = ["parser.py"],
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
deps = [
+ ":doc_controls",
"//tensorflow/python:platform",
"//tensorflow/python:util",
"@astor_archive//:astor",
@@ -68,6 +86,7 @@ py_binary(
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
deps = [
+ ":doc_controls",
":doc_generator_visitor",
":parser",
":pretty_docs",
diff --git a/tensorflow/tools/docs/doc_controls.py b/tensorflow/tools/docs/doc_controls.py
new file mode 100644
index 0000000000..5e526443cc
--- /dev/null
+++ b/tensorflow/tools/docs/doc_controls.py
@@ -0,0 +1,319 @@
+# 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.
+# ==============================================================================
+"""Documentation control decorators."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+_DO_NOT_DOC = "_tf_docs_do_not_document"
+
+
+def do_not_generate_docs(obj):
+ """A decorator: Do not generate docs for this object.
+
+ For example the following classes:
+
+ ```
+ class Parent(object):
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+
+ class Child(Parent):
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+ ```
+
+ Produce the following api_docs:
+
+ ```
+ /Parent.md
+ # method1
+ # method2
+ /Child.md
+ # method1
+ # method2
+ ```
+
+ This decorator allows you to skip classes or methods:
+
+ ```
+ @do_not_generate_docs
+ class Parent(object):
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+
+ class Child(Parent):
+ @do_not_generate_docs
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+ ```
+
+ This will only produce the following docs:
+
+ ```
+ /Child.md
+ # method2
+ ```
+
+ Note: This is implemented by adding a hidden attribute on the object, so it
+ cannot be used on objects which do not allow new attributes to be added. So
+ this decorator must go *below* `@property`, `@classmethod`,
+ or `@staticmethod`:
+
+ ```
+ class Example(object):
+ @property
+ @do_not_generate_docs
+ def x(self):
+ return self._x
+ ```
+
+ Args:
+ obj: The object to hide from the generated docs.
+
+ Returns:
+ obj
+ """
+ setattr(obj, _DO_NOT_DOC, None)
+ return obj
+
+
+_DO_NOT_DOC_INHERITABLE = "_tf_docs_do_not_doc_inheritable"
+
+
+def do_not_doc_inheritable(obj):
+ """A decorator: Do not generate docs for this method.
+
+ This version of the decorator is "inherited" by subclasses. No docs will be
+ generated for the decorated method in any subclass. Even if the sub-class
+ overrides the method.
+
+ For example, to ensure that `method1` is **never documented** use this
+ decorator on the base-class:
+
+ ```
+ class Parent(object):
+ @do_not_doc_inheritable
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+
+ class Child(Parent):
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+ ```
+ This will produce the following docs:
+
+ ```
+ /Parent.md
+ # method2
+ /Child.md
+ # method2
+ ```
+
+ When generating docs for a class's arributes, the `__mro__` is searched and
+ the attribute will be skipped if this decorator is detected on the attribute
+ on any class in the `__mro__`.
+
+ Note: This is implemented by adding a hidden attribute on the object, so it
+ cannot be used on objects which do not allow new attributes to be added. So
+ this decorator must go *below* `@property`, `@classmethod`,
+ or `@staticmethod`:
+
+ ```
+ class Example(object):
+ @property
+ @do_not_doc_inheritable
+ def x(self):
+ return self._x
+ ```
+
+ Args:
+ obj: The class-attribute to hide from the generated docs.
+
+ Returns:
+ obj
+ """
+ setattr(obj, _DO_NOT_DOC_INHERITABLE, None)
+ return obj
+
+
+_FOR_SUBCLASS_IMPLEMENTERS = "_tf_docs_tools_for_subclass_implementers"
+
+
+def for_subclass_implementers(obj):
+ """A decorator: Only generate docs for this method in the defining class.
+
+ Also group this method's docs with and `@abstractmethod` in the class's docs.
+
+ No docs will generated for this class attribute in sub-classes.
+
+ The canonical use case for this is `tf.keras.layers.Layer.call`: It's a
+ public method, essential for anyone implementing a subclass, but it should
+ never be called directly.
+
+ Works on method, or other class-attributes.
+
+ When generating docs for a class's arributes, the `__mro__` is searched and
+ the attribute will be skipped if this decorator is detected on the attribute
+ on any **parent** class in the `__mro__`.
+
+ For example:
+
+ ```
+ class Parent(object):
+ @for_subclass_implementers
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+
+ class Child1(Parent):
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+
+ class Child2(Parent):
+ def method1(self):
+ pass
+ def method2(self):
+ pass
+ ```
+
+ This will produce the following docs:
+
+ ```
+ /Parent.md
+ # method1
+ # method2
+ /Child1.md
+ # method2
+ /Child2.md
+ # method2
+ ```
+
+ Note: This is implemented by adding a hidden attribute on the object, so it
+ cannot be used on objects which do not allow new attributes to be added. So
+ this decorator must go *below* `@property`, `@classmethod`,
+ or `@staticmethod`:
+
+ ```
+ class Example(object):
+ @property
+ @for_subclass_implementers
+ def x(self):
+ return self._x
+ ```
+
+ Args:
+ obj: The class-attribute to hide from the generated docs.
+
+ Returns:
+ obj
+ """
+ setattr(obj, _FOR_SUBCLASS_IMPLEMENTERS, None)
+ return obj
+
+
+def should_skip(obj):
+ """Returns true if docs generation should be skipped for this object.
+
+ checks for the `do_not_generate_docs` or `do_not_doc_inheritable` decorators.
+
+ Args:
+ obj: The object to document, or skip.
+
+ Returns:
+ True if the object should be skipped
+ """
+ # Unwrap fget if the object is a property
+ if isinstance(obj, property):
+ obj = obj.fget
+
+ return hasattr(obj, _DO_NOT_DOC) or hasattr(obj, _DO_NOT_DOC_INHERITABLE)
+
+
+def should_skip_class_attr(cls, name):
+ """Returns true if docs should be skipped for this class attribute.
+
+ Args:
+ cls: The class the attribute belongs to.
+ name: The name of the attribute.
+
+ Returns:
+ True if the attribute should be skipped.
+ """
+ # Get the object with standard lookup, from the nearest
+ # defining parent.
+ try:
+ obj = getattr(cls, name)
+ except AttributeError:
+ # Avoid error caused by enum metaclasses in python3
+ if name in ("name", "value"):
+ return True
+ raise
+
+ # Unwrap fget if the object is a property
+ if isinstance(obj, property):
+ obj = obj.fget
+
+ # Skip if the object is decorated with `do_not_generate_docs` or
+ # `do_not_doc_inheritable`
+ if should_skip(obj):
+ return True
+
+ # Use __dict__ lookup to get the version defined in *this* class.
+ obj = cls.__dict__.get(name, None)
+ if isinstance(obj, property):
+ obj = obj.fget
+ if obj is not None:
+ # If not none, the object is defined in *this* class.
+ # Do not skip if decorated with `for_subclass_implementers`.
+ if hasattr(obj, _FOR_SUBCLASS_IMPLEMENTERS):
+ return False
+
+ # for each parent class
+ for parent in cls.__mro__[1:]:
+ obj = getattr(parent, name, None)
+
+ if obj is None:
+ continue
+
+ if isinstance(obj, property):
+ obj = obj.fget
+
+ # Skip if the parent's definition is decorated with `do_not_doc_inheritable`
+ # or `for_subclass_implementers`
+ if hasattr(obj, _DO_NOT_DOC_INHERITABLE):
+ return True
+
+ if hasattr(obj, _FOR_SUBCLASS_IMPLEMENTERS):
+ return True
+
+ # No blockng decorators --> don't skip
+ return False
diff --git a/tensorflow/tools/docs/doc_controls_test.py b/tensorflow/tools/docs/doc_controls_test.py
new file mode 100644
index 0000000000..410342fb69
--- /dev/null
+++ b/tensorflow/tools/docs/doc_controls_test.py
@@ -0,0 +1,183 @@
+# 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 documentation control decorators."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.python.platform import googletest
+from tensorflow.tools.docs import doc_controls
+
+
+class DocControlsTest(googletest.TestCase):
+
+ def test_do_not_generate_docs(self):
+
+ @doc_controls.do_not_generate_docs
+ def dummy_function():
+ pass
+
+ self.assertTrue(doc_controls.should_skip(dummy_function))
+
+ def test_do_not_doc_on_method(self):
+ """The simple decorator is not aware of inheritance."""
+
+ class Parent(object):
+
+ @doc_controls.do_not_generate_docs
+ def my_method(self):
+ pass
+
+ class Child(Parent):
+
+ def my_method(self):
+ pass
+
+ class GrandChild(Child):
+ pass
+
+ self.assertTrue(doc_controls.should_skip(Parent.my_method))
+ self.assertFalse(doc_controls.should_skip(Child.my_method))
+ self.assertFalse(doc_controls.should_skip(GrandChild.my_method))
+
+ self.assertTrue(doc_controls.should_skip_class_attr(Parent, 'my_method'))
+ self.assertFalse(doc_controls.should_skip_class_attr(Child, 'my_method'))
+ self.assertFalse(
+ doc_controls.should_skip_class_attr(GrandChild, 'my_method'))
+
+ def test_do_not_doc_inheritable(self):
+
+ class Parent(object):
+
+ @doc_controls.do_not_doc_inheritable
+ def my_method(self):
+ pass
+
+ class Child(Parent):
+
+ def my_method(self):
+ pass
+
+ class GrandChild(Child):
+ pass
+
+ self.assertTrue(doc_controls.should_skip(Parent.my_method))
+ self.assertFalse(doc_controls.should_skip(Child.my_method))
+ self.assertFalse(doc_controls.should_skip(GrandChild.my_method))
+
+ self.assertTrue(doc_controls.should_skip_class_attr(Parent, 'my_method'))
+ self.assertTrue(doc_controls.should_skip_class_attr(Child, 'my_method'))
+ self.assertTrue(
+ doc_controls.should_skip_class_attr(GrandChild, 'my_method'))
+
+ def test_do_not_doc_inheritable_property(self):
+
+ class Parent(object):
+
+ @property
+ @doc_controls.do_not_doc_inheritable
+ def my_method(self):
+ pass
+
+ class Child(Parent):
+
+ @property
+ def my_method(self):
+ pass
+
+ class GrandChild(Child):
+ pass
+
+ self.assertTrue(doc_controls.should_skip(Parent.my_method))
+ self.assertFalse(doc_controls.should_skip(Child.my_method))
+ self.assertFalse(doc_controls.should_skip(GrandChild.my_method))
+
+ self.assertTrue(doc_controls.should_skip_class_attr(Parent, 'my_method'))
+ self.assertTrue(doc_controls.should_skip_class_attr(Child, 'my_method'))
+ self.assertTrue(
+ doc_controls.should_skip_class_attr(GrandChild, 'my_method'))
+
+ def test_do_not_doc_inheritable_staticmethod(self):
+
+ class GrandParent(object):
+
+ def my_method(self):
+ pass
+
+ class Parent(GrandParent):
+
+ @staticmethod
+ @doc_controls.do_not_doc_inheritable
+ def my_method():
+ pass
+
+ class Child(Parent):
+
+ @staticmethod
+ def my_method():
+ pass
+
+ class GrandChild(Child):
+ pass
+
+ self.assertFalse(doc_controls.should_skip(GrandParent.my_method))
+ self.assertTrue(doc_controls.should_skip(Parent.my_method))
+ self.assertFalse(doc_controls.should_skip(Child.my_method))
+ self.assertFalse(doc_controls.should_skip(GrandChild.my_method))
+
+ self.assertFalse(
+ doc_controls.should_skip_class_attr(GrandParent, 'my_method'))
+ self.assertTrue(doc_controls.should_skip_class_attr(Parent, 'my_method'))
+ self.assertTrue(doc_controls.should_skip_class_attr(Child, 'my_method'))
+ self.assertTrue(
+ doc_controls.should_skip_class_attr(GrandChild, 'my_method'))
+
+ def testfor_subclass_implementers(self):
+
+ class GrandParent(object):
+
+ def my_method(self):
+ pass
+
+ class Parent(GrandParent):
+
+ @doc_controls.for_subclass_implementers
+ def my_method(self):
+ pass
+
+ class Child(Parent):
+ pass
+
+ class GrandChild(Child):
+
+ def my_method(self):
+ pass
+
+ class Grand2Child(Child):
+ pass
+
+ self.assertFalse(
+ doc_controls.should_skip_class_attr(GrandParent, 'my_method'))
+ self.assertFalse(doc_controls.should_skip_class_attr(Parent, 'my_method'))
+ self.assertTrue(doc_controls.should_skip_class_attr(Child, 'my_method'))
+ self.assertTrue(
+ doc_controls.should_skip_class_attr(GrandChild, 'my_method'))
+ self.assertTrue(
+ doc_controls.should_skip_class_attr(Grand2Child, 'my_method'))
+
+
+if __name__ == '__main__':
+ googletest.main()
diff --git a/tensorflow/tools/docs/doc_generator_visitor.py b/tensorflow/tools/docs/doc_generator_visitor.py
index e5eaf8cc05..a66f3e4493 100644
--- a/tensorflow/tools/docs/doc_generator_visitor.py
+++ b/tensorflow/tools/docs/doc_generator_visitor.py
@@ -269,7 +269,6 @@ class DocGeneratorVisitor(object):
# Choose the master name with a lexical sort on the tuples returned by
# by _score_name.
master_name = min(names, key=self._score_name)
- print(names, master_name)
duplicates[master_name] = names
for name in names:
diff --git a/tensorflow/tools/docs/generate.py b/tensorflow/tools/docs/generate.py
index f96887e4c7..fc93085e3e 100644
--- a/tensorflow/tools/docs/generate.py
+++ b/tensorflow/tools/docs/generate.py
@@ -31,11 +31,6 @@ if __name__ == '__main__':
doc_generator = generate_lib.DocGenerator()
doc_generator.add_output_dir_argument()
doc_generator.add_src_dir_argument()
- doc_generator.argument_parser.add_argument(
- '--site_api_path',
- type=str, default='api_docs/python',
- help='The path from the site-root to api_docs'
- 'directory for this project')
# This doc generator works on the TensorFlow codebase. Since this script lives
# at tensorflow/tools/docs, and all code is defined somewhere inside
diff --git a/tensorflow/tools/docs/generate_lib.py b/tensorflow/tools/docs/generate_lib.py
index 3a93bdcf4a..22d771bdd5 100644
--- a/tensorflow/tools/docs/generate_lib.py
+++ b/tensorflow/tools/docs/generate_lib.py
@@ -22,12 +22,14 @@ import argparse
import fnmatch
import os
import shutil
+import tempfile
import six
from tensorflow.python.util import tf_inspect
from tensorflow.tools.common import public_api
from tensorflow.tools.common import traverse
+from tensorflow.tools.docs import doc_controls
from tensorflow.tools.docs import doc_generator_visitor
from tensorflow.tools.docs import parser
from tensorflow.tools.docs import pretty_docs
@@ -56,7 +58,7 @@ def write_docs(output_dir,
yaml_toc,
root_title='TensorFlow',
search_hints=True,
- site_api_path=None):
+ site_api_path=''):
"""Write previously extracted docs to disk.
Write a docs page for each symbol included in the indices of parser_config to
@@ -74,8 +76,8 @@ def write_docs(output_dir,
root_title: The title name for the root level index.md.
search_hints: (bool) include meta-data search hints at the top of each
output file.
- site_api_path: Used to write the api-duplicates _redirects.yaml file. if
- None (the default) the file is not generated.
+ site_api_path: The output path relative to the site root. Used in the
+ `_toc.yaml` and `_redirects.yaml` files.
Raises:
ValueError: if `output_dir` is not an absolute path
@@ -96,7 +98,7 @@ def write_docs(output_dir,
symbol_to_file = {}
# Collect redirects for an api _redirects.yaml file.
- redirects = ['redirects:\n']
+ redirects = []
# Parse and write Markdown pages, resolving cross-links (@{symbol}).
for full_name, py_object in six.iteritems(parser_config.index):
@@ -110,6 +112,9 @@ def write_docs(output_dir,
_is_free_function(py_object, full_name, parser_config.index)):
continue
+ if doc_controls.should_skip(py_object):
+ continue
+
sitepath = os.path.join('api_docs/python',
parser.documentation_path(full_name)[:-3])
@@ -156,24 +161,27 @@ def write_docs(output_dir,
raise OSError(
'Cannot write documentation for %s to %s' % (full_name, directory))
- if site_api_path:
- duplicates = parser_config.duplicates.get(full_name, [])
- if not duplicates:
- continue
+ duplicates = parser_config.duplicates.get(full_name, [])
+ if not duplicates:
+ continue
+
+ duplicates = [item for item in duplicates if item != full_name]
- duplicates = [item for item in duplicates if item != full_name]
- template = ('- from: /{}\n'
- ' to: /{}\n')
- for dup in duplicates:
- from_path = os.path.join(site_api_path, dup.replace('.', '/'))
- to_path = os.path.join(site_api_path, full_name.replace('.', '/'))
- redirects.append(
- template.format(from_path, to_path))
+ for dup in duplicates:
+ from_path = os.path.join(site_api_path, dup.replace('.', '/'))
+ to_path = os.path.join(site_api_path, full_name.replace('.', '/'))
+ redirects.append((
+ os.path.join('/', from_path),
+ os.path.join('/', to_path)))
- if site_api_path:
- api_redirects_path = os.path.join(output_dir, '_redirects.yaml')
- with open(api_redirects_path, 'w') as redirect_file:
- redirect_file.write(''.join(redirects))
+ redirects = sorted(redirects)
+ template = ('- from: {}\n'
+ ' to: {}\n')
+ redirects = [template.format(f, t) for f, t in redirects]
+ api_redirects_path = os.path.join(output_dir, '_redirects.yaml')
+ with open(api_redirects_path, 'w') as redirect_file:
+ redirect_file.write('redirects:\n')
+ redirect_file.write(''.join(redirects))
if yaml_toc:
# Generate table of contents
@@ -203,7 +211,8 @@ def write_docs(output_dir,
'- title: ' + title,
' section:',
' - title: Overview',
- ' path: /TARGET_DOC_ROOT/VERSION/' + symbol_to_file[module]]
+ ' path: ' + os.path.join('/', site_api_path,
+ symbol_to_file[module])]
header = ''.join([indent+line+'\n' for line in header])
f.write(header)
@@ -214,7 +223,8 @@ def write_docs(output_dir,
for full_name in symbols_in_module:
item = [
' - title: ' + full_name[len(module) + 1:],
- ' path: /TARGET_DOC_ROOT/VERSION/' + symbol_to_file[full_name]]
+ ' path: ' + os.path.join('/', site_api_path,
+ symbol_to_file[full_name])]
item = ''.join([indent+line+'\n' for line in item])
f.write(item)
@@ -237,7 +247,9 @@ def add_dict_to_dict(add_from, add_to):
def _get_default_private_map():
return {
'tf.contrib.autograph': ['utils', 'operators'],
- 'tf.test': ['mock']}
+ 'tf.test': ['mock'],
+ 'tf.compat': ['v1', 'v2'],
+ }
# Exclude members of some libraries.
@@ -523,6 +535,12 @@ class DocGenerator(object):
action='store_false',
default=True)
+ self.argument_parser.add_argument(
+ '--site_api_path',
+ type=str, default='',
+ help='The path from the site-root to api_docs'
+ 'directory for this project')
+
def add_output_dir_argument(self):
self.argument_parser.add_argument(
'--output_dir',
@@ -535,9 +553,9 @@ class DocGenerator(object):
self.argument_parser.add_argument(
'--src_dir',
type=str,
- default=None,
- required=True,
- help='Directory with the source docs.')
+ default=tempfile.mkdtemp(),
+ required=False,
+ help='Optional directory of source docs to add api_docs links to')
def add_base_dir_argument(self, default_base_dir):
self.argument_parser.add_argument(
@@ -639,7 +657,7 @@ class DocGenerator(object):
yaml_toc=self.yaml_toc,
root_title=root_title,
search_hints=getattr(flags, 'search_hints', True),
- site_api_path=getattr(flags, 'site_api_path', None))
+ site_api_path=getattr(flags, 'site_api_path', ''))
# Replace all the @{} references in files under `FLAGS.src_dir`
replace_refs(flags.src_dir, flags.output_dir, reference_resolver, '*.md')
diff --git a/tensorflow/tools/docs/parser.py b/tensorflow/tools/docs/parser.py
index ffb93027ed..8e444a15cf 100644
--- a/tensorflow/tools/docs/parser.py
+++ b/tensorflow/tools/docs/parser.py
@@ -32,6 +32,7 @@ import six
from google.protobuf.message import Message as ProtoMessage
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_inspect
+from tensorflow.tools.docs import doc_controls
# A regular expression capturing a python identifier.
@@ -1175,15 +1176,18 @@ class _ClassPageInfo(object):
# Don't document anything that is defined in object or by protobuf.
defining_class = _get_defining_class(py_class, short_name)
- if (defining_class is object or
- defining_class is type or defining_class is tuple or
- defining_class is BaseException or defining_class is Exception or
- # The following condition excludes most protobuf-defined symbols.
- defining_class and defining_class.__name__ in ['CMessage', 'Message',
- 'MessageMeta']):
+ if defining_class in [object, type, tuple, BaseException, Exception]:
+ continue
+
+ # The following condition excludes most protobuf-defined symbols.
+ if (defining_class and
+ defining_class.__name__ in ['CMessage', 'Message', 'MessageMeta']):
continue
# TODO(markdaoust): Add a note in child docs showing the defining class.
+ if doc_controls.should_skip_class_attr(py_class, short_name):
+ continue
+
child_doc = _parse_md_docstring(child, relative_path,
parser_config.reference_resolver)
@@ -1691,15 +1695,18 @@ class _Metadata(object):
Attributes:
name: The name of the page being described by the Metadata block.
+ version: The source version.
"""
- def __init__(self, name):
+ def __init__(self, name, version='stable'):
"""Creates a Metadata builder.
Args:
name: The name of the page being described by the Metadata block.
+ version: The source version.
"""
self.name = name
+ self.version = version
self._content = []
def append(self, item):
@@ -1716,6 +1723,7 @@ class _Metadata(object):
parts = ['<div itemscope itemtype="%s">' % schema]
parts.append('<meta itemprop="name" content="%s" />' % self.name)
+ parts.append('<meta itemprop="path" content="%s" />' % self.version)
for item in self._content:
parts.append('<meta itemprop="property" content="%s"/>' % item)
diff --git a/tensorflow/tools/docs/parser_test.py b/tensorflow/tools/docs/parser_test.py
index 274d48ef66..9f6b185e81 100644
--- a/tensorflow/tools/docs/parser_test.py
+++ b/tensorflow/tools/docs/parser_test.py
@@ -24,6 +24,7 @@ import sys
from tensorflow.python.platform import googletest
from tensorflow.python.util import tf_inspect
+from tensorflow.tools.docs import doc_controls
from tensorflow.tools.docs import parser
@@ -37,13 +38,27 @@ def test_function_with_args_kwargs(unused_arg, *unused_args, **unused_kwargs):
pass
-class TestClass(object):
+class ParentClass(object):
+
+ @doc_controls.do_not_doc_inheritable
+ def hidden_method(self):
+ pass
+
+
+class TestClass(ParentClass):
"""Docstring for TestClass itself."""
def a_method(self, arg='default'):
"""Docstring for a method."""
pass
+ def hidden_method(self):
+ pass
+
+ @doc_controls.do_not_generate_docs
+ def hidden_method2(self):
+ pass
+
class ChildClass(object):
"""Docstring for a child class."""
pass
@@ -175,6 +190,104 @@ class ParserTest(googletest.TestCase):
# Make sure this file is contained as the definition location.
self.assertEqual(os.path.relpath(__file__, '/'), page_info.defined_in.path)
+ def test_docs_for_class_should_skip(self):
+
+ class Parent(object):
+
+ @doc_controls.do_not_doc_inheritable
+ def a_method(self, arg='default'):
+ pass
+
+ class Child(Parent):
+
+ def a_method(self, arg='default'):
+ pass
+
+ index = {
+ 'Child': Child,
+ 'Child.a_method': Child.a_method,
+ }
+
+ visitor = DummyVisitor(index=index, duplicate_of={})
+
+ reference_resolver = parser.ReferenceResolver.from_visitor(
+ visitor=visitor, doc_index={}, py_module_names=['tf'])
+
+ tree = {
+ 'Child': ['a_method'],
+ }
+
+ parser_config = parser.ParserConfig(
+ reference_resolver=reference_resolver,
+ duplicates={},
+ duplicate_of={},
+ tree=tree,
+ index=index,
+ reverse_index={},
+ guide_index={},
+ base_dir='/')
+
+ page_info = parser.docs_for_object(
+ full_name='Child', py_object=Child, parser_config=parser_config)
+
+ # Make sure the `a_method` is not present
+ self.assertEqual(0, len(page_info.methods))
+
+ def test_docs_for_message_class(self):
+
+ class CMessage(object):
+
+ def hidden(self):
+ pass
+
+ class Message(object):
+
+ def hidden2(self):
+ pass
+
+ class MessageMeta(object):
+
+ def hidden3(self):
+ pass
+
+ class ChildMessage(CMessage, Message, MessageMeta):
+
+ def my_method(self):
+ pass
+
+ index = {
+ 'ChildMessage': ChildMessage,
+ 'ChildMessage.hidden': ChildMessage.hidden,
+ 'ChildMessage.hidden2': ChildMessage.hidden2,
+ 'ChildMessage.hidden3': ChildMessage.hidden3,
+ 'ChildMessage.my_method': ChildMessage.my_method,
+ }
+
+ visitor = DummyVisitor(index=index, duplicate_of={})
+
+ reference_resolver = parser.ReferenceResolver.from_visitor(
+ visitor=visitor, doc_index={}, py_module_names=['tf'])
+
+ tree = {'ChildMessage': ['hidden', 'hidden2', 'hidden3', 'my_method']}
+
+ parser_config = parser.ParserConfig(
+ reference_resolver=reference_resolver,
+ duplicates={},
+ duplicate_of={},
+ tree=tree,
+ index=index,
+ reverse_index={},
+ guide_index={},
+ base_dir='/')
+
+ page_info = parser.docs_for_object(
+ full_name='ChildMessage',
+ py_object=ChildMessage,
+ parser_config=parser_config)
+
+ self.assertEqual(1, len(page_info.methods))
+ self.assertEqual('my_method', page_info.methods[0].short_name)
+
def test_docs_for_module(self):
# Get the current module.
module = sys.modules[__name__]
diff --git a/tensorflow/tools/pip_package/BUILD b/tensorflow/tools/pip_package/BUILD
index ef7ae1aa25..7839eddcf8 100644
--- a/tensorflow/tools/pip_package/BUILD
+++ b/tensorflow/tools/pip_package/BUILD
@@ -9,7 +9,7 @@ load(
"if_windows",
"transitive_hdrs",
)
-load("//third_party/mkl:build_defs.bzl", "if_mkl")
+load("//third_party/mkl:build_defs.bzl", "if_mkl", "if_mkl_ml")
load("//tensorflow:tensorflow.bzl", "if_cuda")
load("@local_config_syslibs//:build_defs.bzl", "if_not_system_lib")
load("//tensorflow/core:platform/default/build_config_root.bzl", "tf_additional_license_deps")
@@ -207,15 +207,19 @@ sh_binary(
name = "build_pip_package",
srcs = ["build_pip_package.sh"],
data = select({
- "//tensorflow:windows": [":simple_console_for_windows"],
- "//tensorflow:windows_msvc": [":simple_console_for_windows"],
+ "//tensorflow:windows": [
+ ":simple_console_for_windows",
+ "//tensorflow/contrib/lite/python:interpreter_test_data",
+ "//tensorflow/contrib/lite/python:tflite_convert",
+ "//tensorflow/contrib/lite/toco/python:toco_from_protos",
+ ],
"//conditions:default": COMMON_PIP_DEPS + [
":simple_console",
"//tensorflow/contrib/lite/python:interpreter_test_data",
"//tensorflow/contrib/lite/python:tflite_convert",
"//tensorflow/contrib/lite/toco/python:toco_from_protos",
],
- }) + if_mkl(["//third_party/mkl:intel_binary_blob"]),
+ }) + if_mkl_ml(["//third_party/mkl:intel_binary_blob"]),
)
# A genrule for generating a marker file for the pip package on Windows
diff --git a/tensorflow/tools/pip_package/MANIFEST.in b/tensorflow/tools/pip_package/MANIFEST.in
index 86c5e4776d..c4b4af93b8 100644
--- a/tensorflow/tools/pip_package/MANIFEST.in
+++ b/tensorflow/tools/pip_package/MANIFEST.in
@@ -1,5 +1,6 @@
include README
recursive-include * *.py
+recursive-include * *.pd
recursive-include * *.so
recursive-include * *.dll
recursive-include * *.lib
diff --git a/tensorflow/tools/pip_package/build_pip_package.sh b/tensorflow/tools/pip_package/build_pip_package.sh
index ca40f2eaa8..666ea75d46 100755
--- a/tensorflow/tools/pip_package/build_pip_package.sh
+++ b/tensorflow/tools/pip_package/build_pip_package.sh
@@ -44,7 +44,7 @@ function cp_external() {
PLATFORM="$(uname -s | tr 'A-Z' 'a-z')"
function is_windows() {
# On windows, the shell script is actually running in msys
- if [[ "${PLATFORM}" =~ msys_nt* ]]; then
+ if [[ "${PLATFORM}" =~ (mingw64|msys)_nt* ]]; then
true
else
false
diff --git a/tensorflow/tools/pip_package/pip_smoke_test.py b/tensorflow/tools/pip_package/pip_smoke_test.py
index 401f833dbd..bfc007bc39 100644
--- a/tensorflow/tools/pip_package/pip_smoke_test.py
+++ b/tensorflow/tools/pip_package/pip_smoke_test.py
@@ -90,6 +90,7 @@ BLACKLIST = [
"//tensorflow/contrib/lite/python:interpreter.py",
"//tensorflow/contrib/lite/python:interpreter_test.py",
"//tensorflow/contrib/ffmpeg:test_data",
+ "//tensorflow/contrib/hadoop:test_data",
"//tensorflow/contrib/factorization/examples:mnist",
"//tensorflow/contrib/factorization/examples:mnist.py",
"//tensorflow/contrib/factorization:factorization_py_CYCLIC_DEPENDENCIES_THAT_NEED_TO_GO", # pylint:disable=line-too-long
diff --git a/tensorflow/tools/pip_package/setup.py b/tensorflow/tools/pip_package/setup.py
index 53b1ca3301..5e179079c5 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.10.0-rc1'
+_VERSION = '1.10.0'
REQUIRED_PACKAGES = [
'absl-py >= 0.1.6',
diff --git a/tensorflow/tools/proto_text/BUILD b/tensorflow/tools/proto_text/BUILD
index 31e8fb9120..b4b70e0a78 100644
--- a/tensorflow/tools/proto_text/BUILD
+++ b/tensorflow/tools/proto_text/BUILD
@@ -39,6 +39,7 @@ cc_binary(
":gen_proto_text_functions_lib",
"@protobuf_archive//:protobuf",
"//tensorflow/core:lib_proto_parsing",
+ "//tensorflow/core:lib_proto_compiler",
] + if_ios(["//tensorflow/core/platform/default/build_config:logging"]),
)
@@ -49,7 +50,6 @@ cc_library(
copts = if_ios(["-DGOOGLE_LOGGING"]),
linkopts = select({
"//tensorflow:windows": [],
- "//tensorflow:windows_msvc": [],
"//tensorflow:darwin": [
"-lm",
"-lpthread",
diff --git a/tensorflow/tools/proto_text/gen_proto_text_functions.cc b/tensorflow/tools/proto_text/gen_proto_text_functions.cc
index 234afe879b..159976f1b0 100644
--- a/tensorflow/tools/proto_text/gen_proto_text_functions.cc
+++ b/tensorflow/tools/proto_text/gen_proto_text_functions.cc
@@ -18,6 +18,7 @@ limitations under the License.
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
+#include "tensorflow/core/platform/protobuf_compiler.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/tools/proto_text/gen_proto_text_functions_lib.h"
diff --git a/tensorflow/workspace.bzl b/tensorflow/workspace.bzl
index 5ad05b2d91..68c78c21cb 100644
--- a/tensorflow/workspace.bzl
+++ b/tensorflow/workspace.bzl
@@ -20,6 +20,10 @@ load(
"def_file_filter_configure",
)
+def initialize_third_party():
+ # Fill in later
+ pass
+
# Sanitize a dependency so that it works correctly from code that includes
# TensorFlow as a submodule.
def clean_dep(dep):
@@ -40,6 +44,8 @@ def tf_workspace(path_prefix = "", tf_repo_name = ""):
syslibs_configure(name = "local_config_syslibs")
python_configure(name = "local_config_python")
+ initialize_third_party()
+
# For windows bazel build
# TODO: Remove def file filter when TensorFlow can export symbols properly on Windows.
def_file_filter_configure(name = "local_config_def_file_filter")
@@ -157,11 +163,11 @@ def tf_workspace(path_prefix = "", tf_repo_name = ""):
tf_http_archive(
name = "com_googlesource_code_re2",
urls = [
- "https://mirror.bazel.build/github.com/google/re2/archive/2018-04-01.tar.gz",
- "https://github.com/google/re2/archive/2018-04-01.tar.gz",
+ "https://mirror.bazel.build/github.com/google/re2/archive/2018-07-01.tar.gz",
+ "https://github.com/google/re2/archive/2018-07-01.tar.gz",
],
- sha256 = "2f945446b71336e7f5a2bcace1abcf0b23fbba368266c6a1be33de3de3b3c912",
- strip_prefix = "re2-2018-04-01",
+ sha256 = "803c7811146edeef8f91064de37c6f19136ff01a2a8cdb3230e940b2fd9f07fe",
+ strip_prefix = "re2-2018-07-01",
system_build_file = clean_dep("//third_party/systemlibs:re2.BUILD"),
)
@@ -395,21 +401,22 @@ def tf_workspace(path_prefix = "", tf_repo_name = ""):
tf_http_archive(
name = "nsync",
urls = [
- "https://mirror.bazel.build/github.com/google/nsync/archive/1.20.0.tar.gz",
- "https://github.com/google/nsync/archive/1.20.0.tar.gz",
+ "https://mirror.bazel.build/github.com/google/nsync/archive/1.20.1.tar.gz",
+ "https://github.com/google/nsync/archive/1.20.1.tar.gz",
],
- sha256 = "0c1b03962b2f8450f21e74a5a46116bf2d6009a807c57eb4207e974a8c4bb7dd",
- strip_prefix = "nsync-1.20.0",
+ sha256 = "692f9b30e219f71a6371b98edd39cef3cbda35ac3abc4cd99ce19db430a5591a",
+ strip_prefix = "nsync-1.20.1",
+ system_build_file = clean_dep("//third_party/systemlibs:nsync.BUILD"),
)
tf_http_archive(
name = "com_google_googletest",
urls = [
- "https://mirror.bazel.build/github.com/google/googletest/archive/9816b96a6ddc0430671693df90192bbee57108b6.zip",
- "https://github.com/google/googletest/archive/9816b96a6ddc0430671693df90192bbee57108b6.zip",
+ "https://mirror.bazel.build/github.com/google/googletest/archive/997d343dd680e541ef96ce71ee54a91daf2577a0.zip",
+ "https://github.com/google/googletest/archive/997d343dd680e541ef96ce71ee54a91daf2577a0.zip",
],
- sha256 = "9cbca84c4256bed17df2c8f4d00c912c19d247c11c9ba6647cd6dd5b5c996b8d",
- strip_prefix = "googletest-9816b96a6ddc0430671693df90192bbee57108b6",
+ sha256 = "353ab86e35cea1cd386115279cf4b16695bbf21b897bfbf2721cf4cb5f64ade8",
+ strip_prefix = "googletest-997d343dd680e541ef96ce71ee54a91daf2577a0",
)
tf_http_archive(
@@ -486,11 +493,11 @@ def tf_workspace(path_prefix = "", tf_repo_name = ""):
tf_http_archive(
name = "llvm",
urls = [
- "https://mirror.bazel.build/github.com/llvm-mirror/llvm/archive/5aa74422b69e309587c4e60e98649fb8a027d260.tar.gz",
- "https://github.com/llvm-mirror/llvm/archive/5aa74422b69e309587c4e60e98649fb8a027d260.tar.gz",
+ "https://mirror.bazel.build/github.com/llvm-mirror/llvm/archive/6203c9bd082a877a20c218033636712135a3c2db.tar.gz",
+ "https://github.com/llvm-mirror/llvm/archive/6203c9bd082a877a20c218033636712135a3c2db.tar.gz",
],
- sha256 = "23371dc9cc589c2226780361012547a49c1125db6f755731216887238fb4738e",
- strip_prefix = "llvm-5aa74422b69e309587c4e60e98649fb8a027d260",
+ sha256 = "83a80f9fb2a5949ca77e526344cbd4581388c3ec7fea5c59e488d46fd38e06d9",
+ strip_prefix = "llvm-6203c9bd082a877a20c218033636712135a3c2db",
build_file = clean_dep("//third_party/llvm:llvm.autogenerated.BUILD"),
)
@@ -521,11 +528,11 @@ def tf_workspace(path_prefix = "", tf_repo_name = ""):
tf_http_archive(
name = "boringssl",
urls = [
- "https://mirror.bazel.build/github.com/google/boringssl/archive/45c4a87ae97eb95a8fc2906c035d6a8d0e02e1b8.tar.gz",
- "https://github.com/google/boringssl/archive/45c4a87ae97eb95a8fc2906c035d6a8d0e02e1b8.tar.gz",
+ "https://mirror.bazel.build/github.com/google/boringssl/archive/7f634429a04abc48e2eb041c81c5235816c96514.tar.gz",
+ "https://github.com/google/boringssl/archive/7f634429a04abc48e2eb041c81c5235816c96514.tar.gz",
],
- sha256 = "972e8d8a9d1daf9892fff7155312b1af46b4754446575a7b285e62f917424c78",
- strip_prefix = "boringssl-45c4a87ae97eb95a8fc2906c035d6a8d0e02e1b8",
+ sha256 = "1188e29000013ed6517168600fc35a010d58c5d321846d6a6dfee74e4c788b45",
+ strip_prefix = "boringssl-7f634429a04abc48e2eb041c81c5235816c96514",
)
tf_http_archive(
@@ -576,11 +583,11 @@ def tf_workspace(path_prefix = "", tf_repo_name = ""):
tf_http_archive(
name = "kafka",
urls = [
- "https://mirror.bazel.build/github.com/edenhill/librdkafka/archive/v0.11.4.tar.gz",
- "https://github.com/edenhill/librdkafka/archive/v0.11.4.tar.gz",
+ "https://mirror.bazel.build/github.com/edenhill/librdkafka/archive/v0.11.5.tar.gz",
+ "https://github.com/edenhill/librdkafka/archive/v0.11.5.tar.gz",
],
- sha256 = "9d8f1eb7b0e29e9ab1168347c939cb7ae5dff00a39cef99e7ef033fd8f92737c",
- strip_prefix = "librdkafka-0.11.4",
+ sha256 = "cc6ebbcd0a826eec1b8ce1f625ffe71b53ef3290f8192b6cae38412a958f4fd3",
+ strip_prefix = "librdkafka-0.11.5",
build_file = clean_dep("//third_party:kafka/BUILD"),
patch_file = clean_dep("//third_party/kafka:config.patch"),
)
diff --git a/third_party/curl.BUILD b/third_party/curl.BUILD
index 1638b72161..c93fac6549 100644
--- a/third_party/curl.BUILD
+++ b/third_party/curl.BUILD
@@ -243,7 +243,6 @@ cc_library(
"lib/vtls/darwinssl.c",
],
"@org_tensorflow//tensorflow:windows": CURL_WIN_SRCS,
- "@org_tensorflow//tensorflow:windows_msvc": CURL_WIN_SRCS,
"//conditions:default": [
"lib/vtls/openssl.c",
],
@@ -260,7 +259,6 @@ cc_library(
],
copts = select({
"@org_tensorflow//tensorflow:windows": CURL_WIN_COPTS,
- "@org_tensorflow//tensorflow:windows_msvc": CURL_WIN_COPTS,
"//conditions:default": [
"-Iexternal/curl/lib",
"-D_GNU_SOURCE",
@@ -280,10 +278,6 @@ cc_library(
# See curl.h for discussion of write size and Windows
"/DCURL_MAX_WRITE_SIZE=16384",
],
- "@org_tensorflow//tensorflow:windows_msvc": [
- # See curl.h for discussion of write size and Windows
- "/DCURL_MAX_WRITE_SIZE=16384",
- ],
"//conditions:default": [
"-DCURL_MAX_WRITE_SIZE=65536",
],
@@ -307,12 +301,6 @@ cc_library(
"-DEFAULTLIB:crypt32.lib",
"-DEFAULTLIB:Normaliz.lib",
],
- "@org_tensorflow//tensorflow:windows_msvc": [
- "-DEFAULTLIB:ws2_32.lib",
- "-DEFAULTLIB:advapi32.lib",
- "-DEFAULTLIB:crypt32.lib",
- "-DEFAULTLIB:Normaliz.lib",
- ],
"//conditions:default": [
"-lrt",
],
@@ -323,7 +311,6 @@ cc_library(
] + select({
"@org_tensorflow//tensorflow:ios": [],
"@org_tensorflow//tensorflow:windows": [],
- "@org_tensorflow//tensorflow:windows_msvc": [],
"//conditions:default": [
"@boringssl//:ssl",
],
@@ -426,7 +413,6 @@ cc_binary(
],
copts = select({
"@org_tensorflow//tensorflow:windows": CURL_BIN_WIN_COPTS,
- "@org_tensorflow//tensorflow:windows_msvc": CURL_BIN_WIN_COPTS,
"//conditions:default": [
"-Iexternal/curl/lib",
"-D_GNU_SOURCE",
diff --git a/third_party/double_conversion.BUILD b/third_party/double_conversion.BUILD
index 9f905216c0..d875a1a2b5 100644
--- a/third_party/double_conversion.BUILD
+++ b/third_party/double_conversion.BUILD
@@ -4,6 +4,11 @@ licenses(["notice"])
exports_files(["LICENSE"])
+config_setting(
+ name = "windows",
+ values = {"cpu": "x64_windows"},
+)
+
cc_library(
name = "double-conversion",
srcs = [
@@ -28,11 +33,10 @@ cc_library(
"double-conversion/ieee.h",
"double-conversion/strtod.h",
],
- includes = [
- ".",
- ],
- linkopts = [
- "-lm",
- ],
+ includes = ["."],
+ linkopts = select({
+ ":windows": [],
+ "//conditions:default": ["-lm"],
+ }),
visibility = ["//visibility:public"],
)
diff --git a/third_party/farmhash.BUILD b/third_party/farmhash.BUILD
index a51e1511c1..4b8464684a 100644
--- a/third_party/farmhash.BUILD
+++ b/third_party/farmhash.BUILD
@@ -3,13 +3,6 @@ licenses(["notice"]) # MIT
exports_files(["COPYING"])
config_setting(
- name = "windows_msvc",
- values = {
- "cpu": "x64_windows_msvc",
- },
-)
-
-config_setting(
name = "windows",
values = {
"cpu": "x64_windows",
@@ -23,7 +16,6 @@ cc_library(
# Disable __builtin_expect support on Windows
copts = select({
":windows": ["/DFARMHASH_OPTIONAL_BUILTIN_EXPECT"],
- ":windows_msvc": ["/DFARMHASH_OPTIONAL_BUILTIN_EXPECT"],
"//conditions:default": [],
}),
includes = ["src/."],
diff --git a/third_party/fft2d/fft2d.BUILD b/third_party/fft2d/fft2d.BUILD
index 3dbd36aec0..74dd3112fc 100644
--- a/third_party/fft2d/fft2d.BUILD
+++ b/third_party/fft2d/fft2d.BUILD
@@ -14,6 +14,11 @@ FFT2D_SRCS = [
"fft/fftsg.c",
]
+config_setting(
+ name = "windows",
+ values = {"cpu": "x64_windows"},
+)
+
# This is the main 2D FFT library. The 2D FFTs in this library call
# 1D FFTs. In addition, fast DCTs are provided for the special case
# of 8x8 and 16x16. This code in this library is referred to as
@@ -21,7 +26,10 @@ FFT2D_SRCS = [
cc_library(
name = "fft2d",
srcs = FFT2D_SRCS,
- linkopts = ["-lm"],
+ linkopts = select({
+ ":windows": [],
+ "//conditions:default": ["-lm"],
+ }),
)
objc_library(
diff --git a/third_party/flatbuffers/flatbuffers.BUILD b/third_party/flatbuffers/flatbuffers.BUILD
index 639dff2cd0..4a3701e893 100644
--- a/third_party/flatbuffers/flatbuffers.BUILD
+++ b/third_party/flatbuffers/flatbuffers.BUILD
@@ -12,12 +12,14 @@ config_setting(
visibility = ["//visibility:public"],
)
-FLATBUFFERS_COPTS = [
- "-fexceptions",
-] + select({
- "@bazel_tools//src:windows": [],
- "@bazel_tools//src:windows_msvc": [],
- "//conditions:default": ["-Wno-implicit-fallthrough"],
+config_setting(
+ name = "windows",
+ values = {"cpu": "x64_windows"},
+)
+
+FLATBUFFERS_COPTS = select({
+ ":windows": [],
+ "//conditions:default": ["-Wno-implicit-fallthrough", "-fexceptions"],
})
# Public flatc library to compile flatbuffer files at runtime.
@@ -121,6 +123,7 @@ cc_binary(
":freebsd": [
"-lm",
],
+ ":windows": [],
"//conditions:default": [
"-lm",
"-ldl",
diff --git a/third_party/gif.BUILD b/third_party/gif.BUILD
index 78fbd6c0e0..cbe730fe10 100644
--- a/third_party/gif.BUILD
+++ b/third_party/gif.BUILD
@@ -21,7 +21,6 @@ cc_library(
],
hdrs = ["lib/gif_lib.h"],
defines = select({
- #"@org_tensorflow//tensorflow:android": [
":android": [
"S_IREAD=S_IRUSR",
"S_IWRITE=S_IWUSR",
@@ -33,7 +32,6 @@ cc_library(
visibility = ["//visibility:public"],
deps = select({
":windows": [":windows_polyfill"],
- ":windows_msvc": [":windows_polyfill"],
"//conditions:default": [],
}),
)
@@ -51,13 +49,6 @@ genrule(
)
config_setting(
- name = "windows_msvc",
- values = {
- "cpu": "x64_windows_msvc",
- },
-)
-
-config_setting(
name = "windows",
values = {
"cpu": "x64_windows",
diff --git a/third_party/gpus/cuda_configure.bzl b/third_party/gpus/cuda_configure.bzl
index e848fa175c..f6a39aeaf1 100644
--- a/third_party/gpus/cuda_configure.bzl
+++ b/third_party/gpus/cuda_configure.bzl
@@ -61,6 +61,7 @@ CUDA_LIB_PATHS = [
CUPTI_HEADER_PATHS = [
"extras/CUPTI/include/",
"include/cuda/CUPTI/",
+ "include/",
]
# Lookup paths for the cupti library, relative to the
@@ -69,7 +70,7 @@ CUPTI_HEADER_PATHS = [
# the other CUDA libraries but rather in a special extras/CUPTI directory.
CUPTI_LIB_PATHS = [
"extras/CUPTI/lib64/",
- "lib/x86_64-linux-gnu",
+ "lib/x86_64-linux-gnu/",
"lib64/",
"extras/CUPTI/libx64/",
"extras/CUPTI/lib/",
@@ -96,6 +97,7 @@ CUDNN_INCLUDE_PATHS = [
NVVM_LIBDEVICE_PATHS = [
"nvvm/libdevice/",
"share/cuda/",
+ "lib/nvidia-cuda-toolkit/libdevice/",
]
# Files used to detect the NVVM libdevice path.
diff --git a/third_party/jpeg/jpeg.BUILD b/third_party/jpeg/jpeg.BUILD
index 663a218733..96e7ac061c 100644
--- a/third_party/jpeg/jpeg.BUILD
+++ b/third_party/jpeg/jpeg.BUILD
@@ -22,7 +22,6 @@ libjpegturbo_copts = select({
"-w",
],
":windows": WIN_COPTS,
- ":windows_msvc": WIN_COPTS,
"//conditions:default": [
"-O3",
"-w",
@@ -272,8 +271,10 @@ cc_library(
"jchuff.h",
"jconfig.h",
"jdct.h",
+ "jerror.h",
"jinclude.h",
"jmorecfg.h",
+ "jpegint.h",
"jpeglib.h",
"jsimd.h",
"jsimddct.h",
@@ -423,7 +424,6 @@ genrule(
outs = ["jconfig.h"],
cmd = select({
":windows": "cp $(location jconfig_win.h) $@",
- ":windows_msvc": "cp $(location jconfig_win.h) $@",
":k8": "cp $(location jconfig_nowin_simd.h) $@",
":armeabi-v7a": "cp $(location jconfig_nowin_simd.h) $@",
":arm64-v8a": "cp $(location jconfig_nowin_simd.h) $@",
@@ -441,7 +441,6 @@ genrule(
outs = ["jconfigint.h"],
cmd = select({
":windows": "cp $(location jconfigint_win.h) $@",
- ":windows_msvc": "cp $(location jconfigint_win.h) $@",
"//conditions:default": "cp $(location jconfigint_nowin.h) $@",
}),
)
@@ -542,11 +541,6 @@ config_setting(
)
config_setting(
- name = "windows_msvc",
- values = {"cpu": "x64_windows_msvc"},
-)
-
-config_setting(
name = "linux_ppc64le",
values = {"cpu": "ppc"},
)
diff --git a/third_party/kafka/BUILD b/third_party/kafka/BUILD
index 75792b0d87..11ec50069a 100644
--- a/third_party/kafka/BUILD
+++ b/third_party/kafka/BUILD
@@ -15,6 +15,7 @@ cc_library(
"src-cpp/KafkaConsumerImpl.cpp",
"src-cpp/MessageImpl.cpp",
"src-cpp/MetadataImpl.cpp",
+ "src-cpp/ProducerImpl.cpp",
"src-cpp/QueueImpl.cpp",
"src-cpp/RdKafka.cpp",
"src-cpp/TopicImpl.cpp",
@@ -47,8 +48,13 @@ cc_library(
"src/rdinterval.h",
"src/rdkafka.c",
"src/rdkafka.h",
+ "src/rdkafka_admin.c",
+ "src/rdkafka_admin.h",
"src/rdkafka_assignor.c",
"src/rdkafka_assignor.h",
+ "src/rdkafka_aux.c",
+ "src/rdkafka_aux.h",
+ "src/rdkafka_background.c",
"src/rdkafka_broker.c",
"src/rdkafka_broker.h",
"src/rdkafka_buf.c",
@@ -57,6 +63,7 @@ cc_library(
"src/rdkafka_cgrp.h",
"src/rdkafka_conf.c",
"src/rdkafka_conf.h",
+ "src/rdkafka_confval.h",
"src/rdkafka_event.h",
"src/rdkafka_feature.c",
"src/rdkafka_feature.h",
@@ -130,7 +137,15 @@ cc_library(
"src/tinycthread.h",
"src/xxhash.c",
"src/xxhash.h",
- ],
+ ] + select({
+ "@org_tensorflow//tensorflow:windows": [
+ "src/rdkafka_sasl_win32.c",
+ "src/rdwin32.h",
+ "src/regexp.c",
+ "src/regexp.h",
+ ],
+ "//conditions:default": [],
+ }),
hdrs = [
"config.h",
"src-cpp/rdkafkacpp.h",
@@ -138,15 +153,25 @@ cc_library(
"src/lz4.c",
"src/snappy_compat.h",
],
- copts = [
- "-Iexternal/kafka/src",
- "-Iexternal/kafka/src-cpp",
- ],
- defines = [
- ],
- linkopts = [
- "-lpthread",
+ copts = select({
+ "@org_tensorflow//tensorflow:windows": [
+ "-DWIN32_LEAN_AND_MEAN",
+ "-DWITHOUT_WIN32_CONFIG",
+ "-DWITH_ZLIB=1",
+ "-DWITH_SSL=1",
+ "-DWITH_SNAPPY=1",
+ ],
+ "//conditions:default": [],
+ }),
+ defines = ["LIBRDKAFKA_STATICLIB"],
+ includes = [
+ "src",
+ "src-cpp",
],
+ linkopts = select({
+ "@org_tensorflow//tensorflow:windows": ["-defaultlib:crypt32.lib"],
+ "//conditions:default": ["-lpthread"],
+ }),
visibility = ["//visibility:public"],
deps = [
"@boringssl//:ssl",
diff --git a/third_party/lmdb.BUILD b/third_party/lmdb.BUILD
index 9b3e1d97c8..f36a698ee3 100644
--- a/third_party/lmdb.BUILD
+++ b/third_party/lmdb.BUILD
@@ -20,7 +20,6 @@ cc_library(
],
linkopts = select({
":windows": ["-DEFAULTLIB:advapi32.lib"], # InitializeSecurityDescriptor, SetSecurityDescriptorDacl
- ":windows_msvc": ["-DEFAULTLIB:advapi32.lib"],
"//conditions:default": ["-lpthread"],
}),
visibility = ["//visibility:public"],
@@ -30,8 +29,3 @@ config_setting(
name = "windows",
values = {"cpu": "x64_windows"},
)
-
-config_setting(
- name = "windows_msvc",
- values = {"cpu": "x64_windows_msvc"},
-)
diff --git a/third_party/mkl/BUILD b/third_party/mkl/BUILD
index a058c46cc4..efff7fd51b 100644
--- a/third_party/mkl/BUILD
+++ b/third_party/mkl/BUILD
@@ -2,17 +2,28 @@ licenses(["notice"]) # 3-Clause BSD
config_setting(
name = "using_mkl",
- values = {
- "define": "using_mkl=true",
+ define_values = {
+ "using_mkl": "true",
+ },
+ visibility = ["//visibility:public"],
+)
+
+config_setting(
+ name = "using_mkl_ml_only",
+ define_values = {
+ "using_mkl": "true",
+ "using_mkl_ml_only": "true",
},
visibility = ["//visibility:public"],
)
config_setting(
name = "using_mkl_lnx_x64",
+ define_values = {
+ "using_mkl": "true",
+ },
values = {
"cpu": "k8",
- "define": "using_mkl=true",
},
visibility = ["//visibility:public"],
)
diff --git a/third_party/mkl/build_defs.bzl b/third_party/mkl/build_defs.bzl
index 53e02769da..06a8c3518c 100644
--- a/third_party/mkl/build_defs.bzl
+++ b/third_party/mkl/build_defs.bzl
@@ -1,6 +1,9 @@
# -*- Python -*-
"""Skylark macros for MKL.
if_mkl is a conditional to check if MKL is enabled or not.
+if_mkl_ml is a conditional to check if MKL-ML is enabled.
+if_mkl_ml_only is a conditional to check for MKL-ML-only (no MKL-DNN) mode.
+if_mkl_lnx_x64 is a conditional to check for MKL
mkl_repository is a repository rule for creating MKL repository rule that can
be pointed to either a local folder, or download it from the internet.
@@ -15,27 +18,89 @@ _TF_MKL_ROOT = "TF_MKL_ROOT"
def if_mkl(if_true, if_false = []):
"""Shorthand for select()'ing on whether we're building with MKL.
- Returns a select statement which evaluates to if_true if we're building
- with MKL enabled. Otherwise, the select statement evaluates to if_false.
+ Args:
+ if_true: expression to evaluate if building with MKL.
+ if_false: expression to evaluate if building without MKL.
+ Returns:
+ a select evaluating to either if_true or if_false as appropriate.
"""
return select({
- str(Label("//third_party/mkl:using_mkl")): if_true,
- "//conditions:default": if_false
+ "//third_party/mkl:using_mkl": if_true,
+ "//conditions:default": if_false,
+ })
+
+def if_mkl_ml(if_true, if_false = []):
+ """Shorthand for select()'ing on whether we're building with MKL-ML.
+
+ Args:
+ if_true: expression to evaluate if building with MKL-ML.
+ if_false: expression to evaluate if building without MKL-ML
+ (i.e. without MKL at all, or with MKL-DNN only).
+
+ Returns:
+ a select evaluating to either if_true or if_false as appropriate.
+ """
+ return select({
+ "//third_party/mkl_dnn:using_mkl_dnn_only":
+ if_false,
+ "//third_party/mkl:using_mkl": if_true,
+ "//conditions:default": if_false,
+ })
+
+def if_mkl_ml_only(if_true, if_false = []):
+ """Shorthand for select()'ing on whether we're building with MKL-ML only.
+
+ Args:
+ if_true: expression to evaluate if building with MKL-ML only.
+ if_false: expression to evaluate if building without MKL, or with MKL-DNN.
+
+ Returns:
+ a select evaluating to either if_true or if_false as appropriate.
+ """
+ return select({
+ "//third_party/mkl:using_mkl_ml_only": if_true,
+ "//conditions:default": if_false,
})
def if_mkl_lnx_x64(if_true, if_false = []):
- """Shorthand for select()'ing on whether we're building with MKL.
+ """Shorthand to select() on if MKL is on and the target is Linux x86-64.
- Returns a select statement which evaluates to if_true if we're building
- with MKL enabled. Otherwise, the select statement evaluates to if_false.
+ Args:
+ if_true: expression to evaluate if building with MKL is enabled and the
+ target platform is Linux x86-64.
+ if_false: expression to evaluate if building without MKL or for a
+ different platform.
+ Returns:
+ a select evaluating to either if_true or if_false as appropriate.
"""
return select({
- str(Label("//third_party/mkl:using_mkl_lnx_x64")): if_true,
- "//conditions:default": if_false
+ "//third_party/mkl:using_mkl_lnx_x64": if_true,
+ "//conditions:default": if_false,
})
+def mkl_deps():
+ """Shorthand for select() to pull in the correct set of MKL library deps.
+
+ Can pull in MKL-ML, MKL-DNN, both, or neither depending on config settings.
+
+ Returns:
+ a select evaluating to a list of library dependencies, suitable for
+ inclusion in the deps attribute of rules.
+ """
+ return select({
+ "//third_party/mkl_dnn:using_mkl_dnn_only":
+ ["@mkl_dnn"],
+ "//third_party/mkl:using_mkl_ml_only":
+ ["//third_party/mkl:intel_binary_blob"],
+ "//third_party/mkl:using_mkl":
+ [
+ "//third_party/mkl:intel_binary_blob",
+ "@mkl_dnn"
+ ],
+ "//conditions:default": []
+ })
def _enable_local_mkl(repository_ctx):
return _TF_MKL_ROOT in repository_ctx.os.environ
diff --git a/third_party/mkl_dnn/BUILD b/third_party/mkl_dnn/BUILD
index d075809ee9..3e567fa9fc 100644
--- a/third_party/mkl_dnn/BUILD
+++ b/third_party/mkl_dnn/BUILD
@@ -4,8 +4,9 @@ exports_files(["LICENSE"])
config_setting(
name = "using_mkl_dnn_only",
- values = {
- "define": "using_mkl_dnn_only=true",
+ define_values = {
+ "using_mkl": "true",
+ "using_mkl_dnn_only": "true",
},
visibility = ["//visibility:public"],
)
diff --git a/third_party/nasm.BUILD b/third_party/nasm.BUILD
index 89330eac54..2b877883b9 100644
--- a/third_party/nasm.BUILD
+++ b/third_party/nasm.BUILD
@@ -142,7 +142,6 @@ cc_binary(
],
copts = select({
":windows": [],
- ":windows_msvc": [],
"//conditions:default": [
"-w",
"-std=c99",
@@ -150,7 +149,6 @@ cc_binary(
}),
defines = select({
":windows": [],
- ":windows_msvc": [],
"//conditions:default": [
"HAVE_SNPRINTF",
"HAVE_SYS_TYPES_H",
@@ -160,13 +158,6 @@ cc_binary(
)
config_setting(
- name = "windows_msvc",
- values = {
- "cpu": "x64_windows_msvc",
- },
-)
-
-config_setting(
name = "windows",
values = {
"cpu": "x64_windows",
diff --git a/third_party/png.BUILD b/third_party/png.BUILD
index 17c5449cc0..c26a289717 100644
--- a/third_party/png.BUILD
+++ b/third_party/png.BUILD
@@ -29,6 +29,10 @@ cc_library(
"pngwtran.c",
"pngwutil.c",
] + select({
+ ":windows": [
+ "intel/intel_init.c",
+ "intel/filter_sse2_intrinsics.c",
+ ],
"@org_tensorflow//tensorflow:linux_ppc64le": [
"powerpc/powerpc_init.c",
"powerpc/filter_vsx_intrinsics.c",
@@ -41,7 +45,14 @@ cc_library(
"pngconf.h",
],
includes = ["."],
- linkopts = ["-lm"],
+ copts = select({
+ ":windows": ["-DPNG_INTEL_SSE_OPT=1"],
+ "//conditions:default": [],
+ }),
+ linkopts = select({
+ ":windows": [],
+ "//conditions:default": ["-lm"],
+ }),
visibility = ["//visibility:public"],
deps = ["@zlib_archive//:zlib"],
)
@@ -52,3 +63,8 @@ genrule(
outs = ["pnglibconf.h"],
cmd = "sed -e 's/PNG_ZLIB_VERNUM 0/PNG_ZLIB_VERNUM 0x12b0/' $< >$@",
)
+
+config_setting(
+ name = "windows",
+ values = {"cpu": "x64_windows"},
+)
diff --git a/third_party/repo.bzl b/third_party/repo.bzl
index 5cb42691c5..7d1aa5dce9 100644
--- a/third_party/repo.bzl
+++ b/third_party/repo.bzl
@@ -19,104 +19,111 @@ _SINGLE_URL_WHITELIST = depset([
])
def _is_windows(ctx):
- return ctx.os.name.lower().find("windows") != -1
+ return ctx.os.name.lower().find("windows") != -1
def _wrap_bash_cmd(ctx, cmd):
- if _is_windows(ctx):
- bazel_sh = _get_env_var(ctx, "BAZEL_SH")
- if not bazel_sh:
- fail("BAZEL_SH environment variable is not set")
- cmd = [bazel_sh, "-l", "-c", " ".join(cmd)]
- return cmd
+ if _is_windows(ctx):
+ bazel_sh = _get_env_var(ctx, "BAZEL_SH")
+ if not bazel_sh:
+ fail("BAZEL_SH environment variable is not set")
+ cmd = [bazel_sh, "-l", "-c", " ".join(cmd)]
+ return cmd
def _get_env_var(ctx, name):
- if name in ctx.os.environ:
- return ctx.os.environ[name]
- else:
- return None
+ if name in ctx.os.environ:
+ return ctx.os.environ[name]
+ else:
+ return None
# Checks if we should use the system lib instead of the bundled one
def _use_system_lib(ctx, name):
- syslibenv = _get_env_var(ctx, "TF_SYSTEM_LIBS")
- if syslibenv:
- for n in syslibenv.strip().split(","):
- if n.strip() == name:
- return True
- return False
+ syslibenv = _get_env_var(ctx, "TF_SYSTEM_LIBS")
+ if syslibenv:
+ for n in syslibenv.strip().split(","):
+ if n.strip() == name:
+ return True
+ return False
# Executes specified command with arguments and calls 'fail' if it exited with
# non-zero code
def _execute_and_check_ret_code(repo_ctx, cmd_and_args):
- result = repo_ctx.execute(cmd_and_args, timeout=10)
- if result.return_code != 0:
- fail(("Non-zero return code({1}) when executing '{0}':\n" + "Stdout: {2}\n"
- + "Stderr: {3}").format(" ".join(cmd_and_args), result.return_code,
- result.stdout, result.stderr))
+ result = repo_ctx.execute(cmd_and_args, timeout = 10)
+ if result.return_code != 0:
+ fail(("Non-zero return code({1}) when executing '{0}':\n" + "Stdout: {2}\n" +
+ "Stderr: {3}").format(
+ " ".join(cmd_and_args),
+ result.return_code,
+ result.stdout,
+ result.stderr,
+ ))
def _repos_are_siblings():
- return Label("@foo//bar").workspace_root.startswith("../")
+ return Label("@foo//bar").workspace_root.startswith("../")
# Apply a patch_file to the repository root directory
# Runs 'patch -p1'
def _apply_patch(ctx, patch_file):
- # Don't check patch on Windows, because patch is only available under bash.
- if not _is_windows(ctx) and not ctx.which("patch"):
- fail("patch command is not found, please install it")
- cmd = _wrap_bash_cmd(
- ctx, ["patch", "-p1", "-d", ctx.path("."), "-i", ctx.path(patch_file)])
- _execute_and_check_ret_code(ctx, cmd)
+ # Don't check patch on Windows, because patch is only available under bash.
+ if not _is_windows(ctx) and not ctx.which("patch"):
+ fail("patch command is not found, please install it")
+ cmd = _wrap_bash_cmd(
+ ctx,
+ ["patch", "-p1", "-d", ctx.path("."), "-i", ctx.path(patch_file)],
+ )
+ _execute_and_check_ret_code(ctx, cmd)
def _apply_delete(ctx, paths):
- for path in paths:
- if path.startswith("/"):
- fail("refusing to rm -rf path starting with '/': " + path)
- if ".." in path:
- fail("refusing to rm -rf path containing '..': " + path)
- cmd = _wrap_bash_cmd(ctx, ["rm", "-rf"] + [ctx.path(path) for path in paths])
- _execute_and_check_ret_code(ctx, cmd)
+ for path in paths:
+ if path.startswith("/"):
+ fail("refusing to rm -rf path starting with '/': " + path)
+ if ".." in path:
+ fail("refusing to rm -rf path containing '..': " + path)
+ cmd = _wrap_bash_cmd(ctx, ["rm", "-rf"] + [ctx.path(path) for path in paths])
+ _execute_and_check_ret_code(ctx, cmd)
def _tf_http_archive(ctx):
- if ("mirror.bazel.build" not in ctx.attr.urls[0] and
- (len(ctx.attr.urls) < 2 and
- ctx.attr.name not in _SINGLE_URL_WHITELIST)):
- fail("tf_http_archive(urls) must have redundant URLs. The " +
- "mirror.bazel.build URL must be present and it must come first. " +
- "Even if you don't have permission to mirror the file, please " +
- "put the correctly formatted mirror URL there anyway, because " +
- "someone will come along shortly thereafter and mirror the file.")
-
- use_syslib = _use_system_lib(ctx, ctx.attr.name)
- if not use_syslib:
- ctx.download_and_extract(
- ctx.attr.urls,
- "",
- ctx.attr.sha256,
- ctx.attr.type,
- ctx.attr.strip_prefix)
- if ctx.attr.delete:
- _apply_delete(ctx, ctx.attr.delete)
- if ctx.attr.patch_file != None:
- _apply_patch(ctx, ctx.attr.patch_file)
-
- if use_syslib and ctx.attr.system_build_file != None:
- # Use BUILD.bazel to avoid conflict with third party projects with
- # BUILD or build (directory) underneath.
- ctx.template("BUILD.bazel", ctx.attr.system_build_file, {
- "%prefix%": ".." if _repos_are_siblings() else "external",
- }, False)
-
- elif ctx.attr.build_file != None:
- # Use BUILD.bazel to avoid conflict with third party projects with
- # BUILD or build (directory) underneath.
- ctx.template("BUILD.bazel", ctx.attr.build_file, {
- "%prefix%": ".." if _repos_are_siblings() else "external",
- }, False)
+ if ("mirror.bazel.build" not in ctx.attr.urls[0] and
+ (len(ctx.attr.urls) < 2 and
+ ctx.attr.name not in _SINGLE_URL_WHITELIST)):
+ fail("tf_http_archive(urls) must have redundant URLs. The " +
+ "mirror.bazel.build URL must be present and it must come first. " +
+ "Even if you don't have permission to mirror the file, please " +
+ "put the correctly formatted mirror URL there anyway, because " +
+ "someone will come along shortly thereafter and mirror the file.")
+
+ use_syslib = _use_system_lib(ctx, ctx.attr.name)
+ if not use_syslib:
+ ctx.download_and_extract(
+ ctx.attr.urls,
+ "",
+ ctx.attr.sha256,
+ ctx.attr.type,
+ ctx.attr.strip_prefix,
+ )
+ if ctx.attr.delete:
+ _apply_delete(ctx, ctx.attr.delete)
+ if ctx.attr.patch_file != None:
+ _apply_patch(ctx, ctx.attr.patch_file)
+
+ if use_syslib and ctx.attr.system_build_file != None:
+ # Use BUILD.bazel to avoid conflict with third party projects with
+ # BUILD or build (directory) underneath.
+ ctx.template("BUILD.bazel", ctx.attr.system_build_file, {
+ "%prefix%": ".." if _repos_are_siblings() else "external",
+ }, False)
+
+ elif ctx.attr.build_file != None:
+ # Use BUILD.bazel to avoid conflict with third party projects with
+ # BUILD or build (directory) underneath.
+ ctx.template("BUILD.bazel", ctx.attr.build_file, {
+ "%prefix%": ".." if _repos_are_siblings() else "external",
+ }, False)
tf_http_archive = repository_rule(
- implementation=_tf_http_archive,
- attrs={
- "sha256": attr.string(mandatory=True),
- "urls": attr.string_list(mandatory=True, allow_empty=False),
+ implementation = _tf_http_archive,
+ attrs = {
+ "sha256": attr.string(mandatory = True),
+ "urls": attr.string_list(mandatory = True, allow_empty = False),
"strip_prefix": attr.string(),
"type": attr.string(),
"delete": attr.string_list(),
@@ -124,12 +131,78 @@ tf_http_archive = repository_rule(
"build_file": attr.label(),
"system_build_file": attr.label(),
},
- environ=[
- "TF_SYSTEM_LIBS",
- ])
+ environ = [
+ "TF_SYSTEM_LIBS",
+ ],
+)
"""Downloads and creates Bazel repos for dependencies.
This is a swappable replacement for both http_archive() and
new_http_archive() that offers some additional features. It also helps
ensure best practices are followed.
"""
+
+def _third_party_http_archive(ctx):
+ if ("mirror.bazel.build" not in ctx.attr.urls[0] and
+ (len(ctx.attr.urls) < 2 and
+ ctx.attr.name not in _SINGLE_URL_WHITELIST)):
+ fail("tf_http_archive(urls) must have redundant URLs. The " +
+ "mirror.bazel.build URL must be present and it must come first. " +
+ "Even if you don't have permission to mirror the file, please " +
+ "put the correctly formatted mirror URL there anyway, because " +
+ "someone will come along shortly thereafter and mirror the file.")
+
+ use_syslib = _use_system_lib(ctx, ctx.attr.name)
+
+ # Use "BUILD.bazel" to avoid conflict with third party projects that contain a
+ # file or directory called "BUILD"
+ buildfile_path = ctx.path("BUILD.bazel")
+
+ if use_syslib:
+ if ctx.attr.system_build_file == None:
+ fail("Bazel was configured with TF_SYSTEM_LIBS to use a system " +
+ "library for %s, but no system build file for %s was configured. " +
+ "Please add a system_build_file attribute to the repository rule" +
+ "for %s." % (ctx.attr.name, ctx.attr.name, ctx.attr.name))
+ ctx.symlink(Label(ctx.attr.system_build_file), buildfile_path)
+
+ else:
+ ctx.download_and_extract(
+ ctx.attr.urls,
+ "",
+ ctx.attr.sha256,
+ ctx.attr.type,
+ ctx.attr.strip_prefix,
+ )
+ if ctx.attr.delete:
+ _apply_delete(ctx, ctx.attr.delete)
+ if ctx.attr.patch_file != None:
+ _apply_patch(ctx, ctx.attr.patch_file)
+ ctx.symlink(Label(ctx.attr.build_file), buildfile_path)
+
+ for internal_src, external_dest in ctx.attr.link_files.items():
+ ctx.symlink(Label(internal_src), ctx.path(external_dest))
+
+# Downloads and creates Bazel repos for dependencies.
+#
+# This is an upgrade for tf_http_archive that works with go/tfbr-thirdparty.
+#
+# For link_files, specify each dict entry as:
+# "//path/to/source:file": "localfile"
+third_party_http_archive = repository_rule(
+ implementation = _third_party_http_archive,
+ attrs = {
+ "sha256": attr.string(mandatory = True),
+ "urls": attr.string_list(mandatory = True, allow_empty = False),
+ "strip_prefix": attr.string(),
+ "type": attr.string(),
+ "delete": attr.string_list(),
+ "build_file": attr.string(mandatory = True),
+ "system_build_file": attr.string(mandatory = False),
+ "patch_file": attr.label(),
+ "link_files": attr.string_dict(),
+ },
+ environ = [
+ "TF_SYSTEM_LIBS",
+ ],
+)
diff --git a/third_party/snappy.BUILD b/third_party/snappy.BUILD
index cc11f52d0e..d93f030769 100644
--- a/third_party/snappy.BUILD
+++ b/third_party/snappy.BUILD
@@ -18,17 +18,9 @@ cc_library(
"snappy-stubs-public.h",
],
hdrs = ["snappy.h"],
- copts = select({
- "@org_tensorflow//tensorflow:windows": [
- "/DHAVE_CONFIG_H",
- "/EHsc",
- ],
- "@org_tensorflow//tensorflow:windows_msvc": [
- "/DHAVE_CONFIG_H",
- "/EHsc",
- ],
+ copts = ["-DHAVE_CONFIG_H"] + select({
+ "@org_tensorflow//tensorflow:windows": [],
"//conditions:default": [
- "-DHAVE_CONFIG_H",
"-fno-exceptions",
"-Wno-sign-compare",
"-Wno-shift-negative-value",
diff --git a/third_party/sqlite.BUILD b/third_party/sqlite.BUILD
index 2876f305f1..8b876fb56f 100644
--- a/third_party/sqlite.BUILD
+++ b/third_party/sqlite.BUILD
@@ -4,7 +4,6 @@
licenses(["unencumbered"]) # Public Domain
SQLITE_COPTS = [
- "-Os",
"-DSQLITE_ENABLE_JSON1",
"-DHAVE_DECL_STRERROR_R=1",
"-DHAVE_STDINT_H=1",
@@ -15,15 +14,14 @@ SQLITE_COPTS = [
"@org_tensorflow//tensorflow:windows": [
"-DSQLITE_MAX_TRIGGER_DEPTH=100",
],
- "@org_tensorflow//tensorflow:windows_msvc": [
- "-DSQLITE_MAX_TRIGGER_DEPTH=100",
- ],
"@org_tensorflow//tensorflow:darwin": [
+ "-Os",
"-DHAVE_GMTIME_R=1",
"-DHAVE_LOCALTIME_R=1",
"-DHAVE_USLEEP=1",
],
"//conditions:default": [
+ "-Os",
"-DHAVE_FDATASYNC=1",
"-DHAVE_GMTIME_R=1",
"-DHAVE_LOCALTIME_R=1",
@@ -48,7 +46,7 @@ cc_library(
"SQLITE_OMIT_DEPRECATED",
],
linkopts = select({
- "@org_tensorflow//tensorflow:windows_msvc": [],
+ "@org_tensorflow//tensorflow:windows": [],
"//conditions:default": [
"-ldl",
"-lpthread",
diff --git a/third_party/swig.BUILD b/third_party/swig.BUILD
index f2f647401b..59a3d9e671 100644
--- a/third_party/swig.BUILD
+++ b/third_party/swig.BUILD
@@ -71,7 +71,6 @@ cc_binary(
],
copts = ["$(STACK_FRAME_UNLIMITED)"] + select({
":windows": [],
- ":windows_msvc": [],
"//conditions:default": [
"-Wno-parentheses",
"-Wno-unused-variable",
@@ -332,11 +331,6 @@ genrule(
)
config_setting(
- name = "windows_msvc",
- values = {"cpu": "x64_windows_msvc"},
-)
-
-config_setting(
name = "windows",
values = {"cpu": "x64_windows"},
)
diff --git a/third_party/systemlibs/nsync.BUILD b/third_party/systemlibs/nsync.BUILD
new file mode 100644
index 0000000000..c5d4ad0a76
--- /dev/null
+++ b/third_party/systemlibs/nsync.BUILD
@@ -0,0 +1,23 @@
+licenses(["notice"]) # BSD 3-Clause
+
+filegroup(
+ name = "LICENSE",
+ visibility = ["//visibility:public"],
+)
+
+cc_library(
+ name = "nsync_headers",
+ visibility = ["//visibility:public"],
+)
+
+cc_library(
+ name = "nsync",
+ linkopts = ["-lnsync"],
+ visibility = ["//visibility:public"],
+)
+
+cc_library(
+ name = "nsync_cpp",
+ linkopts = ["-lnsync_cpp"],
+ visibility = ["//visibility:public"],
+)
diff --git a/third_party/systemlibs/syslibs_configure.bzl b/third_party/systemlibs/syslibs_configure.bzl
index 07a44c317e..8b09c9ac1f 100644
--- a/third_party/systemlibs/syslibs_configure.bzl
+++ b/third_party/systemlibs/syslibs_configure.bzl
@@ -7,9 +7,9 @@
the system version instead
"""
-_TF_SYSTEM_LIBS="TF_SYSTEM_LIBS"
+_TF_SYSTEM_LIBS = "TF_SYSTEM_LIBS"
-VALID_LIBS=[
+VALID_LIBS = [
"astor_archive",
"com_googlesource_code_re2",
"curl",
@@ -22,6 +22,7 @@ VALID_LIBS=[
"jsoncpp_git",
"lmdb",
"nasm",
+ "nsync",
"org_sqlite",
"pcre",
"png_archive",
@@ -32,112 +33,109 @@ VALID_LIBS=[
"zlib_archive",
]
-
def auto_configure_fail(msg):
- """Output failure message when syslibs configuration fails."""
- red = "\033[0;31m"
- no_color = "\033[0m"
- fail("\n%sSystem Library Configuration Error:%s %s\n" % (red, no_color, msg))
-
+ """Output failure message when syslibs configuration fails."""
+ red = "\033[0;31m"
+ no_color = "\033[0m"
+ fail("\n%sSystem Library Configuration Error:%s %s\n" % (red, no_color, msg))
def _is_windows(repository_ctx):
- """Returns true if the host operating system is windows."""
- os_name = repository_ctx.os.name.lower()
- if os_name.find("windows") != -1:
- return True
- return False
-
+ """Returns true if the host operating system is windows."""
+ os_name = repository_ctx.os.name.lower()
+ if os_name.find("windows") != -1:
+ return True
+ return False
def _enable_syslibs(repository_ctx):
- s = repository_ctx.os.environ.get(_TF_SYSTEM_LIBS, '').strip()
- if not _is_windows(repository_ctx) and s != None and s != '':
- return True
- return False
-
+ s = repository_ctx.os.environ.get(_TF_SYSTEM_LIBS, "").strip()
+ if not _is_windows(repository_ctx) and s != None and s != "":
+ return True
+ return False
def _get_system_lib_list(repository_ctx):
- """Gets the list of deps that should use the system lib.
+ """Gets the list of deps that should use the system lib.
- Args:
- repository_ctx: The repository context.
+ Args:
+ repository_ctx: The repository context.
- Returns:
- A string version of a python list
- """
- if _TF_SYSTEM_LIBS not in repository_ctx.os.environ:
- return []
+ Returns:
+ A string version of a python list
+ """
+ if _TF_SYSTEM_LIBS not in repository_ctx.os.environ:
+ return []
- libenv = repository_ctx.os.environ[_TF_SYSTEM_LIBS].strip()
- libs = []
+ libenv = repository_ctx.os.environ[_TF_SYSTEM_LIBS].strip()
+ libs = []
- for lib in list(libenv.split(',')):
- lib = lib.strip()
- if lib == "":
- continue
- if lib not in VALID_LIBS:
- auto_configure_fail("Invalid system lib set: %s" % lib)
- return []
- libs.append(lib)
-
- return libs
+ for lib in list(libenv.split(",")):
+ lib = lib.strip()
+ if lib == "":
+ continue
+ if lib not in VALID_LIBS:
+ auto_configure_fail("Invalid system lib set: %s" % lib)
+ return []
+ libs.append(lib)
+ return libs
def _format_system_lib_list(repository_ctx):
- """Formats the list of deps that should use the system lib.
-
- Args:
- repository_ctx: The repository context.
-
- Returns:
- A list of the names of deps that should use the system lib.
- """
- libs = _get_system_lib_list(repository_ctx)
- ret = ''
- for lib in libs:
- ret += "'%s',\n" % lib
-
- return ret
-
-
-def _tpl(repository_ctx, tpl, substitutions={}, out=None):
- if not out:
- out = tpl.replace(":", "")
- repository_ctx.template(
- out,
- Label("//third_party/systemlibs%s.tpl" % tpl),
- substitutions,
- False)
-
+ """Formats the list of deps that should use the system lib.
+
+ Args:
+ repository_ctx: The repository context.
+
+ Returns:
+ A list of the names of deps that should use the system lib.
+ """
+ libs = _get_system_lib_list(repository_ctx)
+ ret = ""
+ for lib in libs:
+ ret += "'%s',\n" % lib
+
+ return ret
+
+def _tpl(repository_ctx, tpl, substitutions = {}, out = None):
+ if not out:
+ out = tpl.replace(":", "")
+ repository_ctx.template(
+ out,
+ Label("//third_party/systemlibs%s.tpl" % tpl),
+ substitutions,
+ False,
+ )
def _create_dummy_repository(repository_ctx):
- """Creates the dummy repository to build with all bundled libraries."""
-
- _tpl(repository_ctx, ":BUILD")
- _tpl(repository_ctx, ":build_defs.bzl",
- {
- "%{syslibs_enabled}": 'False',
- "%{syslibs_list}": '',
- })
-
+ """Creates the dummy repository to build with all bundled libraries."""
+
+ _tpl(repository_ctx, ":BUILD")
+ _tpl(
+ repository_ctx,
+ ":build_defs.bzl",
+ {
+ "%{syslibs_enabled}": "False",
+ "%{syslibs_list}": "",
+ },
+ )
def _create_local_repository(repository_ctx):
- """Creates the repository to build with system libraries."""
-
- _tpl(repository_ctx, ":BUILD")
- _tpl(repository_ctx, ":build_defs.bzl",
- {
- "%{syslibs_enabled}": 'True',
- "%{syslibs_list}": _format_system_lib_list(repository_ctx),
- })
-
+ """Creates the repository to build with system libraries."""
+
+ _tpl(repository_ctx, ":BUILD")
+ _tpl(
+ repository_ctx,
+ ":build_defs.bzl",
+ {
+ "%{syslibs_enabled}": "True",
+ "%{syslibs_list}": _format_system_lib_list(repository_ctx),
+ },
+ )
def _syslibs_autoconf_impl(repository_ctx):
- """Implementation of the syslibs_configure repository rule."""
- if not _enable_syslibs(repository_ctx):
- _create_dummy_repository(repository_ctx)
- else:
- _create_local_repository(repository_ctx)
-
+ """Implementation of the syslibs_configure repository rule."""
+ if not _enable_syslibs(repository_ctx):
+ _create_dummy_repository(repository_ctx)
+ else:
+ _create_local_repository(repository_ctx)
syslibs_configure = repository_rule(
implementation = _syslibs_autoconf_impl,
diff --git a/third_party/zlib.BUILD b/third_party/zlib.BUILD
index e8048dd98a..33694eaaae 100644
--- a/third_party/zlib.BUILD
+++ b/third_party/zlib.BUILD
@@ -34,7 +34,6 @@ cc_library(
hdrs = ["zlib.h"],
copts = select({
"@org_tensorflow//tensorflow:windows": [],
- "@org_tensorflow//tensorflow:windows_msvc": [],
"//conditions:default": [
"-Wno-shift-negative-value",
"-DZ_HAVE_UNISTD_H",